blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
0c43d5826f6233e092b81ea08d64f02c022b0780
Java
yangyongchaoGitHub/zhgd
/src/main/java/com/dataexpo/service/FaceSearchService.java
UTF-8
6,704
2.046875
2
[]
no_license
package com.dataexpo.service; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import com.dataexpo.domain.WebSocketClient; import com.dataexpo.listener.WebsocketPacketHandleEvent; import com.dataexpo.serviceinterface.FaceSearchServiceInterface; import com.dataexpo.serviceinterface.WSServiceInterface; import com.dataexpo.trans.BaseRequest; import com.dataexpo.trans.BaseResponse; import com.dataexpo.trans.Definds; import com.dataexpo.trans.face.FaceImageInfos; import com.dataexpo.trans.face.FaceInfoRequestParam; import com.dataexpo.trans.face.FaceInfoResponse; import com.dataexpo.trans.face.FaceInfoResponseEntity; import com.dataexpo.trans.face.FacePacket; import com.dataexpo.trans.face.FaceSearchCreateResponseEntity; import com.dataexpo.trans.face.GetPicParam; import com.dataexpo.trans.face.WaitSendRequest; import com.dataexpo.trans.user.UserAddResponse; import com.dataexpo.trans.user.UserDeleteResponse; import com.dataexpo.trans.user.UserSearchResponse; import com.fasterxml.jackson.databind.ObjectMapper; @Component @Service("FaceSearchService") public class FaceSearchService implements FaceSearchServiceInterface, ApplicationListener<WebsocketPacketHandleEvent> { //存储人脸查询组信息 key:设备序列号 HashMap<String, FacePacket> packetsMap = new HashMap<String, FacePacket>(); List<WaitSendRequest> waitList = new ArrayList<WaitSendRequest>(); ObjectMapper mapper = new ObjectMapper(); @Autowired WSServiceInterface wsService; public int getUserPic(String deviceId, String userCode) { int res = 0; BaseRequest request = new BaseRequest(); GetPicParam param = new GetPicParam(); param.setFaceToken("0eee01a404a90a4562ae41c5b90a2b58"); request.setId(wsService.getId()); request.setMethod(Definds.FACE_GET_PIC_BY_TOKEN); request.setParams(param); if (packetsMap.size() == 0) { createFaceSearchPacket(deviceId); WaitSendRequest waitSendRequest = new WaitSendRequest(); waitSendRequest.setDeviceId(deviceId); waitSendRequest.setRequest(request); waitList.add(waitSendRequest); System.out.println("还未创建查询组件"); } else { request.setObject(packetsMap.get(deviceId).getPacketId()); res = wsService.send(deviceId, request); System.out.println("已有查询组件 直接发送!"); } return res; } public int getUserFaceStatus(String deviceId, String id) { int res = 0; BaseRequest request = new BaseRequest(); request.setId(wsService.getId()); request.setMethod(Definds.fACE_GET_INFO_BY_ID); FaceInfoRequestParam param = new FaceInfoRequestParam(); param.setCertificateType("IC"); param.setId(id); request.setParams(param); if (packetsMap.size() == 0) { createFaceSearchPacket(deviceId); WaitSendRequest waitSendRequest = new WaitSendRequest(); waitSendRequest.setDeviceId(deviceId); waitSendRequest.setRequest(request); waitList.add(waitSendRequest); System.out.println("还未创建查询组件"); } else { request.setObject(packetsMap.get(deviceId).getPacketId()); res = wsService.send(deviceId, request); System.out.println("已有查询组件 直接发送!"); } return res; } public int createFaceSearchPacket(String deviceId) { int res = 0; BaseRequest request = new BaseRequest(); request.setId(wsService.getId()); request.setMethod(Definds.FACE_CREATE_GROUP_INTERFACE); res = wsService.send(deviceId, request); return res; } public int destroyFaceSearchPacket(String deviceId) { int res = 0; BaseRequest request = new BaseRequest(); FacePacket packet = packetsMap.get(deviceId); request.setId(wsService.getId()); packet.setDestroyId(request.getId()); packet.setStatus(FacePacket.STATUS_INDESTROY); request.setMethod(Definds.FACE_DESTROY_GROUP_INTERFACE); request.setObject(packet.getPacketId()); res = wsService.send(deviceId, request); return res; } private void sendWait() { for (int i = 0; i < waitList.size(); i++) { BaseRequest request = waitList.get(i).getRequest(); FacePacket packet = packetsMap.get(waitList.get(i).getDeviceId()); if (packet != null) { request.setObject(packet.getPacketId()); wsService.send(waitList.get(i).getDeviceId(), request); } } } /** * 当有设备返回数据包时 触发监听时间 */ public void onApplicationEvent(WebsocketPacketHandleEvent event) { System.out.println("FaceSearchService onApplicationEvent"); String method = event.getMethod(); String payload = event.getPayload(); try { if (Definds.FACE_CREATE_GROUP_INTERFACE.equals(method)) { System.out.println("-----" + Definds.FACE_CREATE_GROUP_INTERFACE); /* * UserAddResponse addResponse = mapper.readValue(payload, * UserAddResponse.class); responseWithUserAdd(addResponse); */ FaceSearchCreateResponseEntity entity = mapper.readValue(payload, FaceSearchCreateResponseEntity.class); FacePacket packet = new FacePacket(); packet.setPacketId(entity.getResult()); packet.setCreate(new Date().getTime()); packetsMap.put((String) event.getSession().getAttributes().get("SerialNo"), packet); sendWait(); } else if (Definds.fACE_GET_INFO_BY_ID.equals(method)) { System.out.println("-----" + Definds.fACE_GET_INFO_BY_ID); FaceInfoResponse response = mapper.readValue(payload, FaceInfoResponse.class); FaceImageInfos infos = response.getParams().getFaceImageInfos().get(0); System.out.println("FaceImageInfos facetoken" + infos.getFaceToken() + " personid " + infos.getPersonID()); } else if (Definds.FACE_GET_PIC_BY_TOKEN.equals(method)) { System.out.println("-----" + Definds.FACE_GET_PIC_BY_TOKEN); System.out.println(payload); } else if (Definds.FACE_DESTROY_GROUP_INTERFACE.equals(method)) { System.out.println("-----" + Definds.FACE_DESTROY_GROUP_INTERFACE); BaseResponse response = mapper.readValue(payload, BaseResponse.class); System.out.println("result: " + response.getResult()); Iterator<Entry<String, FacePacket>> iterator = packetsMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, FacePacket> entry = iterator.next(); //找到对应的packet if (entry.getValue().getDestroyId() == response.getId()) { iterator.remove(); break; } } } } catch (Exception e) { e.printStackTrace(); } } }
true
0237c0bb63444f153fcab4b49f98eb7bccfbb1b2
Java
michkin32/FullStack.MicroWebApplication-Server
/src/main/java/com/groupfour/chatapp/chatapp/repositories/FileAttachmentRepository.java
UTF-8
326
1.828125
2
[]
no_license
package com.groupfour.chatapp.chatapp.repositories; import com.groupfour.chatapp.chatapp.models.FileAttachment; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface FileAttachmentRepository extends CrudRepository<FileAttachment, Long> { }
true
bbe88a69695f53bd7079e72f6770f4d253f1fb31
Java
tayfunyasar/instaton
/src/main/java/com/instaton/repository/TwitterUserProfileRepository.java
UTF-8
305
1.59375
2
[]
no_license
package com.instaton.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.instaton.entity.social.twitter.UserProfile; @Repository public interface TwitterUserProfileRepository extends CrudRepository<UserProfile, String> {}
true
5f5031a810ea2c29f514b67a672ac04259d1ee19
Java
ftahery/Shop8Best
/app/src/main/java/company/shop8best/adapters/ItemTypeAdapter.java
UTF-8
3,488
2.296875
2
[]
no_license
package company.shop8best.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import company.shop8best.R; import company.shop8best.model.MenuModel; import company.shop8best.model.UserAddresses; /** * Created by dat9 on 08/07/18. */ public class ItemTypeAdapter extends BaseExpandableListAdapter { private static final String TAG = "AddressSelectionAdapter"; private Context context; private ArrayList<String> values; private List<MenuModel> listDataHeader; private HashMap<MenuModel, List<MenuModel>> listDataChild; public ItemTypeAdapter(Context context, List<MenuModel> listDataHeader, HashMap<MenuModel, List<MenuModel>> listChildData) { this.context = context; this.listDataHeader = new ArrayList<>(listDataHeader); this.listDataChild = new HashMap<>(listChildData); } @Override public int getGroupCount() { return this.listDataHeader.size(); } @Override public int getChildrenCount(int groupPosition) { if (this.listDataChild.get(this.listDataHeader.get(groupPosition)) == null) { return 0; } else { return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size(); } } @Override public MenuModel getGroup(int groupPosition) { return this.listDataHeader.get(groupPosition); } @Override public MenuModel getChild(int groupPosition, int childPosition) { return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosition); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public boolean hasStableIds() { return false; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String headerTitle = getGroup(groupPosition).menuName; if (convertView == null) { LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inf.inflate(R.layout.navigation_list_group_header, null); } TextView listHeader = (TextView) convertView.findViewById(R.id.nav_list_header); listHeader.setText(headerTitle); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { String childTitle = getChild(groupPosition, childPosition).menuName; if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.navigation_list_group_child, null); } TextView childHeader = (TextView) convertView.findViewById(R.id.nav_list_child); childHeader.setText(childTitle); return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }
true
40c0c79090c7f7abdedcdcfd9708b52f031b913f
Java
whyoyyx/trade
/trade-api/src/main/java/com/hbc/api/trade/order/controller/opt/req/MISEditOrderParam.java
UTF-8
7,788
2.03125
2
[]
no_license
/** * @Author lukangle * @2015年10月7日@下午5:13:41 */ package com.hbc.api.trade.order.controller.opt.req; import javax.validation.constraints.Min; import org.hibernate.validator.constraints.NotBlank; public class MISEditOrderParam { /* --------- 公用 ------------ */ @NotBlank private String orderNo; // 目的地酒店或者区域电话号码 private Integer orderType; // 1-接机;2-送机;3-日租;4-次租 @Min(value = 0, message = "车座位数不能小于0") private Integer carSeatNum; @Min(value = 0, message = "成人座位数不能小于0") private Integer adultNum;// 成人座位数 @Min(value = 0, message = "小孩座位数不能小于0") private Integer childNum;// 小孩座位数 private String serviceAddressTel; // 目的地酒店或者区域电话号码 private String serviceAreaCode; // 目的地区号 private String userAreaCode1; private String userMobile1; private String userAreaCode2; private String userMobile2; private String userAreaCode3; private String userMobile3; private String userEmail; // 客人email private String userRemark; // 客人备注 private String userName; // 客人名称 private Integer isArrivalVisa; private Integer orderChannel; private Integer orderSource; /* --------- 次租 ------------ */ // 暂无额外字段需要更新 /* --------- 日租 ------------ */ private String serviceDate; // 服务时间[2015-10-03 20:02:34]必须为开始时间当天 只容许修改点数 日租 private String serviceRecTime; // 服务时间的时分秒 private String servicePassCitys; // 途径城市 private String startAddress; /* --------- 送机、接机 ------------ */ private String flightBrandSign; // 接机 private String flightNo; private String flightAirportCode; private String flightAirportName; private String flightFlyTimeL; private String flightArriveTimeL; private String flightAirportBuiding; public Integer getOrderSource() { return orderSource; } public void setOrderSource(Integer orderSource) { this.orderSource = orderSource; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public Integer getOrderType() { return orderType; } public void setOrderType(Integer orderType) { this.orderType = orderType; } public Integer getCarSeatNum() { return carSeatNum; } public void setCarSeatNum(Integer carSeatNum) { this.carSeatNum = carSeatNum; } public Integer getAdultNum() { return adultNum; } public void setAdultNum(Integer adultNum) { this.adultNum = adultNum; } public Integer getChildNum() { return childNum; } public void setChildNum(Integer childNum) { this.childNum = childNum; } public String getServiceAddressTel() { return serviceAddressTel; } public void setServiceAddressTel(String serviceAddressTel) { this.serviceAddressTel = serviceAddressTel; } public String getServiceAreaCode() { return serviceAreaCode; } public void setServiceAreaCode(String serviceAreaCode) { this.serviceAreaCode = serviceAreaCode; } public String getUserAreaCode1() { return userAreaCode1; } public void setUserAreaCode1(String userAreaCode1) { this.userAreaCode1 = userAreaCode1; } public String getUserMobile1() { return userMobile1; } public void setUserMobile1(String userMobile1) { this.userMobile1 = userMobile1; } public String getUserAreaCode2() { return userAreaCode2; } public void setUserAreaCode2(String userAreaCode2) { this.userAreaCode2 = userAreaCode2; } public String getUserMobile2() { return userMobile2; } public void setUserMobile2(String userMobile2) { this.userMobile2 = userMobile2; } public String getUserAreaCode3() { return userAreaCode3; } public void setUserAreaCode3(String userAreaCode3) { this.userAreaCode3 = userAreaCode3; } public String getUserMobile3() { return userMobile3; } public void setUserMobile3(String userMobile3) { this.userMobile3 = userMobile3; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getUserRemark() { return userRemark; } public void setUserRemark(String userRemark) { this.userRemark = userRemark; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getIsArrivalVisa() { return isArrivalVisa; } public void setIsArrivalVisa(Integer isArrivalVisa) { this.isArrivalVisa = isArrivalVisa; } public Integer getOrderChannel() { return orderChannel; } public void setOrderChannel(Integer orderChannel) { this.orderChannel = orderChannel; } public String getServiceDate() { return serviceDate; } public void setServiceDate(String serviceDate) { this.serviceDate = serviceDate; } public String getServiceRecTime() { return serviceRecTime; } public void setServiceRecTime(String serviceRecTime) { this.serviceRecTime = serviceRecTime; } public String getServicePassCitys() { return servicePassCitys; } public void setServicePassCitys(String servicePassCitys) { this.servicePassCitys = servicePassCitys; } public String getStartAddress() { return startAddress; } public void setStartAddress(String startAddress) { this.startAddress = startAddress; } public String getFlightBrandSign() { return flightBrandSign; } public void setFlightBrandSign(String flightBrandSign) { this.flightBrandSign = flightBrandSign; } public String getFlightNo() { return flightNo; } public void setFlightNo(String flightNo) { this.flightNo = flightNo; } public String getFlightAirportCode() { return flightAirportCode; } public void setFlightAirportCode(String flightAirportCode) { this.flightAirportCode = flightAirportCode; } public String getFlightAirportName() { return flightAirportName; } public void setFlightAirportName(String flightAirportName) { this.flightAirportName = flightAirportName; } public String getFlightFlyTimeL() { return flightFlyTimeL; } public void setFlightFlyTimeL(String flightFlyTimeL) { this.flightFlyTimeL = flightFlyTimeL; } public String getFlightArriveTimeL() { return flightArriveTimeL; } public void setFlightArriveTimeL(String flightArriveTimeL) { this.flightArriveTimeL = flightArriveTimeL; } public String getFlightAirportBuiding() { return flightAirportBuiding; } public void setFlightAirportBuiding(String flightAirportBuiding) { this.flightAirportBuiding = flightAirportBuiding; } @Override public String toString() { return "MISEditOrderParam [orderNo=" + orderNo + ", orderType=" + orderType + ", carSeatNum=" + carSeatNum + ", adultNum=" + adultNum + ", childNum=" + childNum + ", serviceAddressTel=" + serviceAddressTel + ", serviceAreaCode=" + serviceAreaCode + ", userAreaCode1=" + userAreaCode1 + ", userMobile1=" + userMobile1 + ", userAreaCode2=" + userAreaCode2 + ", userMobile2=" + userMobile2 + ", userAreaCode3=" + userAreaCode3 + ", userMobile3=" + userMobile3 + ", userEmail=" + userEmail + ", userRemark=" + userRemark + ", userName=" + userName + ", isArrivalVisa=" + isArrivalVisa + ", orderChannel=" + orderChannel + ", orderSource=" + orderSource + ", serviceDate=" + serviceDate + ", serviceRecTime=" + serviceRecTime + ", servicePassCitys=" + servicePassCitys + ", startAddress=" + startAddress + ", flightBrandSign=" + flightBrandSign + ", flightNo=" + flightNo + ", flightAirportCode=" + flightAirportCode + ", flightAirportName=" + flightAirportName + ", flightFlyTimeL=" + flightFlyTimeL + ", flightArriveTimeL=" + flightArriveTimeL + ", flightAirportBuiding=" + flightAirportBuiding + "]"; } }
true
70149fdf98ea40d4ae7f438352f5f4ea046e16bc
Java
AWKrol/iPhone-12-feedback
/src/test/java/ru/mvideo/WebDriverSettings.java
UTF-8
1,069
2.203125
2
[]
no_license
package ru.mvideo; import org.junit.After; import org.junit.Before; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class WebDriverSettings { public WebDriver driver; @Before public void setUp() { System.setProperty("webdriver.chrome.driver", "src/main/resources/drivers/chromedriver"); // путь до chromedriver driver = new ChromeDriver(); // создаем экземпляр WebDriver driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // неявное ожидание появления элемента driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS); // неявное ожидагие загрузки страницы driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS); // неявное ожидание отработки скриптов } @After public void close() { driver.quit(); // закрываем браузер } }
true
783ba808563d37e28368bb19f061664c8385e014
Java
mishrole/Android_Boleteria-Conciertos
/app/src/main/java/com/app/appentrada/PerfilActivity.java
UTF-8
4,254
2.078125
2
[]
no_license
package com.app.appentrada; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.app.appentrada.dao.MySqlUsuario; import com.app.appentrada.entidad.Usuario; public class PerfilActivity extends AppCompatActivity implements View.OnClickListener { Toolbar toolbar; EditText edtNickname, edtPassword, edtNombre, edtApellidos, edtCorreo, edtDni; Button btnGuardar; MySqlUsuario daoUsuario = new MySqlUsuario(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_perfil); toolbar = (Toolbar) findViewById(R.id.toolbarPersonalizado); setSupportActionBar(toolbar); edtNickname = (EditText) findViewById(R.id.edtNickname_Perfil); edtPassword = (EditText) findViewById(R.id.edtPassword_Perfil); edtNombre = (EditText) findViewById(R.id.edtNombre_Perfil); edtApellidos = (EditText) findViewById(R.id.edtApellidos_Perfil); edtCorreo = (EditText) findViewById(R.id.edtCorreo_Perfil); edtDni = (EditText) findViewById(R.id.edtDni_Perfil); btnGuardar = (Button) findViewById(R.id.btnGuardar_Perfil); btnGuardar.setOnClickListener(this); if(daoUsuario.objetoUsuario != null) { edtNickname.setText(""+daoUsuario.objetoUsuario.getNickname()); edtPassword.setText(""+daoUsuario.objetoUsuario.getContrasena()); edtNombre.setText(""+daoUsuario.objetoUsuario.getNombre()); edtApellidos.setText(""+daoUsuario.objetoUsuario.getApellidos()); edtCorreo.setText(""+daoUsuario.objetoUsuario.getCorreo()); edtDni.setText(""+daoUsuario.objetoUsuario.getDni()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); if (id == R.id.opcion1) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } else if (id == R.id.opcion2) { Intent intent = new Intent(this, PerfilActivity.class); startActivity(intent); } else if (id == R.id.opcion3) { Toast.makeText(this, "OPCION 3", Toast.LENGTH_SHORT).show(); } else if (id == R.id.opcion3) { Toast.makeText(this, "OPCION 4", Toast.LENGTH_SHORT).show(); } else if (id == R.id.opcion4) { Toast.makeText(this, "OPCION 5", Toast.LENGTH_SHORT).show(); } else if (id == R.id.opcion5) { Intent intent = new Intent(this, IniciarSesionActivity.class); startActivity(intent); } return true; } @Override public void onClick(View view) { if(view == btnGuardar) { Usuario bean = new Usuario(); bean.setCodUsuario(daoUsuario.objetoUsuario.getCodUsuario()); bean.setNickname(edtNickname.getText().toString()); bean.setContrasena(edtPassword.getText().toString()); bean.setNombre(edtNombre.getText().toString()); bean.setApellidos(edtApellidos.getText().toString()); bean.setCorreo(edtCorreo.getText().toString()); bean.setDni(edtDni.getText().toString()); int salida; salida = daoUsuario.actualizarUsuario(bean); if (salida > 0){ mensaje("Los cambios han sido guardados"); daoUsuario.objetoUsuario = bean; Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } else { mensaje("No se pudieron guardar los cambios"); } } } void mensaje(String m){ Toast.makeText(this,m,Toast.LENGTH_LONG).show(); } }
true
d89f0a95978013184aa846850534be5daa56e363
Java
ansariom/TFBSScanSuite
/src/osu/megraw/llscan/ComputeLoglikScoreROEROC.java
UTF-8
5,192
2.15625
2
[]
no_license
package osu.megraw.llscan; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; public class ComputeLoglikScoreROEROC implements Callable<LoglikScoreResult>{ private String sampleName; private int BG_WIN; private char[] seq; DoubleColReturn scoreCutoffValue; int nucsAfterTSS; private PWMReturn pwms; String[] strands = {"FWD", "REV"}; private String seqName; long numberNonzeros = 0; private HashMap<String, List<Coordinate>> openCoordinatesLeaf; private HashMap<String, List<Coordinate>> openCoordinatesRoot; private String[] winVarNames; private int[] winVarL; private int[] winVarR; private int[] winVarPWMIndex; private String[] winVarStrand; private int nWinVars; public ComputeLoglikScoreROEROC(char[] seq, DoubleColReturn scoreCutOffs, int nucsAfterTSS, int bG_WIN, String seqName, PWMReturn pwms, String[] winVarNames, int[] winVarL, int[] winVarR, int[] winVarPWMIndex, String[] winVarStrand, HashMap<String, List<Coordinate>> leafCoordsHash, HashMap<String, List<Coordinate>> rootCoordsHash, int nWinVars) { super(); this.seqName = seqName; this.seq = seq; this.scoreCutoffValue = scoreCutOffs; this.pwms = pwms; this.BG_WIN = bG_WIN; this.nucsAfterTSS = nucsAfterTSS; this.openCoordinatesLeaf = leafCoordsHash; this.openCoordinatesRoot = rootCoordsHash; this.winVarNames = winVarNames; this.winVarL = winVarL; this.winVarR = winVarR; this.winVarPWMIndex = winVarPWMIndex; this.nWinVars = nWinVars; this.winVarStrand = winVarStrand; } @Override public LoglikScoreResult call() throws Exception { // Compute and store local background values for this sequence double[][] B = Utils.getWholeSeqLocalBackground(seq, BG_WIN); double[][][] B_M1 = Utils.getWholeSeqLocalM1Background(seq, BG_WIN); int pos = 0; // Stores featureWinId and corresponding cumScore value HashMap<String, Double> featureHash = new HashMap<>(); if (openCoordinatesLeaf == null) { System.out.println("Open Chromatin is Null " + seqName); openCoordinatesLeaf = new HashMap<>(); } if (openCoordinatesRoot == null) { System.out.println("Open Chromatin is Null " + seqName); openCoordinatesRoot = new HashMap<>(); } for (int wv = 0; wv < nWinVars; wv++) { int pwmIdx = winVarPWMIndex[wv]; String strand = winVarStrand[wv]; double[][] ThetaT; // SHAWN //System.out.print("Label: " + pwms.labels[pwmIdx] + " " + seqName + " "); if (strand.equals("FWD")) { ThetaT = pwms.pwms[pwmIdx]; } else { // REV ThetaT = pwms.revcmp_pwms[pwmIdx]; } List<Coordinate> leafCoorList = openCoordinatesLeaf.get(winVarNames[wv]); List<Coordinate> rootCoorList = openCoordinatesRoot.get(winVarNames[wv]); if (leafCoorList == null) { leafCoorList = new ArrayList<>(); System.out.println("chromatin is closed < " + seqName + " - " + winVarNames[wv]); } if (rootCoorList == null) { rootCoorList = new ArrayList<>(); System.out.println("chromatin is closed < " + seqName + " - " + winVarNames[wv]); } Collections.sort(leafCoorList); Collections.sort(rootCoorList); String leafFeatureId = winVarNames[wv] + "_LEAF"; double leafWinSum = 0.0d; for (Coordinate coordinate : leafCoorList) { double score = Utils.getCumScoreInWindow(coordinate.getStart(), coordinate.getEnd(), seq, ThetaT, strand, B, B_M1, scoreCutoffValue.values[pwmIdx], nucsAfterTSS); leafWinSum += score; } featureHash.put(leafFeatureId, leafWinSum); String rootFeatureId = winVarNames[wv] + "_ROOT"; double rootWinSum = 0.0d; for (Coordinate coordinate : rootCoorList) { double score = Utils.getCumScoreInWindow(coordinate.getStart(), coordinate.getEnd(), seq, ThetaT, strand, B, B_M1, scoreCutoffValue.values[pwmIdx], nucsAfterTSS); rootWinSum += score; } featureHash.put(rootFeatureId, rootWinSum); } // Calculate GC Content (-100 to +100 related to TSS) int GC_WIN = 100; double gccontent = Utils.getGCContent( -1 * GC_WIN, GC_WIN, seq, nucsAfterTSS); String featureId = "GCcontent"; featureHash.put(featureId, gccontent); if (gccontent != 0) numberNonzeros++; double CAcontent = Utils.getSeqContent(-1 * GC_WIN, GC_WIN, seq, nucsAfterTSS, new char[]{'C', 'A'}); featureId = "CAcontent"; featureHash.put(featureId, CAcontent); if (gccontent != 0) numberNonzeros++; double GAcontent = Utils.getSeqContent(-1 * GC_WIN, GC_WIN, seq, nucsAfterTSS, new char[]{'G', 'A'}); featureId = "GAcontent"; featureHash.put(featureId, GAcontent); if (gccontent != 0) numberNonzeros++; sampleName = seqName + "_0"; LoglikScoreResult loglikScoreResult = new LoglikScoreResult(featureHash, sampleName, numberNonzeros); return loglikScoreResult; } }
true
e164423958eaca0cef6b8c19773d84ebf79648dd
Java
thangout/pal
/pal04/src/pal/Main.java
UTF-8
1,248
2.671875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pal; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author Thang Do */ public class Main { static int A, C, M, K, N; /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { // BufferedReader in = new BufferedReader(new FileReader("pub10.in")); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String firstLine = in.readLine(); StringTokenizer tokenizer = new StringTokenizer(firstLine); // while (tokenizer.hasMoreTokens()) { // numOfBuildings = Integer.valueOf(tokenizer.nextToken()); // } A = Integer.valueOf(tokenizer.nextToken()); C = Integer.valueOf(tokenizer.nextToken()); M = Integer.valueOf(tokenizer.nextToken()); K = Integer.valueOf(tokenizer.nextToken()); N = Integer.valueOf(tokenizer.nextToken()); Generator ge = new Generator(A, C, M, K, N); ge.findMostChallange(); // long[] a = new long[300000000]; } }
true
607d3af02a7ca5751c59bbf3144330e21fdd716a
Java
bozimmerman/CoffeeMud
/com/planet_ink/coffee_mud/Libraries/mcppkgs/MCPNegotiatePackage.java
UTF-8
2,010
1.851563
2
[ "Apache-2.0" ]
permissive
package com.planet_ink.coffee_mud.Libraries.mcppkgs; import java.util.Map; import com.planet_ink.coffee_mud.Common.interfaces.Session; import com.planet_ink.coffee_mud.Libraries.interfaces.ProtocolLibrary.MCPPackage; import com.planet_ink.coffee_mud.core.CMath; import com.planet_ink.coffee_mud.core.Log; /* Copyright 2015-2023 Bo Zimmerman 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. */ public class MCPNegotiatePackage implements MCPPackage { @Override public String packageName() { return "mcp-negotiate"; } @Override public float minVersion() { return (float)1.0; } @Override public float maxVersion() { return (float)2.0; } @Override public void executePackage(final Session session, final String command, final Map<String, float[]> clientSupported, final Map<String, String> variables) { if(command.equalsIgnoreCase("mcp-negotiate-end")) { // nothing to do, really return; } else if(command.equalsIgnoreCase("mcp-negotiate-can")) { final String packageName = variables.get("package"); final String minVersion = variables.get("min-version"); final String maxVersion = variables.get("max-version"); if(packageName != null) { clientSupported.put(packageName, new float[]{CMath.s_float(minVersion),CMath.s_float(maxVersion)}); } else Log.errOut("MCP negotiate-can without package name!"); } else Log.errOut("Unknown MCP negotiate command: "+command); } }
true
65dece3021b081963a64c0ac72e330fd25b474a3
Java
userpvt/cs2018-06-19
/src/by/it/prudnikau/lesson01/Main.java
UTF-8
958
3.625
4
[]
no_license
import java.util.Formatter; /* * Доработайте ее так, чтобы кроме этих двух представлений были еще 8- * ричные и 16-ричные числа для типа данных byte, а вывод был от -128 до * 127). Для этого найдите аналоги метода Integer.toBinaryString */ public class Main { public static void main(String[] args) { Formatter f = new Formatter(); for (byte i = -128; i != 127; i++) { String binary = Integer.toBinaryString(i); f.format("Hex: %x, Octal: %o", i, i); if (binary.length() > 8) binary = binary.substring(binary.length() - 8); binary = String.format("%8s", binary).replace(" ", "0"); System.out.print(binary + " "); System.out.print(f); System.out.print(" " + i + "\n"); f = new Formatter(); } } }
true
5cda780cd7c0aa850df3d876d4ba4bed7c4ac338
Java
tsvetelin-tsvetanov/Udemy_Java_Masterclass
/While/src/com/company/SharedDigit.java
UTF-8
646
3.171875
3
[]
no_license
package com.company; public class SharedDigit { public static boolean hasSharedDigit(int firstNumber, int secondNumber){ if(firstNumber < 10 || firstNumber > 99 || secondNumber < 10 || secondNumber > 99){ return false; } int firstDigitA = firstNumber / 10; int secondDigitA = firstNumber % 10; int firstDigitB = secondNumber / 10; int secondDigitB = secondNumber % 10; return firstDigitA == firstDigitB || firstDigitA == secondDigitB || secondDigitA == firstDigitB || secondDigitA == secondDigitB; } }
true
cca54193e3c5b00f67d888cf9bc2f1cc32a74ffb
Java
xianglvs/school-api
/src/main/java/org/spring/springboot/app/base/ApiIndex.java
UTF-8
1,231
1.554688
2
[]
no_license
package org.spring.springboot.app.base; /** * api文档排序 * Created with IntelliJ IDEA. * Description: * UserSesson: eric * Date: 2017-12-15 * Time: 13:45 */ public class ApiIndex { /* * 用户管理接口 */ public static final String USER = "用户管理接口"; /* * 角色管理接口 */ public static final String ROLE = "角色管理接口"; /* * 菜单管理接口 */ public static final String MENU = "菜单管理接口"; /* * 机构管理接口 */ public static final String OFFICE = "机构管理接口"; /* * 文章管理接口 */ public static final String ARTICLE = "文章管理接口"; /* * 区域管理接口 */ public static final String AREA = "区域管理接口"; /* * 字典管理接口 */ public static final String DICT = "字典管理接口"; /* * 文章分类管理接口 */ public static final String CATEGORY = "文章分类管理接口"; /* * 文件管理接口 */ public static final String FILE = "文件管理接口"; /* * 首页管理接口 */ public static final String INDEX = "首页管理接口"; }
true
7a365d135a80a0bcebea254c9b8020e81aad1c41
Java
reachtokish/appsmith
/app/server/appsmith-plugins/mongoPlugin/src/main/java/com/external/plugins/utils/MongoPluginUtils.java
UTF-8
9,602
2.140625
2
[ "Apache-2.0" ]
permissive
package com.external.plugins.utils; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; import com.appsmith.external.helpers.PluginUtils; import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.DatasourceConfiguration; import com.appsmith.external.models.DatasourceStructure; import com.external.plugins.commands.Aggregate; import com.external.plugins.commands.Count; import com.external.plugins.commands.Delete; import com.external.plugins.commands.Distinct; import com.external.plugins.commands.Find; import com.external.plugins.commands.Insert; import com.external.plugins.commands.MongoCommand; import com.external.plugins.commands.UpdateMany; import org.bson.Document; import org.bson.json.JsonParseException; import org.bson.types.Decimal128; import org.bson.types.ObjectId; import org.springframework.util.StringUtils; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import static com.appsmith.external.helpers.PluginUtils.STRING_TYPE; import static com.appsmith.external.helpers.PluginUtils.getDataValueSafelyFromFormData; import static com.external.plugins.constants.FieldName.BODY; import static com.external.plugins.constants.FieldName.COMMAND; import static com.external.plugins.constants.FieldName.RAW; public class MongoPluginUtils { public static Document parseSafely(String fieldName, String input) { try { return Document.parse(input); } catch (JsonParseException e) { throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, fieldName + " could not be parsed into expected JSON format."); } } public static Boolean isRawCommand(Map<String, Object> formData) { String command = PluginUtils.getDataValueSafelyFromFormData(formData, COMMAND, null); return RAW.equals(command); } public static String convertMongoFormInputToRawCommand(ActionConfiguration actionConfiguration) { Map<String, Object> formData = actionConfiguration.getFormData(); if (formData != null && !formData.isEmpty()) { // If its not raw command, then it must be one of the mongo form commands if (!isRawCommand(formData)) { // Parse the commands into raw appropriately MongoCommand command = getMongoCommand(actionConfiguration); if (!command.isValid()) { throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "Try again after configuring the fields : " + command.getFieldNamesWithNoConfiguration()); } return command.parseCommand().toJson(); } } // We reached here. This means either this is a RAW command input or some configuration error has happened // in which case, we default to RAW return PluginUtils.getDataValueSafelyFromFormData(formData, BODY, PluginUtils.STRING_TYPE); } private static MongoCommand getMongoCommand(ActionConfiguration actionConfiguration) throws AppsmithPluginException { Map<String, Object> formData = actionConfiguration.getFormData(); MongoCommand command; switch (getDataValueSafelyFromFormData(formData, COMMAND, STRING_TYPE, "")) { case "INSERT": command = new Insert(actionConfiguration); break; case "FIND": command = new Find(actionConfiguration); break; case "UPDATE": command = new UpdateMany(actionConfiguration); break; case "DELETE": command = new Delete(actionConfiguration); break; case "COUNT": command = new Count(actionConfiguration); break; case "DISTINCT": command = new Distinct(actionConfiguration); break; case "AGGREGATE": command = new Aggregate(actionConfiguration); break; default: throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_EXECUTE_ARGUMENT_ERROR, "No valid mongo command found. Please select a command from the \"Command\" dropdown and try " + "again"); } return command; } public static String getDatabaseName(DatasourceConfiguration datasourceConfiguration) { String databaseName = null; // Explicitly set default database. if (datasourceConfiguration.getConnection() != null) { databaseName = datasourceConfiguration.getConnection().getDefaultDatabaseName(); } // If that's not available, pick the authentication database. final DBAuth authentication = (DBAuth) datasourceConfiguration.getAuthentication(); if (!StringUtils.hasLength(databaseName) && authentication != null) { databaseName = authentication.getDatabaseName(); } if (databaseName == null) { throw new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_ARGUMENT_ERROR, "Missing default database name."); } return databaseName; } public static void generateTemplatesAndStructureForACollection(String collectionName, Document document, ArrayList<DatasourceStructure.Column> columns, ArrayList<DatasourceStructure.Template> templates) { String filterFieldName = null; String filterFieldValue = null; Map<String, String> sampleInsertValues = new LinkedHashMap<>(); for (Map.Entry<String, Object> entry : document.entrySet()) { final String name = entry.getKey(); final Object value = entry.getValue(); String type; boolean isAutogenerated = false; if (value instanceof Integer) { type = "Integer"; sampleInsertValues.put(name, "1"); } else if (value instanceof Long) { type = "Long"; sampleInsertValues.put(name, "NumberLong(\"1\")"); } else if (value instanceof Double) { type = "Double"; sampleInsertValues.put(name, "1"); } else if (value instanceof Decimal128) { type = "BigDecimal"; sampleInsertValues.put(name, "NumberDecimal(\"1\")"); } else if (value instanceof String) { type = "String"; sampleInsertValues.put(name, "\"new value\""); if (filterFieldName == null || filterFieldName.compareTo(name) > 0) { filterFieldName = name; filterFieldValue = (String) value; } } else if (value instanceof ObjectId) { type = "ObjectId"; isAutogenerated = true; if (!value.equals("_id")) { sampleInsertValues.put(name, "ObjectId(\"a_valid_object_id_hex\")"); } } else if (value instanceof Collection) { type = "Array"; sampleInsertValues.put(name, "[1, 2, 3]"); } else if (value instanceof Date) { type = "Date"; sampleInsertValues.put(name, "new Date(\"2019-07-01\")"); } else { type = "Object"; sampleInsertValues.put(name, "{}"); } columns.add(new DatasourceStructure.Column(name, type, null, isAutogenerated)); } columns.sort(Comparator.naturalOrder()); Map<String, Object> templateConfiguration = new HashMap<>(); templateConfiguration.put("collectionName", collectionName); templateConfiguration.put("filterFieldName", filterFieldName); templateConfiguration.put("filterFieldValue", filterFieldValue); templateConfiguration.put("sampleInsertValues", sampleInsertValues); templates.addAll( new Find().generateTemplate(templateConfiguration) ); templates.addAll( new Insert().generateTemplate(templateConfiguration) ); templates.addAll( new UpdateMany().generateTemplate(templateConfiguration) ); templates.addAll( new Delete().generateTemplate(templateConfiguration) ); templates.addAll( new Count().generateTemplate(templateConfiguration) ); templates.addAll( new Distinct().generateTemplate(templateConfiguration) ); templates.addAll( new Aggregate().generateTemplate(templateConfiguration) ); } public static String urlEncode(String text) { return URLEncoder.encode(text, StandardCharsets.UTF_8); } public static String getRawQuery(ActionConfiguration actionConfiguration) { MongoCommand command = getMongoCommand(actionConfiguration); return command.getRawQuery(); } }
true
c1b0c5955cd8a01779846b8300894f57a0ed6d89
Java
cckmit/erp-4
/Maven_Accounting/src/main/java/com/krawler/spring/accounting/account/accCusVenMapDAOImpl.java
UTF-8
13,518
1.710938
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.krawler.spring.accounting.account; import com.krawler.common.dao.BaseDAO; import com.krawler.common.service.ServiceException; import com.krawler.common.util.StringUtil; import com.krawler.hql.accounting.Customer; import com.krawler.hql.accounting.CustomerVendorMapping; import com.krawler.hql.accounting.InvoiceTermsSales; import com.krawler.hql.accounting.Tax; import com.krawler.hql.accounting.TaxTermsMapping; import com.krawler.hql.accounting.Vendor; import com.krawler.spring.common.KwlReturnObject; import com.krawler.utils.json.base.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * * @author krawler */ public class accCusVenMapDAOImpl extends BaseDAO implements accCusVenMapDAO { public CustomerVendorMapping checkCustomerMappingExists(String customerid) throws ServiceException { CustomerVendorMapping customervendormapping = null; String query = "select id,vendoraccountid from customervendormapping where customeraccountid = ?"; List list = executeSQLQuery( query, new Object[]{customerid}); Iterator it = list.iterator(); if (it.hasNext()) { Object obj[] = (Object[]) it.next(); String mappingid = obj[0].toString(); String venid = obj[1].toString(); Vendor vendor = (Vendor) get(Vendor.class, venid); if(vendor!=null){ customervendormapping = (CustomerVendorMapping) get(CustomerVendorMapping.class, mappingid); } } return customervendormapping; } public CustomerVendorMapping checkVendorMappingExists(String vendorid) throws ServiceException { CustomerVendorMapping customervendormapping = null; String query = "select id,customeraccountid from customervendormapping where vendoraccountid = ?"; List list = executeSQLQuery( query, new Object[]{vendorid}); Iterator it = list.iterator(); if (it.hasNext()) { Object obj[] = (Object[]) it.next(); String mappingid = obj[0].toString(); String custid = obj[1].toString(); Customer customer = (Customer) get(Customer.class, custid); if(customer!=null){ customervendormapping = (CustomerVendorMapping) get(CustomerVendorMapping.class, mappingid); } } return customervendormapping; } public KwlReturnObject saveUpdateCustomerVendorMapping(JSONObject accjson) throws ServiceException { List list = new ArrayList(); try { CustomerVendorMapping customerVendorMapping = null; if (accjson.has("id")) { customerVendorMapping = (CustomerVendorMapping) get(CustomerVendorMapping.class, (String) accjson.get("id")); } else { customerVendorMapping = new CustomerVendorMapping(); } if (accjson.has("customeraccountid")) { Customer account = (accjson.get("customeraccountid") == null ? null : (Customer) get(Customer.class, (String) accjson.get("customeraccountid"))); customerVendorMapping.setCustomeraccountid(account); } if (accjson.has("vendoraccountid")) { Vendor account = (accjson.get("vendoraccountid") == null ? null : (Vendor) get(Vendor.class, (String) accjson.get("vendoraccountid"))); customerVendorMapping.setVendoraccountid(account); } if (accjson.has("mappingflag")) { customerVendorMapping.setMappingflag((Boolean) accjson.get("mappingflag")); } saveOrUpdate(customerVendorMapping); list.add(customerVendorMapping); } catch (Exception e) { throw ServiceException.FAILURE("saveUpdateCustomerVendorMapping : " + e.getMessage(), e); } return new KwlReturnObject(true, "Customer-Vendor mapping has been done successfully.", null, list, list.size()); } public KwlReturnObject getCustomerVendorMapping(HashMap<String, Object> filterParams) throws ServiceException { List returnList = new ArrayList(); ArrayList params = new ArrayList(); String condition = ""; String query = "from CustomerVendorMapping ab "; if (filterParams.containsKey("customeraccountid")) { condition += (condition.length() == 0 ? " where " : " and ") + "ab.customeraccountid.ID=?"; params.add(filterParams.get("customeraccountid")); } if (filterParams.containsKey("vendoraccountid")) { condition += (condition.length() == 0 ? " where " : " and ") + "ab.vendoraccountid.ID=?"; params.add(filterParams.get("vendoraccountid")); } condition += (condition.length() == 0 ? " where " : " and ") + "ab.mappingflag=true"; query += condition; returnList = executeQuery( query, params.toArray()); return new KwlReturnObject(true, "", null, returnList, returnList.size()); } public KwlReturnObject saveTermForTax(HashMap<String, Object> termMap) throws ServiceException { List list = new ArrayList(); try { TaxTermsMapping taxTermsMapping = new TaxTermsMapping(); if (termMap.containsKey("id")) { taxTermsMapping = (TaxTermsMapping) get(TaxTermsMapping.class, termMap.get("id").toString()); } if (termMap.containsKey("term")) { taxTermsMapping.setInvoicetermssales((InvoiceTermsSales) get(InvoiceTermsSales.class, termMap.get("term").toString())); } if (termMap.containsKey("tax")) { taxTermsMapping.setTax((Tax) get(Tax.class, termMap.get("tax").toString())); } saveOrUpdate(taxTermsMapping); list.add(taxTermsMapping); } catch (Exception ex) { throw ServiceException.FAILURE(ex.getMessage(), ex); } return new KwlReturnObject(true, null, null, list, list.size()); } public List getTerms(String tax) throws ServiceException { String query = "select invoicetermssales from taxtermsmapping where tax = ?"; List list = executeSQLQuery( query, new Object[]{tax}); return list; } public List deleteTermForTax(String tax) throws ServiceException { String query = "delete from taxtermsmapping where tax = ?"; int list = executeSQLUpdate( query, new Object[]{tax}); return null; } public boolean isCustomerUsedInTransactions(String accountid, String companyid) throws ServiceException { List list = new ArrayList(); boolean isused = false; List params = new ArrayList(); String qforDN = " Select 1 from debitnote where customer=? and company=?"; params.add(accountid); params.add(companyid); String qforCN = " Select 1 from creditnote where customer=? and company=?"; params.add(accountid); params.add(companyid); String qforPayment = " Select 1 from payment where customer=? and company=?"; params.add(accountid); params.add(companyid); String qforReceipt = " Select 1 from receipt where customer=? and company=?"; params.add(accountid); params.add(companyid); String qforInvoice = " Select 1 from invoice where customer=? and company=?"; params.add(accountid); params.add(companyid); String qforSO = " Select 1 from salesorder where customer=? and company=?"; params.add(accountid); params.add(companyid); String qforCQ = " Select 1 from quotation where customer=? and company=?"; params.add(accountid); params.add(companyid); String qforDO = " Select 1 from deliveryorder where customer=? and company=?"; params.add(accountid); params.add(companyid); String qforSR = " Select 1 from salesreturn where customer=? and company=?"; params.add(accountid); params.add(companyid); String finalQuery = qforDN + " UNION" + qforCN + " UNION" + qforPayment + " UNION" + qforReceipt + " UNION" + qforInvoice + " UNION" + qforSO + " UNION" + qforCQ + " UNION" + qforDO + " UNION" + qforSR; list = executeSQLQuery(finalQuery, params.toArray()); if (list.size() > 0) { isused = true; } return isused; } public boolean isVendorUsedInTransactions(String accountid, String companyid) throws ServiceException { List list = new ArrayList(); boolean isused = false; List params = new ArrayList(); String qforDN = " Select 1 from debitnote where vendor=? and company=?"; params.add(accountid); params.add(companyid); String qforPayment = " Select 1 from payment where vendor=? and company=?"; params.add(accountid); params.add(companyid); String qforReceipt = " Select 1 from receipt where vendor=? and company=?"; params.add(accountid); params.add(companyid); String qforInvoice = " Select 1 from goodsreceipt where vendor=? and company=?"; params.add(accountid); params.add(companyid); String qforPO = " Select 1 from purchaseorder where vendor=? and company=?"; params.add(accountid); params.add(companyid); String qforVQ = " Select 1 from vendorquotation where vendor=? and company=?"; params.add(accountid); params.add(companyid); String qforPR = " Select 1 from purchasereturn where vendor=? and company=?"; params.add(accountid); params.add(companyid); String qforCN = " Select 1 from creditnote where vendor=? and company=?"; params.add(accountid); params.add(companyid); String finalQuery = qforDN + " UNION" + qforCN + " UNION" + qforPayment + " UNION" + qforReceipt + " UNION" + qforInvoice + " UNION" + qforPO + " UNION" + qforVQ + " UNION" + qforPR; list = executeSQLQuery(finalQuery,params.toArray()); if (list.size() > 0) { isused = true; } return isused; } //To Find Out whether TDS Transactions are made using selected vendor. public boolean isVendorUsedInTDSTransactions(String accountid, String companyid) throws ServiceException { List list = new ArrayList(); boolean isused = false; List params = new ArrayList(); // String qforDN = " Select 1 from debitnote where vendor=? and company=?"; // params.add(accountid); // params.add(companyid); String qforaDVPayment = " SELECT 1 from tdsdetails INNER JOIN advancedetail on advancedetail.id = tdsdetails.advancedetail " + " INNER JOIN payment on payment.id=advancedetail.payment " + " WHERE vendor=? and payment.company=? AND tdsdetails.tdsassessableamount>0 "; params.add(accountid); params.add(companyid); String qforPaymentdet = " SELECT 1 from tdsdetails INNER JOIN paymentdetail on paymentdetail.id = tdsdetails.paymentdetail "+ " INNER JOIN payment on payment.id=paymentdetail.payment " + " WHERE vendor=? and payment.company=? AND tdsassessableamount>0 "; params.add(accountid); params.add(companyid); String qforProductInvoice = " SELECT 1 from grdetails INNER JOIN goodsreceipt on grdetails.goodsreceipt = goodsreceipt.id "+ " WHERE vendor=? and goodsreceipt.company=? AND tdsassessableamount>0"; params.add(accountid); params.add(companyid); String qforExpenseInvoice = " SELECT 1 from expenseggrdetails INNER JOIN goodsreceipt on expenseggrdetails.goodsreceipt = goodsreceipt.id "+ " WHERE vendor=? and goodsreceipt.company=? AND tdsassessableamount>0"; params.add(accountid); params.add(companyid); String finalQuery = qforaDVPayment + " UNION "+qforPaymentdet + " UNION" + qforProductInvoice + " UNION " + qforExpenseInvoice; list = executeSQLQuery(finalQuery, params.toArray()); if (list.size() > 0) { isused = true; } return isused; } //To Verify whether Vendor's TDS Interest Payable account is Used in TDS Interest Make Payment Transactionor not. public boolean isVendorTDSInterestPayableAccUsedInTrans(String VendorTDSInterestPayableAccount, String companyid) throws ServiceException { List list = new ArrayList(); boolean isused = false; List params = new ArrayList(); //As this account is used only while making TDS Interest Payment i.e. Make Payment Against GL so checking it in "paymentdetailotherwise" only. if (!StringUtil.isNullOrEmpty(VendorTDSInterestPayableAccount) && !StringUtil.isNullOrEmpty(companyid)) { String qforPI = "SELECT pd.id FROM paymentdetailotherwise pd INNER JOIN payment p ON pd.payment = p.id where pd.account = ? and p.company = ? "; params.add(VendorTDSInterestPayableAccount); params.add(companyid); list = executeSQLQuery(qforPI, params.toArray()); if (list.size() > 0) { isused = true; } } return isused; } }
true
4f5d9f071beffbfdc12797a7d2adba08726d8f61
Java
Thidox/GiantShop-2.0
/src/main/java/nl/giantit/minecraft/giantshop/API/GSW/Commands/Console/Reload.java
UTF-8
840
1.921875
2
[]
no_license
package nl.giantit.minecraft.giantshop.API.GSW.Commands.Console; import nl.giantit.minecraft.giantcore.Misc.Heraut; import nl.giantit.minecraft.giantcore.Misc.Messages; import nl.giantit.minecraft.giantshop.API.GSW.GSWAPI; import nl.giantit.minecraft.giantshop.API.GiantShopAPI; import nl.giantit.minecraft.giantshop.API.conf; import nl.giantit.minecraft.giantshop.GiantShop; import org.bukkit.command.CommandSender; /** * * @author Giant */ public class Reload { private static Messages mH = GiantShop.getPlugin().getMsgHandler(); private static GSWAPI gA = GiantShopAPI.Obtain().getGSWAPI(); public static void exec(CommandSender sender, String[] args) { conf c = gA.getConfig(); c.reload(); gA.reload(); Heraut.say(sender, mH.getConsoleMsg(Messages.msgType.ADMIN, "confReload")); } }
true
3f6a43958bfe4639c4f8235962b92e89c217cd5c
Java
lin199231/WechatService
/src/main/java/win/demonlegion/wechatservice/module/message/ShortVideoMessage.java
UTF-8
952
1.945313
2
[ "Apache-2.0" ]
permissive
package win.demonlegion.wechatservice.module.message; import com.alibaba.fastjson.annotation.JSONField; import java.io.Serializable; /** * 小视频消息 */ public class ShortVideoMessage extends WechatMessage implements Serializable { private static final long serialVersionUID = 2456728850219704094L; private String MediaId; private String ThumbMediaId; private String MsgId; @JSONField(name = "MediaId") public String getMediaId() { return MediaId; } @JSONField(name = "ThumbMediaId") public String getThumbMediaId() { return ThumbMediaId; } @JSONField(name = "MsgId") public String getMsgId() { return MsgId; } public void setMediaId(String mediaId) { MediaId = mediaId; } public void setThumbMediaId(String thumbMediaId) { ThumbMediaId = thumbMediaId; } public void setMsgId(String msgId) { MsgId = msgId; } }
true
6773eef2b3ed391ae8f4f00d016403c8912235d5
Java
cckmit/UPHMIS_dhis_2.30
/dhis-2/dhis-web/dhis-web-excelimport/src/main/java/org/hisp/dhis/excelimport/util/ExcelImport_OUDeCode.java
UTF-8
1,854
2.484375
2
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
package org.hisp.dhis.excelimport.util; public class ExcelImport_OUDeCode { /** * Sheet number */ private int sheetno; /** * Row number */ private int rowno; /** * Column number */ private int colno; /** * Formula to calculate the values. */ private String expression; /** * Organisation Unit Code. */ private int ouCode; // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- public ExcelImport_OUDeCode() { } public ExcelImport_OUDeCode(int sheetno, int rowno, int colno, String expression, int ouCode) { this.sheetno = sheetno; this.rowno = rowno; this.colno = colno; this.expression = expression; this.ouCode = ouCode; } // ------------------------------------------------------------------------- // Getters and setters // ------------------------------------------------------------------------- public int getSheetno() { return sheetno; } public void setSheetno( int sheetno ) { this.sheetno = sheetno; } public int getRowno() { return rowno; } public void setRowno( int rowno ) { this.rowno = rowno; } public int getColno() { return colno; } public void setColno( int colno ) { this.colno = colno; } public String getExpression() { return expression; } public void setExpression( String expression ) { this.expression = expression; } public int getOuCode() { return ouCode; } public void setOuCode(int ouCode) { this.ouCode = ouCode; } }
true
ff414eb9049f590d058df0d7d91e8c2fd687ed5c
Java
reactome-fi/CytoscapePlugIn
/src/main/java/org/reactome/cytoscape3/GeneSetFINetworkPopupMenuHandler.java
UTF-8
3,137
2.125
2
[]
no_license
package org.reactome.cytoscape3; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import org.cytoscape.application.swing.CyMenuItem; import org.cytoscape.application.swing.CyNetworkViewContextMenuFactory; import org.cytoscape.view.model.CyNetworkView; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.reactome.cytoscape.service.FIVisualStyle; import org.reactome.cytoscape.util.PlugInObjectManager; /** * Some extra work needs for a FI network generated from a gene set. * */ public class GeneSetFINetworkPopupMenuHandler extends FINetworkPopupMenuHandler { public GeneSetFINetworkPopupMenuHandler() { } @Override protected void installMenus() { super.installMenus(); FIAnnotationFetcherMenu annotFIsMenu = new FIAnnotationFetcherMenu(); installOtherNetworkMenu(annotFIsMenu, "Fetch FI Annotations"); } /** * A class for the network view context menu item to fetch FI annotations. * * @author Eric T. Dawson * */ private class FIAnnotationFetcherMenu implements CyNetworkViewContextMenuFactory { @Override public CyMenuItem createMenuItem(final CyNetworkView view) { JMenuItem fetchFIAnnotationsMenu = new JMenuItem( "Fetch FI Annotations"); fetchFIAnnotationsMenu.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Thread t = new Thread() { @Override public void run() { try { if(EdgeActionCollection.annotateFIs(view)) { BundleContext context = PlugInObjectManager.getManager().getBundleContext(); ServiceReference servRef = context.getServiceReference(FIVisualStyle.class.getName()); FIVisualStyle visStyler = (FIVisualStyle) context.getService(servRef); visStyler.setVisualStyle(view, false); // If there is one already, don't recreate it. context.ungetService(servRef); } } catch (Exception t) { JOptionPane.showMessageDialog( PlugInObjectManager.getManager().getCytoscapeDesktop(), "The visual style could not be applied.", "Visual Style Error", JOptionPane.ERROR_MESSAGE); } } }; t.start(); } }); return new CyMenuItem(fetchFIAnnotationsMenu, 1.0f); } } }
true
b9ed356602b563cfec3ff89a5c2a204dc1a18bc5
Java
Jefidev/Reseau
/JavaLibraryCompta/src/library_compta/RecPayClass.java
UTF-8
330
2.015625
2
[]
no_license
package library_compta; import java.io.Serializable; public class RecPayClass implements Serializable { public String idFacture; public double montant; public String compte; public RecPayClass(String i, double m, String c) { idFacture = i; montant = m; compte = c; } }
true
116b3c78969edf68abe1ae5f9cd5113980b62d38
Java
firestar/EnchantingPlus
/src/main/java/com/aesireanempire/eplus/handlers/LanguageHandler.java
UTF-8
2,226
2.390625
2
[]
no_license
package com.aesireanempire.eplus.handlers; import com.aesireanempire.eplus.EnchantingPlus; import cpw.mods.fml.common.registry.LanguageRegistry; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * @author Freyja Lesser GNU Public License v3 * (http://www.gnu.org/licenses/lgpl.html) */ public class LanguageHandler { private static LanguageHandler INSTANCE = new LanguageHandler(); private final List<String> languages = new ArrayList<String>(); private final String location = "/assets/eplus/lang/"; private LanguageHandler() { } public static LanguageHandler getInstance() { return INSTANCE; } public void addLanguage(String uri) { if (!languages.contains(uri)) { languages.add(uri); } } public void addLanguages(String langs) { final InputStream resourceAsStream = getClass().getResourceAsStream(langs); final Scanner scanner = new Scanner(resourceAsStream); while (scanner.hasNextLine()) { addLanguage(location + scanner.nextLine()); } scanner.close(); } public List<String> getLanguages() { return languages; } private String getLocalFromFileName(String lang) { return lang.substring(lang.lastIndexOf("/") + 1, lang.lastIndexOf(".")); } public String getTranslatedString(String string) { return LanguageRegistry.instance().getStringLocalization(string).isEmpty() ? LanguageRegistry.instance().getStringLocalization(string, "en_US") : LanguageRegistry .instance().getStringLocalization(string); } private boolean isXMLlangfile(String lang) { return lang.endsWith(".xml"); } public void loadLangauges() { for (final String lang : languages) { LanguageRegistry.instance().loadLocalization(lang, getLocalFromFileName(lang), isXMLlangfile(lang)); EnchantingPlus.log.info("Localization " + getLocalFromFileName(lang) + " loaded"); } } }
true
1ccdc72ea5e75e1740e8f0fc06d9879059253bb4
Java
exbotpro/XPlatform
/src/xplatform/platform/adaptation/ThreadCoordinator.java
UTF-8
3,097
2.53125
3
[]
no_license
package xplatform.platform.adaptation; import java.util.ArrayList; import java.util.Hashtable; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; public class ThreadCoordinator { private int n = 10; private Hashtable<String, Long> initTime = new Hashtable<String, Long>(); private Hashtable<String, Long> endTime = new Hashtable<String, Long>(); private volatile static ThreadCoordinator coordinator; private Hashtable<String, Integer> numberOfData = new Hashtable<String, Integer>(); private Hashtable<String, Vector<Double>> allDataTable = new Hashtable<String, Vector<Double>>(); private Hashtable<String, Double> avgTimeTable = new Hashtable<String, Double>(); private ConcurrentHashMap<String, Long> intervalTable = new ConcurrentHashMap<String, Long>(); private ConcurrentHashMap<String, Long> maxTimeTable = new ConcurrentHashMap<String, Long>(); private ThreadCoordinator(){ } public static ThreadCoordinator getThreadCoordinator(){ if(coordinator==null) { synchronized (ThreadCoordinator.class){ if(coordinator==null) { coordinator = new ThreadCoordinator(); } } } return coordinator; } public void setInitTime(String id, long time){ this.initTime.put(id, time); } public void setEndTime(String id, long time){ this.endTime.put(id, time); long x_cur = time - this.initTime.get(id); this.addTimeTo(id, x_cur); } public long getInterval(ArrayList<String> depedentApps){ long interval = 0; for(String appId: depedentApps){ if(intervalTable.containsKey(appId) && intervalTable.get(appId)>interval) { interval = intervalTable.get(appId); } } return interval; } public long getMyInterval(String id){ long interval = 0; if(intervalTable.containsKey(id)) { interval = intervalTable.get(id); } return interval; } public boolean isSetIntervalOf(String id){ return intervalTable.containsKey(id); } public void setInterval(String id){ intervalTable.put(id, (long)(this.avgTimeTable.get(id).intValue())); } public void initInterval(String id){ intervalTable.remove(id); } public void addTimeTo(String id, long x_cur){ int k = 0; double x_bar_prev = 0; if(numberOfData.containsKey(id)){ if(x_cur > this.maxTimeTable.get(id)) this.maxTimeTable.put(id, (long)x_cur); if(this.allDataTable.get(id).size()>=n) this.allDataTable.get(id).removeElementAt(0); this.allDataTable.get(id).addElement((double)x_cur); k = numberOfData.get(id); x_bar_prev = avgTimeTable.get(id); double x_bar = DOAMeasurer.getMovingAverage(n, x_bar_prev, x_cur, allDataTable.get(id).get(0)); this.numberOfData.put(id, k+1); this.avgTimeTable.put(id, x_bar); }else{ this.maxTimeTable.put(id, (long)x_cur); Vector<Double> data = new Vector<Double>(); data.addElement((double)x_cur); this.allDataTable.put(id, data); numberOfData.put(id, k+1); avgTimeTable.put(id, (double)x_cur); } } }
true
8b4969965341be4a882769ccb351820ae5b3144a
Java
Ivanovitch76/Labo-GWT2048
/gwt-2048/src/be/steformations/it/client/ui/widget/Case.java
UTF-8
259
1.820313
2
[]
no_license
package be.steformations.it.client.ui.widget; import com.google.gwt.core.client.GWT; import gwt.material.design.client.ui.MaterialButton; public class Case extends MaterialButton{ public Case() { super(); GWT.log("Case.Case()"); } }
true
8903553a5be6c6f9611e34ddb24ffb06db9be12e
Java
alphagov/pay-java-commons
/model/src/test/java/uk/gov/service/payments/commons/api/json/ApiResponseDateTimeSerializerTest.java
UTF-8
1,255
2.265625
2
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
package uk.gov.service.payments.commons.api.json; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.time.ZonedDateTime; import static org.junit.jupiter.api.Assertions.assertEquals; public class ApiResponseDateTimeSerializerTest { private final ApiResponseDateTimeSerializer serializer = new ApiResponseDateTimeSerializer(); @Test public void shouldSerializeWithMillisecondPrecision() throws IOException { ZonedDateTime testValue = ZonedDateTime.parse("2019-01-29T11:34:53.849012345Z"); Writer jsonWriter = new StringWriter(); JsonGenerator jsonGenerator = new JsonFactory().createGenerator(jsonWriter); final SerializerProvider serializerProvider = new ObjectMapper().getSerializerProvider(); serializer.serialize(testValue, jsonGenerator, serializerProvider); jsonGenerator.flush(); final String actual = jsonWriter.toString(); assertEquals("\"2019-01-29T11:34:53.849Z\"", actual); } }
true
1942cbbdbf853a47fec0c1c56078224a87876405
Java
Archer1A/report-service
/src/main/java/com/vic/report/model/Report.java
UTF-8
362
1.632813
2
[]
no_license
package com.vic.report.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.web.multipart.MultipartFile; @Data @AllArgsConstructor @NoArgsConstructor public class Report { private String id; private String userName; private String idCard; private MultipartFile reportBlob; }
true
dfbc91f3b7273dc97be2dee428179837c80f5be3
Java
tiwiz/WTT_FitApp
/app/src/main/java/net/orgiu/wttfitapp/session/SessionAdapter.java
UTF-8
1,227
2.1875
2
[]
no_license
package net.orgiu.wttfitapp.session; import android.support.v7.util.DiffUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.fitness.data.Session; import com.google.android.gms.fitness.result.SessionReadResult; import net.orgiu.wttfitapp.R; import java.util.ArrayList; import java.util.List; class SessionAdapter extends RecyclerView.Adapter<SessionViewHolder> { private List<Session> results; SessionAdapter() { results = new ArrayList<>(0); } @Override public SessionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.session_item_overview, parent, false); return new SessionViewHolder(view); } @Override public void onBindViewHolder(SessionViewHolder holder, int position) { holder.bindTo(results.get(position)); } @Override public int getItemCount() { return results.size(); } void setResults(SessionReadResult results) { this.results.addAll(results.getSessions()); notifyDataSetChanged(); } }
true
c0799f4421d288382115987bf4a519d173aa721a
Java
abardam/colonization-sea
/SoutheastAsia/src/southeastasia/loader/ActionsLoader.java
UTF-8
4,045
2.703125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package southeastasia.loader; import java.util.ArrayList; import southeastasia.game.SoutheastAsiaAction; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author Leland * Call ActionsLoader.loadactions(filename) to get stuff from xml file. */ public class ActionsLoader { public static ArrayList<SoutheastAsiaAction> loadActions (String filename) { ArrayList <SoutheastAsiaAction> r = new ArrayList <SoutheastAsiaAction> (); try { File file = new File(""+filename); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); NodeList list = doc.getElementsByTagName("action"); for (int s = 0; s < list.getLength(); s++) { Node node = list.item(s); if (node.getNodeType() == Node.ELEMENT_NODE) { Element first = (Element) node; NodeList nameList = first.getElementsByTagName("name"); Element nameElement = (Element) nameList.item(0); NodeList name = nameElement.getChildNodes(); NodeList descList = first.getElementsByTagName("desc"); Element descElement = (Element) descList.item(0); NodeList desc = descElement.getChildNodes(); NodeList statList = first.getElementsByTagName("stat"); Element statElement = (Element) statList.item(0); NodeList stat = statElement.getChildNodes(); String[] stats = stat.item(0).getNodeValue().split(","); if (stats.length > 3) { SoutheastAsiaAction seact=new SoutheastAsiaAction(name.item(0).getNodeValue(), desc.item(0).getNodeValue(), Integer.parseInt(stats[0].trim()), Integer.parseInt(stats[1].trim()), Integer.parseInt(stats[2].trim()), Integer.parseInt(stats[3].trim()) ); NodeList warList = first.getElementsByTagName("war"); if(warList.getLength()>0) { Element warElement = (Element) warList.item(0); NodeList war = warElement.getChildNodes(); if(war.item(0).getNodeValue().equals("attack")) seact.war=SoutheastAsiaAction.WAR_ATTACK; else if(war.item(0).getNodeValue().equals("surrender")) seact.war=SoutheastAsiaAction.WAR_GIVEUP; } NodeList itemList = first.getElementsByTagName("item"); if(itemList.getLength()>0) { Element itemElement=(Element)itemList.item(0); NodeList item=itemElement.getChildNodes(); if(item.item(0).getNodeValue().equals("gain")) seact.item=SoutheastAsiaAction.ITEM_GAIN; else if(item.item(0).getNodeValue().equals("trade")) seact.item=SoutheastAsiaAction.ITEM_TRADE; } r.add(seact); } } } } catch (Exception x) { System.out.println("Action loader error. " + x.toString()); SoutheastAsiaAction m = r.get(r.size()-1); System.out.println(m.name); } return r; } }
true
3eb16b558293c35f22b89db8ac6177f419b937a5
Java
Mickai55/Desk-Rent-Spring
/work/desk/src/main/java/com/renting/desk/repository/DeskRepository.java
UTF-8
313
1.90625
2
[]
no_license
package com.renting.desk.repository; import com.renting.desk.model.Desk; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; @Repository public interface DeskRepository extends MongoRepository<Desk, Long> { Desk findByName(String name); }
true
387a4e4bc64caa142db8b49a8367048564f185b0
Java
sahil-diwan/java-programming-2021
/DeserializationUsingInheritance/src/Deserialization.java
UTF-8
974
3.203125
3
[]
no_license
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.ObjectInputStream; import java.io.Serializable; class Person implements Serializable{ String name = "Sahil Diwan"; long phone = 99999; } class Student extends Person implements Serializable{ int sid; static int count = 3; Student(int sid,String name,long phone){ this.sid = sid; this.name = name; this.phone = phone; } @Override public String toString() { return "Student [sid=" + sid + ", name=" + name + ", phone=" + phone + "]"; } } public class Deserialization { public static void main(String[] args) throws Exception { try { FileInputStream fis = new FileInputStream("D:\\abc.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Object obj = ois.readObject(); System.out.println(obj); System.out.println("Object Deserialized"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
b0d39679fe4f9301f7052bb74830ee370702acc2
Java
parsaramesh/demo-cache
/src/main/java/org/demo/cache/movie/MovieDaoImpl.java
UTF-8
2,238
2.40625
2
[]
no_license
package org.demo.cache.movie; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import javax.inject.Named; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; /** * * @author rameshparsa * */ @Repository("movieDao") @Named public class MovieDaoImpl implements MovieDao { private JdbcTemplate jdbcTemplate; @Autowired public void setJdbcTemplate(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Cacheable(value = "movieCache", key = "#name") public Movie findByName(String name) { final long before = System.currentTimeMillis(); System.out.println("******* findByName is retrieving from Database ******** "); String query = "SELECT * FROM MOVIE WHERE name = ?"; final Movie movie = jdbcTemplate.queryForObject(query, new Object[] { name }, new MovieRowMapper()); final long after = System.currentTimeMillis(); System.out.println("Time taken to retrieve from database in ms : " + (after - before)); return movie; } public Number addMoviePlayStatus(final Movie movie) { final String INSERT_MOVIE_STATUS = "insert into movie_play_status (movie_name, status, release_date) values(?, ?, ?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement( Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement( INSERT_MOVIE_STATUS, new String[] { "id" }); ps.setString(1, movie.getName()); ps.setString(2, "RECVD"); ps.setTimestamp(3, new Timestamp(System.currentTimeMillis())); return ps; } }, keyHolder); return keyHolder.getKey(); } }
true
93c6f63f48c0ba7351b92ecd89f817c5b282fc7e
Java
1700301020/TodayNews
/app/src/main/java/com/example/todaynews/main/shanghai/module/ShangHaiDetailHttpTask.java
UTF-8
724
1.8125
2
[]
no_license
package com.example.todaynews.main.shanghai.module; import com.example.http.LfHttpServer; import com.example.http.result.IResult; import java.util.HashMap; import java.util.Map; public class ShangHaiDetailHttpTask<T> extends LfHttpServer { //负责封装参数 public IResult<T> getJokeList(String sort, String page, String pagesize){ Map<String,Object> params = new HashMap<>(); params.put("sort", sort); params.put("page", page); params.put("pagesize", pagesize); params.put("time", System.currentTimeMillis() / 1000 + ""); params.put("key", "e1ffc011820d4c36cef7271f7e89b735"); return super.executed(IShangHaiDetailRequest.jokeRequest,params); } }
true
dfe9c9ad8a3ad9364e432a1307611821a8acb0ac
Java
adsLFUP/dxj-base
/src/main/java/com/aic/ssm/entity/SidebarTree.java
UTF-8
3,002
2.140625
2
[]
no_license
package com.aic.ssm.entity; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class SidebarTree { private String text; private String href; private String guid; private String level; private String parent_guid; //父节点 private String parent_level; private String t_organization_r_guid; private String t_line_r_guid; private String t_line_r_content_guid; private String t_device_r_guid; private String t_item_r_guid; private String state; public String getState() { return state; } public void setState(String state) { this.state = state; } public String getT_line_r_content_guid() { return t_line_r_content_guid; } public void setT_line_r_content_guid(String t_line_r_content_guid) { this.t_line_r_content_guid = t_line_r_content_guid; } public void setT_item_r_guid(String t_item_r_guid) { this.t_item_r_guid = t_item_r_guid; } public String getT_item_r_guid() { return t_item_r_guid; } public String getT_organization_r_guid() { return t_organization_r_guid; } public void setT_organization_r_guid(String t_organization_r_guid) { this.t_organization_r_guid = t_organization_r_guid; } public String getT_line_r_guid() { return t_line_r_guid; } public void setT_line_r_guid(String t_line_r_guid) { this.t_line_r_guid = t_line_r_guid; } public String getT_device_r_guid() { return t_device_r_guid; } public void setT_device_r_guid(String t_device_r_guid) { this.t_device_r_guid = t_device_r_guid; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } private List<SidebarTree> nodes= new ArrayList(); //存放子节点 // private List<SidebarTree> nodes= new CopyOnWriteArrayList(); //存放子节点 public String getParent_guid() { return parent_guid; } public void setParent_guid(String parent_guid) { this.parent_guid = parent_guid; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getParent_level() { return parent_level; } public void setParent_level(String parent_level) { this.parent_level = parent_level; } public String getText() { return text; } public void setText(String text) { this.text = text; } public List<SidebarTree> getNodes() { return nodes; } public void setNodes(List<SidebarTree> nodes) { this.nodes = nodes; } @Override public String toString() { return "text=" + text + ", guid=" + guid + ", level=" + level + ", parent_guid=" + parent_guid + ", parent_level=" + parent_level + ", nodes=" + nodes+ ", href=" + href+ ", t_organization_r_guid=" + t_organization_r_guid+ ", t_line_r_guid=" + t_line_r_guid+ ", t_device_r_guid=" + t_device_r_guid+ ", t_item_r_guid=" + t_item_r_guid+",state="+state; } }
true
4c24bce919d97671bf083a4556d11df42378fcb9
Java
Happydon/job4j_tracker
/src/main/java/ru/job4j/oop/College.java
UTF-8
189
2.046875
2
[]
no_license
package ru.job4j.oop; public class College { public static void main(String[] args) { Freshman joe = new Freshman(); Student stud = joe; Object obj = joe; } }
true
e65fb6dccb2ca6a7be18cdae175686886ff1cc8f
Java
timmypes/config
/configTest/src/main/java/com/tim/configtest/starter/Starter.java
UTF-8
523
1.757813
2
[ "MIT" ]
permissive
package com.tim.configtest.starter; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * @description: * @author: li si */ @SpringBootApplication @ComponentScan("com.tim") @MapperScan("com.tim.config.dao") public class Starter { public static void main(String[] args){ SpringApplication.run(Starter.class, args); } }
true
6deb31be7e71535f2080d00dfcd44e4a9520dbd8
Java
FernandoAcTr/NASA
/src/services/apod/APODService.java
UTF-8
1,389
2.625
3
[]
no_license
package services.apod; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import model.APODBean; import services.RequestException; import services.Service; import java.io.IOException; public class APODService { private static final String endpoint = "https://api.nasa.gov/planetary/apod?api_key="; private static final String apiKey = "MlYLzw4KhLpIhVZEL3ly4ZItTFfefzYvDpnFcIlb"; private static final String url = endpoint + apiKey; /** * Make a HTTP Request to he APOD Service * @return * @throws IOException * @throws RequestException */ public static APODBean getAPOD() throws IOException, RequestException { APODBean apodBean = null; String JSONRes = Service.getRequest(url); if(JSONRes != null) { //this code indicate that all is fine //convert result String of JSON to a Bean ObjectMapper mapper = new ObjectMapper(); /*Si en el Bean no incluyo todas las propiedades que me regresan el JSON el mapper va a crashear, por eso * se le pasa este flag, para que las ignore. * En este caso no me interesa el hdurl. */ mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); apodBean = mapper.readValue(JSONRes, APODBean.class); } return apodBean; } }
true
f40e172e261d694b850daa6cefbb31065713f7f5
Java
lochel/VANESA
/src/biologicalObjects/nodes/CompoundNode.java
UTF-8
576
2.359375
2
[]
no_license
package biologicalObjects.nodes; import biologicalElements.Elementdeclerations; //import edu.uci.ics.jung.graph.Vertex; import graph.jung.graphDrawing.VertexShapes; public class CompoundNode extends BiologicalNodeAbstract { public CompoundNode(String label, String name) { super(label, name); setBiologicalElement(Elementdeclerations.compound); shapes = new VertexShapes(); attributeSetter(this.getClass().getSimpleName(), this); } // public void lookUpAtAllDatabases() { // // String db = getDB(); // addID(db, getLabel()); // // } }
true
b02fdb0b8a58efb0217d3d50cdcab5d8c71c1275
Java
CryceTruly/Nutritius
/app/src/main/java/com/happy/nutritius/fragments/FoodsToAvoidFragment.java
UTF-8
5,523
2.0625
2
[]
no_license
package com.happy.nutritius.fragments; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.happy.nutritius.R; import com.happy.nutritius.adapters.FoodsToAvoidHolder; import com.happy.nutritius.api.APIService; import com.happy.nutritius.api.Api; import com.happy.nutritius.model.Food; import com.happy.nutritius.model.Nutrient; import java.util.ArrayList; import java.util.List; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * A simple {@link Fragment} subclass. */ public class FoodsToAvoidFragment extends Fragment{ private RecyclerView results; private static final String TAG = "FoodsFragment"; private TextView textViewResult; private ProgressBar progressBar; private BottomSheetBehavior mBehavior; private BottomSheetDialog mBottomSheetDialog; private View bottom_sheet; private List<Food> foods=new ArrayList<>(); LinearLayout linearLayout; public FoodsToAvoidFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment final View view= inflater.inflate(R.layout.fragment_foods, container, false); textViewResult=view.findViewById(R.id.textViewResult); results=view.findViewById(R.id.result); results.setHasFixedSize(true); linearLayout=view.findViewById(R.id.lyt_no_connection); results.setLayoutManager(new LinearLayoutManager(getActivity())); progressBar=view.findViewById(R.id.progress_bar1); bottom_sheet = view.findViewById(R.id.bottom_sheet); mBehavior = BottomSheetBehavior.from(bottom_sheet); FoodsToAvoidHolder holder=new FoodsToAvoidHolder(); results.setAdapter(holder); //building retrofit object Retrofit retrofit = new Retrofit.Builder() .baseUrl(Api.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); //Defining retrofit api service APIService service = retrofit.create(APIService.class); Call<List<Food>> call = service.getFoodToAvoid(); call.enqueue(new Callback<List<Food>>() { @Override public void onResponse(Call<List<Food>> call, Response<List<Food>> response) { Log.d(TAG, "onResponse: "+response); progressBar.setVisibility(View.GONE); if(!response.isSuccessful()){ textViewResult.setText(response.message()); return; } foods.addAll(response.body()); results.setAdapter(new FoodsToAvoidHolder(foods, getContext(), new FoodsToAvoidHolder.ItemHolder.OnItemClickListener() { @Override public void onItemClick(View view, Food obj, int pos) { showBottomSheetDialog(obj); } })); progressBar.setVisibility(View.GONE); linearLayout.setVisibility(View.GONE); } @Override public void onFailure(Call<List<Food>> call, Throwable t) { Log.d(TAG, "onFailure: "+t.getMessage()); progressBar.setVisibility(View.GONE); if(t.getMessage().contains("Unable to resolve host")){ linearLayout.setVisibility(View.VISIBLE); } } }); return view; } private void showBottomSheetDialog(Food obj) { if (mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) { mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } final View view = getLayoutInflater().inflate(R.layout.sheet_basic, null); ((TextView) view.findViewById(R.id.name)).setText(obj.getName()); ((TextView) view.findViewById(R.id.reason)).setText(obj.getReason()); (view.findViewById(R.id.bt_close)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mBottomSheetDialog.dismiss(); } }); mBottomSheetDialog = new BottomSheetDialog(getContext()); mBottomSheetDialog.setContentView(view); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mBottomSheetDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } mBottomSheetDialog.show(); mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { mBottomSheetDialog = null; } }); } }
true
5b6360d064a2f4dd0f6c98c68123e40dcee6c114
Java
fansyL/nezha
/src/com/upload/ImageBean.java
UTF-8
841
2.59375
3
[]
no_license
package com.upload; import java.io.Serializable; public class ImageBean implements Serializable { private String thumb; private String middle; private String master; public ImageBean(String thumb, String middle, String master) { super(); this.thumb = thumb; this.middle = middle; this.master = master; } public ImageBean() { super(); } public String getThumb() { return thumb; } public void setThumb(String thumb) { this.thumb = thumb; } public String getMiddle() { return middle; } public void setMiddle(String middle) { this.middle = middle; } public String getMaster() { return master; } public void setMaster(String master) { this.master = master; } @Override public String toString() { return "ImageBean [thumb=" + thumb + ", middle=" + middle + ", master=" + master + "]"; } }
true
afa60211cfb6ab4ab69daef1ebde5d2be7fff7ab
Java
arvalon/GPSLocation
/app/src/main/java/ru/scancode/gpslocation/MyFusedLocationProviderClient.java
UTF-8
11,644
2.015625
2
[]
no_license
package ru.scancode.gpslocation; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.net.Uri; import android.provider.Settings; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.snackbar.Snackbar; /** * FusedLocationProviderClient * * https://stackoverflow.com/a/47951456/6346970 */ public class MyFusedLocationProviderClient extends AppCompatActivity { private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 14; private static final long UPDATE_INTERVAL = 1500, FASTEST_INTERVAL = 1500; private TextView locationTv; // private AddressResultReceiver mResultReceiver; // removed here because cause wrong code when implemented and // its not necessary like the author says //Define fields for Google API Client private FusedLocationProviderClient mFusedLocationClient; private Location lastLocation; private LocationRequest locationRequest; private LocationCallback mLocationCallback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fused_location_provider_client); Logs.info(this,"onCreate"); locationTv = findViewById(R.id.location); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); try{ mFusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> { if (location != null) { Logs.info(this,"onSuccessListener"); showLocation(); } }); locationRequest = LocationRequest.create(); locationRequest.setInterval(UPDATE_INTERVAL); locationRequest.setFastestInterval(FASTEST_INTERVAL); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { Logs.info(this,"onLocationResult, locations count: " +locationResult.getLocations().size()); for (Location location : locationResult.getLocations()) { // Update location data and UI Logs.info(this, shortLocation(location)); lastLocation=location; showLocation(); } } }; }catch (SecurityException ex){ Logs.error(this,ex.getMessage(),ex); } } @Override protected void onStart() { super.onStart(); Logs.info(this,"onStart"); if (!checkPermissions()) { startLocationUpdates(); requestPermissions(); } else { getLastLocation(); startLocationUpdates(); } } @Override public void onPause() { Logs.info(this,"onPause"); stopLocationUpdates(); super.onPause(); } /** Return the current state of the permissions needed */ private boolean checkPermissions() { Logs.info(this,"checkPermissions"); int permissionState = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); return permissionState == PackageManager.PERMISSION_GRANTED; } private void startLocationPermissionRequest() { Logs.info(this,"startLocationPermissionRequest"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSIONS_REQUEST_CODE); } private void requestPermissions() { Logs.info(this,"requestPermission"); boolean shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION); // Provide an additional rationale to the user. This would happen if the user denied the // request previously, but didn't check the "Don't ask again" checkbox. if (shouldProvideRationale) { Logs.info(this, "Displaying permission rationale to provide additional context."); showSnackbar(R.string.permission_rationale, android.R.string.ok, view -> { // Request permission startLocationPermissionRequest(); }); } else { Logs.info(this, "Requesting permission"); // Request permission. It's possible this can be auto answered if device policy // sets the permission in a given state or the user denied the permission // previously and checked "Never ask again". startLocationPermissionRequest(); } } /** Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { Logs.info(this, "onRequestPermissionResult"); if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) { if (grantResults.length <= 0) { // If user interaction was interrupted, the permission request is cancelled and you // receive empty arrays. Logs.info(this, "User interaction was cancelled."); } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted. getLastLocation(); } else { // Permission denied. // Notify the user via a SnackBar that they have rejected a core permission for the // app, which makes the Activity useless. In a real app, core permissions would // typically be best requested during a welcome-screen flow. // Additionally, it is important to remember that a permission might have been // rejected without asking the user for permission (device policy or "Never ask // again" prompts). Therefore, a user interface affordance is typically implemented // when permissions are denied. Otherwise, your app could appear unresponsive to // touches or interactions which have required permissions. showSnackbar(R.string.permission_denied_explanation, R.string.settings, view -> { // Build intent that displays the App settings screen. Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null); intent.setData(uri); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); }); } } } /** * Provides a simple way of getting a device's location and is well suited for * applications that do not require a fine-grained location and that do not need location * updates. Gets the best and most recent location currently available, which may be null * in rare cases when a location is not available. * <p> * Note: this method should be called after location permission has been granted. */ @SuppressWarnings("MissingPermission") private void getLastLocation() { Logs.info(this,"getLastLocation"); mFusedLocationClient.getLastLocation() .addOnCompleteListener(this, new OnCompleteListener<Location>() { @Override public void onComplete(@NonNull Task<Location> task) { Logs.info(this,"onCompleteListener"); if (task.isSuccessful() && task.getResult() != null) { lastLocation = task.getResult(); Logs.info(this,"onCompleteListener last " +shortLocation(lastLocation)); showLocation(); } else { Logs.info(this,"onCompleteListener NO LAST LOCATION"); showSnackbar(R.string.no_location_detected, android.R.string.ok, null); if (task.getException()!=null){ Logs.error(this, task.getException().getMessage(), task.getException()); } } } }); } private void stopLocationUpdates() { Logs.info(this,"stopLocationUpdates"); mFusedLocationClient.removeLocationUpdates(mLocationCallback); } private void startLocationUpdates() { Logs.info(this,"startLocationUpdates"); if (ActivityCompat .checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } mFusedLocationClient.requestLocationUpdates(locationRequest, mLocationCallback, null); } private void showSnackbar(final int mainTextStringId, final int actionStringId, View.OnClickListener listener) { Logs.info(this,"showSnackbar"); Snackbar.make(this.findViewById(android.R.id.content), getString(mainTextStringId), Snackbar.LENGTH_SHORT) .setAction(getString(actionStringId), listener).show(); } private void showLocation(){ if (lastLocation!=null){ locationTv.setText("Latitude : " + lastLocation.getLatitude() + "\nLongitude : " + lastLocation.getLongitude()); } } private String shortLocation(Location loc){ return "location, latitude: " +loc.getLatitude() +", longitude: "+loc.getLongitude(); } }
true
01446bc239b012cc99eae07b69ba4656ac4d668c
Java
devRohitGangurde/demoShoppingCart
/app/src/main/java/com/android/shopingDemoTest/adapter/CartListAdapter.java
UTF-8
4,402
2.3125
2
[]
no_license
package com.android.shopingDemoTest.adapter; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import com.android.shopingDemoTest.R; import com.android.shopingDemoTest.model.ProductModel; import java.util.ArrayList; import static android.Manifest.permission.CALL_PHONE; public class CartListAdapter extends RecyclerView.Adapter<CartListAdapter.MyViewHolder> { ArrayList<ProductModel> cartProductArrayList; Context context; private CartListAdapter.OnItemClickListener mListener; public interface OnItemClickListener { public void onItemClick(CartListAdapter.MyViewHolder view, int position); public void onLongItemClick(View view, int position); } public CartListAdapter(Context context, ArrayList<ProductModel> cartProductArrayList, CartListAdapter.OnItemClickListener mListener) { this.context = context; this.cartProductArrayList = cartProductArrayList; this.mListener = mListener; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cart, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(final MyViewHolder holder, final int position) { final ProductModel dataModel = cartProductArrayList.get(position); holder.product_name.setText(dataModel.getProductname()); holder.product_price.setText("Price : "+dataModel.getPrice()); holder.txt_product_vendor_name.setText(dataModel.getVendorname()); holder.txt_product_vendor_address.setText(dataModel.getVendoraddress()); holder.txt_product_vendor_number.setText("Call Vendor : "+dataModel.getPhoneNumber()); holder.txtRemoveFromCart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mListener.onItemClick(holder,position); int newPosition = position; cartProductArrayList.remove(newPosition); notifyItemRemoved(newPosition); notifyItemRangeChanged(newPosition, cartProductArrayList.size()); } }); holder.txt_product_vendor_number.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CALL_PHONE},1); } else { Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + dataModel.getPhoneNumber())); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); context.startActivity(intent); } } }); } @Override public int getItemCount() { return cartProductArrayList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView product_name,product_price,txt_product_vendor_name,txt_product_vendor_address,txtRemoveFromCart,txt_product_vendor_number; public MyViewHolder(View itemView) { super(itemView); product_name = (TextView) itemView.findViewById(R.id.txt_product_name); product_price = (TextView) itemView.findViewById(R.id.txt_product_price); txt_product_vendor_name = (TextView) itemView.findViewById(R.id.txt_product_vendor_name); txt_product_vendor_address = (TextView) itemView.findViewById(R.id.txt_product_vendor_address); txtRemoveFromCart = (TextView) itemView.findViewById(R.id.txtRemoveFromCart); txt_product_vendor_number = (TextView) itemView.findViewById(R.id.txt_product_vendor_number); } } }
true
0aa705b6e3e42c7794a2b5e43a873f8565b46748
Java
GraduationProject718/Tea
/Tea/src/entity/HuiFu.java
UTF-8
1,082
2.390625
2
[]
no_license
package entity; import java.util.Date; public class HuiFu { private String id; private String uid; private String lid; private String content; private Date date; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getLid() { return lid; } public void setLid(String lid) { this.lid = lid; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public HuiFu(String id, String uid, String lid, String content, Date date) { super(); this.id = id; this.uid = uid; this.lid = lid; this.content = content; this.date = date; } @Override public String toString() { return "HuiFu [id=" + id + ", uid=" + uid + ", lid=" + lid + ", content=" + content + "]"; } public HuiFu() { } }
true
bf0d371c8a699ed331a4ef520f5e9dc5e9e9379a
Java
ssriha0/sl-b2b-platform
/MarketBusinessInterface/src/main/java/com/newco/marketplace/business/iBusiness/trans/ITransProcessor.java
UTF-8
127
1.625
2
[]
no_license
package com.newco.marketplace.business.iBusiness.trans; public interface ITransProcessor { public void processData(); }
true
4360a4c93a9630b27599948d9a25d945e9ab0cea
Java
lukacupic/Java-Course
/hw15 - Simple Blog with Java Persistence API/src/main/java/hr/fer/zemris/java/hw15/dao/jpa/JPADAOImpl.java
UTF-8
3,070
2.796875
3
[]
no_license
package hr.fer.zemris.java.hw15.dao.jpa; import hr.fer.zemris.java.hw15.dao.DAO; import hr.fer.zemris.java.hw15.dao.DAOException; import hr.fer.zemris.java.hw15.model.BlogComment; import hr.fer.zemris.java.hw15.model.BlogEntry; import hr.fer.zemris.java.hw15.model.BlogUser; import javax.persistence.Query; import java.util.List; /** * This class represents a DAO implementation using the JPA technology. * * @author Luka Čupić */ public class JPADAOImpl implements DAO { @Override public BlogEntry getEntry(Long id) throws DAOException { BlogEntry entry; try { entry = JPAEMProvider.getEntityManager().find(BlogEntry.class, id); return entry; } catch (Exception ex) { throw new DAOException("An error has occurred while obtaining the blog entry.", ex); } } @Override public List<BlogEntry> getEntries(Long id) throws DAOException { try { BlogUser user = JPAEMProvider.getEntityManager().find(BlogUser.class, id); return (user != null) ? user.getEntries() : null; } catch (Exception ex) { throw new DAOException("An error has occurred while obtaining the list of entries.", ex); } } @Override public void addNewEntry(BlogEntry entry) throws DAOException { try { JPAEMProvider.getEntityManager().persist(entry); } catch (Exception ex) { throw new DAOException("An error has occurred while adding a new entry.", ex); } } @Override public void updateEntry(BlogEntry entry) throws DAOException { try { JPAEMProvider.getEntityManager().merge(entry); } catch (Exception ex) { throw new DAOException("An error has occurred while updating the entry.", ex); } } @Override public void addNewComment(BlogComment comment) throws DAOException { try { JPAEMProvider.getEntityManager().persist(comment); } catch (Exception ex) { throw new DAOException("An error has occurred while adding a new comment.", ex); } } @Override @SuppressWarnings("unchecked") public BlogUser getUser(String nick) throws DAOException { try { String query = "SELECT DISTINCT u FROM BlogUser AS u WHERE u.nick=:nick"; Query q = JPAEMProvider.getEntityManager().createQuery(query).setParameter("nick", nick); List<BlogUser> users = (List<BlogUser>) q.getResultList(); return (users != null && users.size() != 0) ? users.get(0) : null; } catch (Exception ex) { throw new DAOException("An error has occurred while obtaining the user.", ex); } } @Override @SuppressWarnings("unchecked") public List<BlogUser> getUsers() throws DAOException { try { String query = "SELECT DISTINCT u FROM BlogUser AS u"; Query q = JPAEMProvider.getEntityManager().createQuery(query); return (List<BlogUser>) q.getResultList(); } catch (Exception ex) { throw new DAOException("An error has occurred while obtaining the list of users.", ex); } } @Override public void addUser(BlogUser user) throws DAOException { try { JPAEMProvider.getEntityManager().persist(user); } catch (Exception ex) { throw new DAOException("An error has occurred while adding the user.", ex); } } }
true
c1489ae8536a44838af9de691a8fe9040731e285
Java
childnn/ssm-samples
/spring_day03_proxy/src/test/java/org/anonymous/test/Demo01.java
UTF-8
860
2.078125
2
[]
no_license
package org.anonymous.test; import org.anonymous.service.UserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author child * 2019/4/16 21:47 */ public class Demo01 { @Test //前置,后置,最终,异常通知 public void test1() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml"); UserService userService = (UserService) applicationContext.getBean("userService"); userService.save(); } @Test //环绕通知 public void test2() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean0.xml"); UserService userService = (UserService) applicationContext.getBean("userService"); userService.save(); } }
true
dcc8a4a88ab0d8704d49b53f96de7151ff052c70
Java
novotnyr/consul-intellij-plugin
/src/main/java/com/github/novotnyr/idea/consul/tree/InProgressKeyAndValue.java
UTF-8
259
1.648438
2
[]
no_license
package com.github.novotnyr.idea.consul.tree; public class InProgressKeyAndValue extends KeyAndValue { public InProgressKeyAndValue() { super("", "Loading..."); } @Override public boolean isContainer() { return true; } }
true
a262ac808593214aa9174357707370f2984243f8
Java
blin-1/jhipster-sample-application
/src/main/java/io/github/jhipster/application/service/dto/CMFCodesValuesCriteria.java
UTF-8
9,774
2.109375
2
[]
no_license
package io.github.jhipster.application.service.dto; import java.io.Serializable; import java.util.Objects; import io.github.jhipster.service.Criteria; import io.github.jhipster.service.filter.BooleanFilter; import io.github.jhipster.service.filter.DoubleFilter; import io.github.jhipster.service.filter.Filter; import io.github.jhipster.service.filter.FloatFilter; import io.github.jhipster.service.filter.IntegerFilter; import io.github.jhipster.service.filter.LongFilter; import io.github.jhipster.service.filter.StringFilter; import io.github.jhipster.service.filter.BigDecimalFilter; import io.github.jhipster.service.filter.InstantFilter; /** * Criteria class for the {@link io.github.jhipster.application.domain.CMFCodesValues} entity. This class is used * in {@link io.github.jhipster.application.web.rest.CMFCodesValuesResource} to receive all the possible filtering options from * the Http GET request parameters. * For example the following could be a valid request: * {@code /cmf-codes-values?id.greaterThan=5&attr1.contains=something&attr2.specified=false} * As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use * fix type specific filters. */ public class CMFCodesValuesCriteria implements Serializable, Criteria { private static final long serialVersionUID = 1L; private LongFilter id; private BigDecimalFilter codeValKey; private BigDecimalFilter codeTableKey; private StringFilter codeClassfctnTypeCode; private StringFilter srcSysCode; private StringFilter lifecycleStatusCode; private StringFilter codeColValCode; private StringFilter descColValText; private InstantFilter effDate; private InstantFilter endDate; private StringFilter commentText; private StringFilter nameColValName; private InstantFilter createDate; private StringFilter createUserId; private InstantFilter updDate; private StringFilter updUserId; public CMFCodesValuesCriteria(){ } public CMFCodesValuesCriteria(CMFCodesValuesCriteria other){ this.id = other.id == null ? null : other.id.copy(); this.codeValKey = other.codeValKey == null ? null : other.codeValKey.copy(); this.codeTableKey = other.codeTableKey == null ? null : other.codeTableKey.copy(); this.codeClassfctnTypeCode = other.codeClassfctnTypeCode == null ? null : other.codeClassfctnTypeCode.copy(); this.srcSysCode = other.srcSysCode == null ? null : other.srcSysCode.copy(); this.lifecycleStatusCode = other.lifecycleStatusCode == null ? null : other.lifecycleStatusCode.copy(); this.codeColValCode = other.codeColValCode == null ? null : other.codeColValCode.copy(); this.descColValText = other.descColValText == null ? null : other.descColValText.copy(); this.effDate = other.effDate == null ? null : other.effDate.copy(); this.endDate = other.endDate == null ? null : other.endDate.copy(); this.commentText = other.commentText == null ? null : other.commentText.copy(); this.nameColValName = other.nameColValName == null ? null : other.nameColValName.copy(); this.createDate = other.createDate == null ? null : other.createDate.copy(); this.createUserId = other.createUserId == null ? null : other.createUserId.copy(); this.updDate = other.updDate == null ? null : other.updDate.copy(); this.updUserId = other.updUserId == null ? null : other.updUserId.copy(); } @Override public CMFCodesValuesCriteria copy() { return new CMFCodesValuesCriteria(this); } public LongFilter getId() { return id; } public void setId(LongFilter id) { this.id = id; } public BigDecimalFilter getCodeValKey() { return codeValKey; } public void setCodeValKey(BigDecimalFilter codeValKey) { this.codeValKey = codeValKey; } public BigDecimalFilter getCodeTableKey() { return codeTableKey; } public void setCodeTableKey(BigDecimalFilter codeTableKey) { this.codeTableKey = codeTableKey; } public StringFilter getCodeClassfctnTypeCode() { return codeClassfctnTypeCode; } public void setCodeClassfctnTypeCode(StringFilter codeClassfctnTypeCode) { this.codeClassfctnTypeCode = codeClassfctnTypeCode; } public StringFilter getSrcSysCode() { return srcSysCode; } public void setSrcSysCode(StringFilter srcSysCode) { this.srcSysCode = srcSysCode; } public StringFilter getLifecycleStatusCode() { return lifecycleStatusCode; } public void setLifecycleStatusCode(StringFilter lifecycleStatusCode) { this.lifecycleStatusCode = lifecycleStatusCode; } public StringFilter getCodeColValCode() { return codeColValCode; } public void setCodeColValCode(StringFilter codeColValCode) { this.codeColValCode = codeColValCode; } public StringFilter getDescColValText() { return descColValText; } public void setDescColValText(StringFilter descColValText) { this.descColValText = descColValText; } public InstantFilter getEffDate() { return effDate; } public void setEffDate(InstantFilter effDate) { this.effDate = effDate; } public InstantFilter getEndDate() { return endDate; } public void setEndDate(InstantFilter endDate) { this.endDate = endDate; } public StringFilter getCommentText() { return commentText; } public void setCommentText(StringFilter commentText) { this.commentText = commentText; } public StringFilter getNameColValName() { return nameColValName; } public void setNameColValName(StringFilter nameColValName) { this.nameColValName = nameColValName; } public InstantFilter getCreateDate() { return createDate; } public void setCreateDate(InstantFilter createDate) { this.createDate = createDate; } public StringFilter getCreateUserId() { return createUserId; } public void setCreateUserId(StringFilter createUserId) { this.createUserId = createUserId; } public InstantFilter getUpdDate() { return updDate; } public void setUpdDate(InstantFilter updDate) { this.updDate = updDate; } public StringFilter getUpdUserId() { return updUserId; } public void setUpdUserId(StringFilter updUserId) { this.updUserId = updUserId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final CMFCodesValuesCriteria that = (CMFCodesValuesCriteria) o; return Objects.equals(id, that.id) && Objects.equals(codeValKey, that.codeValKey) && Objects.equals(codeTableKey, that.codeTableKey) && Objects.equals(codeClassfctnTypeCode, that.codeClassfctnTypeCode) && Objects.equals(srcSysCode, that.srcSysCode) && Objects.equals(lifecycleStatusCode, that.lifecycleStatusCode) && Objects.equals(codeColValCode, that.codeColValCode) && Objects.equals(descColValText, that.descColValText) && Objects.equals(effDate, that.effDate) && Objects.equals(endDate, that.endDate) && Objects.equals(commentText, that.commentText) && Objects.equals(nameColValName, that.nameColValName) && Objects.equals(createDate, that.createDate) && Objects.equals(createUserId, that.createUserId) && Objects.equals(updDate, that.updDate) && Objects.equals(updUserId, that.updUserId); } @Override public int hashCode() { return Objects.hash( id, codeValKey, codeTableKey, codeClassfctnTypeCode, srcSysCode, lifecycleStatusCode, codeColValCode, descColValText, effDate, endDate, commentText, nameColValName, createDate, createUserId, updDate, updUserId ); } @Override public String toString() { return "CMFCodesValuesCriteria{" + (id != null ? "id=" + id + ", " : "") + (codeValKey != null ? "codeValKey=" + codeValKey + ", " : "") + (codeTableKey != null ? "codeTableKey=" + codeTableKey + ", " : "") + (codeClassfctnTypeCode != null ? "codeClassfctnTypeCode=" + codeClassfctnTypeCode + ", " : "") + (srcSysCode != null ? "srcSysCode=" + srcSysCode + ", " : "") + (lifecycleStatusCode != null ? "lifecycleStatusCode=" + lifecycleStatusCode + ", " : "") + (codeColValCode != null ? "codeColValCode=" + codeColValCode + ", " : "") + (descColValText != null ? "descColValText=" + descColValText + ", " : "") + (effDate != null ? "effDate=" + effDate + ", " : "") + (endDate != null ? "endDate=" + endDate + ", " : "") + (commentText != null ? "commentText=" + commentText + ", " : "") + (nameColValName != null ? "nameColValName=" + nameColValName + ", " : "") + (createDate != null ? "createDate=" + createDate + ", " : "") + (createUserId != null ? "createUserId=" + createUserId + ", " : "") + (updDate != null ? "updDate=" + updDate + ", " : "") + (updUserId != null ? "updUserId=" + updUserId + ", " : "") + "}"; } }
true
eec874d88587de27e2172bec8e7a3967d890b7a5
Java
hpkarugendo/refactoring
/RefactoringSolution/src/refactored/MyStats.java
UTF-8
5,298
2.453125
2
[]
no_license
package refactored; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import entities.Customer; import entities.CustomerAccount; public abstract class MyStats { public static final List<Customer> customerList = new ArrayList<Customer>(); //Frames public static JFrame f = null; public static JFrame f1 = null; public static JFrame fAdmin = null; public static JFrame fCustomer = null; public static Container content = null; public static Container cAdmin = null; //Buttons public static final JButton deleteAccount = new JButton("Delete Account"); public static final JButton deleteCustomer = new JButton("Delete Customer"); public static final JButton bankChargesButton = new JButton("Apply Bank Charges"); public static final JButton interestButton = new JButton("Apply Interest"); public static final JButton editCustomerButton = new JButton("Edit existing Customer"); public static final ButtonGroup userType = new ButtonGroup(); public static final JButton returnButton = new JButton("Exit Admin Menu"); public static final JButton accountButton = new JButton("Add an Account to a Customer"); public static final JButton summaryButton = new JButton("Display Summary Of All Accounts"); public static final JButton navigateButton = new JButton("Navigate Customer Collection"); public static final JButton add = new JButton("Add"); public static final JButton cancel = new JButton("Cancel"); //--------CustomerMenu------------- public static final JButton returnButtonC = new JButton("Return"); public static final JButton continueButtonC = new JButton("Continue"); public static final JButton statementButtonC = new JButton("Display Bank Statement"); public static final JButton lodgementButtonC = new JButton("Lodge money into account"); public static final JButton withdrawButtonC = new JButton("Withdraw money from account"); public static final JButton exitButtonC = new JButton("Exit Customer Menu"); //--------Admin Menu--------------- public static final JButton continueButtonA = new JButton("Apply Interest"); public static final JButton returnButtonA = new JButton("Return"); public static final JButton exitButtonA = new JButton("Exit Admin Menu"); //Labels //------Customer----------------- public static final JLabel firstNameLabel = new JLabel("First Name:", SwingConstants.RIGHT); public static final JLabel surnameLabel = new JLabel("Surname:", SwingConstants.RIGHT); public static final JLabel pPPSLabel = new JLabel("PPS Number:", SwingConstants.RIGHT); public static final JLabel dOBLabel = new JLabel("Date of birth", SwingConstants.RIGHT); //-----Admin--------------------- public static final JLabel firstNameLabelA = new JLabel("First Name:", SwingConstants.LEFT); public static final JLabel surnameLabelA = new JLabel("Surname:", SwingConstants.LEFT); public static final JLabel pPPSLabelA = new JLabel("PPS Number:", SwingConstants.LEFT); public static final JLabel dOBLabelA = new JLabel("Date of birth", SwingConstants.LEFT); public static final JLabel customerIDLabelA = new JLabel("CustomerID:", SwingConstants.LEFT); public static final JLabel passwordLabelA = new JLabel("Password:", SwingConstants.LEFT); //TextFields public static final JTextField firstNameTextField = new JTextField(20); public static final JTextField surnameTextField = new JTextField(20); public static final JTextField pPSTextField = new JTextField(20); public static final JTextField dOBTextField = new JTextField(20); //-------Admin------------------- public static final JTextField firstNameTextFieldA = new JTextField(20); public static final JTextField surnameTextFieldA = new JTextField(20); public static final JTextField pPSTextFieldA = new JTextField(20); public static final JTextField dOBTextFieldA = new JTextField(20); public static final JTextField customerIDTextFieldA = new JTextField(20); public static final JTextField passwordTextFieldA = new JTextField(20); //Panels public static final JPanel panel2 = new JPanel(); //Strings public static String PPS = ""; public static String firstName = ""; public static String surname = ""; public static String DOB = ""; public static String CustomerID = ""; public static String password = ""; public static String id = ""; public static String adminUsername = "admin"; public static String adminPassword = "pass"; //Booleans public static boolean loop = true; public static boolean loop2 = true; public static boolean found = false; public static boolean cont = false; public static boolean on = false; //Doubles public static double balanceC = 0.0; public static double withdrawC = 0.0; //Integers public static int position = 0; //Objects public static Customer customer; public static CustomerAccount acc; }
true
fc99a19be1f314dad970a80abf80c5908733e03a
Java
chinawaz008/spw
/spw/src/main/java/com/spw/elife/mobile/schedule/controller/ScheduleController.java
UTF-8
7,874
2.21875
2
[]
no_license
package com.spw.elife.mobile.schedule.controller; import java.io.IOException; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.spw.elife.mobile.common.Response; import com.spw.elife.mobile.schedule.bean.Schedule; import com.spw.elife.mobile.schedule.service.ScheduleService; /** * * 日程Controller * * @author Administrator * */ @Controller @RequestMapping public class ScheduleController{ @Resource private ScheduleService scheduleService; /****************************************************APP端后台*******************************************************************************************************************/ /** * @param 日程列表查询 * @return * @throws */ @RequestMapping(value="/schedule/queryScheduleList" ,method = RequestMethod.POST) @ResponseBody public void queryScheduleList(HttpServletRequest request,HttpServletResponse response) throws IOException{ String staffid = request.getParameter("staffid"); if(StringUtils.isEmpty(staffid)){ throw new RuntimeException("员工id不能为空"); } List<Schedule> scheduleList = scheduleService.queryScheduleList(staffid); JSONObject jb = new JSONObject(); jb.accumulate("result", "1"); jb.accumulate("message","成功"); jb.accumulate("list",scheduleList); response.getWriter().print(jb); } /** * 添加 * @param Schedule * @return * @throws Exception */ @RequestMapping(value="/schedule/saveSchedule",method = RequestMethod.POST) @ResponseBody public void saveSchedule(HttpServletResponse response,HttpServletRequest request) throws IOException{ response.setContentType("text/html;charset=GBK");//解决中文乱码 response.setCharacterEncoding("utf-8"); JSONObject jb = new JSONObject(); String staffid = request.getParameter("staffid"); if(StringUtils.isEmpty(staffid)){ throw new RuntimeException("员工id不能为空"); } String type = request.getParameter("type"); if(StringUtils.isEmpty(type)){ throw new RuntimeException("日程类型不能为空"); } String name = request.getParameter("name"); if(StringUtils.isEmpty(name)){ throw new RuntimeException("日程名称不能为空"); } String startTime = request.getParameter("start_time"); if(StringUtils.isEmpty(startTime)){ throw new RuntimeException("日程开始时间不能为空"); } String endTime = request.getParameter("end_time"); if(StringUtils.isEmpty(endTime)){ throw new RuntimeException("日程结束时间不能为空"); } String partake = request.getParameter("partake"); if(StringUtils.isEmpty(partake)){ throw new RuntimeException("参与人不能为空"); } String note = request.getParameter("note"); Schedule schedule = new Schedule(); schedule.setStaffId(staffid); schedule.setType(type); schedule.setName(name); schedule.setStartTime(startTime); schedule.setEndTime(endTime); schedule.setPartake(partake); schedule.setNote(note); schedule.setIsDel("0"); Response rp = scheduleService.saveSchedule(schedule); jb.accumulate("result", rp.getCode()); jb.accumulate("message", rp.getMessage()); response.getWriter().print(jb); } /** * * @param staffid * @param schedule * @return schedule * @throws Exception */ @RequestMapping(value="/schedule/queryDetail",method = RequestMethod.POST) @ResponseBody public void queryDetail(HttpServletResponse response,HttpServletRequest request) throws IOException{ response.setContentType("text/html;charset=GBK");//解决中文乱码 response.setCharacterEncoding("utf-8"); JSONObject jb = new JSONObject(); String id = request.getParameter("scheduleid"); if(StringUtils.isEmpty(id)){ throw new RuntimeException("id不能为空"); } String staffid = request.getParameter("staffid"); if(StringUtils.isEmpty(staffid)){ throw new RuntimeException("员工id不能为空"); } Response rp = scheduleService.queryDetail(staffid, id); jb.accumulate("result", rp.getCode()); jb.accumulate("message",rp.getMessage()); jb.accumulate("schedule",rp.getData()); response.getWriter().print(jb); } /** * 修改 * @param Schedule * @return * @throws Exception */ @RequestMapping(value="/schedule/updateSchedule",method = RequestMethod.POST) @ResponseBody public void updateSchedule(HttpServletResponse response,HttpServletRequest request) throws IOException{ response.setContentType("text/html;charset=GBK");//解决中文乱码 response.setCharacterEncoding("utf-8"); JSONObject jb = new JSONObject(); String id = request.getParameter("scheduleid"); if(StringUtils.isEmpty(id)){ throw new RuntimeException("id不能为空"); } String staffid = request.getParameter("staffid"); if(StringUtils.isEmpty(staffid)){ throw new RuntimeException("员工id不能为空"); } String type = request.getParameter("type"); if(StringUtils.isEmpty(type)){ throw new RuntimeException("日程类型不能为空"); } String name = request.getParameter("name"); if(StringUtils.isEmpty(name)){ throw new RuntimeException("日程名称不能为空"); } String startTime = request.getParameter("start_time"); if(StringUtils.isEmpty(startTime)){ throw new RuntimeException("日程开始时间不能为空"); } String endTime = request.getParameter("end_time"); if(StringUtils.isEmpty(endTime)){ throw new RuntimeException("日程结束时间不能为空"); } String partake = request.getParameter("partake"); if(StringUtils.isEmpty(partake)){ throw new RuntimeException("参与人不能为空"); } String note = request.getParameter("note"); Schedule schedule = new Schedule(); schedule.setId(id); schedule.setStaffId(staffid); schedule.setType(type); schedule.setName(name); schedule.setStartTime(startTime); schedule.setEndTime(endTime); schedule.setPartake(partake); schedule.setNote(note); Response rp = scheduleService.updateSchedule(schedule); jb.accumulate("result", rp.getCode()); jb.accumulate("message",rp.getMessage()); response.getWriter().print(jb); } /** * 删除 * @param Schedule * @return * @throws Exception */ @RequestMapping(value="/schedule/deleteSchedule",method = RequestMethod.POST) @ResponseBody public void deleteSchedule(HttpServletResponse response,HttpServletRequest request) throws IOException{ response.setContentType("text/html;charset=GBK");//解决中文乱码 response.setCharacterEncoding("utf-8"); JSONObject jb = new JSONObject(); String scheduleid = request.getParameter("scheduleid"); if(StringUtils.isEmpty(scheduleid)){ throw new RuntimeException("id不能为空"); } String staffid = request.getParameter("staffid"); if(StringUtils.isEmpty(staffid)){ throw new RuntimeException("员工id不能为空"); } Response rp = scheduleService.deleteSchedule(scheduleid,staffid); jb.accumulate("result", rp.getCode()); jb.accumulate("message",rp.getMessage()); response.getWriter().print(jb); } }
true
0db300d5417807483a222dda828a8d194f64d7e4
Java
jeinbi/springsec
/sample-war/src/main/java/org/wsipersd/core/security/auth/JdbcFilterInvocationSecurityMetadataSource.java
UTF-8
1,123
2.171875
2
[]
no_license
package org.wsipersd.core.security.auth; import java.util.Collection; import java.util.Collections; import javax.servlet.http.HttpServletRequest; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; public class JdbcFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { FilterInvocation fi = (FilterInvocation) object; String url = fi.getRequestUrl(); HttpServletRequest request = fi.getHttpRequest(); String[] roles = new String[] { "ROLE_ADMIN", "ROLE_USER" }; return SecurityConfig.createList(roles); } public Collection<ConfigAttribute> getAllConfigAttributes() { return Collections.emptyList(); } public boolean supports(Class<?> clazz) { return FilterInvocation.class.isAssignableFrom(clazz); } }
true
96c055a63028f29c3e0705d4e27a0b138bce72ef
Java
jimikby/spring_advanced
/src/main/java/com/epam/theatre/soap/client/EventServiceClient.java
UTF-8
4,381
2.0625
2
[]
no_license
package com.epam.theatre.soap.client; import java.time.LocalDate; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.ws.client.core.WebServiceTemplate; import com.epam.theatre.domain.Event; import com.epam.theatre.domain.Ticket; import com.epam.theatre.soap.event.Delete; import com.epam.theatre.soap.event.GetAll; import com.epam.theatre.soap.event.GetAllForDateRange; import com.epam.theatre.soap.event.GetAllForDateRangeResponse; import com.epam.theatre.soap.event.GetAllNextEvents; import com.epam.theatre.soap.event.GetAllNextEventsResponse; import com.epam.theatre.soap.event.GetAllResponse; import com.epam.theatre.soap.event.GetBookedTickets; import com.epam.theatre.soap.event.GetBookedTicketsResponse; import com.epam.theatre.soap.event.GetById; import com.epam.theatre.soap.event.GetByIdResponse; import com.epam.theatre.soap.event.GetByName; import com.epam.theatre.soap.event.GetByNameResponse; import com.epam.theatre.soap.event.Save; import com.epam.theatre.soap.event.SaveAll; import com.epam.theatre.soap.event.Update; @Component public class EventServiceClient { private static final Logger LOGGER = LogManager.getLogger(CustomerServiceClient.class); @Autowired private WebServiceTemplate webServiceTemplate; public void save(Event event) { Save save = new Save(); save.setArg0(event); webServiceTemplate.marshalSendAndReceive(save); } public void delete(Event event) { Delete delete = new Delete(); delete.setArg0(event); webServiceTemplate.marshalSendAndReceive(delete); } public Event getById(Long id) { GetById getById = new GetById(); getById.setArg0(id); GetByIdResponse getByIdResponse = (GetByIdResponse) webServiceTemplate.marshalSendAndReceive(getById); Event event = getByIdResponse.getReturn(); LOGGER.info("SOAP result: " + event.toString()); return event; } public Event getByName() { GetByName getByName = new GetByName(); GetByNameResponse getByNameResponse = (GetByNameResponse) webServiceTemplate.marshalSendAndReceive(getByName); Event event = getByNameResponse.getReturn(); return event; } public List<Event> getAll() { GetAll getAll = new GetAll(); GetAllResponse getAllResponse = (GetAllResponse) webServiceTemplate.marshalSendAndReceive(getAll); List<Event> events = getAllResponse.getReturn(); return events; } public List<Event> getAllForDateRange(LocalDate from, LocalDate to) { GetAllForDateRange getAllForDateRange = new GetAllForDateRange(); getAllForDateRange.setArg0(from); getAllForDateRange.setArg1(to); GetAllForDateRangeResponse getAllForDateRangeResponse = (GetAllForDateRangeResponse) webServiceTemplate .marshalSendAndReceive(getAllForDateRange); List<Event> events = getAllForDateRangeResponse.getReturn(); return events; } public List<Event> getAllNextEvents(LocalDate to) { GetAllNextEvents getAllNextEvents = new GetAllNextEvents(); getAllNextEvents.setArg0(to); GetAllNextEventsResponse getAllNextEventsResponse = (GetAllNextEventsResponse) webServiceTemplate .marshalSendAndReceive(getAllNextEvents); List<Event> events = getAllNextEventsResponse.getReturn(); return events; } public void update(Event event) { Update update = new Update(); update.setArg0(event); webServiceTemplate.marshalSendAndReceive(update); } public void saveAll(List<Event> events) { SaveAll saveAll = new SaveAll(); saveAll.setArg0(events); webServiceTemplate.marshalSendAndReceive(saveAll); } public List<Ticket> getBookedTickets(Event event) { GetBookedTickets getBookedTickets = new GetBookedTickets(); getBookedTickets.setArg0(event); GetBookedTicketsResponse getBookedTicketsResponse = (GetBookedTicketsResponse) webServiceTemplate .marshalSendAndReceive(getBookedTickets); List<Ticket> tickets = getBookedTicketsResponse.getReturn(); return tickets; } }
true
e0eeedcbee19b3a4d1d4a9be589ebadc69b6f077
Java
irina-borisevich/academy
/by.academy/src/by/academy/homework/homework3/Main.java
UTF-8
3,531
3.296875
3
[]
no_license
package by.academy.homework.homework3; import java.util.Scanner; import by.academy.homework.homework3.Deal; public class Main { public static final int MAX_PRODUCTS = 3; private static void Menu() { System.out.println("Enter command: "); System.out.println("-----------------"); System.out.println("1. Execute deal"); System.out.println("2. Print bill"); System.out.println("3. Insert product"); System.out.println("4. Remove product"); System.out.println("Exit"); } public static void main(String[] args) { Scanner scn = new Scanner(System.in); manageDeal(scn); scn.close(); } private static void manageDeal(Scanner scn) { Menu(); String choice = scn.next(); enterProduct: { while (!"Exit".equals(choice)) { switch (choice) { case "1": ExecuteDeal(); break; case "2": break; case "3": System.out.println("Insert product"); break; case "4": System.out.println("Remove product"); break; case "Exit": break enterProduct; default: System.out.println("Invalid input! Pleas1e enter command again:"); } Menu(); choice = scn.next(); } scn.close(); } } public static void ExecuteDeal() { Scanner scn = new Scanner(System.in); System.out.print("Дата сделки: "); String date = scn.nextLine(); System.out.println("Продавец: "); Person seller = new Person(); seller.enterPerson(); System.out.print("Покупатель: "); Person buyer = new Person(); buyer.enterPerson(); Product[] products = new Product[MAX_PRODUCTS]; for (int i = 0; i < products.length; i++) { products[i] = inputProduct(); } Deal deal = new Deal(date, seller, buyer, products); deal.printBill(); } private static Product inputProduct() { Scanner scn = new Scanner(System.in); for (;;) { System.out.println("Input № product: 1 - Foto, 2 - Fridge, 3 - Hob"); Integer sel = scn.nextInt(); if ((sel != 1) && (sel != 2) && (sel != 3)) { System.err.println("Unknown product"); } else { System.out.println("Name: "); String title = scn.next(); System.out.println("Price: "); Double price = scn.nextDouble(); System.out.println("Quantity: "); Integer quantity = scn.nextInt(); Product product = null; switch (sel) { case 1: System.out.println("Megapixels: "); Integer megapx = scn.nextInt(); System.out.println("Digital (true/false): "); Boolean digital = scn.nextBoolean(); Camera camera = new Camera(); camera.setMegapix(Integer.valueOf(megapx)); camera.setDigital(Boolean.valueOf(digital)); product = camera; break; case 2: System.out.println("Color:"); String color = scn.next(); Fridge fridge = new Fridge(); fridge.setColor(color); product = fridge; break; case 3: System.out.println("Type (gas; electrical; combined):"); String type = scn.next(); System.out.println("induction (true/false): "); Boolean induct = scn.nextBoolean(); Hob hob = new Hob(); hob.setType(type); hob.setInduct(Boolean.valueOf(induct)); product = hob; break; } product.setTitle(title); product.setPrice(Double.valueOf(price)); product.setQuantity(Integer.valueOf(quantity)); return product; } } } }
true
29c41978404235a168185e71e7565314bd6caf12
Java
zhongshuiyuan/hyrtproject
/cei/ceiTerminal/src/com/hyrt/mwpm/vo/OaViewMailList.java
UTF-8
3,444
1.914063
2
[]
no_license
package com.hyrt.mwpm.vo; import java.util.Date; /** * OaViewMailListId entity. * * @author MyEclipse Persistence Tools */ public class OaViewMailList implements java.io.Serializable { // Fields private String id; private String title; private String message; private String fileId; private String fileList; private String userList; private String owner; private String ownerAccount; private Date date; private String userName; private String account; private Byte view; private Date viewDate; private Byte isDel; private Byte oisDel; // Constructors /** default constructor */ public OaViewMailList() { } /** minimal constructor */ public OaViewMailList(String id) { this.id = id; } /** full constructor */ public OaViewMailList(String id, String title, String message, String fileId, String fileList, String userList, String owner, String ownerAccount, Date date, String userName, String account, Byte view, Date viewDate, Byte isDel, Byte oisDel) { this.id = id; this.title = title; this.message = message; this.fileId = fileId; this.fileList = fileList; this.userList = userList; this.owner = owner; this.ownerAccount = ownerAccount; this.date = date; this.userName = userName; this.account = account; this.view = view; this.viewDate = viewDate; this.isDel = isDel; this.oisDel = oisDel; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public String getFileId() { return this.fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public String getFileList() { return this.fileList; } public void setFileList(String fileList) { this.fileList = fileList; } public String getUserList() { return this.userList; } public void setUserList(String userList) { this.userList = userList; } public String getOwner() { return this.owner; } public void setOwner(String owner) { this.owner = owner; } public String getOwnerAccount() { return this.ownerAccount; } public void setOwnerAccount(String ownerAccount) { this.ownerAccount = ownerAccount; } public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getAccount() { return this.account; } public void setAccount(String account) { this.account = account; } public Byte getView() { return this.view; } public void setView(Byte view) { this.view = view; } public Date getViewDate() { return this.viewDate; } public void setViewDate(Date viewDate) { this.viewDate = viewDate; } public Byte getIsDel() { return this.isDel; } public void setIsDel(Byte isDel) { this.isDel = isDel; } public Byte getOisDel() { return this.oisDel; } public void setOisDel(Byte oisDel) { this.oisDel = oisDel; } }
true
0cde6ee8ccb05688bdb5c916744258891aff01bc
Java
viniciusehonda/POOTrab1
/src/fatec/poo/control/DaoProduto.java
UTF-8
3,017
2.765625
3
[]
no_license
package fatec.poo.control; import fatec.poo.model.Produto; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author honda */ public class DaoProduto { private Connection conn; public DaoProduto(Connection conn) { this.conn = conn; } public void inserir (Produto produto) { PreparedStatement ps = null; try { ps = conn.prepareStatement("INSERT into tbProduto(Cod_Prod, Desc_Prod, " + " Qtd_Prod, Pco_Prod, MinEst_Prod) " + "VALUES(?,?,?,?,?)"); ps.setInt(1, produto.getCodigo()); ps.setString(2, produto.getDescricao()); ps.setInt(3, produto.getQtdeDisponivel()); ps.setDouble(4, produto.getPrecoUnit()); ps.setInt(5, produto.getEstoqueMin()); ps.execute(); } catch (SQLException ex){ System.out.println(ex.toString()); } } public void alterar(Produto produto) { PreparedStatement ps = null; try { ps = conn.prepareStatement("UPDATE tbProduto set Desc_Prod = ?, " + "Qtd_Prod = ?, Pco_Prod = ?," + "MinEst_Prod = ?" + " where Cod_Prod = ? "); ps.setString(1, produto.getDescricao()); ps.setInt(2, produto.getQtdeDisponivel()); ps.setDouble(3, produto.getPrecoUnit()); ps.setInt(4, produto.getEstoqueMin()); ps.setInt(5, produto.getCodigo()); ps.execute(); } catch (SQLException ex) { System.out.println(ex.toString()); } } public Produto consultar (int codigo) { Produto p = null; PreparedStatement ps = null; try { ps = conn.prepareStatement("SELECT * from tbProduto where Cod_Prod = ?"); ps.setInt(1, codigo); ResultSet rs = ps.executeQuery(); if (rs.next() == true) { p = new Produto (codigo, rs.getString("Desc_Prod")); p.setQtdeDisponivel(rs.getInt("Qtd_Prod")); p.setPrecoUnit(rs.getDouble("Pco_Prod")); p.setEstoqueMin(rs.getInt("MinEst_Prod")); } } catch (SQLException ex){ System.out.println(ex.toString()); } return (p); } public void excluir (Produto produto) { PreparedStatement ps = null; try { ps = conn.prepareStatement("DELETE from tbProduto where Cod_Prod = ?"); ps.setInt(1, produto.getCodigo()); ps.execute(); } catch (SQLException ex){ System.out.println(ex.toString()); } } }
true
06a2aa29ec043d0633a2ef96f8af84e13f744759
Java
chasseurcode/novassure
/src/main/java/ma/novassure/daoimpl/AffaireDAOImpl.java
UTF-8
2,645
2.5
2
[]
no_license
package ma.novassure.daoimpl; import ma.novassure.dao.AffaireDAO; import ma.novassure.domaine.Affaire; import ma.novassure.domaine.Client; import ma.novassure.domaine.Document; import ma.novassure.domaine.Paiement; import ma.novassure.domaine.Quittance; import org.hibernate.Session; /** * @author TARAM & BODIE */ public class AffaireDAOImpl implements AffaireDAO { private Session session; public AffaireDAOImpl(Session session) { this.session=session; } public void createAffaire(Affaire affaire) { session.beginTransaction(); session.save(affaire); session.getTransaction().commit(); } public void addClient(Client client) { session.beginTransaction(); session.save(client); session.getTransaction().commit(); } public void updateAffaire(Affaire affaire) { session.beginTransaction(); session.update(affaire); session.getTransaction().commit(); } public Affaire findAffaireById(int id) { return (Affaire) session.get(Affaire.class, id); } public void addQuittance(Quittance quittance) { session.beginTransaction(); session.save(quittance); session.getTransaction().commit(); } public void addDocument(Document document) { session.beginTransaction(); session.save(document); session.getTransaction().commit(); } public void addPaiement(Paiement paiement) { session.beginTransaction(); session.save(paiement); session.getTransaction().commit(); } public void updateQuittance(Quittance quittance) { session.beginTransaction(); session.update(quittance); session.getTransaction().commit(); } public Quittance findQuittanceById(int id) { return (Quittance) session.get(Quittance.class, id); } public Quittance findQuittanceByNumPolice(String numero) { Quittance quittance=(Quittance) session.createQuery("from Quittance where numPolice= :numero") .setString("numero", numero).uniqueResult(); return quittance; } public void updateDocument(Document document) { session.beginTransaction(); session.update(document); session.getTransaction().commit(); } public Document findDocumentById(int id) { return (Document) session.get(Document.class, id); } public void updatePaiement(Paiement paiement) { session.beginTransaction(); session.update(paiement); session.getTransaction().commit(); } public Paiement findPaiementById(int id) { return (Paiement) session.get(Paiement.class, id); } public Document findDocumentByTitle(String title) { Document document=(Document) session.createQuery("from Document where titre= :title") .setString("title", title).uniqueResult(); return document; } }
true
9a5e191a89e4e799d967daae3206a5e45bcb7a30
Java
52inc/android-Showcase
/app/src/main/java/com/ftinc/showcase/ui/lock/Lockscreen.java
UTF-8
11,559
2.421875
2
[ "Apache-2.0" ]
permissive
package com.ftinc.showcase.ui.lock; import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.ftinc.showcase.R; import com.ftinc.showcase.ui.lock.auth.Auth; import com.ftinc.showcase.ui.lock.storage.Storage; import com.ftinc.showcase.ui.lock.ui.LockUI; import static com.ftinc.showcase.ui.lock.LockState.*; import butterknife.ButterKnife; import butterknife.InjectView; /** * Project: Showcase * Package: com.ftinc.showcase.ui.lock * Created by drew.heavner on 2/27/15. */ public class Lockscreen implements LockUI.UICallbacks { /*********************************************************************************************** * * Variables * */ @InjectView(R.id.title) TextView mTitle; @InjectView(R.id.content) RelativeLayout mContentFrame; /* * Upper level components */ private Context mCtx; private LayoutInflater mInflater; private LockscreenCallbacks mCallbacks; /* * Interface methods that make the lockscreen work */ private LockUI mUi; private Storage mStorage; private Auth mAuthenticator; /* * The type of lockscreen that this is setup to be */ private LockType mType; /* * The state of the lockscreen */ private LockState mState = LockState.LOCKED; /* * The staged input data in the setup process before the user input's again * to confirm their setup */ private byte[] mStaged; /** * Hidden Internal Constructor * * @see com.ftinc.showcase.ui.lock.Lockscreen.Builder to build this component * @param ctx the context reference */ private Lockscreen(Context ctx){ mCtx = ctx; mInflater = LayoutInflater.from(mCtx); } /*********************************************************************************************** * * Lifecycle Methods * */ /** * Called to signify the creation process for this lockscreen and prepare it for use */ public void onCreate(){ mUi.setUiCallbacks(this); mUi.onCreate(); } /** * Called to destroy the lockscreen and finalize all it's resources */ public void onDestroy(){ mUi.onDestroy(); } /** * Create the lockscreen UI * * @param parent * @return */ public View onCreateView(ViewGroup parent){ // Inflate Base Layout and Inject it View layout = mInflater.inflate(R.layout.layout_lockscreen, parent, false); ButterKnife.inject(this, layout); // Set background to black80 if not setup if(mState != SETUP) layout.setBackgroundColor(mCtx.getResources().getColor(R.color.black80)); // Inflate Lock UI layout and insert it View lockUi = mUi.onCreateView(mInflater, parent); mContentFrame.addView(lockUi); // Show the title depending on the mode switch (mState){ case SETUP: showSetup(); mTitle.setGravity(Gravity.CENTER_HORIZONTAL); break; case CONFIRM: showConfirmation(); break; default: showTitle(); } // Return the combined layout return layout; } /*********************************************************************************************** * * Helper Methods * */ /** * Start any special animation to add lockscreen components for pizazz * @param duration the duration of the animation allowed */ public void onAnimateIn(long duration){ mUi.onAnimateIn(duration); } /** * Start any special animation to remove the lockscreen components for pizzaz * * @param duration the duration of the animation allowed */ public void onAnimateOut(long duration){ mUi.onAnimateOut(duration); } /** * Show the main display text on the lockscreen * */ public void showTitle(){ mTitle.setText(mUi.getTitleText()); } /** * Show the setup display text on the lockscreen */ public void showSetup(){ mTitle.setText(mUi.getSetupText()); } /** * Show the setup confirmation text on the lockscreen */ public void showConfirmation(){ mTitle.setText(mUi.getConfirmationText()); } /** * Show the failure text */ public void showFailure(){ mTitle.setText(mUi.getFailureText()); } /** * Set whether or not this lockscreen is being setup in the * {@link com.ftinc.showcase.ui.screens.setup.LockscreenSetupActivity} * @param state the setup value */ public void setState(LockState state){ mState = state; if(mUi != null) mUi.setState(state); } /** * Set the lockscreen callbacks * @param callbacks */ public void setCallbacks(LockscreenCallbacks callbacks){ mCallbacks = callbacks; } /*********************************************************************************************** * * Callback Interface Methods * */ /** * Called upon submitted input from the UI portion of the lockscreen to indicate the user is * trying to submit lock data for authentication/storage * * @param data the input data */ @Override public void onInput(byte[] data) { switch (mState){ case SETUP: // 1) Stage the data mStaged = data; // 2) Proceed state to confirm mode and update the title mState = CONFIRM; showConfirmation(); // 3) Reset the Lock UI for another round of input mUi.onReset(); break; case CONFIRM: // 1) Valid staged data, use authenticator to verify the data if(mAuthenticator.authenticate(data, mStaged)){ // 2a) Success! Notify UI mUi.onSuccess(); // 3a) Store the input data mStorage.deposit(data, mType); // 4a) Notify Listeners of setup completion if(mCallbacks != null) mCallbacks.onSuccess(); }else{ // 2b) Failure?! Notify UI to show failure and reset itself mUi.onFailure(); // 3b) Show failure text showFailure(); // 4b) Notify callbacks if(mCallbacks != null) mCallbacks.onFailure(); } break; default: // 1) Get data from storage byte[] stored = mStorage.withdraw(mType); // 2) Authenticate input against stored if(mAuthenticator.authenticate(data, stored)){ // 2a) Show success on UI mUi.onSuccess(); // 3a) Signal listeners of match if(mCallbacks != null) mCallbacks.onSuccess(); }else{ // 2b) Show failure on UI and have it reset itself mUi.onFailure(); // 3b) Show failure text showFailure(); // 4b) Notify callbacks if(mCallbacks != null) mCallbacks.onFailure(); } } } /*********************************************************************************************** * * Builder * */ /** * Helper class to construct lockscreen with dynamic components using the method chaining * Builer paradigm */ public static class Builder{ // The lockscreen that is being built private Lockscreen mLock; /** * Constructor * @param ctx the context reference * @param type the lockscreen type, this is a required parameter */ public Builder(Context ctx, LockType type){ mLock = new Lockscreen(ctx); mLock.mType = type; } /** * Set the UI component of this lockscreen your building whether it be a Pin Code UI, * Pattern Ui, or Password UI * * @param ui the {@link com.ftinc.showcase.ui.lock.ui.LockUI} component of this lockscreen * @return self for chaining */ public Builder ui(LockUI ui){ mLock.mUi = ui; return this; } /** * Set the Storage component of this lockscreen that will store the input data once confirmed * from the UI component * * @param storage the {@link com.ftinc.showcase.ui.lock.storage.Storage} component * for storing the lock data for later verification * @return self for chaining */ public Builder storage(Storage storage){ mLock.mStorage = storage; return this; } /** * Set the Authenticator component of this lockscreen that will verify the input data against * the stored data in the {@link com.ftinc.showcase.ui.lock.storage.Storage} component * * @param auth the {@link com.ftinc.showcase.ui.lock.auth.Auth} component for this lockscreen * @return self for chaining */ public Builder authenticator(Auth auth){ mLock.mAuthenticator = auth; return this; } /** * Set whether or not this lockscreen is being setup right now to be stored in the * {@link com.ftinc.showcase.ui.lock.storage.Storage} component * * @param flag the setup flag * @return self for chaining */ public Builder setup(boolean flag){ mLock.setState(flag ? LockState.SETUP : LockState.LOCKED); return this; } /** * Build the Lockscreen with all the previously specified components * * @return the built lockscreen * @throws java.lang.UnsupportedOperationException if all the components haven't been * specified */ public Lockscreen build(){ // Validate all the components of the lockscreen if(mLock.mUi == null || mLock.mStorage == null || mLock.mAuthenticator == null){ throw new UnsupportedOperationException("Lockscreen UI, Storage, or Authenticator has not been setup"); } // Set the setup flag in the UI so it can appropriate generate itself on the mode // TODO: Make this solution prettier mLock.mUi.setState(mLock.mState); mLock.mUi.setContext(mLock.mCtx); // Return the compiled lock return mLock; } } /*********************************************************************************************** * * Callbacks * */ public static interface LockscreenCallbacks{ public void onSuccess(); public void onFailure(); } }
true
46f2ce8690532d6ab706d485822f91b16778dae0
Java
lenisaputri/Ileen-Mobile
/app/src/main/java/com/example/ileen_mobile/practice/Model/Ranking.java
UTF-8
878
2.484375
2
[]
no_license
package com.example.ileen_mobile.practice.Model; import com.google.firebase.database.Exclude; import java.util.HashMap; import java.util.Map; public class Ranking { private String userName; private long score; public Ranking() { } public Ranking(String userName, long score) { this.userName = userName; this.score = score; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public long getScore() { return score; } public void setScore(long score) { this.score = score; } @Exclude public Map<String, Object> toMap() { HashMap<String, Object> result = new HashMap<>(); result.put("userName", userName); result.put("score", score); return result; } }
true
a4bb6e48380cb0a696d629f0f5e1df341f384485
Java
nickzhangf/algorithm
/project/src/zf/application/Gcd.java
UTF-8
389
2.984375
3
[]
no_license
package zf.application; /** * Gcd 求两个数的最大公约数 * * @author zf * @date 2016/1/4 0004 */ public class Gcd { /** * * @param m * @param n * @return */ public static long gcd(long m, long n) { while (n != 0) { long rem = m % n; m = n; n = rem; } return m; } }
true
ed5f9b19c3d58a674fdcc160bf4ab2ebd7928641
Java
MikeJones999/Rock-Paper-Scissors
/src/GameObjs/Pair.java
UTF-8
850
3.875
4
[]
no_license
package GameObjs; /** * Generic Pair class to hold two items - specifically used to hold String and Integer * This class holds the string name of a GameObject and its incremented value * @author mike * * @param <X> * @param <Y> */ public class Pair<X,Y> { private final X obj; private final Y value; public X getObj() { return obj; } public Y getValue() { return value; } public Pair(X obj, Y value) { this.obj = obj; this.value = value; } @Override public int hashCode() { return obj.hashCode() ^ value.hashCode(); } @Override public boolean equals(Object o) { if(!(o instanceof Pair)) return false; Pair p = (Pair) o; return this.obj.equals(p.getObj()) && this.value.equals(p.getValue()); } @Override public String toString() { return "Pair [obj=" + obj + ", value=" + value + "]"; } }
true
56c9eb1a86d70e21ce677f5e0610a388e8453301
Java
deks23/malarze
/malarze/model/Painter.java
UTF-8
1,595
2.953125
3
[]
no_license
package malarze.model; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import java.util.Scanner; public class Painter { private final StringProperty name; private final StringProperty info; private final ObservableList<StringProperty> paintingPath = FXCollections.observableArrayList(); private final ObservableList<StringProperty> paintingInfo = FXCollections.observableArrayList(); private final ObservableList<StringProperty> paintingTitle = FXCollections.observableArrayList(); public Painter() { this.name = new SimpleStringProperty(""); this.info = new SimpleStringProperty(""); } public Painter(String data) { Scanner scan = new Scanner(data); this.name = new SimpleStringProperty(scan.nextLine()); this.info = new SimpleStringProperty(scan.nextLine()); while (scan.hasNextLine()) { String line = scan.nextLine(); String lines[] = line.split("\t"); paintingPath.add(new SimpleStringProperty(lines[0])); paintingTitle.add(new SimpleStringProperty(lines[1])); paintingInfo.add(new SimpleStringProperty(lines[2])); } scan.close(); } public String getName() { return name.get(); } public String getInfo() { return info.get(); } public ObservableList<StringProperty> getPaintingPath() { return this.paintingPath; } public ObservableList<StringProperty> getPaintingInfo() { return this.paintingInfo; } public ObservableList<StringProperty> getPaintingTitle() { return this.paintingTitle; } }
true
0431755e84857bda5e838637595c797f33256004
Java
yuxinling/int2
/integrate-core/src/main/java/com/integrate/env/Env.java
UTF-8
418
2.34375
2
[]
no_license
package com.integrate.env; public abstract class Env { private static String env = PropertiesHelper.getProp("env"); /** * @return true 外网生产环境 */ public static boolean isProd() { //默认是生产环境,以免外网出错 return env == null || "prod".equals(env); } /** * @return true 开发人员自己的环境 */ public static boolean isDev() { return "dev".equals(env); } }
true
e55137c8166436c3e00126e2b9e193e0733edda9
Java
Alex3m/springboot-module
/exercises/week2/exercise9/src/test/java/academy/everyonecodes/app/IssuerTest.java
UTF-8
1,066
2.59375
3
[]
no_license
package academy.everyonecodes.app; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.Set; import java.util.stream.Stream; class IssuerTest { private static Stream<Arguments> parameters() { return Stream.of( Arguments.of(true, new Issuer("American Express", Set.of("34", "37"), Set.of(15)), "345676553434545"), Arguments.of(true, new Issuer("Discover", Set.of("6011", "644", "645", "646", "647", "648", "649", "65"), Set.of(16, 19)), "6475676553434545"), Arguments.of(false, new Issuer("American Express", Set.of("51", "52", "53", "54", "55"), Set.of(16)), "3456765") ); } @ParameterizedTest @MethodSource("parameters") void issues(boolean expected, Issuer issuer, String input) { boolean result = issuer.issues(input); Assertions.assertEquals(expected, result); } }
true
d8308b8df5d102dd649daf324f319567e6354038
Java
neoabi1000/my-off-proj
/LabMgmt/src/main/java/com/jsapl/services/InvalidTestSampleException.java
UTF-8
254
1.75
2
[]
no_license
package com.jsapl.services; class InvalidTestSampleException extends Exception{ private static final long serialVersionUID = -8231971194841337941L; public InvalidTestSampleException(){} public InvalidTestSampleException(String msg){super(msg);} }
true
388cb94fcdd15180f854f14977b9a627b0de87b9
Java
iorlanov-lf/ballo-as
/app/src/androidTest/java/com/logiforge/balloapp/HttpAdapterTest.java
UTF-8
4,403
2.375
2
[]
no_license
package com.logiforge.balloapp; import android.content.Context; import android.support.test.InstrumentationRegistry; import com.logiforge.ballo.net.HttpAdapter; import com.logiforge.ballo.net.HttpAdaptorBuilder; import com.logiforge.ballo.net.PostRequest; import com.logiforge.ballo.net.Response; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.ByteArrayOutputStream; import java.lang.reflect.Constructor; import java.util.Arrays; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /** * Created by iorlanov on 8/18/17. */ @RunWith(Parameterized.class) public class HttpAdapterTest { private static final String REQ_PAR_OP = "op"; private static final String REQ_PAR_VALUE = "value"; private static final String REQ_PAR_BIN_VALUE = "bin_value"; private static final String OP_PLAIN_TEXT = "plain_text"; private static final String OP_BINARY = "binary"; private static final String OP_SET_SESSION_VALUE = "set_session_value"; private static final String OP_GET_SESSION_VALUE = "get_session_value"; private static final String TEXT_VALUE = "Aa 日本語のキーボード"; //private static final String TEST_URL = "http://10.0.0.21:8080/test"; private static final String TEST_URL = "https://ballo-test.appspot.com/test"; @Parameterized.Parameters public static Iterable<Object[]> data() { return Arrays.asList(new Object[][]{ {"com.logiforge.ballo.net.httpclient.HttpClientAdaptorBuilder"}, {"com.logiforge.ballo.net.okhttp.OkHttpAdaptorBuilder"} }); } private HttpAdapter httpAdapter; private HttpAdapter httpAdapterWithCookies; public HttpAdapterTest(String adaptorClassName) throws Exception{ httpAdapter = createAdaptor(adaptorClassName, false); httpAdapterWithCookies = createAdaptor(adaptorClassName, true); } @Test public void contextTest() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.logiforge.balloapp", appContext.getPackageName()); } @Test public void cookieTest() throws Exception { PostRequest postRequest = new PostRequest(TEST_URL, 1); postRequest.addStringPart(REQ_PAR_OP, OP_SET_SESSION_VALUE); postRequest.addStringPart(REQ_PAR_VALUE, TEXT_VALUE); httpAdapterWithCookies.execute(postRequest); postRequest = new PostRequest(TEST_URL, 1); postRequest.addStringPart(REQ_PAR_OP, OP_GET_SESSION_VALUE); Response response = httpAdapterWithCookies.execute(postRequest); assertEquals(response.getStringResponse(), TEXT_VALUE); } @Test public void textPost() throws Exception { PostRequest postRequest = new PostRequest(TEST_URL, 1); postRequest.addStringPart(REQ_PAR_OP, OP_PLAIN_TEXT); postRequest.addStringPart(REQ_PAR_VALUE, TEXT_VALUE); Response response = httpAdapter.execute(postRequest); assertEquals(response.getStringResponse(), TEXT_VALUE); } @Test public void multipartPost() throws Exception { PostRequest postRequest = new PostRequest(TEST_URL, 1); postRequest.addStringPart(REQ_PAR_OP, OP_BINARY); postRequest.addStringPart(REQ_PAR_VALUE, TEXT_VALUE); postRequest.addBinaryPart(REQ_PAR_BIN_VALUE, TEXT_VALUE.getBytes()); Response response = httpAdapter.execute(postRequest); ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int n = -1; while((n = response.getBinaryResponse().read(buffer, 0, 2048)) != -1) { content.write(buffer, 0, n); } response.getBinaryResponse().close(); assertArrayEquals(content.toByteArray(), TEXT_VALUE.getBytes()); } private HttpAdapter createAdaptor(String adaptorBuilderClassName, boolean useCookies) throws Exception { Class<?> adaptorClass = Class.forName(adaptorBuilderClassName); Constructor<?> ctor = adaptorClass.getConstructor(); HttpAdaptorBuilder adaptorBuilder = (HttpAdaptorBuilder)ctor.newInstance(); if(useCookies) { adaptorBuilder.useCookies(); } return adaptorBuilder.build(); } }
true
39cb44568751d7a67c15385b349b4c5ba9157ad9
Java
Nayemuzzaman/Retrofit_Login_with_API
/Retrofitlog/app/src/main/java/com/waltonbd/retrofitpera/RetrofitClient.java
UTF-8
1,265
2.3125
2
[]
no_license
package com.waltonbd.retrofitpera; /*import org.json.JSONObject;*/ import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; import com.google.gson.JsonObject; import org.json.JSONObject; import java.util.List; /** * Created by nayemuzzaman on 10/13/2018 */ public class RetrofitClient { private static Api service; private static RetrofitClient retrofitClient; private RetrofitClient(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://000.000.000.00:8080/") //put your api link .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); service = retrofit.create(Api.class); } public static RetrofitClient getInstance() { if (retrofitClient == null) { retrofitClient = new RetrofitClient(); } return retrofitClient; } public void getUser(JSONObject login, Callback<User> callback) { Call<User> loginCall = service.getUser( String.valueOf( login ) ); loginCall.enqueue(callback); } }
true
abbb49b841342fca5d434f0b0abc3c478e46db83
Java
israelPreciado/estrategia-integral-aes
/src/main/java/com/estrategia/avances/EliminarFile.java
UTF-8
3,373
2.40625
2
[]
no_license
package com.estrategia.avances; import java.io.IOException; import java.io.PrintWriter; 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 org.json.JSONArray; import org.json.JSONObject; import com.google.cloud.storage.BlobId; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; import db.EstrategiaDriverManagerConn; import utilities.ConfigProperties; /** * Servlet implementation class EliminarFile */ @WebServlet("/eliminar-file") public class EliminarFile extends HttpServlet { private static final long serialVersionUID = 1L; private static String BUCKET_NAME = "estrategia-integral"; private Storage storage; { try { // Instance Cloud Storage storage = StorageOptions.getDefaultInstance().getService(); } finally { } } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); response.addHeader("Access-Control-Allow-Origin", "*"); try (PrintWriter out = response.getWriter()) { JSONObject jMessage = new JSONObject(); try { ConfigProperties configProperties = new ConfigProperties("api-key.properties"); String apiKey = configProperties.getProperty("key"); String strApiKey = request.getParameter("api_key"); String strFileId = request.getParameter("fid"); Integer fileId = 0; if (strFileId != null && !"".equals(strFileId)) fileId = Integer.valueOf(strFileId); if ( strApiKey == null || !apiKey.equals(strApiKey) ) { jMessage.put("error", "access denied"); out.println(jMessage.toString()); } else if (fileId == 0) { jMessage.put("error", "1022: Empty parameters"); out.println(jMessage.toString()); } else { JSONArray jArray = new JSONArray(); String xml = "<a>"; xml += "<fid>" + fileId + "</fid>"; xml += "</a>"; System.out.println("xml:" + xml); EstrategiaDriverManagerConn estrategiaConn = new EstrategiaDriverManagerConn("0", false); jArray = estrategiaConn.execute("delete_file", xml); estrategiaConn.closeConnection(); for (int i = 0; i < jArray.length(); i++) { JSONObject obj = jArray.getJSONObject(i); if (obj.getString("respuesta").equals("OK")) { BlobId blobId = BlobId.of(BUCKET_NAME, "avances-proyectos" + "/" + obj.getString("nombre_fisico")); boolean delete = storage.delete(blobId); } } out.println(jArray); } } catch(Exception ex) { jMessage.put("error", ex.getMessage()); out.println(jMessage.toString()); } } } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }
true
824171e0b50631e0d69e66358231c182d2c7deed
Java
tamada/tuchinoko
/src/test/java/com/github/tuchinoko/ProcessorServicePoolTest.java
UTF-8
1,540
2.484375
2
[ "Apache-2.0" ]
permissive
package com.github.tuchinoko; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ProcessorServicePoolTest{ private ProcessorServicePool pool; private Environment env; @Before public void setUp() throws Exception{ env = new Environment(); pool = new ProcessorServicePool(); pool.addProvider(env.getService("nop")); } @Test public void testBasic() throws Exception{ Assert.assertEquals(1, pool.getServiceCount()); Assert.assertTrue(pool.contains("nop")); Assert.assertTrue(pool.contains(env.getService("nop"))); Assert.assertTrue(pool.removeProvider(env.getService("nop"))); Assert.assertEquals(0, pool.getServiceCount()); Assert.assertFalse(pool.contains("strenc")); Assert.assertFalse(pool.contains("nop")); } @Test public void testBasic2() throws Exception{ pool = new ProcessorServicePool(pool); Assert.assertEquals(1, pool.getServiceCount()); Assert.assertTrue(pool.contains("nop")); Assert.assertTrue(pool.contains(env.getService("nop"))); Assert.assertTrue(pool.removeProvider(env.getService("nop"))); Assert.assertEquals(0, pool.getServiceCount()); Assert.assertFalse(pool.contains("strenc")); Assert.assertFalse(pool.contains("nop")); } @Test(expected=NullPointerException.class) public void testNullCheck1() throws Exception{ Assert.assertFalse(pool.removeProvider(null)); } }
true
d464d719f237ac36f46ea08585163aabc6262d09
Java
Gurochas/Estrutura-de-Dados
/Aulas e Atividades/src/ExercicioFixacao/Casa.java
UTF-8
201
2.15625
2
[]
no_license
package ExercicioFixacao; public class Casa { String rua; String cor; int numero; public Casa(String rua, String cor, int numero) { this.rua=rua; this.cor=cor; this.numero=numero; } }
true
596a290bf71901a3bf784b90c5b70000af674632
Java
swantescholz/jogl
/src/main/java/de/sscholz/util/IndexPool.java
UTF-8
648
3.09375
3
[]
no_license
package de.sscholz.util; import java.util.LinkedList; import java.util.Queue; public class IndexPool { Queue<Integer> free = new LinkedList<Integer>(); Queue<Integer> used = new LinkedList<Integer>(); public void add(int value) { free.add(value); } public int aquire() { Integer value = free.poll(); if (value == null) throw new RuntimeException("No free index left to aquire."); used.add(value); return value; } public void release(int value) { if (used.contains(value)) { used.remove(value); free.add(value); } } }
true
9a0ac96801f0685ed09f7c81486bac0a682cb974
Java
vtc197104101/210CT
/week4/q6Test.java
UTF-8
896
3.4375
3
[]
no_license
package week4; import java.util.Stack; import java.util.Iterator; public class q6Test { public static void main(String args[]) { Stack s = new Stack(); System.out.println(s); System.out.println("Patrick is at " + s.search("Patrick")); s.push('A'); System.out.println(s); s.push('B'); System.out.println(s); s.push("Cat"); System.out.println(s); s.push("Dog"); System.out.println(s); s.push(123); System.out.println(s); s.push("Patrick"); System.out.println(s); s.push('E'); System.out.println(s); s.push(789.123); System.out.println(s); System.out.println("peek() returns: " + s.peek()); System.out.println("Patrick is at " + s.search("Patrick")); System.out.println("A is at " + s.search('A')); System.out.println("789.123 is at " + s.search(789.123)); System.out.println("Peter is at " + s.search("Peter")); System.out.println(); } }
true
8c1b9e699ba0a127b736e6e2fcb6ccd2f9f89cc4
Java
bianapis/sd-branch-location-operations-v3
/src/main/java/org/bian/dto/BQCashInventoryHandlingRetrieveInputModel.java
UTF-8
3,315
1.945313
2
[ "Apache-2.0" ]
permissive
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.BQCashInventoryHandlingRetrieveInputModelCashInventoryHandlingInstanceAnalysis; import org.bian.dto.BQCashInventoryHandlingRetrieveInputModelCashInventoryHandlingInstanceReport; import javax.validation.Valid; /** * BQCashInventoryHandlingRetrieveInputModel */ public class BQCashInventoryHandlingRetrieveInputModel { private Object cashInventoryHandlingRetrieveActionTaskRecord = null; private String cashInventoryHandlingRetrieveActionRequest = null; private BQCashInventoryHandlingRetrieveInputModelCashInventoryHandlingInstanceReport cashInventoryHandlingInstanceReport = null; private BQCashInventoryHandlingRetrieveInputModelCashInventoryHandlingInstanceAnalysis cashInventoryHandlingInstanceAnalysis = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The retrieve service call consolidated processing record * @return cashInventoryHandlingRetrieveActionTaskRecord **/ public Object getCashInventoryHandlingRetrieveActionTaskRecord() { return cashInventoryHandlingRetrieveActionTaskRecord; } public void setCashInventoryHandlingRetrieveActionTaskRecord(Object cashInventoryHandlingRetrieveActionTaskRecord) { this.cashInventoryHandlingRetrieveActionTaskRecord = cashInventoryHandlingRetrieveActionTaskRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the retrieve action service request (lists requested reports) * @return cashInventoryHandlingRetrieveActionRequest **/ public String getCashInventoryHandlingRetrieveActionRequest() { return cashInventoryHandlingRetrieveActionRequest; } public void setCashInventoryHandlingRetrieveActionRequest(String cashInventoryHandlingRetrieveActionRequest) { this.cashInventoryHandlingRetrieveActionRequest = cashInventoryHandlingRetrieveActionRequest; } /** * Get cashInventoryHandlingInstanceReport * @return cashInventoryHandlingInstanceReport **/ public BQCashInventoryHandlingRetrieveInputModelCashInventoryHandlingInstanceReport getCashInventoryHandlingInstanceReport() { return cashInventoryHandlingInstanceReport; } public void setCashInventoryHandlingInstanceReport(BQCashInventoryHandlingRetrieveInputModelCashInventoryHandlingInstanceReport cashInventoryHandlingInstanceReport) { this.cashInventoryHandlingInstanceReport = cashInventoryHandlingInstanceReport; } /** * Get cashInventoryHandlingInstanceAnalysis * @return cashInventoryHandlingInstanceAnalysis **/ public BQCashInventoryHandlingRetrieveInputModelCashInventoryHandlingInstanceAnalysis getCashInventoryHandlingInstanceAnalysis() { return cashInventoryHandlingInstanceAnalysis; } public void setCashInventoryHandlingInstanceAnalysis(BQCashInventoryHandlingRetrieveInputModelCashInventoryHandlingInstanceAnalysis cashInventoryHandlingInstanceAnalysis) { this.cashInventoryHandlingInstanceAnalysis = cashInventoryHandlingInstanceAnalysis; } }
true
d8edf8cc562acfd028322ca2d6a2708ec8ce443d
Java
yakiramar/Tow-holes-sliding-puzzle
/Tow-holes-sliding-puzzle/src/Ex1.java
UTF-8
1,245
3.140625
3
[]
no_license
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Ex1 { // readFileText get String that contain path to txt file and return his content public static String readFileTXT(String filePath) { String fileContent=""; try { File myObj = new File(filePath); Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) { fileContent = fileContent + myReader.nextLine()+"\n"; } myReader.close(); } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace(); } return fileContent; } public static void main(String[] args) { String fileContent = readFileTXT("C:\\Users\\User\\git\\Tow-holes-sliding-puzzle\\Tow-holes-sliding-puzzle\\src\\input.txt"); //System.out.println(fileContent); Puzzle p = new Puzzle(fileContent); p.printPuzzle(); Boolean movingBlock; System.out.println("\n"); movingBlock= p.oneBlockUp(1); System.out.println("test"); System.out.println("moving tow block sucsess ? "+movingBlock); p.printBoard(p.board); // TODO Auto-generated method stub } }
true
d04adcf99b66d608288dc5ce5b2f7d3f4bd0619c
Java
sanjay900/tangentPuzzleAPI
/src/main/java/com/sanjay900/puzzleapi/api/PlotType.java
UTF-8
304
2.0625
2
[]
no_license
package com.sanjay900.puzzleapi.api; import org.bukkit.material.MaterialData; public interface PlotType { public PlotGame getGame(); public String getName(); public MaterialData getInnerWall(); public MaterialData getOuterWall(); public MaterialData getRoof(); public MaterialData getFloor(); }
true
c337bf727b03ec5f93449f80a62a8a32fb84ef88
Java
zjj412550708/information
/info/information/src/main/java/com/example/information/JsonUtil.java
UTF-8
1,343
2.40625
2
[]
no_license
package com.example.information; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.util.HashMap; import java.util.Map; public class JsonUtil { public JSONObject getMap(){ Map<String , Object> result = new HashMap<String , Object>(); result.put("reason","成功的返回"); // result.put("stat","1"); Person p=new Person(); p.setUsercode("123"); p.setUsername("张三"); p.setDepartment("技术部"); Person p1=new Person(); p1.setUsercode("456"); p1.setUsername("李四"); p1.setDepartment("远程交付中心"); JSONObject jb = new JSONObject(); jb.put("usercode",p.getUsercode()); jb.put("username",p.getUsername()); jb.put("department",p.getDepartment()); JSONObject jb1= new JSONObject(); jb1.put("usercode",p1.getUsercode()); jb1.put("username",p1.getUsername()); jb1.put("department",p1.getDepartment()); JSONArray ja = new JSONArray(); ja.add(jb); ja.add(jb1); // result.put("data",ja); JSONObject jb3 = new JSONObject(); jb3.put("stat","1"); jb3.put("data",ja); result.put("result",jb3); JSONObject jsonObject = JSONObject.fromObject(result); return jsonObject; } }
true
048464fa5ec988eda33eca74f7ebdf939d8e6969
Java
wingsum93/RMS
/app/src/main/java/com/example/james/rms/Core/ServePath/QuantityServePath.java
UTF-8
1,380
1.898438
2
[]
no_license
package com.example.james.rms.Core.ServePath; import com.example.james.rms.NetWork.ServeProfile; /** * Created by jamie on 2017/4/23. */ public class QuantityServePath { public static String serve_findAll(){ String serve = ServeProfile.getServe(); String path = ServeProfile.getQuantity_findAll(); String serve_path = serve+path; return serve_path; } public static String serve_findByPartyId(){ String serve = ServeProfile.getServe(); String path = ServeProfile.getQuantity_findByPartyId(); String serve_path = serve+path; return serve_path; } public static String serve_quantityDelete(){ String serve = ServeProfile.getServe(); String path = ServeProfile.getQuantity_delete(); String serve_path = serve+path; return serve_path; } public static String serve_save(){ String serve = ServeProfile.getServe(); String path = ServeProfile.getQuantity_save(); String serve_path = serve+path; return serve_path; } // public static String serve_updateQtyByQuantityIdAndPartyIdAndQtyUnit(){ // String serve = ServeProfile.getServe(); // String path = ServeProfile.getQuantity_updateQtyByQuantityIdAndPartyIdAndQtyUnit(); // String serve_path = serve+path; // return serve_path; // } }
true
1735b111a21a46fcc8c96e84e96ebcb420d3d16c
Java
ctron/apt-repo
/src/main/java/de/dentrassi/build/apt/repo/Distribution.java
UTF-8
3,525
2.328125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 Jens Reimann. * * 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 de.dentrassi.build.apt.repo; import java.util.HashSet; import java.util.Set; /** * An APT distribution description * * @author Jens Reimann */ public class Distribution { private String name = "devel"; private String label = "Development"; private String origin = "Unknown"; private String description; private final Set<Component> components = new HashSet<Component> (); public Distribution () { } public Distribution ( final Distribution other ) { this.name = other.name; this.label = other.label; this.origin = other.origin; this.description = other.description; for ( final Component comp : other.components ) { addComponent ( comp ); } } public void setDescription ( final String description ) { this.description = description; } public String getDescription () { return this.description; } public void setOrigin ( final String origin ) { this.origin = origin; } public String getOrigin () { return this.origin; } public void setLabel ( final String label ) { this.label = label; } public String getLabel () { return this.label; } public void setName ( final String name ) { Names.validate ( "name", name ); this.name = name; } public String getName () { return this.name; } public Set<Component> getComponents () { return this.components; } /** * Add a new component to the distribution. <br/> * The component is copied and cannot be altered after adding * * @param component * the component to add */ public void addComponent ( final Component component ) { final Component newComp = new Component ( component ); newComp.setDistribution ( this ); this.components.add ( newComp ); } @Override public String toString () { return this.name; } @Override public int hashCode () { final int prime = 31; int result = 1; result = prime * result + ( this.name == null ? 0 : this.name.hashCode () ); return result; } @Override public boolean equals ( final Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass () != obj.getClass () ) { return false; } final Distribution other = (Distribution)obj; if ( this.name == null ) { if ( other.name != null ) { return false; } } else if ( !this.name.equals ( other.name ) ) { return false; } return true; } }
true
cd127512d7d7ac3df77c246112f46b35c0ab0f41
Java
lixuesheng83829/JavaEE
/ItcastOA/src/cn/itcast/oa/util/FileUtils.java
UTF-8
2,283
2.859375
3
[]
no_license
package cn.itcast.oa.util; import java.io.File; import java.util.Date; import java.util.UUID; import org.apache.struts2.ServletActionContext; public class FileUtils { /** * 完成文件上传的同时,返回路径path * @param savePath * @param file:上传的文件 * @param string:上传的文件名 * @param model:模块名称,要加上"/"后缀,防止拼接路径出错 * @param savePath:文件上传路径 * @return:文件路径 * * 1:完成文件上传的要求 1:将上传的文件统一放置到upload的文件夹下 2:将每天上传的文件,使用日期格式的文件夹分开,将每个业务的模块放置统一文件夹下 3:上传的文件名要指定唯一,可以使用UUID的方式,也可以使用日期作为文件名 4:封装一个文件上传的方法,该方法可以支持多文件的上传,即支持各种格式文件的上传 5:保存路径path的时候,使用相对路径进行保存,这样便于项目的可移植性 */ public static String fileUploadReturnPath(File file, String fileName, String model, String savePath) { // 1:获取上传文件统一的路径path(D:\Tomcat 7.0\webapps\ItcastOA\WEB-INF/upload) String basepath = ServletActionContext.getServletContext().getRealPath(savePath); //2:获取日期文件夹(格式:/yyyy/MM/dd/:/2016/02/14/) String datepath = DateUtils.dateToStringByFile(new Date()); //格式(upload\2014\12\01\用户管理) String filePath = basepath+datepath+model;//服务器上的物理存储路径 //3:判断该文件夹是否存在,如果不存在,创建 File dateFile = new File(filePath); if(!dateFile.exists()){ dateFile.mkdirs();//创建 } //4:生成对应的UUID文件名:UUID+"_"+fileName+prefix //文件的后缀 //String prefix = fileName.substring(fileName.lastIndexOf(".")); //uuid的文件名 String uuidFileName = UUID.randomUUID().toString()+"_"+fileName; //最终上传的文件(目标文件) File destFile = new File(dateFile,uuidFileName); //上传文件,renameTo剪切临时文件到目的文件 file.renameTo(destFile); //返回相对路径 return "/WEB-INF/upload"+datepath+model+uuidFileName; } }
true
2d44377153a9ed6a5442268e43c97fdf2bc2baf4
Java
nromanen/Ch-039
/src/main/java/com/hospitalsearch/controller/ManagerController.java
UTF-8
2,575
2.1875
2
[]
no_license
package com.hospitalsearch.controller; import com.hospitalsearch.entity.UserDetail; import com.hospitalsearch.service.HospitalService; import com.hospitalsearch.service.ManagerService; import com.hospitalsearch.service.UserDetailService; import com.hospitalsearch.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * Created by igortsapyak on 24.05.16. */ @Controller public class ManagerController { @Autowired private HospitalService hospitalService; @Autowired private UserService userService; @Autowired private ManagerService managerService; @Autowired private UserDetailService userDetailService; @RequestMapping(value = "/manageDoctors", method = RequestMethod.GET) public String getDoctorsByManager(Map<String, Object> model) { model.put("doctors", managerService.getDoctorsByManager()); return "manageDoctors"; } @RequestMapping(value = "/editHospitalsManagers", method = RequestMethod.GET) public String getManagersAndHospitals(Map<String, Object> model) { model.put("hospitals", hospitalService.getAll()); model.put("users", userService.getByRole("MANAGER")); return "editHospitalsManagers"; } @RequestMapping(value = "/applyManager", method = RequestMethod.POST) public String applyManager(@RequestBody Map<String, Long> hospitalData) { managerService.applyManager(hospitalData); return "redirect:/editHospitalsManagers"; } @RequestMapping(value = "/deleteManager", method = RequestMethod.POST) public String deleteManager(@RequestParam Long hospitalId) { managerService.deleteHospitalManager(hospitalId); return "redirect: /editHospitalsManagers"; } @RequestMapping(value = "/doctor/{d_id}/manage", method = RequestMethod.GET) public String getManage( @PathVariable("d_id") Long doctorId, ModelMap model) { UserDetail userDetail = userDetailService.getById(doctorId); model.addAttribute("id", userDetail.getDoctorsDetails().getId()); model.addAttribute("doctor", userDetailService.getById(doctorId)); return "manage"; } @RequestMapping(value = "/docs", method = RequestMethod.GET) public String docs(Map<String, Object> model){ model.put("doctors", userService.getByRole("DOCTOR")); return "doctorsTwo"; } }
true
1b5b51df4c8d7094d5bfa113024cb837b7d66102
Java
DFZYL/xichuanxunfang
/app/src/main/java/com/weisen/xcxf/receiver/MyReceiver.java
UTF-8
7,788
2.15625
2
[]
no_license
package com.weisen.xcxf.receiver; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import org.json.JSONObject; import com.weisen.xcxf.Constant; import com.weisen.xcxf.activity.MessageDetailActivity; import com.weisen.xcxf.bean.Notice; import com.weisen.xcxf.bean.NoticeDao; import com.weisen.xcxf.tool.CommonTool; import cn.jpush.android.api.JPushInterface; /** * 自定义接收器 * * 如果不定义这个 Receiver,则: * 1) 默认用户会打开主界面 * 2) 接收不到自定义消息 */ public class MyReceiver extends BroadcastReceiver { private static final String TAG = "JPush"; @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle)); // 注册ID的广播这个比较重要,因为所有的推送服务都必须,注册才可以额接收消息 // 注册是在后台自动完成的,如果不能注册成功,那么所有的推送方法都无法正常进行 // 这个注册的消息,可以发送给自己的业务服务器上。也就是在用户登录的时候,给自己的服务器发送 if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) { String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID); Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId); // processCustomMessage(context,bundle); } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) { Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE)); // processCustomMessage(context,bundle); } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) { Log.d(TAG, "[MyReceiver] 接收到推送下来的通知"); int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID); Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId); processCustomMessage(context,bundle); } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) { Log.d(TAG, "[MyReceiver] 用户点击打开了通知"); String type = bundle.getString(JPushInterface.EXTRA_EXTRA); String nid = "",url = "",flag = "3",latitude = "",longitude = "",userIname = "",userIphone = "",userDescription = ""; if (type != null && !"".equals(type)) { JSONObject Object = CommonTool.parseFromJson(type); url = CommonTool.getJsonString(Object, "url"); flag = CommonTool.getJsonString(Object, "flag"); nid = CommonTool.getJsonString(Object, "id"); latitude = CommonTool.getJsonString(Object, "latitude"); longitude = CommonTool.getJsonString(Object, "longitude"); userIname = CommonTool.getJsonString(Object, "userName"); userIphone = CommonTool.getJsonString(Object, "userIphone"); userDescription = CommonTool.getJsonString(Object, "userDescription"); } String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE); String context1 = bundle.getString(JPushInterface.EXTRA_ALERT); Intent intent2 = new Intent(); intent2.setAction(Constant.BROADCAST_UPDATE_MESSAGE); context.sendBroadcast(intent2); Intent intent1 = new Intent(context, MessageDetailActivity.class); intent1.putExtra("nid", nid); intent1.putExtra("title", bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE)); intent1.putExtra("content", bundle.getString(JPushInterface.EXTRA_ALERT)); intent1.putExtra("flag", flag); intent1.putExtra("url", url); intent1.putExtra("time", CommonTool.getNowDate()); intent1.putExtra("latitude", latitude); intent1.putExtra("longitude", longitude); intent1.putExtra("userIname", userIname); intent1.putExtra("userIphone", userIphone); intent1.putExtra("userDescription", userDescription); intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); context.startActivity(intent1); } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) { Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA)); //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码,比如打开新的Activity, 打开一个网页等.. } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) { boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false); Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected); } else { Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction()); } } // 打印所有的 intent extra 数据 @SuppressLint("NewApi") private static String printBundle(Bundle bundle) { StringBuilder sb = new StringBuilder(); for (String key : bundle.keySet()) { if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) { sb.append("\nkey:" + key + ", value:" + bundle.getInt(key)); }else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){ sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key)); } else { sb.append("\nkey:" + key + ", value:" + bundle.getString(key)); } } return sb.toString(); } public boolean isEmpty(String s) { if (null == s) return true; if (s.length() == 0) return true; if (s.trim().length() == 0) return true; return false; } //发送消息 private void processCustomMessage(Context context, Bundle bundle) { String nid = "",url = "",flag = "3",latitude = "",longitude = "",userIname = "",userIphone = "",userDescription = ""; String customContentString = bundle.getString(JPushInterface.EXTRA_EXTRA); if (customContentString != null && !"".equals(customContentString)) { JSONObject Object = CommonTool.parseFromJson(customContentString); url = CommonTool.getJsonString(Object, "url"); flag = CommonTool.getJsonString(Object, "flag"); nid = CommonTool.getJsonString(Object, "id"); latitude = CommonTool.getJsonString(Object, "latitude"); longitude = CommonTool.getJsonString(Object, "longitude"); userIname = CommonTool.getJsonString(Object, "userName"); userIphone = CommonTool.getJsonString(Object, "userIphone"); userDescription = CommonTool.getJsonString(Object, "userDescription"); } Notice notice = new Notice(); notice.setNid(nid); notice.setTitle(bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE));//标题 notice.setContent(bundle.getString(JPushInterface.EXTRA_ALERT));//内容 notice.setFlag(flag); notice.setUrl(url); notice.setIsRead("N"); notice.setTime(CommonTool.getNowDate()); notice.setLatitude(latitude); notice.setLongitude(longitude); notice.setUserIname(userIname); notice.setUserPhone(userIphone); notice.setUserDescription(userDescription); NoticeDao noticeDao = new NoticeDao(context); noticeDao.addNotice(notice); Intent intent = new Intent(); intent.setAction(Constant.BROADCAST_UPDATE_MESSAGE); context.sendBroadcast(intent); } }
true
ee0b4a35d705f7bd14a6076b3f89dfd1b796f6d3
Java
claudiacameliaa/lnt-mid-project
/src/main/Main.java
UTF-8
4,728
3.234375
3
[]
no_license
package main; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import java.util.Scanner; import data.Admin; import data.Employee; import data.Manager; import data.Supervisor; public class Main { private Scanner scan = new Scanner(System.in); private ArrayList<Employee> list = new ArrayList<Employee>(); //kayaknya ini harus dijadiin private void Main public Main() { int choice = 0; do { System.out.println("PT. Mentol"); System.out.println("----------"); System.out.println("1. Insert Data Karyawan"); System.out.println("2. View Data Karyawan"); System.out.println("3. Update Data Karyawan"); System.out.println("4. Delete Data Karyawan"); System.out.print("Pilih menu : "); choice = tryCatch(); } while (choice < 1 || choice > 4); switch (choice) { case 1: insertData(); break; case 2: viewData(); break; case 3: updateData(); break; case 4: deleteData(); break; } } private void insertData() { String nama, jk, jabatan, kode=""; int gaji=0, bonus=0; do { System.out.print("Input nama karyawan [>= 3]: "); nama = scan.nextLine(); } while (nama.length() < 3); do { System.out.print("Input jenis kelamin [Laki-laki | Perempuan] (Case Sensitive): "); jk = scan.nextLine(); } while (!(jk.equals("Laki-laki") || jk.equals("Perempuan"))); do { System.out.print("Input jabatan [Manager | Supervisor | Admin] (Case Sensitive): "); jabatan = scan.nextLine(); } while (!(jabatan.equals("Manager") || jabatan.equals("Supervisor") || jabatan.equals("Admin"))); Random rndm = new Random(); //0+65 = 65 A , 1+65 = 65 B kode = "" + (char)(rndm.nextInt(26)+65) + (char)(rndm.nextInt(26)+65) + "-" + rndm.nextInt(10) + rndm.nextInt(10) + rndm.nextInt(10) + rndm.nextInt(10); System.out.println("Berhasil menambahkan karyawan dengan id " +kode); switch (jabatan) { case "Manager": list.add(new Manager(nama, kode, jabatan, jk, gaji, bonus)); break; case "Supervisor": list.add(new Supervisor(nama, kode, jabatan, jk, gaji, bonus)); break; case "Admin": list.add(new Admin(nama, kode, jabatan, jk, gaji, bonus)); break; } if (jabatan.equals("Manager")) { String bonusM = "10%"; System.out.println("Bonus sebesar" + bonusM + "telah diberikan kepada karyawan dengan id" + kode); }else if (jabatan.equals("Supervisor")) { String bonusS = "7,5%"; System.out.println("Bonus sebesar" + bonusS + "telah diberikan kepada karyawan dengan id" + kode); }else if (jabatan.equals("Admin")) { String bonusA = "5%"; System.out.println("Bonus sebesar" + bonusA + "telah diberikan kepada karyawan dengan id" + kode); } } private void viewData() { if (list.isEmpty()) { System.out.println("Data Belum di Masukkan"); }else { System.out.println("|---|-----------------|-------------------------|---------------|---------------|-------------|"); System.out.printf("| %-3s| %-17s| %-25s| %-15s| %-15s| %-13s|\n", "No" , "Kode Karyawan" , "Nama Karyawan" , "Jenis Kelamin", "Jabatan", "Gaji Karyawan"); System.out.println("|---|-----------------|-------------------------|---------------|---------------|-------------|"); //Collections.sort(list); int i = 0; for (Employee employee : list) { i++; System.out.printf("| %-3d| %-17d| %-25d| %-15d| %-15d| %-13d|\n", i , employee.getKode(), employee.getNama(), employee.getJk(), employee.getJabatan(), employee.getGaji()); } System.out.println("|---|-----------------|-------------------------|---------------|---------------|-------------|"); } } private void updateData() { viewData(); int update = 0; do { System.out.println("Silahkan masukkan nomor yang ingin diupdate [1 - " +(list.size())+ "]: "); update = scan.nextInt(); scan.nextLine(); insertData(); scan.nextLine(); } while (update < 1 || update > list.size()); } private void deleteData() { viewData(); int angka = 0; do { System.out.print("Silahkan masukkan nomor yang ingin dihapus [1 - " +(list.size())+ "]: "); angka = scan.nextInt(); scan.nextLine(); } while (angka < 1 || angka > list.size()); list.remove(angka-1); } public static void enter() { System.out.println("Press enter to Continue..."); try { System.in.read(); } catch (Exception e) { } System.out.println(); } private Integer tryCatch() { int a = 0; try { a = scan.nextInt(); } catch (Exception e) { a = -1; System.err.println("Please input number only"); } scan.nextLine(); return a; } public static void main(String[] args) { // TODO Auto-generated method stub } }
true
5693fdcd4ad33e11365431f6288b05c745ae24df
Java
allworldall/rpc
/src/linekong-erating-api/src/main/java/com/linekong/erating/api/pojo/response/UserCashExchangeRespDTO.java
UTF-8
1,013
2.125
2
[]
no_license
package com.linekong.erating.api.pojo.response; import com.linekong.erating.api.pojo.resultmapper.UserCashExchangeDO; import java.util.List; /** * 元宝流通,应答数据对象 * CMD_USER_CASH_EXCHANGE_EX4_RES 0x20003718 *本协议包是变长包,将依据balanceCount表示的个数决定subjectId,srcBalance,dstBalance重复的次数 */ public class UserCashExchangeRespDTO { private int resultCode; //返回结果。 private List<UserCashExchangeDO> list; @Override public String toString() { return String.format("resultCode=%s|userCashExchangeInfo=%s", resultCode,list == null ? "" : list.toString()); } public int getResultCode() { return resultCode; } public void setResultCode(int resultCode) { this.resultCode = resultCode; } public List<UserCashExchangeDO> getList() { return list; } public void setList(List<UserCashExchangeDO> list) { this.list = list; } }
true
9a9d7ae46f6a696b8b6b8a4cad3860c9daebbba6
Java
patwit/advanced_compro_lecture_examples
/coe/java/demos/c6/events/MouseEventDemo.java
UTF-8
4,644
2.90625
3
[]
no_license
package coe.java.demos.c6.events; /* * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * MouseEventDemo.java * Modified by Kanda Runapongsa Saikaew */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MouseEventDemo extends JPanel implements MouseListener { BlankArea blankArea; JTextArea textArea; static final String NEWLINE = System.getProperty("line.separator"); public MouseEventDemo() { super(new GridLayout(0,1)); blankArea = new BlankArea(Color.YELLOW); add(blankArea); textArea = new JTextArea(); textArea.setEditable(false); textArea.setForeground(Color.DARK_GRAY); textArea.setFont(new Font("Arial",Font.BOLD,20)); JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setPreferredSize(new Dimension(800, 75)); add(scrollPane); //Register for mouse events on blankArea and the panel. blankArea.addMouseListener(this); addMouseListener(this); setPreferredSize(new Dimension(800, 450)); setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); } public void mousePressed(MouseEvent e) { eventOutput("Mouse pressed (# of clicks: " + e.getClickCount() + ")", e); } public void mouseReleased(MouseEvent e) { eventOutput("Mouse released (# of clicks: " + e.getClickCount() + ")", e); } public void mouseEntered(MouseEvent e) { eventOutput("Mouse entered", e); } public void mouseExited(MouseEvent e) { eventOutput("Mouse exited", e); } public void mouseClicked(MouseEvent e) { eventOutput("Mouse clicked (# of clicks: " + e.getClickCount() + ")", e); textArea.append("Mouse clicked at x = " + e.getX() + " y = " + e.getY()); } public static void main(String[] args) { JFrame frame = new JFrame("MouseEventDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent newContentPane = new MouseEventDemo(); // How do JComponent, MouseEventDemo, and // JPanel relate to one another? frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true); } void eventOutput(String eventDescription, MouseEvent e) { int diameter = 10; String sourceClassname = e.getComponent().getClass().getName(); if (sourceClassname.contains("BlankArea")) { Graphics g = blankArea.getGraphics(); g.setColor(Color.RED); // draw the filled circle at // x coordinate and y coordinate // with width = diamter and height = diameter g.fillOval(e.getX(), e.getY(), diameter, diameter); } textArea.append(eventDescription + " detected on " + sourceClassname + "." + NEWLINE); textArea.setCaretPosition( textArea.getDocument().getLength()); } }
true
27634860d417be82be726d1dca67b4eecb50e87b
Java
itsmasud/testFlagCountry
/projects/FieldNation/fieldnation/src/main/java/com/fieldnation/service/data/photo/PhotoClient.java
UTF-8
5,141
2.25
2
[]
no_license
package com.fieldnation.service.data.photo; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import com.fieldnation.App; import com.fieldnation.fnlog.Log; import com.fieldnation.fnpigeon.Pigeon; import com.fieldnation.fnpigeon.PigeonRoost; import com.fieldnation.fntools.AsyncTaskEx; import com.fieldnation.fntools.misc; import java.lang.ref.WeakReference; import java.util.Hashtable; /** * Created by Michael Carver on 3/12/2015. */ public abstract class PhotoClient extends Pigeon implements PhotoConstants { private static final String TAG = "PhotoClient"; private static final Hashtable<String, WeakReference<BitmapDrawable>> _pictureCache = new Hashtable<>(); public void sub() { PigeonRoost.sub(this, ADDRESS_GET_PHOTO); } public void unsub() { PigeonRoost.unsub(this, ADDRESS_GET_PHOTO); } /** * Gets the image at sourceUrl. Sends the request to PhotoService for lookup in the database or downloading * * @param context The application context * @param sourceUrl The URL of the image to look up (must be http or https) * @param makeCircle true if you want the circle crop, false for full image * @param isSync true if this is a background process */ public static void get(Context context, String sourceUrl, boolean makeCircle, boolean isSync) { if (misc.isEmptyOrNull(sourceUrl)) return; PhotoSystem.get(context, sourceUrl, makeCircle, isSync); } public static void clearPhotoClientCache() { _pictureCache.clear(); } /** * Called when a get() operation finishes * * @param sourceUri The original URL used to get the file * @param localUri The URI pointing to the local content * @param isCircle true if circle cropped, false if full image * @param success true if successful, false otherwise */ public abstract void imageDownloaded(String sourceUri, Uri localUri, boolean isCircle, boolean success); /** * Called if the image download was successful. * * @param sourceUri the Uri that originated the request * @param isCircle true if circle cropped, false if full image * @return true if you want a BitmapDrawable created for you. The drawable will be retruend in onImageReady */ public abstract boolean doGetImage(String sourceUri, boolean isCircle); /** * Called after the bitmap has been created * * @param sourceUri * @param localUri * @param drawable * @param isCircle * @param success */ public abstract void onImageReady(String sourceUri, Uri localUri, BitmapDrawable drawable, boolean isCircle, boolean success); @Override public void onMessage(String address, Object message) { Bundle bundle = (Bundle) message; String action = bundle.getString(PARAM_ACTION); if (action.startsWith(PARAM_ACTION_GET)) { String sourceUrl = bundle.getString(PARAM_SOURCE_URL); Uri localUri = bundle.getParcelable(PARAM_CACHE_URI); boolean isCircle = bundle.getBoolean(PARAM_IS_CIRCLE); boolean success = bundle.getBoolean(PARAM_SUCCESS); imageDownloaded(sourceUrl, localUri, isCircle, success); if (success && doGetImage(sourceUrl, isCircle)) { new BitmapAsyncTask(this).executeEx(sourceUrl, localUri, isCircle); } } } private static class BitmapAsyncTask extends AsyncTaskEx<Object, Object, BitmapDrawable> { String sourceUrl; Uri localUri; boolean isCircle; PhotoClient client; public BitmapAsyncTask(PhotoClient client) { this.client = client; } @Override protected BitmapDrawable doInBackground(Object... params) { try { sourceUrl = (String) params[0]; localUri = (Uri) params[1]; isCircle = (Boolean) params[2]; String key = isCircle + ":" + sourceUrl; BitmapDrawable result = null; if (_pictureCache.containsKey(key)) { WeakReference<BitmapDrawable> wr = _pictureCache.get(key); if (wr == null || wr.get() == null) { _pictureCache.remove(key); } else { result = wr.get(); } } if (result == null) { result = new BitmapDrawable(App.get().getResources(), App.get().getContentResolver().openInputStream(localUri)); _pictureCache.put(key, new WeakReference<>(result)); } return result; } catch (Exception ex) { Log.v(TAG, ex); } return null; } @Override protected void onPostExecute(BitmapDrawable bitmapDrawable) { client.onImageReady(sourceUrl, localUri, bitmapDrawable, isCircle, bitmapDrawable != null); } } }
true
8bedf28795897d7557720838fa7c348ff36165d6
Java
Haybu/demo-bootup-testing
/src/test/java/io/agilehandy/bootuptesting/RegistrationRepositoryTest.java
UTF-8
1,045
2.15625
2
[]
no_license
package io.agilehandy.bootuptesting; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; /** * By Haytham Mohamed */ @RunWith(SpringRunner.class) @DataJpaTest public class RegistrationRepositoryTest { @Autowired RegistrationRepository repository; @Test public void test() { Registration savedRegistration = repository.save(new Registration(1L, "Haytham", "Math")); Registration registration = repository.findByName("Haytham"); assertThat(registration).isNotNull(); assertThat(registration.getId()).isEqualTo(savedRegistration.getId()); assertThat(registration.getName()).isEqualTo(savedRegistration.getName()); assertThat(registration.getClassName()).isEqualTo(savedRegistration.getClassName()); } }
true
14da2e34a9244b878669271d9cf90d49065e2277
Java
enjektor/enjektor-web
/src/main/java/com/github/enjektor/akasya/WebConstants.java
UTF-8
491
1.90625
2
[]
no_license
package com.github.enjektor.akasya; public class WebConstants { private WebConstants() { throw new AssertionError(); } public static final byte HTTP_METHOD_GET = (byte) 0x0; public static final byte HTTP_METHOD_POST = (byte) 0x1; public static final byte HTTP_METHOD_DELETE = (byte) 0x2; public static final byte HTTP_METHOD_PUT = (byte) 0x3; public static final byte HASH_KEY = (byte) 0x7F; public static final byte MASKING_VALUE = (byte) 0xFF; }
true
ad5c258195179ac745a5f806a38349105f1a1aaa
Java
bongboy/Funda
/functionaldesign/src/chainofresponsibility/ChainOfRespGOF.java
UTF-8
2,752
3.515625
4
[]
no_license
package chainofresponsibility; public class ChainOfRespGOF { public static void main(String[] args) { FileParser textFileParser = new TextFileParser(); FileParser presentationFileParser = new PresentationFileParser(); FileParser audioFileParser = new AudioFileParser(); textFileParser.setNextParser(presentationFileParser).setNextParser(audioFileParser); //presentationFileParser.setNextParser(audioFileParser); File audioFile = new File(File.Type.AUDIO, "This is Audio file"); File videoFile = new File(File.Type.VIDEO, "This is Video file"); System.out.println(textFileParser.parse(videoFile)); } public interface FileParser { String parse(File file); FileParser setNextParser(FileParser next); } public static abstract class AbstractFileParser implements FileParser { protected FileParser next; @Override public FileParser setNextParser(FileParser next) { this.next = next; return next; } } public static class TextFileParser extends AbstractFileParser { @Override public String parse(File file) { if (file.getType() == File.Type.TEXT) return "Text File:" + file.getContent(); else if (next != null) return next.parse(file); else throw new RuntimeException("Unknown file: " + file); } } public static class PresentationFileParser extends AbstractFileParser { @Override public String parse(File file) { if (file.getType() == File.Type.PRESENTATION) return "Presentation File:" + file.getContent(); else if (next != null) return next.parse(file); else throw new RuntimeException("Unknown file: " + file); } } public static class AudioFileParser extends AbstractFileParser { @Override public String parse(File file) { if (file.getType() == File.Type.AUDIO) return "Audio File:" + file.getContent(); else if (next != null) return next.parse(file); else throw new RuntimeException("Unknown file: " + file); } } public static class VideoFileParser extends AbstractFileParser { @Override public String parse(File file) { if (file.getType() == File.Type.VIDEO) return "Video File:" + file.getContent(); else if (next != null) return next.parse(file); else throw new RuntimeException("Unknown file: " + file); } } }
true
b04d7392162ac5ad677dd3043f1842b7b4921804
Java
cuba-platform/cuba
/modules/web/src/com/haulmont/cuba/web/gui/components/JavaScriptComponent.java
UTF-8
6,904
1.953125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2008-2018 Haulmont. * * 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.haulmont.cuba.web.gui.components; import com.haulmont.cuba.gui.components.Component; import com.haulmont.cuba.gui.components.HasContextHelp; import com.haulmont.cuba.gui.components.HasRequiredIndicator; import elemental.json.JsonArray; import elemental.json.JsonValue; import javax.annotation.Nullable; import java.util.EventObject; import java.util.List; import java.util.function.Consumer; /** * A JavaScript wrapper. */ public interface JavaScriptComponent extends Component, Component.HasCaption, Component.HasDescription, Component.HasIcon, Component.BelongToFrame, HasContextHelp, HasRequiredIndicator { String NAME = "jsComponent"; /** * @return a list of dependencies */ List<ClientDependency> getDependencies(); /** * Sets a list of dependencies. * Each dependency represented with a {@link ClientDependency} object which path corresponds to one of the sources: * * <ul> * <li>WebJar resource - starts with {@code webjar://}</li> * <li>VAADIN directory - starts with {@code vaadin://}</li> * </ul> * * @param dependencies dependencies to set */ void setDependencies(List<ClientDependency> dependencies); /** * Adds a dependency. Path path corresponds to one of the sources: * * <ul> * <li>WebJar resource - starts with {@code webjar://}</li> * <li>VAADIN directory - starts with {@code vaadin://}</li> * </ul> * * @param path a dependency path * @param type a dependency type */ void addDependency(String path, DependencyType type); /** * Adds dependency paths. Each path corresponds to one of the sources: * * <ul> * <li>WebJar resource - starts with {@code webjar://}</li> * <li>VAADIN directory - starts with {@code vaadin://}</li> * </ul> * * @param dependencies dependencies to add */ void addDependencies(String... dependencies); /** * @return an initialization function name that will be * used to find an entry point for the JS component connector */ String getInitFunctionName(); /** * Sets an initialization function name that will be * used to find an entry point for the JS component connector. * <p> * CAUTION: the initialization function name must be unique within window. * * @param initFunctionName an initialization function name */ void setInitFunctionName(String initFunctionName); /** * @return Returns a state object */ Object getState(); /** * Sets a state object that can be used in the client-side JS connector * and accessible from the {@code data} field of the component's state. * <p> * Here an example of accessing the state object: * * <pre>{@code * connector.onStateChange = function () { * var state = connector.getState(); * let data = state.data; * ... * } * }</pre> * <p> * The state object should be a POJO. * <p> * CAUTION: {@link java.util.Date} fields serialized as strings * with {@link com.haulmont.cuba.web.widgets.serialization.DateJsonSerializer#DATE_FORMAT} format. * * @param state a state object to set */ void setState(Object state); /** * Register a {@link Consumer} that can be called from the * JavaScript using the provided name. A JavaScript function with the * provided name will be added to the connector wrapper object (initially * available as <code>this</code>). Calling that JavaScript function will * cause the call method in the registered {@link Consumer} to be * invoked with the same arguments passed to the {@link JavaScriptCallbackEvent}. * * @param name the name that should be used for client-side function * @param function the {@link Consumer} object that will be invoked * when the JavaScript function is called */ void addFunction(String name, Consumer<JavaScriptCallbackEvent> function); /** * Invoke a named function that the connector JavaScript has added to the * JavaScript connector wrapper object. The arguments can be any boxed * primitive type, String, {@link JsonValue} or arrays of any other * supported type. Complex types (e.g. List, Set, Map, Connector or any * JavaBean type) must be explicitly serialized to a {@link JsonValue} * before sending. * * @param name the name of the function * @param arguments function arguments */ void callFunction(String name, Object... arguments); /** * Repaint UI representation of the component. */ void repaint(); /** * An event that is fired when a method is called by a client-side JavaScript function. */ class JavaScriptCallbackEvent extends EventObject { protected JsonArray arguments; /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred * @throws IllegalArgumentException if source is null */ public JavaScriptCallbackEvent(JavaScriptComponent source, JsonArray arguments) { super(source); this.arguments = arguments; } @Override public JavaScriptComponent getSource() { return (JavaScriptComponent) super.getSource(); } /** * @return a list of arguments with which the JavaScript function was called */ public JsonArray getArguments() { return arguments; } } /** * The type of dependency. */ enum DependencyType { STYLESHEET, JAVASCRIPT } class ClientDependency { protected String path; protected DependencyType type; public ClientDependency(String path) { this.path = path; } public ClientDependency(String path, @Nullable DependencyType type) { this.path = path; this.type = type; } public String getPath() { return path; } @Nullable public DependencyType getType() { return type; } } }
true
08379d574398a84d6ab72e2fdc20bd9ee7929779
Java
Abhishek0395/ChessMasters
/ChessGame-master/src/chess/HomePageController.java
UTF-8
494
1.804688
2
[]
no_license
package chess; import javafx.event.ActionEvent; import javafx.fxml.Initializable; import java.net.URL; import java.util.ResourceBundle; /** * Created by Rupak on 6/4/2016. */ import javafx.fxml.FXML; import javafx.scene.image.ImageView; public class HomePageController { @FXML private ImageView ExitBtn; @FXML void Exit(ActionEvent event) { } @FXML void Create_Host(ActionEvent event) { } @FXML void Join_Game(ActionEvent event) { } }
true
a50fd0137b0f535c1afbb95df0f3473dc6a89f3e
Java
vvbulbule/WedDriverOffice
/WebDriver_Office/src/Sample3.java
UTF-8
279
2.59375
3
[]
no_license
public class Sample3 { public static void rank(int marks){ if(marks<35){ System.out.println("Student is fail"); }else System.out.println("Pass"); } public static void main(String[] args) { // TODO Auto-generated method stub rank(60); } }
true
92feb82bd7d51fc531ca9ceae1c9bd95e9238a37
Java
Micromoving/bcp
/代码bcp1.0/010_source/src/main/java/cn/micromoving/bcp/modules/hr/entity/SalaryInstancePerformance.java
UTF-8
739
2.078125
2
[ "Apache-2.0" ]
permissive
package cn.micromoving.bcp.modules.hr.entity; import cn.micromoving.bcp.common.persistence.DataEntity; import cn.micromoving.bcp.modules.sys.entity.Office; /** * 离职表Entity * @author shihengji * */ public class SalaryInstancePerformance extends DataEntity<SalaryInstancePerformance>{ private static final long serialVersionUID = 1L; /* 部门 */ private Office office; /*工资实例*/ private SalaryInstance SalaryInstance; public Office getOffice() { return office; } public void setOffice(Office office) { this.office = office; } public SalaryInstance getSalaryInstance() { return SalaryInstance; } public void setSalaryInstance(SalaryInstance salaryInstance) { SalaryInstance = salaryInstance; } }
true
b3509bf973e4e71eb89292ac41aaefce3ddaa801
Java
chzhxiang/tower
/src/main/java/com/cdhenren/fetch/entity/TmpSiteDavyPreview.java
UTF-8
3,424
1.921875
2
[]
no_license
package com.cdhenren.fetch.entity; /** * @author Baopz * @date 2018/05/24 */ public class TmpSiteDavyPreview implements ResultSet{ private String 省; private String 市; private String 区; private String 站址运维ID; private String 资源系统站址编码; private String 站址名称; private String 合同编号; private String 合同名称; private String 对方主体编号; private String 供应商名称; private String 费用类型; private String 金额元; @Override public String toString() { return "TmpSiteDavyPreview{" + "省='" + 省 + '\'' + ", 市='" + 市 + '\'' + ", 区='" + 区 + '\'' + ", 站址运维ID='" + 站址运维ID + '\'' + ", 资源系统站址编码='" + 资源系统站址编码 + '\'' + ", 站址名称='" + 站址名称 + '\'' + ", 合同编号='" + 合同编号 + '\'' + ", 合同名称='" + 合同名称 + '\'' + ", 对方主体编号='" + 对方主体编号 + '\'' + ", 供应商名称='" + 供应商名称 + '\'' + ", 费用类型='" + 费用类型 + '\'' + ", 金额元='" + 金额元 + '\'' + '}'; } public String get省() { return 省; } public void set省(String 省) { this.省 = 省; } public String get市() { return 市; } public void set市(String 市) { this.市 = 市; } public String get区() { return 区; } public void set区(String 区) { this.区 = 区; } public String get站址运维ID() { return 站址运维ID; } public void set站址运维ID(String 站址运维ID) { this.站址运维ID = 站址运维ID; } public String get资源系统站址编码() { return 资源系统站址编码; } public void set资源系统站址编码(String 资源系统站址编码) { this.资源系统站址编码 = 资源系统站址编码; } public String get站址名称() { return 站址名称; } public void set站址名称(String 站址名称) { this.站址名称 = 站址名称; } public String get合同编号() { return 合同编号; } public void set合同编号(String 合同编号) { this.合同编号 = 合同编号; } public String get合同名称() { return 合同名称; } public void set合同名称(String 合同名称) { this.合同名称 = 合同名称; } public String get对方主体编号() { return 对方主体编号; } public void set对方主体编号(String 对方主体编号) { this.对方主体编号 = 对方主体编号; } public String get供应商名称() { return 供应商名称; } public void set供应商名称(String 供应商名称) { this.供应商名称 = 供应商名称; } public String get费用类型() { return 费用类型; } public void set费用类型(String 费用类型) { this.费用类型 = 费用类型; } public String get金额元() { return 金额元; } public void set金额元(String 金额元) { this.金额元 = 金额元; } }
true
31e7160e7e4679ba574a035478e9d61ac2e4165e
Java
macedo-ca/util1
/src/main/java/ca/macedo/util1/factory/QueryUtils.java
UTF-8
5,130
2.390625
2
[]
no_license
/****************************************************************************** * Copyright (c) 2017 Johan Macedo * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Johan Macedo *****************************************************************************/ package ca.macedo.util1.factory; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Utility to parse query-strings for parameters */ public class QueryUtils { public static Map<String, Object> parseQuery(String uri, boolean useRaw, boolean lenient) throws URISyntaxException { if (!lenient) { if (uri != null && uri.endsWith("&")) { throw new URISyntaxException(uri, "Invalid uri syntax: Trailing & marker found. " + "Check the uri and remove the trailing & marker."); } } if (uri == null || uri.trim().length()==0) { return new LinkedHashMap<String, Object>(0); } try { Map<String, Object> rc = new LinkedHashMap<String, Object>(); boolean isKey = true; boolean isValue = false; boolean isRaw = false; StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); for (int i = 0; i < uri.length(); i++) { char ch = uri.charAt(i); char next; if (i <= uri.length() - 2) { next = uri.charAt(i + 1); } else { next = '\u0000'; } if (isKey && ch == '=') { isKey = false; isValue = true; isRaw = false; continue; } if (ch == '&') { addParam(key.toString(), value.toString(), rc, useRaw || isRaw); key.setLength(0); value.setLength(0); isKey = true; isValue = false; isRaw = false; continue; } if (isKey) { key.append(ch); } else if (isValue) { value.append(ch); } } if (key.length() > 0) { addParam(key.toString(), value.toString(), rc, useRaw || isRaw); } return rc; } catch (UnsupportedEncodingException e) { URISyntaxException se = new URISyntaxException(e.toString(), "Invalid encoding"); se.initCause(e); throw se; } } private static final String CHARSET = "UTF-8"; @SuppressWarnings("unchecked") private static void addParam(String name, String value, Map<String, Object> map, boolean isRaw) throws UnsupportedEncodingException { name = URLDecoder.decode(name, CHARSET); if (!isRaw) { String s = replaceAll(value, "%", "%25"); value = URLDecoder.decode(s, CHARSET); } if (map.containsKey(name)) { Object existing = map.get(name); List<String> list; if (existing instanceof List) { list = (List<String>) existing; } else { list = new ArrayList<String>(); String s = existing != null ? existing.toString() : null; if (s != null) { list.add(s); } } list.add(value); map.put(name, list); } else { map.put(name, value); } } private static String replaceAll(String input, String from, String to) { if (input==null || input.trim().length()==0) { return input; } if (from == null) { throw new IllegalArgumentException("from cannot be null"); } if (to == null) { throw new IllegalArgumentException("to cannot be null"); } if (!input.contains(from)) { return input; } final int len = from.length(); final int max = input.length(); StringBuilder sb = new StringBuilder(max); for (int i = 0; i < max;) { if (i + len <= max) { String token = input.substring(i, i + len); if (from.equals(token)) { sb.append(to); i = i + len; continue; } } sb.append(input.charAt(i)); i++; } return sb.toString(); } }
true
c2cf00833b7f487d4e5819d448d8384d6ff30187
Java
rachelee/Leetcode
/Leetcode/src/Solution5.java
UTF-8
4,494
3.3125
3
[ "MIT" ]
permissive
public class Solution5 { //1. Naive solution public static String longestPalindrome(String s) { int start = 0; int end = s.length()-1; int max = 0; String str = new String(); while(start <= end-max) { boolean found = false; for(int strEnd = end; strEnd>=start; strEnd--) { int tempMax = strEnd - start + 1; String tempStr = s.substring(start, end+1); int i = start, j = strEnd; while(i < j) { if(s.charAt(i) != s.charAt(j)) break; else if((i == j || i == j-1) && (s.charAt(i) == s.charAt(j))) { if(tempMax > max) { str = tempStr; max = tempMax; } found = true; i++; j--; } else { i++; j--; } } if(found == true) break; } start++; } return str; } //dp solution Time O(n^2) Space O(n^2) public String longestPalindromeDp(String s) { if(s == null) return s; int len = s.length(); String ret = null; int max = 0; boolean[][] dp = new boolean[len][len]; //all value in boolean default to false for(int j = 0; j < len; j++) { for(int i = 0; i <= j; i++) { if(s.charAt(i) == s.charAt(j) && ((j-i <=2)||dp[i+1][j-1])) { dp[i][j] = true; if(j-i+1 > max) { max = j-i+1; ret = s.substring(i, j+1); } } } } return ret; } //Method to expand from the middle. Time O(n^2) Space O(1) public String longestPalindromeExpand(String s) { if(s == null) return null; int max = 0; String ret = null; for(int i = 0; i < s.length(); i++) { String sub; //odd number palindrome sub = getPString(s, i, i); if(sub.length() > max) { ret = sub; max = sub.length(); } //even number palindrome sub = getPString(s, i, i+1); if(sub.length() > max) { ret = sub; max = sub.length(); } } return ret; } private String getPString(String s, int left, int right) { while(left >= 0 && right <s.length()) { if(s.charAt(left) != s.charAt(right)) break; left--; right++; } return s.substring(left+1, right); } public static String longestPalindrome3(String s) { String res = ""; for(int i = 0; i < s.length();i++){ int l = i; int r = i; while(s.charAt(l) == s.charAt(r)){ l--; r++; if(l<0||r>s.length()-1) break; } l++; r--; if(r-l+1 > res.length()) res = s.substring(l, r+1); } if(s.length()>1) for(int i = 0; i < s.length()-1;i++){ int l = i; int r = i+1; while(s.charAt(l) == s.charAt(r)){ l--; r++; if(l<0||r>s.length()-1) break; } l++; r--; if(r-l+1 > res.length()) res = s.substring(l, r+1); } return res; } public static void main(String[] args) { // TODO Auto-generated method stub String str = "bb"; System.out.println(longestPalindrome3(str)); } }
true
109abf81d71f36484c6dad516b8080007546630a
Java
davidtadeovargas/era_views
/src/main/java/com/era/views/tables/headers/PedidosPartssTableHeader.java
UTF-8
5,763
1.953125
2
[]
no_license
package com.era.views.tables.headers; public class PedidosPartssTableHeader extends BaseTableHeader { private final ColumnTable ROWNUMBER = new ColumnTable("No"); public ColumnTable getROWNUMBER() { return this.ROWNUMBER; } private final ColumnTable ALMA = new ColumnTable("Almacén"); public ColumnTable getALMA() { return this.ALMA; } private final ColumnTable CANT = new ColumnTable("Cantidad"); public ColumnTable getCANT() { return this.CANT; } private final ColumnTable CODIMPUE = new ColumnTable("Impuesto"); public ColumnTable getCODIMPUE() { return this.CODIMPUE; } private final ColumnTable COLO = new ColumnTable("Color"); public ColumnTable getCOLO() { return this.COLO; } private final ColumnTable COMENSER = new ColumnTable("Comentario Serie"); public ColumnTable getCOMENSER() { return this.COMENSER; } private final ColumnTable COST = new ColumnTable("Costo"); public ColumnTable getCOST() { return this.COST; } private final ColumnTable DESC_1 = new ColumnTable("Descuento 1"); public ColumnTable getDESC_1() { return this.DESC_1; } private final ColumnTable DESC_2 = new ColumnTable("Descuento 2"); public ColumnTable getDESC_2() { return this.DESC_2; } private final ColumnTable DESC_3 = new ColumnTable("Descuento 3"); public ColumnTable getDESC_3() { return this.DESC_3; } private final ColumnTable DESC_4 = new ColumnTable("Descuento 4"); public ColumnTable getDESC_4() { return this.DESC_4; } private final ColumnTable DESC_5 = new ColumnTable("Descuento 5"); public ColumnTable getDESC_5() { return this.DESC_5; } private final ColumnTable DESCRIP = new ColumnTable("Descripción"); public ColumnTable getDESCRIP() { return this.DESCRIP; } private final ColumnTable DESCRIPCIONOPCIONAL = new ColumnTable("Descripción Opcional"); public ColumnTable getDESCRIPCIONOPCIONAL() { return this.DESCRIPCIONOPCIONAL; } private final ColumnTable ESKIT = new ColumnTable("Kit"); public ColumnTable getESKIT() { return this.ESKIT; } private final ColumnTable ESTAC = new ColumnTable("Usuario"); public ColumnTable getESTAC() { return this.ESTAC; } private final ColumnTable FALT = new ColumnTable("Fecha Alta"); public ColumnTable getFALT() { return this.FALT; } private final ColumnTable FCADU = new ColumnTable("Fecha Caducidad"); public ColumnTable getFCADU() { return this.FCADU; } private final ColumnTable FENTRE = new ColumnTable("Fecha Entrega"); public ColumnTable getFENTRE() { return this.FENTRE; } private final ColumnTable FMOD = new ColumnTable("Fecha Modificación"); public ColumnTable getFMOD() { return this.FMOD; } private final ColumnTable GARAN = new ColumnTable("Garantía"); public ColumnTable getGARAN() { return this.GARAN; } private final ColumnTable IMPO = new ColumnTable("Importe"); public ColumnTable getIMPO() { return this.IMPO; } private final ColumnTable IMPO_2 = new ColumnTable("Importe 2"); public ColumnTable getIMPO_2() { return this.IMPO_2; } private final ColumnTable IMPODESC = new ColumnTable("Importe Descuento"); public ColumnTable getIMPODESC() { return this.IMPODESC; } private final ColumnTable IMPUEIMPO = new ColumnTable("Importe Impuesto"); public ColumnTable getIMPUEIMPO() { return this.IMPUEIMPO; } private final ColumnTable IMPUEIMPO_2 = new ColumnTable("Importe Impuesto 2"); public ColumnTable getIMPUEIMPO_2() { return this.IMPUEIMPO_2; } private final ColumnTable IMPUEVAL = new ColumnTable("Impuesto Valor"); public ColumnTable getIMPUEVAL() { return this.IMPUEVAL; } private final ColumnTable LIST = new ColumnTable("Lista"); public ColumnTable getLIST() { return this.LIST; } private final ColumnTable LOT = new ColumnTable("Lote"); public ColumnTable getLOT() { return this.LOT; } private final ColumnTable MON = new ColumnTable("Moneda"); public ColumnTable getMON() { return this.MON; } private final ColumnTable NOCAJ = new ColumnTable("Caja"); public ColumnTable getNOCAJ() { return this.NOCAJ; } private final ColumnTable PEDIDOID = new ColumnTable("Pedido ID"); public ColumnTable getPEDIDOID() { return this.PEDIDOID; } private final ColumnTable PEDIMEN = new ColumnTable("Pedimento"); public ColumnTable getPEDIMEN() { return this.PEDIMEN; } private final ColumnTable PRE = new ColumnTable("Precio"); public ColumnTable getPRE() { return this.PRE; } private final ColumnTable PRE_2 = new ColumnTable("Precio 2"); public ColumnTable getPRE_2() { return this.PRE_2; } private final ColumnTable PROD = new ColumnTable("Producto"); public ColumnTable getPROD() { return this.PROD; } private final ColumnTable RECIBIDAS = new ColumnTable("Recibidas"); public ColumnTable getRECIBIDAS() { return this.RECIBIDAS; } private final ColumnTable SERPROD = new ColumnTable("Serie Producto"); public ColumnTable getSERPROD() { return this.SERPROD; } private final ColumnTable SUCU = new ColumnTable("Sucursal"); public ColumnTable getSUCU() { return this.SUCU; } private final ColumnTable TIPCAM = new ColumnTable("Tipo Cambio"); public ColumnTable getTIPCAM() { return this.TIPCAM; } private final ColumnTable UNID = new ColumnTable("Unidad"); public ColumnTable getUNID() { return this.UNID; } }
true
928e6bef1f0c0e8e15caec6c913699da7097edf4
Java
Brijmohan-13/OJT-Java----Logical
/src/June04_Uppercase_Lowercase_ReverseString/ChangeCaseForOnlyForFirstLetter.java
UTF-8
631
3.5
4
[]
no_license
package June04_Uppercase_Lowercase_ReverseString; import java.io.BufferedReader; import java.io.InputStreamReader; public class ChangeCaseForOnlyForFirstLetter { public static void main(String[] args) throws Exception { System.out.println("Please enter text"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)) ; String s=br.readLine(); char[] ch=s.toCharArray(); //[B][r][i][j][m][o][h][a][n] if(ch[0]>=65 && ch[0]<=90) { ch[0]=(char) (ch[0]+32); } else if(ch[0]>=97 && ch[0]<=122) { ch[0]=(char) (ch[0]-32); } System.out.println(ch); } }
true
29e7b3e92933d2acb8f09ae05de424c5d8d549d8
Java
RalphTheWonderLlama/CardGames
/src/Cards/Poker/FiveCard.java
UTF-8
332
2.234375
2
[]
no_license
package Cards.Poker; import java.util.Scanner; import java.util.Arrays; import java.util.Random; import javax.swing.JFrame; import javax.swing.JOptionPane; public class FiveCard extends PokerRound{ public FiveCard(PokerPlayer[] p, int minRaise) { super(p, minRaise); } public boolean playRound() { return RoundEnd(); } }
true
702f4b666e25478915acb553203a321502122fe7
Java
dnowak2/Quintrix
/Practice/src/Customer.java
UTF-8
284
2.984375
3
[]
no_license
public class Customer { private String name; private double accountBalance; public Customer(String name, double money) { this.name = name; this.accountBalance = money; } public static double getAccountBalance(Customer customer) { return customer.accountBalance; } }
true
c74b46385c686c315d67ea90c388772031744ff9
Java
Yuchengw/Lesbonne
/core/appserver/src/main/java/com/lesbonne/lib/platformService/PlatformPostService.java
UTF-8
682
2.109375
2
[]
no_license
package com.lesbonne.lib.platformService; import java.util.List; import com.lesbonne.api.rest.AppRestPostClientImpl; import com.lesbonne.api.rest.AppRestUserClientImpl; import com.lesbonne.business.bean.Post; import com.lesbonne.business.bean.User; /** * This is the service layer concatenate platform PostEntityObject with appserver PostEntityProvider * * @author yucheng * @version 1 * */ public abstract class PlatformPostService implements PlatformService{ public AppRestPostClientImpl getPostRestClient() { return new AppRestPostClientImpl(Post.class); } public AppRestUserClientImpl getUserRestClient() { return new AppRestUserClientImpl(User.class); } }
true
129eb2384f9866eb69e630c05222f78b175a5d01
Java
AnchaSravani/Tauria-Assignment
/TestScenarios/src/main/java/Utils/LoadPropertiesFile.java
UTF-8
551
2.375
2
[]
no_license
package Utils; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class LoadPropertiesFile { public static Properties prop ; public void Load() throws IOException { prop =new Properties(); try { String s= Utils.getRootDir(); prop.load(new FileInputStream( s+"\\config.properties")); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
true
ad8467b28bf498de265530e9b6d5aef004f0a055
Java
AMEYA4TECH/LoginAppDemo
/src/com/service/impl/PostServiceImpl.java
UTF-8
4,110
2.21875
2
[]
no_license
package com.service.impl; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import com.ExternalAPIResponse; import com.Product; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.service.PostService; public class PostServiceImpl implements PostService{ Product product = null; //AccessBean accessBean = null; private Logger _LOGGER = Logger.getLogger(getClass()); //AccessBean accessBean1 = null; private RestTemplate restTemplateClass; private String postApiURL; ExternalAPIResponse extRespose=null; @Override public ExternalAPIResponse postProduct(String authToken, Product product) { try { ObjectMapper mapper = new ObjectMapper(); _LOGGER.info("Product Data : " + mapper.writeValueAsString(product)); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); //headers.add("AuthToken",authToken); //headers.add("Authorization", scheme + " " + authToken); Map<String, Object> body = new HashMap<String, Object>(); body.put("AuthToken", authToken); body.put("Product", product); //body.put("Password", log.getPassword()); //HttpEntity<Product> requestEntity = new HttpEntity<>(product, headers); HttpEntity<?> requestEntity = new HttpEntity<Object>(body, headers); // ResponseEntity<?> response = restTemplate.postForObject(productSearchUrl, product, ResponseEntity.class); _LOGGER.info("Posting product to RADAR on url: " + postApiURL); ResponseEntity<Object> response = restTemplateClass.exchange(postApiURL, HttpMethod.POST, requestEntity, Object.class); _LOGGER.info("Result : " + response); extRespose= (ExternalAPIResponse) response.getBody();//getExternalAPIResponse("Product Saved successfully", HttpStatus.OK, null); } catch (HttpClientErrorException hce) { _LOGGER.error("Exception while posting product to Radar API", hce); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return extRespose; } private ExternalAPIResponse getExternalAPIResponse(String message, HttpStatus statusCode, Set<String> additionalInfo) { ExternalAPIResponse response = new ExternalAPIResponse(); if (statusCode != null && message != null && message.toLowerCase().startsWith("{\"Message\":\"Not Valid".toLowerCase())) { response.setMessage("Product saved successfully but not active"); response.setStatusCode(HttpStatus.OK); } else { response.setStatusCode(statusCode); response.setMessage(message); } response.setAdditionalInfo(additionalInfo); return response; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public RestTemplate getRestTemplateClass() { return restTemplateClass; } public void setRestTemplateClass(RestTemplate restTemplateClass) { this.restTemplateClass = restTemplateClass; } public String getPostApiURL() { return postApiURL; } public void setPostApiURL(String postApiURL) { this.postApiURL = postApiURL; } }
true
b3cdf85aacc84527744f22930551f7247aa64275
Java
nyh9704/zzz
/src/java/com/wyzc/htgl/controller/ChannelHouseController.java
UTF-8
3,890
1.898438
2
[]
no_license
package com.wyzc.htgl.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.wyzc.htgl.bo.houseTableBo; import com.wyzc.htgl.po.ChannelHousePo; import com.wyzc.htgl.po.ChannelHousePo2; import com.wyzc.htgl.service.ChannelHouseService; @Controller public class ChannelHouseController { @Autowired private ChannelHouseService chs; /* * 分页查询 */ @RequestMapping("/showChannelHouse") public Map<String, Object> showChannelHouse(ChannelHousePo po, ChannelHousePo2 po2) { Map<String, Object> map = new HashMap<>(); try { map = this.chs.showChannelHouse(po, po2); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } /* * 新增 */ @RequestMapping("/addChannelHouse") public Map<String, Object> addChannelHouse(ChannelHousePo po) { Map<String, Object> map = new HashMap<>(); try { map = this.chs.addChannelHouse(po); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } /* * 新增 */ @RequestMapping("/modifyChannelHouse") public Map<String, Object> modifyChannelHouse(ChannelHousePo po) { Map<String, Object> map = new HashMap<>(); try { map = this.chs.modifyChannelHouse(po); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } /* * 修改回显 */ @RequestMapping("/searchModifyChannelXq") public Map<String, Object> searchModifyChannelXq(ChannelHousePo po) { Map<String, Object> map = new HashMap<>(); try { map = this.chs.searchModifyChannelXq(po); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } /** * 删除 */ @RequestMapping("/deleteCode") public Map<String, Object> deleteCode(ChannelHousePo po) { Map<String, Object> map = new HashMap<>(); try { map = this.chs.deleteCode(po); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } /** * 展示详情 */ @RequestMapping("/showChannelHouseXq") public Map<String, Object> showChannelHouseXq(ChannelHousePo po) { Map<String, Object> map = new HashMap<>(); try { map = this.chs.showChannelHouseXq(po); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } /** * 展示详情 */ @RequestMapping("/deleteChannelMoreHouse") public Map<String, Object> deleteChannelMoreHouse(ChannelHousePo po) { Map<String, Object> map = new HashMap<>(); try { map = this.chs.deleteChannelMoreHouse(po); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } /** * 查询是否渠道部 */ @RequestMapping("/searchQd") public Map<String, Object> searchQd(ChannelHousePo po) { Map<String, Object> map = new HashMap<>(); try { map = this.chs.searchQd(po); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return map; } }
true