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
06773727fa8c164af2548cf3f5aa25d1de83f8ca
Java
uol-jdb50/CampusFood
/code/CampusFood/app/src/main/java/uol/co4224/campusfood/CampusSelect.java
UTF-8
5,852
2.078125
2
[]
no_license
package uol.co4224.campusfood; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import org.json.JSONArray; import org.json.JSONException; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class CampusSelect extends AppCompatActivity implements RecyclerViewAdapterString.ItemClickListener, ApiResponse { Button btnAllergen; Button btnOrders; RecyclerView recyclerView; RecyclerViewAdapterString adapter; ApiRetrieval apiRetrieval = new ApiRetrieval(); List<String> campuses = new ArrayList<>(); String userid = ""; int allergenMatrix = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_campus_select); getSupportActionBar().setTitle("CampusFood | Select a Campus"); userid = checkUserExists(); btnAllergen = (Button) findViewById(R.id.btnAllergens); btnAllergen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { viewAllergens(v); } }); btnOrders = (Button) findViewById(R.id.btnOrders); btnOrders.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { viewOrders(v); } }); // Campus List apiRetrieval.delegate = this; apiRetrieval.execute("campuses"); } @Override public void onItemClick(View view, int position, int request) { Intent i = new Intent(this, LocationSelect.class); i.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); i.putExtra("CAMPUS", campuses.get(position)); i.putExtra("USER", userid); i.putExtra("ALLERGEN", allergenMatrix); startActivity(i); } @Override public void processFinish(String response) { campuses = processResult(response); recyclerView = findViewById(R.id.campusList); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new RecyclerViewAdapterString(this, campuses); adapter.setClickListener(this); recyclerView.setAdapter(adapter); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { allergenMatrix = data.getIntExtra("ALLERGEN", 0); try { File file2 = new File(this.getFilesDir(), "allergen.txt"); BufferedWriter writer2 = new BufferedWriter(new FileWriter(file2, false)); writer2.write(Integer.toString(allergenMatrix)); writer2.close(); } catch (Exception e) { e.printStackTrace(); } } } public List<String> processResult(String json) { List<String> output = new ArrayList<>(); try { JSONArray obj = new JSONArray(json); for (int i = 0; i < obj.length(); i++) { output.add((String) obj.getJSONObject(i).get("CampusName")); } } catch (JSONException e) { e.printStackTrace(); } return output; } public void viewAllergens(View v) { Intent i = new Intent(this, UserSettingsActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); i.putExtra("ALLERGEN", allergenMatrix); startActivityForResult(i, 1); } public void viewOrders(View v) { Intent i = new Intent(this, OrdersActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); i.putExtra("USER", userid); startActivity(i); } public String checkUserExists() { String user = ""; BufferedReader br; try { File file = new File(this.getFilesDir(), "user.txt"); if (!file.exists()) { file.createNewFile(); } br = new BufferedReader(new FileReader(new File(this.getFilesDir(), "user.txt"))); String line; while ((line = br.readLine()) != null) { user = line; } if (user.equals("")) { user = UUID.randomUUID().toString(); BufferedWriter writer = new BufferedWriter(new FileWriter(file, false)); writer.write(user); writer.close(); System.out.println("New user: " + user); } else { System.out.println("Current user found: " + user); } } catch (Exception e) { e.printStackTrace(); } try { File file2 = new File(this.getFilesDir(), "allergen.txt"); if (!file2.exists()) { file2.createNewFile(); } br = new BufferedReader(new FileReader(new File(this.getFilesDir(), "allergen.txt"))); String line2; while ((line2 = br.readLine()) != null) { allergenMatrix = Integer.parseInt(line2); } if (allergenMatrix == 0) { BufferedWriter writer2 = new BufferedWriter(new FileWriter(file2, false)); writer2.write("0"); writer2.close(); } } catch (Exception e) { e.printStackTrace(); } return user; } }
true
56d0ce24f6af63661c9c7febfd8fb589d6e54581
Java
wuhuaqing/PromoteProject
/app/src/main/java/com/example/promoteproject/bean/LoginReq.java
UTF-8
500
2.15625
2
[ "Apache-2.0" ]
permissive
package com.example.promoteproject.bean; import retrofit2.http.Field; public class LoginReq { String identifier ; String workNum; String password; int softWareType; int version; public LoginReq(String identifier, String workNum, String password, int softWareType, int version) { this.identifier = identifier; this.workNum = workNum; this.password = password; this.softWareType = softWareType; this.version = version; } }
true
b5b1038cc7b7f8d5ce91a2116103f21a5ddfde54
Java
datasphere-oss/datasphere-mdm
/org.datasphere.mdm.data/src/main/java/org/datasphere/mdm/data/dto/RelationsBulkResultDTO.java
UTF-8
2,893
1.859375
2
[]
no_license
package org.datasphere.mdm.data.dto; import java.util.Collections; import java.util.List; import java.util.Objects; import org.datasphere.mdm.system.type.pipeline.batch.BatchedPipelineOutput; import org.datasphere.mdm.system.type.pipeline.fragment.FragmentId; import org.datasphere.mdm.system.type.pipeline.fragment.OutputFragment; /** * The all-in-one bulk ops result transfer object. * @author Dmitry Kopin on 14.02.2019. */ public class RelationsBulkResultDTO extends AbstractBulkResultDTO implements BatchedPipelineOutput, OutputFragment<RelationsBulkResultDTO> { /** * The id. */ public static final FragmentId<RelationsBulkResultDTO> ID = new FragmentId<>("RELATIONS_BULK_RESULT"); /** * Upserted rels info. */ private List<UpsertRelationsDTO> upsertRelations; /** * Deleted rels info. */ private List<DeleteRelationsDTO> deleteRelations; /** * Merged rels info. */ private List<MergeRelationsDTO> mergeRelations; /** * Merged rels info. */ private List<RestoreRelationsDTO> restoreRelations; /** * Gets rels upserts. * @return upserts */ public List<UpsertRelationsDTO> getUpsertRelations() { return Objects.isNull(upsertRelations) ? Collections.emptyList() : upsertRelations; } /** * Sets rels upserts. * @param relations */ public void setUpsertRelations(List<UpsertRelationsDTO> relations) { this.upsertRelations = relations; } /** * Gets rel deletes. * @return deletes */ public List<DeleteRelationsDTO> getDeleteRelations() { return Objects.isNull(deleteRelations) ? Collections.emptyList() : deleteRelations; } /** * Sets rels deletes. * @param deleteRelations */ public void setDeleteRelations(List<DeleteRelationsDTO> deleteRelations) { this.deleteRelations = deleteRelations; } /** * @return the mergeRelations */ public List<MergeRelationsDTO> getMergeRelations() { return Objects.isNull(mergeRelations) ? Collections.emptyList() : mergeRelations; } /** * @param mergeRelations the mergeRelations to set */ public void setMergeRelations(List<MergeRelationsDTO> mergeRelations) { this.mergeRelations = mergeRelations; } /** * @return the restoreRelations */ public List<RestoreRelationsDTO> getRestoreRelations() { return Objects.isNull(restoreRelations) ? Collections.emptyList() : restoreRelations; } /** * @param restoreRelations the restoreRelations to set */ public void setRestoreRelations(List<RestoreRelationsDTO> restoreRelations) { this.restoreRelations = restoreRelations; } /** * {@inheritDoc} */ @Override public FragmentId<RelationsBulkResultDTO> fragmentId() { return ID; } }
true
fff48e997a1a4c173ffd7a067d42ec78116609d5
Java
babyheros/mayberun
/app/src/main/java/com/finalexam/bottom/WechatShareManager.java
UTF-8
3,684
2.328125
2
[]
no_license
package com.finalexam.bottom; import android.content.Context; import com.tencent.mm.sdk.modelmsg.SendMessageToWX; import com.tencent.mm.sdk.modelmsg.WXMediaMessage; import com.tencent.mm.sdk.modelmsg.WXTextObject; import com.tencent.mm.sdk.openapi.WXAPIFactory; /** * 实现微信分享功能的核心类 * @author chengcj1 * */ public class WechatShareManager { private static final int THUMB_SIZE = 150; public static final int WECHAT_SHARE_WAY_TEXT = 1; //文字 private static WechatShareManager mInstance; private ShareContent mShareContentText; private Context mContext; private WechatShareManager(Context context){ this.mContext = context; //初始化数据 //初始化微信分享代码 initWechatShare(context); } /** * 获取WeixinShareManager实例 * 非线程安全,请在UI线程中操作 * @return */ public static WechatShareManager getInstance(Context context){ if(mInstance == null){ mInstance = new WechatShareManager(context); } return mInstance; } private void initWechatShare(Context context){ if (Constants.wx_api == null) { Constants.wx_api = WXAPIFactory.createWXAPI(context, Constants.APP_ID, true); } Constants.wx_api.registerApp(Constants.APP_ID); } public void shareByWebchat(ShareContent shareContent){ switch (shareContent.getShareWay()) { case WECHAT_SHARE_WAY_TEXT: shareText(shareContent); break; } } private abstract class ShareContent { protected abstract int getShareWay(); protected abstract String getContent(); protected abstract String getTitle(); } /** * 设置分享文字的内容 * @author chengcj1 * */ public class ShareContentText extends ShareContent { private String content; public ShareContentText(String content){ this.content = content; } @Override protected int getShareWay() { return WECHAT_SHARE_WAY_TEXT; } @Override protected String getContent() { return content; } @Override protected String getTitle() { return null; } } /* * 获取文本分享对象 */ public ShareContent getShareContentText(String content) { if (mShareContentText == null) { mShareContentText = new ShareContentText(content); } return (ShareContentText) mShareContentText; } /* * 分享文字 */ private void shareText(ShareContent shareContent) { String text = shareContent.getContent(); //初始化一个WXTextObject对象 WXTextObject textObj = new WXTextObject(); textObj.text = text; //用WXTextObject对象初始化一个WXMediaMessage对象 WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = textObj; msg.description = text; //构造一个Req SendMessageToWX.Req req = new SendMessageToWX.Req(); //transaction字段用于唯一标识一个请求 req.transaction = buildTransaction("textshare"); req.message = msg; //发送的目标场景, 可以选择发送到会话 WXSceneSession 或者朋友圈 WXSceneTimeline。 默认发送到会话。 Constants.wx_api.sendReq(req); } private String buildTransaction(final String type) { return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis(); } }
true
5681543251aa29c1be7f52baa257756f7b883fde
Java
9553432712/sadarem
/src/org/bf/disability/form/TerritoryForm.java
UTF-8
75,917
1.617188
2
[]
no_license
/* * TerritoryForm.java * * Created on June 18, 2008, 3:33 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.bf.disability.form; import java.util.ArrayList; import java.util.ArrayList; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionFormBean; import org.apache.struts.action.ActionMapping; import org.bf.disability.dto.TerritoryDTO; /** * This class contains the fields, used is terrtory selection module * @version 1.0 */ public class TerritoryForm extends ActionForm { private String district_id; private String assembly_id; private String physiotheraphy; private String occupationaltherapy; private String occupationaltheraphy; private String aadharcardNumber; public String getAadharcardNumber() { return aadharcardNumber; } public void setAadharcardNumber(String aadharcardNumber) { this.aadharcardNumber = aadharcardNumber; } public String getOccupationaltheraphy() { return occupationaltheraphy; } public void setOccupationaltheraphy(String occupationaltheraphy) { this.occupationaltheraphy = occupationaltheraphy; } private String selectwheelchair = null; private String selecttricycle = null; private String selectwalkingstick = null; private String selectcrutches = null; private String crutchestype = null; private String selectwalkingframe; private String aeroplanesplint; private String figure8splint; private String forearmsplint; private String handsplint; private String shoulderprosthesis; private String aboveelbowprosthesis; private String elbowdisarticulationprosthesis; private String belowelbowprosthesis; private String wristdisarticulationprosthesis; private String handprosthesis; private String cosmeticfingerprosthesis; private String hkafo; private String kafo; private String afo; private String kneeorthosis; private String dbsplint; private String modifiedshoe; private String serialcasting; private String hipprothesis; private String rationCardNo; private String flag; public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } public String getRationCardNo() { return rationCardNo; } public void setRationCardNo(String rationCardNo) { this.rationCardNo = rationCardNo; } public String getAboveelbowprosthesis() { return aboveelbowprosthesis; } public void setAboveelbowprosthesis(String aboveelbowprosthesis) { this.aboveelbowprosthesis = aboveelbowprosthesis; } public String getAbovekneeprothesis() { return abovekneeprothesis; } public void setAbovekneeprothesis(String abovekneeprothesis) { this.abovekneeprothesis = abovekneeprothesis; } public String getAeroplanesplint() { return aeroplanesplint; } public void setAeroplanesplint(String aeroplanesplint) { this.aeroplanesplint = aeroplanesplint; } public String getAfo() { return afo; } public void setAfo(String afo) { this.afo = afo; } public String getAnyotherinlocomotor() { return anyotherinlocomotor; } public void setAnyotherinlocomotor(String anyotherinlocomotor) { this.anyotherinlocomotor = anyotherinlocomotor; } public String getBathing() { return bathing; } public void setBathing(String bathing) { this.bathing = bathing; } public String getBedtransfer() { return bedtransfer; } public void setBedtransfer(String bedtransfer) { this.bedtransfer = bedtransfer; } public String getBelowelbowprosthesis() { return belowelbowprosthesis; } public void setBelowelbowprosthesis(String belowelbowprosthesis) { this.belowelbowprosthesis = belowelbowprosthesis; } public String getBelowkneeprothesis() { return belowkneeprothesis; } public void setBelowkneeprothesis(String belowkneeprothesis) { this.belowkneeprothesis = belowkneeprothesis; } public String getBrushing() { return brushing; } public void setBrushing(String brushing) { this.brushing = brushing; } public String getCervicalcollar() { return cervicalcollar; } public void setCervicalcollar(String cervicalcollar) { this.cervicalcollar = cervicalcollar; } public String getCombing() { return combing; } public void setCombing(String combing) { this.combing = combing; } public String getCosmeticfingerprosthesis() { return cosmeticfingerprosthesis; } public void setCosmeticfingerprosthesis(String cosmeticfingerprosthesis) { this.cosmeticfingerprosthesis = cosmeticfingerprosthesis; } public String getCrutchestype() { return crutchestype; } public void setCrutchestype(String crutchestype) { this.crutchestype = crutchestype; } public String getDbsplint() { return dbsplint; } public void setDbsplint(String dbsplint) { this.dbsplint = dbsplint; } public String getDressing() { return dressing; } public void setDressing(String dressing) { this.dressing = dressing; } public String getDrivingcycling() { return drivingcycling; } public void setDrivingcycling(String drivingcycling) { this.drivingcycling = drivingcycling; } public String getElbowdisarticulationprosthesis() { return elbowdisarticulationprosthesis; } public void setElbowdisarticulationprosthesis(String elbowdisarticulationprosthesis) { this.elbowdisarticulationprosthesis = elbowdisarticulationprosthesis; } public String getFeeding() { return feeding; } public void setFeeding(String feeding) { this.feeding = feeding; } public String getFigure8splint() { return figure8splint; } public void setFigure8splint(String figure8splint) { this.figure8splint = figure8splint; } public String getForearmsplint() { return forearmsplint; } public void setForearmsplint(String forearmsplint) { this.forearmsplint = forearmsplint; } public String getHandprosthesis() { return handprosthesis; } public void setHandprosthesis(String handprosthesis) { this.handprosthesis = handprosthesis; } public String getHandsplint() { return handsplint; } public void setHandsplint(String handsplint) { this.handsplint = handsplint; } public String getHipprothesis() { return hipprothesis; } public void setHipprothesis(String hipprothesis) { this.hipprothesis = hipprothesis; } public String getHkafo() { return hkafo; } public void setHkafo(String hkafo) { this.hkafo = hkafo; } public String getKafo() { return kafo; } public void setKafo(String kafo) { this.kafo = kafo; } public String getKneedisarticulation() { return kneedisarticulation; } public void setKneedisarticulation(String kneedisarticulation) { this.kneedisarticulation = kneedisarticulation; } public String getKneeorthosis() { return kneeorthosis; } public void setKneeorthosis(String kneeorthosis) { this.kneeorthosis = kneeorthosis; } public String getLsbrace() { return lsbrace; } public void setLsbrace(String lsbrace) { this.lsbrace = lsbrace; } public String getModifiedshoe() { return modifiedshoe; } public void setModifiedshoe(String modifiedshoe) { this.modifiedshoe = modifiedshoe; } public String getOccupationaltherapy() { return occupationaltherapy; } public void setOccupationaltherapy(String occupationaltherapy) { this.occupationaltherapy = occupationaltherapy; } public String getPartialfoodprothesis() { return partialfoodprothesis; } public void setPartialfoodprothesis(String partialfoodprothesis) { this.partialfoodprothesis = partialfoodprothesis; } public String getPhysiotheraphy() { return physiotheraphy; } public void setPhysiotheraphy(String physiotheraphy) { this.physiotheraphy = physiotheraphy; } public String getSelectcrutches() { return selectcrutches; } public void setSelectcrutches(String selectcrutches) { this.selectcrutches = selectcrutches; } public String getSelecttricycle() { return selecttricycle; } public void setSelecttricycle(String selecttricycle) { this.selecttricycle = selecttricycle; } public String getSelectwalkingframe() { return selectwalkingframe; } public void setSelectwalkingframe(String selectwalkingframe) { this.selectwalkingframe = selectwalkingframe; } public String getSelectwalkingstick() { return selectwalkingstick; } public void setSelectwalkingstick(String selectwalkingstick) { this.selectwalkingstick = selectwalkingstick; } public String getSelectwheelchair() { return selectwheelchair; } public void setSelectwheelchair(String selectwheelchair) { this.selectwheelchair = selectwheelchair; } public String getSerialcasting() { return serialcasting; } public void setSerialcasting(String serialcasting) { this.serialcasting = serialcasting; } public String getShoulderprosthesis() { return shoulderprosthesis; } public void setShoulderprosthesis(String shoulderprosthesis) { this.shoulderprosthesis = shoulderprosthesis; } public String getSymeprothesis() { return symeprothesis; } public void setSymeprothesis(String symeprothesis) { this.symeprothesis = symeprothesis; } public String getTlsobrace() { return tlsobrace; } public void setTlsobrace(String tlsobrace) { this.tlsobrace = tlsobrace; } public String getWristdisarticulationprosthesis() { return wristdisarticulationprosthesis; } public void setWristdisarticulationprosthesis(String wristdisarticulationprosthesis) { this.wristdisarticulationprosthesis = wristdisarticulationprosthesis; } public String getWriting() { return writing; } public void setWriting(String writing) { this.writing = writing; } private String abovekneeprothesis; private String kneedisarticulation; private String belowkneeprothesis; private String symeprothesis; private String partialfoodprothesis; private String cervicalcollar; private String lsbrace; private String tlsobrace; private String feeding; private String bathing; private String brushing; private String combing; private String dressing; private String writing; private String drivingcycling; private String bedtransfer; private String anyotherinlocomotor = null; private String mandal_id; private String village_id; private String panchayat_id; private String panchayat_name; private String village_name; private String district_name; private String mandal_name; private String habitation_id; private String habitation_name; private String personcode; private ArrayList personcodelist = new ArrayList(); private ArrayList districtlist = new ArrayList(); private ArrayList districtList = new ArrayList(); private ArrayList assemblylist = new ArrayList(); private ArrayList mandallist = new ArrayList(); private ArrayList panchayatlist = new ArrayList(); private ArrayList villagelist = new ArrayList(); private ArrayList habitationlist = new ArrayList(); private String UpperExtremity_Total; private String LowerExtremity_Total; private String Amputation_Total; private String Transverse_Total; private String Trunk_Total; private String Physical_Impairments_Total; private String Pulmonary_Condition; private String Dwarfism_Total; private String Mental_Disability_Total; private String Mental_Retardation_Total; private String Visual_Impairment; private String Hearing_Percentage; private String personid; private String surname; private String lastname; private String firstname; private String gender; private String relationname; private String name; private String age; private String conditionofdisability; private String conditionimprove; private String reassessmentrecommended; private int reassessmentyears; private int reassessmentmonth; private String othercause; private String congenital; private String hereditary; private String birthinjury; private String duseaseandinfection; private String malnutrition; private String accident; private String disabilitytype; private double disabilityvalue; private double locomotortotal; private String housenumber; private String hospitalname; private String hospitaladdress; private String dateofisse; private String dateofbirth; private String firstdoctorname; private String firstdoctornumber; private String firstdesgination; private String seconddoctorname; private String seconddoctornumber; private String seconddesgination; private String moleone; private String moletwo; private String thirddoctorname; private String thirddoctornumber; private String thirddesgination; private String telugupersonname; private String telugufathername; private String relationship; private String disabilityintellec; private String disabilitySubIds; private String disabilitySubIds1; private String disabilitySubIds2; private String disabilitySubIds3; private String disabilitySubIds4; private String disabilitySubIds5; private String disabilitySubIds6; private String disabilitySubIds7; private String disabilitySubIds8; private String disabilitySubIds9; private String disabilitySubIds10; private String disabilitySubIds11; private String disabilitySubIds12; private String disabilitySubIds13; private String disabilitySubIds14; private String disabilitySubIds15; private String disabilitySubIds16; private String disabilitySubIds17; private String disabilitySubIds18; private String disabilitySubIds19; private String disabilitySubIds20; private String disabilitySubIds21; private String disabilitySubIds22; private String disabilitySubIds23; private String disabilitySubIds24; private String disabilitySubIds25; private String disabilitySubIds26; private String disabilitySubIds27; private String disabilitySubIds28; private String disabilitySubIds29; private String disabilitySubIds30; private String disabilitySubIds31; private String disabilitySubSubIds; private String disabilitySubSubIds1; private String disabilitySubSubIds2; private String disabilitySubSubIds3; private String disabilitySubSubIds4; private String disabilitySubSubIds5; private String disabilitySubSubIds6; private String disabilitySubSubIds7; private String disabilitySubSubIds8; private String disabilitySubSubIds9; private String disabilitySubSubIds10; private String typeofdisability; // Analysis report private String reportcategory; private String reportSubcategory; private String disabilityreason; private String disabilityduration; //Added BY Raghavendra for DailyReports date wise private String belowfourtyforphysical = "0"; private String fourtytosixtyforphysical = "0"; private String sixtytoeightyforphysical = "0"; private String aboveeightyoneforphysical = "0"; private String totalforphysical = "0"; private String belowfourtyforvisual = "0"; private String fourtytosixtyforvisual = "0"; private String sixtyonetoeightyforvisual = "0"; private String aboveeightyoneforvisual = "0"; private String belowfourtyforhearing = "0"; private String fourtytosixtyforhearing = "0"; private String sixtyonetoeightyforhearing = "0"; private String aboveeightyoneforhearing = "0"; private String totalforhearing = "0"; private String belowfourtyformentalretardation = "0"; private String fourtytosixtyformentalretardation = "0"; private String sixtyonetoeightyformentalretardation = "0"; private String aboveeightyoneformentalretardation = "0"; private String totalformentalretardation = "0"; private String totalforvisual = "0"; private String belowfourtyformentalillness = "0"; private String fourtytosixtyformentalillness = "0"; private String sixtyonetoeightyformentalillness = "0"; private String aboveeightyoneformentalillness = "0"; private String totalformentalillness = "0"; private String belowfourtyformultipledisability = "0"; private String fourtytosixtyformultipledisability = "0"; private String sixtyonetoeightyformultipledisability = "0"; private String aboveeightyoneformultipledisability = "0"; private String totalformultipledisability = "0"; private String totaldisability = "0"; private String fromdate; private String todate; private String belowfourtypercent = "0"; private String fourtypercent = "0"; private String fourtytosixtypercent = "0"; private String sixtyonetoeightypercent = "0"; private String aboveeightyonepercent = "0"; private String disabledpensioners = "0"; private String noofpersonsassessed = "0"; private String noofpersonsrejected = "0"; private String personsassesedbelowfourty = "0"; private String personsassesedfourtytosixty = "0"; private String personsassesedsixtytoeighty = "0"; private String personsassesedaboveeighty = "0"; private String rejectedpersonscount = "0"; private String assessedandrejectedtotal = "0"; //END BY Raghavendra for DailyReports date wise private String personstatus; // Death case private String status; private String period; private String kindofdisability; private String surgery; private String physiotherapy; private String councelling; private String anyother; private String referredto; private String surgeryforrejected; private String councellingandguidance; private String speechtherapy; private String hearingaid; private String behaviourmodification; private String phychotherapy; private String admissioninpsychiatrichospital; private String Physiotherapyforreject; private String lowvisionaid; private String anyotherneed; private boolean brFlag; private String validity; private String genderInitial1; private String genderInitial2; private String percentageInWord; private int disabilityPercentage; private String multipleRadio; private String disabilityId; private boolean railwaycertificate; private String teluguDisabilityName; private String comment = null; private String ohcondition1; private String ohcondition2; private String ohcondition3; private String ohcondition4; private String ohcondition5; private String ohcondition6; private String ohcondition7; private String ohcondition8; private String ohcondition9; private String ohcondition10; private String ohcondition11; private String differenceFlag; private String user_name; private String sadaremId; private String parentsName; public ArrayList getDistrictList() { return districtList; } public void setDistrictList(ArrayList districtList) { this.districtList = districtList; } public String getParentsName() { return parentsName; } public void setParentsName(String parentsName) { this.parentsName = parentsName; } public String getSadaremId() { return sadaremId; } public void setSadaremId(String sadaremId) { this.sadaremId = sadaremId; } public TerritoryForm() { } public String getDistrict_id() { return district_id; } public void setDistrict_id(String district_id) { this.district_id = district_id; } public String getMandal_id() { return mandal_id; } public void setMandal_id(String mandal_id) { this.mandal_id = mandal_id; } public String getVillage_id() { return village_id; } public void setVillage_id(String village_id) { this.village_id = village_id; } public String getPanchayat_id() { return panchayat_id; } public void setPanchayat_id(String panchayat_id) { this.panchayat_id = panchayat_id; } public String getPanchayat_name() { return panchayat_name; } public void setPanchayat_name(String panchayat_name) { this.panchayat_name = panchayat_name; } public String getVillage_name() { return village_name; } public void setVillage_name(String village_name) { this.village_name = village_name; } public String getDistrict_name() { return district_name; } public void setDistrict_name(String district_name) { this.district_name = district_name; } public String getMandal_name() { return mandal_name; } public void setMandal_name(String mandal_name) { this.mandal_name = mandal_name; } public String getHabitation_id() { return habitation_id; } public void setHabitation_id(String habitation_id) { this.habitation_id = habitation_id; } public String getHabitation_name() { return habitation_name; } public void setHabitation_name(String habitation_name) { this.habitation_name = habitation_name; } public ArrayList getDistrictlist() { return districtlist; } public void setDistrictlist(ArrayList districtlist) { this.districtlist = districtlist; } public ArrayList getMandallist() { return mandallist; } public void setMandallist(ArrayList mandallist) { this.mandallist = mandallist; } public ArrayList getPanchayatlist() { return panchayatlist; } public void setPanchayatlist(ArrayList panchayatlist) { this.panchayatlist = panchayatlist; } public ArrayList getVillagelist() { return villagelist; } public void setVillagelist(ArrayList villagelist) { this.villagelist = villagelist; } public ArrayList getHabitationlist() { return habitationlist; } public void setHabitationlist(ArrayList habitationlist) { this.habitationlist = habitationlist; } public void reset(ActionMapping mapping, HttpServletRequest request) { // this.districtlist=null ; // this.mandallist=null; // this.panchayatlist=null; // this.villagelist=null; // this.habitationlist=null; // // this. district_id=null; // this. mandal_id=null; // this. village_id=null; // this. panchayat_id=null; // this. panchayat_name=null; // this. village_name=null; // this. district_name=null; // this. mandal_name=null; // this. habitation_id=null; // this. habitation_name=null; } public String getPersoncode() { return personcode; } public void setPersoncode(String personcode) { this.personcode = personcode; } public ArrayList getPersoncodelist() { return personcodelist; } public void setPersoncodelist(ArrayList personcodelist) { this.personcodelist = personcodelist; } public String getUpperExtremity_Total() { return UpperExtremity_Total; } public void setUpperExtremity_Total(String UpperExtremity_Total) { this.UpperExtremity_Total = UpperExtremity_Total; } public String getLowerExtremity_Total() { return LowerExtremity_Total; } public void setLowerExtremity_Total(String LowerExtremity_Total) { this.LowerExtremity_Total = LowerExtremity_Total; } public String getAmputation_Total() { return Amputation_Total; } public void setAmputation_Total(String Amputation_Total) { this.Amputation_Total = Amputation_Total; } public String getTransverse_Total() { return Transverse_Total; } public void setTransverse_Total(String Transverse_Total) { this.Transverse_Total = Transverse_Total; } public String getTrunk_Total() { return Trunk_Total; } public void setTrunk_Total(String Trunk_Total) { this.Trunk_Total = Trunk_Total; } public String getPhysical_Impairments_Total() { return Physical_Impairments_Total; } public void setPhysical_Impairments_Total(String Physical_Impairments_Total) { this.Physical_Impairments_Total = Physical_Impairments_Total; } public String getPulmonary_Condition() { return Pulmonary_Condition; } public void setPulmonary_Condition(String Pulmonary_Condition) { this.Pulmonary_Condition = Pulmonary_Condition; } public String getDwarfism_Total() { return Dwarfism_Total; } public void setDwarfism_Total(String Dwarfism_Total) { this.Dwarfism_Total = Dwarfism_Total; } public String getMental_Disability_Total() { return Mental_Disability_Total; } public void setMental_Disability_Total(String Mental_Disability_Total) { this.Mental_Disability_Total = Mental_Disability_Total; } public String getMental_Retardation_Total() { return Mental_Retardation_Total; } public void setMental_Retardation_Total(String Mental_Retardation_Total) { this.Mental_Retardation_Total = Mental_Retardation_Total; } public String getVisual_Impairment() { return Visual_Impairment; } public void setVisual_Impairment(String Visual_Impairment) { this.Visual_Impairment = Visual_Impairment; } public String getHearing_Percentage() { return Hearing_Percentage; } public void setHearing_Percentage(String Hearing_Percentage) { this.Hearing_Percentage = Hearing_Percentage; } public String getPersonid() { return personid; } public void setPersonid(String personid) { this.personid = personid; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getRelationname() { return relationname; } public void setRelationname(String relationname) { this.relationname = relationname; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getConditionofdisability() { return conditionofdisability; } public void setConditionofdisability(String conditionofdisability) { this.conditionofdisability = conditionofdisability; } public String getConditionimprove() { return conditionimprove; } public void setConditionimprove(String conditionimprove) { this.conditionimprove = conditionimprove; } public String getReassessmentrecommended() { return reassessmentrecommended; } public void setReassessmentrecommended(String reassessmentrecommended) { this.reassessmentrecommended = reassessmentrecommended; } public int getReassessmentyears() { return reassessmentyears; } public void setReassessmentyears(int reassessmentyears) { this.reassessmentyears = reassessmentyears; } public int getReassessmentmonth() { return reassessmentmonth; } public void setReassessmentmonth(int reassessmentmonth) { this.reassessmentmonth = reassessmentmonth; } public String getOthercause() { return othercause; } public void setOthercause(String othercause) { this.othercause = othercause; } public String getCongenital() { return congenital; } public void setCongenital(String congenital) { this.congenital = congenital; } public String getHereditary() { return hereditary; } public void setHereditary(String hereditary) { this.hereditary = hereditary; } public String getBirthinjury() { return birthinjury; } public void setBirthinjury(String birthinjury) { this.birthinjury = birthinjury; } public String getDuseaseandinfection() { return duseaseandinfection; } public void setDuseaseandinfection(String duseaseandinfection) { this.duseaseandinfection = duseaseandinfection; } public String getMalnutrition() { return malnutrition; } public void setMalnutrition(String malnutrition) { this.malnutrition = malnutrition; } public String getAccident() { return accident; } public void setAccident(String accident) { this.accident = accident; } public String getDisabilitytype() { return disabilitytype; } public void setDisabilitytype(String disabilitytype) { this.disabilitytype = disabilitytype; } public double getDisabilityvalue() { return disabilityvalue; } public void setDisabilityvalue(double disabilityvalue) { this.disabilityvalue = disabilityvalue; } public String getHousenumber() { return housenumber; } public void setHousenumber(String housenumber) { this.housenumber = housenumber; } public String getHospitalname() { return hospitalname; } public void setHospitalname(String hospitalname) { this.hospitalname = hospitalname; } public String getHospitaladdress() { return hospitaladdress; } public void setHospitaladdress(String hospitaladdress) { this.hospitaladdress = hospitaladdress; } public double getLocomotortotal() { return locomotortotal; } public void setLocomotortotal(double locomotortotal) { this.locomotortotal = locomotortotal; } public String getDateofisse() { return dateofisse; } public void setDateofisse(String dateofisse) { this.dateofisse = dateofisse; } public String getDateofbirth() { return dateofbirth; } public void setDateofbirth(String dateofbirth) { this.dateofbirth = dateofbirth; } public String getFirstdoctorname() { return firstdoctorname; } public void setFirstdoctorname(String firstdoctorname) { this.firstdoctorname = firstdoctorname; } public String getFirstdoctornumber() { return firstdoctornumber; } public void setFirstdoctornumber(String firstdoctornumber) { this.firstdoctornumber = firstdoctornumber; } public String getFirstdesgination() { return firstdesgination; } public void setFirstdesgination(String firstdesgination) { this.firstdesgination = firstdesgination; } public String getSeconddoctorname() { return seconddoctorname; } public void setSeconddoctorname(String seconddoctorname) { this.seconddoctorname = seconddoctorname; } public String getSeconddoctornumber() { return seconddoctornumber; } public void setSeconddoctornumber(String seconddoctornumber) { this.seconddoctornumber = seconddoctornumber; } public String getSeconddesgination() { return seconddesgination; } public void setSeconddesgination(String seconddesgination) { this.seconddesgination = seconddesgination; } public String getMoleone() { return moleone; } public void setMoleone(String moleone) { this.moleone = moleone; } public String getMoletwo() { return moletwo; } public void setMoletwo(String moletwo) { this.moletwo = moletwo; } public String getThirddoctorname() { return thirddoctorname; } public void setThirddoctorname(String thirddoctorname) { this.thirddoctorname = thirddoctorname; } public String getThirddoctornumber() { return thirddoctornumber; } public void setThirddoctornumber(String thirddoctornumber) { this.thirddoctornumber = thirddoctornumber; } public String getThirddesgination() { return thirddesgination; } public void setThirddesgination(String thirddesgination) { this.thirddesgination = thirddesgination; } public String getTelugupersonname() { return telugupersonname; } public void setTelugupersonname(String telugupersonname) { this.telugupersonname = telugupersonname; } public String getTelugufathername() { return telugufathername; } public void setTelugufathername(String telugufathername) { this.telugufathername = telugufathername; } public String getRelationship() { return relationship; } public void setRelationship(String relationship) { this.relationship = relationship; } public String getDisabilityintellec() { return disabilityintellec; } public void setDisabilityintellec(String disabilityintellec) { this.disabilityintellec = disabilityintellec; } public String getTypeofdisability() { return typeofdisability; } public void setTypeofdisability(String typeofdisability) { this.typeofdisability = typeofdisability; } public String getDisabilityreason() { return disabilityreason; } public void setDisabilityreason(String disabilityreason) { this.disabilityreason = disabilityreason; } public String getDisabilityduration() { return disabilityduration; } public void setDisabilityduration(String disabilityduration) { this.disabilityduration = disabilityduration; } public String getBelowfourtyforphysical() { return belowfourtyforphysical; } public void setBelowfourtyforphysical(String belowfourtyforphysical) { this.belowfourtyforphysical = belowfourtyforphysical; } public String getFourtytosixtyforphysical() { return fourtytosixtyforphysical; } public void setFourtytosixtyforphysical(String fourtytosixtyforphysical) { this.fourtytosixtyforphysical = fourtytosixtyforphysical; } public String getSixtytoeightyforphysical() { return sixtytoeightyforphysical; } public void setSixtytoeightyforphysical(String sixtytoeightyforphysical) { this.sixtytoeightyforphysical = sixtytoeightyforphysical; } public String getAboveeightyoneforphysical() { return aboveeightyoneforphysical; } public void setAboveeightyoneforphysical(String aboveeightyoneforphysical) { this.aboveeightyoneforphysical = aboveeightyoneforphysical; } public String getTotalforphysical() { return totalforphysical; } public void setTotalforphysical(String totalforphysical) { this.totalforphysical = totalforphysical; } public String getBelowfourtyforvisual() { return belowfourtyforvisual; } public void setBelowfourtyforvisual(String belowfourtyforvisual) { this.belowfourtyforvisual = belowfourtyforvisual; } public String getFourtytosixtyforvisual() { return fourtytosixtyforvisual; } public void setFourtytosixtyforvisual(String fourtytosixtyforvisual) { this.fourtytosixtyforvisual = fourtytosixtyforvisual; } public String getSixtyonetoeightyforvisual() { return sixtyonetoeightyforvisual; } public void setSixtyonetoeightyforvisual(String sixtyonetoeightyforvisual) { this.sixtyonetoeightyforvisual = sixtyonetoeightyforvisual; } public String getAboveeightyoneforvisual() { return aboveeightyoneforvisual; } public void setAboveeightyoneforvisual(String aboveeightyoneforvisual) { this.aboveeightyoneforvisual = aboveeightyoneforvisual; } public String getBelowfourtyforhearing() { return belowfourtyforhearing; } public void setBelowfourtyforhearing(String belowfourtyforhearing) { this.belowfourtyforhearing = belowfourtyforhearing; } public String getFourtytosixtyforhearing() { return fourtytosixtyforhearing; } public void setFourtytosixtyforhearing(String fourtytosixtyforhearing) { this.fourtytosixtyforhearing = fourtytosixtyforhearing; } public String getSixtyonetoeightyforhearing() { return sixtyonetoeightyforhearing; } public void setSixtyonetoeightyforhearing(String sixtyonetoeightyforhearing) { this.sixtyonetoeightyforhearing = sixtyonetoeightyforhearing; } public String getAboveeightyoneforhearing() { return aboveeightyoneforhearing; } public void setAboveeightyoneforhearing(String aboveeightyoneforhearing) { this.aboveeightyoneforhearing = aboveeightyoneforhearing; } public String getTotalforhearing() { return totalforhearing; } public void setTotalforhearing(String totalforhearing) { this.totalforhearing = totalforhearing; } public String getBelowfourtyformentalretardation() { return belowfourtyformentalretardation; } public void setBelowfourtyformentalretardation(String belowfourtyformentalretardation) { this.belowfourtyformentalretardation = belowfourtyformentalretardation; } public String getFourtytosixtyformentalretardation() { return fourtytosixtyformentalretardation; } public void setFourtytosixtyformentalretardation(String fourtytosixtyformentalretardation) { this.fourtytosixtyformentalretardation = fourtytosixtyformentalretardation; } public String getSixtyonetoeightyformentalretardation() { return sixtyonetoeightyformentalretardation; } public void setSixtyonetoeightyformentalretardation(String sixtyonetoeightyformentalretardation) { this.sixtyonetoeightyformentalretardation = sixtyonetoeightyformentalretardation; } public String getAboveeightyoneformentalretardation() { return aboveeightyoneformentalretardation; } public void setAboveeightyoneformentalretardation(String aboveeightyoneformentalretardation) { this.aboveeightyoneformentalretardation = aboveeightyoneformentalretardation; } public String getTotalformentalretardation() { return totalformentalretardation; } public void setTotalformentalretardation(String totalformentalretardation) { this.totalformentalretardation = totalformentalretardation; } public String getBelowfourtyformentalillness() { return belowfourtyformentalillness; } public void setBelowfourtyformentalillness(String belowfourtyformentalillness) { this.belowfourtyformentalillness = belowfourtyformentalillness; } public String getFourtytosixtyformentalillness() { return fourtytosixtyformentalillness; } public void setFourtytosixtyformentalillness(String fourtytosixtyformentalillness) { this.fourtytosixtyformentalillness = fourtytosixtyformentalillness; } public String getSixtyonetoeightyformentalillness() { return sixtyonetoeightyformentalillness; } public void setSixtyonetoeightyformentalillness(String sixtyonetoeightyformentalillness) { this.sixtyonetoeightyformentalillness = sixtyonetoeightyformentalillness; } public String getAboveeightyoneformentalillness() { return aboveeightyoneformentalillness; } public void setAboveeightyoneformentalillness(String aboveeightyoneformentalillness) { this.aboveeightyoneformentalillness = aboveeightyoneformentalillness; } public String getTotalformentalillness() { return totalformentalillness; } public void setTotalformentalillness(String totalformentalillness) { this.totalformentalillness = totalformentalillness; } public String getBelowfourtyformultipledisability() { return belowfourtyformultipledisability; } public void setBelowfourtyformultipledisability(String belowfourtyformultipledisability) { this.belowfourtyformultipledisability = belowfourtyformultipledisability; } public String getFourtytosixtyformultipledisability() { return fourtytosixtyformultipledisability; } public void setFourtytosixtyformultipledisability(String fourtytosixtyformultipledisability) { this.fourtytosixtyformultipledisability = fourtytosixtyformultipledisability; } public String getSixtyonetoeightyformultipledisability() { return sixtyonetoeightyformultipledisability; } public void setSixtyonetoeightyformultipledisability(String sixtyonetoeightyformultipledisability) { this.sixtyonetoeightyformultipledisability = sixtyonetoeightyformultipledisability; } public String getAboveeightyoneformultipledisability() { return aboveeightyoneformultipledisability; } public void setAboveeightyoneformultipledisability(String aboveeightyoneformultipledisability) { this.aboveeightyoneformultipledisability = aboveeightyoneformultipledisability; } public String getTotalformultipledisability() { return totalformultipledisability; } public void setTotalformultipledisability(String totalformultipledisability) { this.totalformultipledisability = totalformultipledisability; } public String getTotaldisability() { return totaldisability; } public void setTotaldisability(String totaldisability) { this.totaldisability = totaldisability; } public String getFromdate() { return fromdate; } public void setFromdate(String fromdate) { this.fromdate = fromdate; } public String getTodate() { return todate; } public void setTodate(String todate) { this.todate = todate; } public String getBelowfourtypercent() { return belowfourtypercent; } public void setBelowfourtypercent(String belowfourtypercent) { this.belowfourtypercent = belowfourtypercent; } public String getFourtypercent() { return fourtypercent; } public void setFourtypercent(String fourtypercent) { this.fourtypercent = fourtypercent; } public String getFourtytosixtypercent() { return fourtytosixtypercent; } public void setFourtytosixtypercent(String fourtytosixtypercent) { this.fourtytosixtypercent = fourtytosixtypercent; } public String getSixtyonetoeightypercent() { return sixtyonetoeightypercent; } public void setSixtyonetoeightypercent(String sixtyonetoeightypercent) { this.sixtyonetoeightypercent = sixtyonetoeightypercent; } public String getAboveeightyonepercent() { return aboveeightyonepercent; } public void setAboveeightyonepercent(String aboveeightyonepercent) { this.aboveeightyonepercent = aboveeightyonepercent; } public String getTotalforvisual() { return totalforvisual; } public void setTotalforvisual(String totalforvisual) { this.totalforvisual = totalforvisual; } public String getDisabledpensioners() { return disabledpensioners; } public void setDisabledpensioners(String disabledpensioners) { this.disabledpensioners = disabledpensioners; } public String getNoofpersonsassessed() { return noofpersonsassessed; } public void setNoofpersonsassessed(String noofpersonsassessed) { this.noofpersonsassessed = noofpersonsassessed; } public String getNoofpersonsrejected() { return noofpersonsrejected; } public void setNoofpersonsrejected(String noofpersonsrejected) { this.noofpersonsrejected = noofpersonsrejected; } public String getPersonsassesedbelowfourty() { return personsassesedbelowfourty; } public void setPersonsassesedbelowfourty(String personsassesedbelowfourty) { this.personsassesedbelowfourty = personsassesedbelowfourty; } public String getPersonsassesedfourtytosixty() { return personsassesedfourtytosixty; } public void setPersonsassesedfourtytosixty(String personsassesedfourtytosixty) { this.personsassesedfourtytosixty = personsassesedfourtytosixty; } public String getPersonsassesedsixtytoeighty() { return personsassesedsixtytoeighty; } public void setPersonsassesedsixtytoeighty(String personsassesedsixtytoeighty) { this.personsassesedsixtytoeighty = personsassesedsixtytoeighty; } public String getPersonsassesedaboveeighty() { return personsassesedaboveeighty; } public void setPersonsassesedaboveeighty(String personsassesedaboveeighty) { this.personsassesedaboveeighty = personsassesedaboveeighty; } public String getRejectedpersonscount() { return rejectedpersonscount; } public void setRejectedpersonscount(String rejectedpersonscount) { this.rejectedpersonscount = rejectedpersonscount; } public String getPersonstatus() { return personstatus; } public void setPersonstatus(String personstatus) { this.personstatus = personstatus; } public String getPeriod() { return period; } public void setPeriod(String period) { this.period = period; } public String getKindofdisability() { return kindofdisability; } public void setKindofdisability(String kindofdisability) { this.kindofdisability = kindofdisability; } public String getSurgery() { return surgery; } public void setSurgery(String surgery) { this.surgery = surgery; } public String getPhysiotherapy() { return physiotherapy; } public void setPhysiotherapy(String physiotherapy) { this.physiotherapy = physiotherapy; } public String getCouncelling() { return councelling; } public void setCouncelling(String councelling) { this.councelling = councelling; } public String getAnyother() { return anyother; } public void setAnyother(String anyother) { this.anyother = anyother; } public String getReferredto() { return referredto; } public void setReferredto(String referredto) { this.referredto = referredto; } public String getCouncellingandguidance() { return councellingandguidance; } public void setCouncellingandguidance(String councellingandguidance) { this.councellingandguidance = councellingandguidance; } public String getSpeechtherapy() { return speechtherapy; } public void setSpeechtherapy(String speechtherapy) { this.speechtherapy = speechtherapy; } public String getHearingaid() { return hearingaid; } public void setHearingaid(String hearingaid) { this.hearingaid = hearingaid; } public String getBehaviourmodification() { return behaviourmodification; } public void setBehaviourmodification(String behaviourmodification) { this.behaviourmodification = behaviourmodification; } public String getPhychotherapy() { return phychotherapy; } public void setPhychotherapy(String phychotherapy) { this.phychotherapy = phychotherapy; } public String getAdmissioninpsychiatrichospital() { return admissioninpsychiatrichospital; } public void setAdmissioninpsychiatrichospital(String admissioninpsychiatrichospital) { this.admissioninpsychiatrichospital = admissioninpsychiatrichospital; } public String getLowvisionaid() { return lowvisionaid; } public void setLowvisionaid(String lowvisionaid) { this.lowvisionaid = lowvisionaid; } public String getAnyotherneed() { return anyotherneed; } public void setAnyotherneed(String anyotherneed) { this.anyotherneed = anyotherneed; } public String getSurgeryforrejected() { return surgeryforrejected; } public void setSurgeryforrejected(String surgeryforrejected) { this.surgeryforrejected = surgeryforrejected; } public String getPhysiotherapyforreject() { return Physiotherapyforreject; } public void setPhysiotherapyforreject(String Physiotherapyforreject) { this.Physiotherapyforreject = Physiotherapyforreject; } public boolean isBrFlag() { return brFlag; } public void setBrFlag(boolean brFlag) { this.brFlag = brFlag; } public String getAssessedandrejectedtotal() { return assessedandrejectedtotal; } public void setAssessedandrejectedtotal(String assessedandrejectedtotal) { this.assessedandrejectedtotal = assessedandrejectedtotal; } public String getValidity() { return validity; } public void setValidity(String validity) { this.validity = validity; } public String getGenderInitial1() { return genderInitial1; } public void setGenderInitial1(String genderInitial1) { this.genderInitial1 = genderInitial1; } public String getGenderInitial2() { return genderInitial2; } public void setGenderInitial2(String genderInitial2) { this.genderInitial2 = genderInitial2; } public String getPercentageInWord() { return percentageInWord; } public void setPercentageInWord(String percentageInWord) { this.percentageInWord = percentageInWord; } public int getDisabilityPercentage() { return disabilityPercentage; } public void setDisabilityPercentage(int disabilityPercentage) { this.disabilityPercentage = disabilityPercentage; } public String getMultipleRadio() { return multipleRadio; } public void setMultipleRadio(String multipleRadio) { this.multipleRadio = multipleRadio; } public String getTeluguDisabilityName() { return teluguDisabilityName; } public void setTeluguDisabilityName(String teluguDisabilityName) { this.teluguDisabilityName = teluguDisabilityName; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } /** * @return the ohcondition1 */ public String getOhcondition1() { return ohcondition1; } /** * @param ohcondition1 the ohcondition1 to set */ public void setOhcondition1(String ohcondition1) { this.ohcondition1 = ohcondition1; } /** * @return the ohcondition2 */ public String getOhcondition2() { return ohcondition2; } /** * @param ohcondition2 the ohcondition2 to set */ public void setOhcondition2(String ohcondition2) { this.ohcondition2 = ohcondition2; } /** * @return the ohcondition3 */ public String getOhcondition3() { return ohcondition3; } /** * @param ohcondition3 the ohcondition3 to set */ public void setOhcondition3(String ohcondition3) { this.ohcondition3 = ohcondition3; } /** * @return the ohcondition4 */ public String getOhcondition4() { return ohcondition4; } /** * @param ohcondition4 the ohcondition4 to set */ public void setOhcondition4(String ohcondition4) { this.ohcondition4 = ohcondition4; } /** * @return the ohcondition5 */ public String getOhcondition5() { return ohcondition5; } /** * @param ohcondition5 the ohcondition5 to set */ public void setOhcondition5(String ohcondition5) { this.ohcondition5 = ohcondition5; } /** * @return the ohcondition6 */ public String getOhcondition6() { return ohcondition6; } /** * @param ohcondition6 the ohcondition6 to set */ public void setOhcondition6(String ohcondition6) { this.ohcondition6 = ohcondition6; } /** * @return the ohcondition7 */ public String getOhcondition7() { return ohcondition7; } /** * @param ohcondition7 the ohcondition7 to set */ public void setOhcondition7(String ohcondition7) { this.ohcondition7 = ohcondition7; } /** * @return the ohcondition8 */ public String getOhcondition8() { return ohcondition8; } /** * @param ohcondition8 the ohcondition8 to set */ public void setOhcondition8(String ohcondition8) { this.ohcondition8 = ohcondition8; } /** * @return the ohcondition9 */ public String getOhcondition9() { return ohcondition9; } /** * @param ohcondition9 the ohcondition9 to set */ public void setOhcondition9(String ohcondition9) { this.ohcondition9 = ohcondition9; } /** * @return the ohcondition10 */ public String getOhcondition10() { return ohcondition10; } /** * @param ohcondition10 the ohcondition10 to set */ public void setOhcondition10(String ohcondition10) { this.ohcondition10 = ohcondition10; } /** * @return the ohcondition11 */ public String getOhcondition11() { return ohcondition11; } /** * @param ohcondition11 the ohcondition11 to set */ public void setOhcondition11(String ohcondition11) { this.ohcondition11 = ohcondition11; } /** * @return the disabilitySubIds */ public String getDisabilitySubIds() { return disabilitySubIds; } /** * @param disabilitySubIds the disabilitySubIds to set */ public void setDisabilitySubIds(String disabilitySubIds) { this.disabilitySubIds = disabilitySubIds; } /** * @return the disabilitySubSubIds */ public String getDisabilitySubSubIds() { return disabilitySubSubIds; } /** * @param disabilitySubSubIds the disabilitySubSubIds to set */ public void setDisabilitySubSubIds(String disabilitySubSubIds) { this.disabilitySubSubIds = disabilitySubSubIds; } /** * @return the disabilitySubIds1 */ public String getDisabilitySubIds1() { return disabilitySubIds1; } /** * @param disabilitySubIds1 the disabilitySubIds1 to set */ public void setDisabilitySubIds1(String disabilitySubIds1) { this.disabilitySubIds1 = disabilitySubIds1; } /** * @return the disabilitySubIds2 */ public String getDisabilitySubIds2() { return disabilitySubIds2; } /** * @param disabilitySubIds2 the disabilitySubIds2 to set */ public void setDisabilitySubIds2(String disabilitySubIds2) { this.disabilitySubIds2 = disabilitySubIds2; } /** * @return the disabilitySubIds3 */ public String getDisabilitySubIds3() { return disabilitySubIds3; } /** * @param disabilitySubIds3 the disabilitySubIds3 to set */ public void setDisabilitySubIds3(String disabilitySubIds3) { this.disabilitySubIds3 = disabilitySubIds3; } /** * @return the disabilitySubIds4 */ public String getDisabilitySubIds4() { return disabilitySubIds4; } /** * @param disabilitySubIds4 the disabilitySubIds4 to set */ public void setDisabilitySubIds4(String disabilitySubIds4) { this.disabilitySubIds4 = disabilitySubIds4; } /** * @return the disabilitySubIds5 */ public String getDisabilitySubIds5() { return disabilitySubIds5; } /** * @param disabilitySubIds5 the disabilitySubIds5 to set */ public void setDisabilitySubIds5(String disabilitySubIds5) { this.disabilitySubIds5 = disabilitySubIds5; } /** * @return the disabilitySubIds6 */ public String getDisabilitySubIds6() { return disabilitySubIds6; } /** * @param disabilitySubIds6 the disabilitySubIds6 to set */ public void setDisabilitySubIds6(String disabilitySubIds6) { this.disabilitySubIds6 = disabilitySubIds6; } /** * @return the disabilitySubIds7 */ public String getDisabilitySubIds7() { return disabilitySubIds7; } /** * @param disabilitySubIds7 the disabilitySubIds7 to set */ public void setDisabilitySubIds7(String disabilitySubIds7) { this.disabilitySubIds7 = disabilitySubIds7; } /** * @return the disabilitySubIds8 */ public String getDisabilitySubIds8() { return disabilitySubIds8; } /** * @param disabilitySubIds8 the disabilitySubIds8 to set */ public void setDisabilitySubIds8(String disabilitySubIds8) { this.disabilitySubIds8 = disabilitySubIds8; } /** * @return the disabilitySubIds9 */ public String getDisabilitySubIds9() { return disabilitySubIds9; } /** * @param disabilitySubIds9 the disabilitySubIds9 to set */ public void setDisabilitySubIds9(String disabilitySubIds9) { this.disabilitySubIds9 = disabilitySubIds9; } /** * @return the disabilitySubIds10 */ public String getDisabilitySubIds10() { return disabilitySubIds10; } /** * @param disabilitySubIds10 the disabilitySubIds10 to set */ public void setDisabilitySubIds10(String disabilitySubIds10) { this.disabilitySubIds10 = disabilitySubIds10; } /** * @return the disabilitySubIds11 */ public String getDisabilitySubIds11() { return disabilitySubIds11; } /** * @param disabilitySubIds11 the disabilitySubIds11 to set */ public void setDisabilitySubIds11(String disabilitySubIds11) { this.disabilitySubIds11 = disabilitySubIds11; } /** * @return the disabilitySubIds12 */ public String getDisabilitySubIds12() { return disabilitySubIds12; } /** * @param disabilitySubIds12 the disabilitySubIds12 to set */ public void setDisabilitySubIds12(String disabilitySubIds12) { this.disabilitySubIds12 = disabilitySubIds12; } /** * @return the disabilitySubIds13 */ public String getDisabilitySubIds13() { return disabilitySubIds13; } /** * @param disabilitySubIds13 the disabilitySubIds13 to set */ public void setDisabilitySubIds13(String disabilitySubIds13) { this.disabilitySubIds13 = disabilitySubIds13; } /** * @return the disabilitySubIds14 */ public String getDisabilitySubIds14() { return disabilitySubIds14; } /** * @param disabilitySubIds14 the disabilitySubIds14 to set */ public void setDisabilitySubIds14(String disabilitySubIds14) { this.disabilitySubIds14 = disabilitySubIds14; } /** * @return the disabilitySubIds15 */ public String getDisabilitySubIds15() { return disabilitySubIds15; } /** * @param disabilitySubIds15 the disabilitySubIds15 to set */ public void setDisabilitySubIds15(String disabilitySubIds15) { this.disabilitySubIds15 = disabilitySubIds15; } /** * @return the disabilitySubIds16 */ public String getDisabilitySubIds16() { return disabilitySubIds16; } /** * @param disabilitySubIds16 the disabilitySubIds16 to set */ public void setDisabilitySubIds16(String disabilitySubIds16) { this.disabilitySubIds16 = disabilitySubIds16; } /** * @return the disabilitySubIds17 */ public String getDisabilitySubIds17() { return disabilitySubIds17; } /** * @param disabilitySubIds17 the disabilitySubIds17 to set */ public void setDisabilitySubIds17(String disabilitySubIds17) { this.disabilitySubIds17 = disabilitySubIds17; } /** * @return the disabilitySubIds18 */ public String getDisabilitySubIds18() { return disabilitySubIds18; } /** * @param disabilitySubIds18 the disabilitySubIds18 to set */ public void setDisabilitySubIds18(String disabilitySubIds18) { this.disabilitySubIds18 = disabilitySubIds18; } /** * @return the disabilitySubIds19 */ public String getDisabilitySubIds19() { return disabilitySubIds19; } /** * @param disabilitySubIds19 the disabilitySubIds19 to set */ public void setDisabilitySubIds19(String disabilitySubIds19) { this.disabilitySubIds19 = disabilitySubIds19; } /** * @return the disabilitySubIds20 */ public String getDisabilitySubIds20() { return disabilitySubIds20; } /** * @param disabilitySubIds20 the disabilitySubIds20 to set */ public void setDisabilitySubIds20(String disabilitySubIds20) { this.disabilitySubIds20 = disabilitySubIds20; } /** * @return the disabilitySubIds21 */ public String getDisabilitySubIds21() { return disabilitySubIds21; } /** * @param disabilitySubIds21 the disabilitySubIds21 to set */ public void setDisabilitySubIds21(String disabilitySubIds21) { this.disabilitySubIds21 = disabilitySubIds21; } /** * @return the disabilitySubIds22 */ public String getDisabilitySubIds22() { return disabilitySubIds22; } /** * @param disabilitySubIds22 the disabilitySubIds22 to set */ public void setDisabilitySubIds22(String disabilitySubIds22) { this.disabilitySubIds22 = disabilitySubIds22; } /** * @return the disabilitySubIds23 */ public String getDisabilitySubIds23() { return disabilitySubIds23; } /** * @param disabilitySubIds23 the disabilitySubIds23 to set */ public void setDisabilitySubIds23(String disabilitySubIds23) { this.disabilitySubIds23 = disabilitySubIds23; } /** * @return the disabilitySubIds24 */ public String getDisabilitySubIds24() { return disabilitySubIds24; } /** * @param disabilitySubIds24 the disabilitySubIds24 to set */ public void setDisabilitySubIds24(String disabilitySubIds24) { this.disabilitySubIds24 = disabilitySubIds24; } /** * @return the disabilitySubIds25 */ public String getDisabilitySubIds25() { return disabilitySubIds25; } /** * @param disabilitySubIds25 the disabilitySubIds25 to set */ public void setDisabilitySubIds25(String disabilitySubIds25) { this.disabilitySubIds25 = disabilitySubIds25; } /** * @return the disabilitySubIds26 */ public String getDisabilitySubIds26() { return disabilitySubIds26; } /** * @param disabilitySubIds26 the disabilitySubIds26 to set */ public void setDisabilitySubIds26(String disabilitySubIds26) { this.disabilitySubIds26 = disabilitySubIds26; } /** * @return the disabilitySubIds27 */ public String getDisabilitySubIds27() { return disabilitySubIds27; } /** * @param disabilitySubIds27 the disabilitySubIds27 to set */ public void setDisabilitySubIds27(String disabilitySubIds27) { this.disabilitySubIds27 = disabilitySubIds27; } /** * @return the disabilitySubIds28 */ public String getDisabilitySubIds28() { return disabilitySubIds28; } /** * @param disabilitySubIds28 the disabilitySubIds28 to set */ public void setDisabilitySubIds28(String disabilitySubIds28) { this.disabilitySubIds28 = disabilitySubIds28; } /** * @return the disabilitySubIds29 */ public String getDisabilitySubIds29() { return disabilitySubIds29; } /** * @param disabilitySubIds29 the disabilitySubIds29 to set */ public void setDisabilitySubIds29(String disabilitySubIds29) { this.disabilitySubIds29 = disabilitySubIds29; } /** * @return the disabilitySubIds30 */ public String getDisabilitySubIds30() { return disabilitySubIds30; } /** * @param disabilitySubIds30 the disabilitySubIds30 to set */ public void setDisabilitySubIds30(String disabilitySubIds30) { this.disabilitySubIds30 = disabilitySubIds30; } /** * @return the disabilitySubIds31 */ public String getDisabilitySubIds31() { return disabilitySubIds31; } /** * @param disabilitySubIds31 the disabilitySubIds31 to set */ public void setDisabilitySubIds31(String disabilitySubIds31) { this.disabilitySubIds31 = disabilitySubIds31; } /** * @return the disabilitySubSubIds1 */ public String getDisabilitySubSubIds1() { return disabilitySubSubIds1; } /** * @param disabilitySubSubIds1 the disabilitySubSubIds1 to set */ public void setDisabilitySubSubIds1(String disabilitySubSubIds1) { this.disabilitySubSubIds1 = disabilitySubSubIds1; } /** * @return the disabilitySubSubIds2 */ public String getDisabilitySubSubIds2() { return disabilitySubSubIds2; } /** * @param disabilitySubSubIds2 the disabilitySubSubIds2 to set */ public void setDisabilitySubSubIds2(String disabilitySubSubIds2) { this.disabilitySubSubIds2 = disabilitySubSubIds2; } /** * @return the disabilitySubSubIds3 */ public String getDisabilitySubSubIds3() { return disabilitySubSubIds3; } /** * @param disabilitySubSubIds3 the disabilitySubSubIds3 to set */ public void setDisabilitySubSubIds3(String disabilitySubSubIds3) { this.disabilitySubSubIds3 = disabilitySubSubIds3; } /** * @return the disabilitySubSubIds4 */ public String getDisabilitySubSubIds4() { return disabilitySubSubIds4; } /** * @param disabilitySubSubIds4 the disabilitySubSubIds4 to set */ public void setDisabilitySubSubIds4(String disabilitySubSubIds4) { this.disabilitySubSubIds4 = disabilitySubSubIds4; } /** * @return the disabilitySubSubIds5 */ public String getDisabilitySubSubIds5() { return disabilitySubSubIds5; } /** * @param disabilitySubSubIds5 the disabilitySubSubIds5 to set */ public void setDisabilitySubSubIds5(String disabilitySubSubIds5) { this.disabilitySubSubIds5 = disabilitySubSubIds5; } /** * @return the disabilitySubSubIds6 */ public String getDisabilitySubSubIds6() { return disabilitySubSubIds6; } /** * @param disabilitySubSubIds6 the disabilitySubSubIds6 to set */ public void setDisabilitySubSubIds6(String disabilitySubSubIds6) { this.disabilitySubSubIds6 = disabilitySubSubIds6; } /** * @return the disabilitySubSubIds7 */ public String getDisabilitySubSubIds7() { return disabilitySubSubIds7; } /** * @param disabilitySubSubIds7 the disabilitySubSubIds7 to set */ public void setDisabilitySubSubIds7(String disabilitySubSubIds7) { this.disabilitySubSubIds7 = disabilitySubSubIds7; } /** * @return the disabilitySubSubIds8 */ public String getDisabilitySubSubIds8() { return disabilitySubSubIds8; } /** * @param disabilitySubSubIds8 the disabilitySubSubIds8 to set */ public void setDisabilitySubSubIds8(String disabilitySubSubIds8) { this.disabilitySubSubIds8 = disabilitySubSubIds8; } /** * @return the disabilitySubSubIds9 */ public String getDisabilitySubSubIds9() { return disabilitySubSubIds9; } /** * @param disabilitySubSubIds9 the disabilitySubSubIds9 to set */ public void setDisabilitySubSubIds9(String disabilitySubSubIds9) { this.disabilitySubSubIds9 = disabilitySubSubIds9; } /** * @return the disabilitySubSubIds10 */ public String getDisabilitySubSubIds10() { return disabilitySubSubIds10; } /** * @param disabilitySubSubIds10 the disabilitySubSubIds10 to set */ public void setDisabilitySubSubIds10(String disabilitySubSubIds10) { this.disabilitySubSubIds10 = disabilitySubSubIds10; } /** * @return the differenceFlag */ public String getDifferenceFlag() { return differenceFlag; } /** * @param differenceFlag the differenceFlag to set */ public void setDifferenceFlag(String differenceFlag) { this.differenceFlag = differenceFlag; } /** * @return the user_name */ public String getUser_name() { return user_name; } /** * @param user_name the user_name to set */ public void setUser_name(String user_name) { this.user_name = user_name; } /** * @return the disabilityId */ public String getDisabilityId() { return disabilityId; } /** * @param disabilityId the disabilityId to set */ public void setDisabilityId(String disabilityId) { this.disabilityId = disabilityId; } /** * @return the railwaycertificate */ public boolean isRailwaycertificate() { return railwaycertificate; } /** * @param railwaycertificate the railwaycertificate to set */ public void setRailwaycertificate(boolean railwaycertificate) { this.railwaycertificate = railwaycertificate; } /** * @return the status */ public String getStatus() { return status; } /** * @param status the status to set */ public void setStatus(String status) { this.status = status; } /** * @return the assembly_id */ public String getAssembly_id() { return assembly_id; } /** * @param assembly_id the assembly_id to set */ public void setAssembly_id(String assembly_id) { this.assembly_id = assembly_id; } /** * @return the assemblylist */ public ArrayList getAssemblylist() { return assemblylist; } /** * @param assemblylist the assemblylist to set */ public void setAssemblylist(ArrayList assemblylist) { this.assemblylist = assemblylist; } /** * @return the reportcategory */ public String getReportcategory() { return reportcategory; } /** * @param reportcategory the reportcategory to set */ public void setReportcategory(String reportcategory) { this.reportcategory = reportcategory; } /** * @return the reportSubcategory */ public String getReportSubcategory() { return reportSubcategory; } /** * @param reportSubcategory the reportSubcategory to set */ public void setReportSubcategory(String reportSubcategory) { this.reportSubcategory = reportSubcategory; } }
true
f603454809d6e9fcae5ef0b13b6a015ded23f49d
Java
ZongzheYuan/RobotAndMaze
/src/robot/IntelligentRobot.java
UTF-8
2,138
3.421875
3
[]
no_license
package robot; import java.util.ArrayList; import java.util.List; import direction.Direction; public abstract class IntelligentRobot extends AbstractRobot{ /* * the intelligent robot class * it has two additional method * one is to record its walk path * the other one is to judge the path according to its walk path */ private List<String> reachPosition = new ArrayList<String>(); private List<String> finishPosition = new ArrayList<String>(); private List<Direction> orderList=new ArrayList<Direction>(); public IntelligentRobot(int[] position, int[] destination, Direction face) { super(position, destination, face); reachPosition.add(""+position[0]+","+position[1]); } public List<String> getReachPosition() { return reachPosition; } public List<String> getFinishPosition() { return finishPosition; } public List<Direction> getOrderList() { return orderList; } /* * the method to record the walk path */ public void changePath(int[] originPosition){ if (!reachPosition.contains(""+getPosition()[0]+","+getPosition()[1])) { reachPosition.add(""+getPosition()[0]+","+getPosition()[1]); } else { reachPosition.remove(""+originPosition[0]+","+originPosition[1]); if (!finishPosition.contains(""+originPosition[0]+","+originPosition[1])) { finishPosition.add(""+originPosition[0]+","+originPosition[1]); } } } /* * the method to judge the path * different from the stupid method imagine * it will firstly go the path that have never reached * and record the reached path */ public boolean think (char [] [] maze) { int i = (getTryPosition()[0] + getPosition() [0])/2; int j = (getTryPosition()[1] + getPosition() [1])/2; if (maze[i][j]!=' ') { return false; } else if (finishPosition.contains(""+getTryPosition()[0]+","+getTryPosition()[1])) { return false; } else if (reachPosition.contains(""+getTryPosition()[0]+","+getTryPosition()[1])) { orderList.add(getMoveDirection()); return false; } else { return true; } } @Override public abstract void strategy(char[][] maze); public abstract String getName(); }
true
955ff1e0a88f5e0abf9f3113b773a2ac3d4b3ef5
Java
aheadlcx/analyzeApk
/budejie/sources/com/budejie/www/activity/video/i.java
UTF-8
6,669
2.484375
2
[]
no_license
package com.budejie.www.activity.video; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Map; public class i { public static boolean a = true; public static boolean b = false; public static String a() { Map a = h.a("cat /proc/cpuinfo"); if (a == null) { return "Sorry, Run Cmd Failure !!!"; } InputStream inputStream = (InputStream) a.get("input"); Reader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String str = ""; while (true) { try { str = bufferedReader.readLine(); if (str == null) { break; } else if (str.indexOf("Features") != -1) { stringBuilder.append(str); } } catch (Exception e) { String str2 = "Read InputStream Failure !!!"; if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e2) { } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (IOException e3) { } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e4) { } } return str2; } catch (Throwable th) { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e5) { } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (IOException e6) { } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e7) { } } } } if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e8) { } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (IOException e9) { } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e10) { } } return stringBuilder.toString(); } public static String b() throws Exception { Map a = h.a("cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"); if (a == null) { return "Sorry, Run Cmd Failure !!!"; } InputStream inputStream = (InputStream) a.get("input"); Reader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder stringBuilder = new StringBuilder(); String str = ""; while (true) { try { str = bufferedReader.readLine(); if (str == null) { break; } stringBuilder.append(str); } catch (Exception e) { String str2 = "Read InputStream Failure !!!"; if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e2) { } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (IOException e3) { } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e4) { } } return str2; } catch (Throwable th) { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e5) { } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (IOException e6) { } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e7) { } } } } if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e8) { } } if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (IOException e9) { } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e10) { } } return stringBuilder.toString(); } public static boolean c() { String a = a(); if (a.indexOf("neon") == -1 && a.indexOf("vfp") == -1) { return false; } return true; } public static boolean d() { if (a().indexOf("neon") != -1) { return true; } return false; } public static int e() { int parseInt; try { parseInt = Integer.parseInt(b()); } catch (NumberFormatException e) { e.printStackTrace(); parseInt = 0; } catch (Exception e2) { e2.printStackTrace(); parseInt = 0; } if (parseInt < 800000) { return 0; } if (parseInt < 800000 || parseInt > 1100000) { return 2; } return 1; } public static boolean f() { if (b) { return true; } if (e() == 0 || a || !c()) { return false; } return true; } }
true
170de6d32aa468a5349780666082b0719a0437ac
Java
skokorev/rockpaperscissors-javatraining
/src/test/java/ru/test/PlayerTest.java
UTF-8
897
2.5625
3
[]
no_license
package ru.test; import org.junit.jupiter.api.Test; import ru.test.players.PaperShowingPlayer; import ru.test.players.RandomPlayer; import static org.junit.jupiter.api.Assertions.*; public class PlayerTest { @Test public void shouldShowPaperResult() { Player p = new PaperShowingPlayer(); Result result = p.getResult(); assertNotNull(result); assertEquals(Result.PAPER, result); } @Test public void shouldShowRandomResult() { Player p = new RandomPlayer(); Result result = p.getResult(); assertNotNull(result); } @Test public void shouldCheckPlayerName() { Player p = new RandomPlayer(); assertEquals("Player", p.getName()); } @Test public void shouldCheckPlayer2Name() { Player p = new RandomPlayer("Player2"); assertEquals("Player2", p.getName()); } }
true
18ec514b81b00f7d36951bb3f04c81071e7af62f
Java
tonyhuangyu7/EA103G7
/src/com/meal/controller/MealServletUploadImg.java
UTF-8
862
2.140625
2
[]
no_license
package com.meal.controller; import java.io.*; import javax.servlet.ServletException; import javax.servlet.annotation.*; import javax.servlet.http.*; import com.meal.model.MealService; @WebServlet("/meal/meal.UploadImg") @MultipartConfig public class MealServletUploadImg extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { Part part = req.getPart("meal_img"); String mealNo = req.getParameter("meal_no"); try{ InputStream in = part.getInputStream(); byte[] buffer = new byte [in.available()]; MealService mealSrv = new MealService(); mealSrv.searchByNo(mealNo).setMeal_img(buffer); // in.close(); }catch(Exception e) { } } }
true
453281c975fd43c125e68e30f28357a22603fe7e
Java
designreuse/BugTracker-1
/src/main/java/com/bugtracker/mapper/UserMapper.java
UTF-8
342
2.078125
2
[]
no_license
package com.bugtracker.mapper; import com.bugtracker.dto.UserDTO; import com.bugtracker.entity.User; import java.util.Set; public interface UserMapper { UserDTO userToUserDTO(User user); User userDTOToUser(UserDTO userDTO); Set<UserDTO> usersToUserDTOs(Set<User> users); Set<User> userDTOsToUsers(Set<UserDTO> userDTOs); }
true
88173503f143ff38954ac1a48a2f6b332be33c0f
Java
nityanantan23/androidtestng
/src/test/java/Common/AppInteraction.java
UTF-8
8,312
2.234375
2
[ "Apache-2.0" ]
permissive
package Common; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Properties; import org.apache.commons.io.IOUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import Enums.FindElementBy; import Model.TestConfiguration; import io.appium.java_client.MobileElement; import io.appium.java_client.TouchAction; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.ios.IOSDriver; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class AppInteraction { private AndroidDriver<MobileElement> _driver; private TouchAction touchAction = null; public static final int MAX_DELAY = 15000; public AppInteraction(AndroidDriver<MobileElement> driver) { this._driver = driver; touchAction = new TouchAction(driver); } public MobileElement FindElement(String id, FindElementBy by, int delayInSeconds) { MobileElement element; if (by == FindElementBy.XPath) { element = (MobileElement) _driver.findElement(By.xpath(id)); } else { element = (MobileElement) _driver.findElement(By.id(id)); } if(delayInSeconds > 0) { WaitForElement(id, by, delayInSeconds); } return element; } public void TapElement(String id, FindElementBy by, int delay) { MobileElement element = FindElement(id, by, delay); touchAction.tap(element.getLocation().x, element.getLocation().y).perform(); } public void ClickElement(String id, FindElementBy by, int delay) { MobileElement element = FindElement(id, by, delay); element.click(); } public void SendKey(String id, String key, FindElementBy by, int delay) { MobileElement element = FindElement(id, by, delay); element.clear(); element.sendKeys(key); } public boolean WaitForElement(String id, FindElementBy by, int delayInSeconds) { try { MobileElement element; if (by == FindElementBy.XPath) { element = (MobileElement) _driver.findElement(By.xpath(id)); } else { element = (MobileElement) _driver.findElement(By.id(id)); } WebDriverWait wait = new WebDriverWait(_driver, delayInSeconds); wait.until(ExpectedConditions.visibilityOf(element)); return element.isDisplayed(); } catch (Exception e) { return false; } } public long RecordVisible(String id, FindElementBy by, int delayInSeconds) { long start = System.currentTimeMillis(); try { MobileElement element; By findBy; if (by == FindElementBy.XPath) { findBy = By.xpath(id); } else { findBy = By.id(id); } element = (MobileElement) _driver.findElement(findBy); WebDriverWait wait = new WebDriverWait(_driver, 300); wait.until(ExpectedConditions.visibilityOfElementLocated(findBy)); long finish = System.currentTimeMillis(); long timeElapsed = finish - start; if(element.isDisplayed()) { return timeElapsed; } else { return -1; } } catch (Exception e) { return -1; } } protected long RecordInvisible(String id, FindElementBy by) { long start = System.currentTimeMillis(); try { By findBy; if (by == FindElementBy.XPath) { findBy = By.xpath(id); } else { findBy = By.id(id); } WebDriverWait wait = new WebDriverWait(_driver, 300); wait.until(ExpectedConditions.invisibilityOfElementLocated(findBy)); long finish = System.currentTimeMillis(); long timeElapsed = finish - start; /* writeToFile("Starts: " + Long.toString(start) + "\r\n Ends: " + Long.toString(finish) + "\r\n Elapsed: " + Long.toString(timeElapsed));*/ return timeElapsed; } catch (Exception e) { return 0; } } public boolean TakeScreenshot(final String name) { String screenshotDirectory = System.getProperty("appium.screenshots.dir", System.getProperty("java.io.tmpdir", "")); File screenshot = ((TakesScreenshot) _driver).getScreenshotAs(OutputType.FILE); return screenshot.renameTo(new File(screenshotDirectory, String.format("%s.png", name))); } public void WriteToReport(String text) { String filePath = System.getenv("DEVICEFARM_LOG_DIR") + "/report.txt"; File reportFile = new File(filePath); System.out.println("filepath: " + filePath); if(!reportFile.exists()) { try(PrintWriter output = new PrintWriter(new FileWriter(reportFile))) { output.printf("%s\r\n", text); } catch (Exception e) { System.out.println("Report file not found."); System.out.println(e.getMessage()); } } else { try(PrintWriter output = new PrintWriter(new FileWriter(reportFile, true))) { output.printf("%s\r\n", text); } catch (Exception e) { System.out.println("Report file not found. (Existing)"); System.out.println(e.getMessage()); } } } public void WriteConfigFile() { TestConfiguration configuration = getTestConfiguration(); String filePath = System.getenv("DEVICEFARM_LOG_DIR") + "/config.json"; File configFile = new File(filePath); System.out.println("filepath: " + filePath); try(PrintWriter output = new PrintWriter(new FileWriter(configFile))) { output.printf("{\r\n"); output.printf("\"TestResultSender\": \"%s\",\r\n", configuration.TestResultSender); output.printf("\"TestResultRecipient\": \"%s\"\r\n", configuration.TestResultRecipient); output.printf("}"); } catch (Exception e) { System.out.println("config file not found."); System.out.println(e.getMessage()); } } public TestConfiguration getTestConfiguration() { TestConfiguration configuration = new TestConfiguration(); String driverID = "5009003"; String password = "12345"; String otp = "1234"; String emailSender = "eugeneng@axrail.com"; String emailRecipient = "yhlaw@axrail.com"; TestConfiguration defaultConfiguration = new TestConfiguration(); defaultConfiguration.DriverID = driverID; defaultConfiguration.Password = password; defaultConfiguration.Otp = otp; defaultConfiguration.TestResultSender = emailSender; defaultConfiguration.TestResultRecipient = emailRecipient; ObjectMapper mapper = new ObjectMapper(); String fileName = "config/config.json"; InputStream testConfigurationResourceStream = null; ClassLoader classLoader = ClassLoader.getSystemClassLoader(); String testConfigurationResourceData = ""; try { //System.out.println("file in resource: " + classLoader.getResource(fileName).getFile()); testConfigurationResourceStream = classLoader.getResourceAsStream(fileName); testConfigurationResourceData = IOUtils.toString(testConfigurationResourceStream, "UTF-8"); } catch (Exception e) { e.printStackTrace(); return defaultConfiguration; } if(testConfigurationResourceStream != null) { try { TestConfiguration testConfigurationResourceModel = mapper.readValue(testConfigurationResourceData, TestConfiguration.class); configuration.TestResultSender = isValidConfiguration(testConfigurationResourceModel.TestResultSender) ? testConfigurationResourceModel.TestResultSender : emailSender; configuration.TestResultRecipient = isValidConfiguration(testConfigurationResourceModel.TestResultRecipient) ? testConfigurationResourceModel.TestResultRecipient : emailRecipient; configuration.DriverID = isValidConfiguration(testConfigurationResourceModel.DriverID) ? testConfigurationResourceModel.DriverID : driverID; configuration.Password = isValidConfiguration(testConfigurationResourceModel.Password) ? testConfigurationResourceModel.Password : password; configuration.Otp = isValidConfiguration(testConfigurationResourceModel.Otp) ? testConfigurationResourceModel.Otp : otp; } catch (IOException e) { e.printStackTrace(); return defaultConfiguration; } } return configuration; } private boolean isValidConfiguration(String configurationString) { return !(configurationString == null || configurationString.equals("")); } }
true
3549f962c89a73bbc743f31d2017cd293e914904
Java
diegopreviero/ExemploSpring
/src/main/java/br/com/estudae/springtest/web/PostRestController.java
UTF-8
1,069
2.125
2
[]
no_license
package br.com.estudae.springtest.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import br.com.estudae.springtest.model.Post; import br.com.estudae.springtest.repository.PostRepository; @RestController public class PostRestController { private final PostRepository postRepository; @Autowired public PostRestController (PostRepository postRepository) { this.postRepository = postRepository; } @RequestMapping(value="/post/findByTitle") public Post findOneByTitle(@RequestParam("title") String title) { return postRepository.findOneByTitle(title); } @RequestMapping("/post/search") public List<Post> findByBodyContaining(@RequestParam("keyword") String keyword){ return postRepository.findByBodyContaining(keyword); } @RequestMapping("/post/count") public long count() { return postRepository.count(); } }
true
38e4df6de02740cb56d981a6f1912531de6606f6
Java
Azalkor/ProjetAL
/src/model/ShapeGroup.java
UTF-8
4,287
2.796875
3
[]
no_license
package model; import java.util.ArrayList; import com.sun.javafx.geom.Vec2d; import javafx.geometry.Point2D; import javafx.scene.paint.Color; public class ShapeGroup implements Shape { private ArrayList<IShapeObserver> observeurs; private ArrayList<Shape> shapes; private Shape etat; private Rectangle selection; private int id; private Shape parent; public Shape restaure(Memento m) { etat = m.getEtat(); return etat; } public Point2D getCentre() { Point2D centre = new Point2D(0,0); if(selection!=null) centre.add(selection.getPosition()); return centre; } public ArrayList<Shape> getShapes() { return shapes; } public void setShapes(ArrayList<Shape> shapes) { this.shapes = shapes; } public ShapeGroup() { shapes = new ArrayList<Shape>(); observeurs = new ArrayList<IShapeObserver>(); selection=null; } public ShapeGroup(float largeur, float hauteur, Point2D pos) { shapes = new ArrayList<Shape>(); observeurs = new ArrayList<IShapeObserver>(); selection=new Rectangle(largeur, hauteur, pos, Color.TRANSPARENT); } @Override public void rotation(double deg) { Point2D oldPos = selection.getPosition(); this.selection.rotation(deg); Point2D newPos = selection.getPosition(); Vec2d dir = new Vec2d(newPos.getX()-oldPos.getX(), newPos.getY()-oldPos.getY()); for (Shape shape : shapes) { shape.translation(dir); shape.rotation(deg); } notifier(); } @Override public void translation(Vec2d dir) { this.selection.translation(dir); for (Shape shape : shapes) { shape.translation(dir); } notifier(); } public void addShape(Shape shape) { if(this.parent != null){ ShapeGroup tmp = (ShapeGroup)this.getParent(); tmp.getShapes().remove(shape); tmp.setShapes(tmp.getShapes()); } shape.setParent(this); shapes.add(shape); } public void liste() { String str = new String(); for (Shape shape : shapes) { str = str + shape.toString(); } System.out.println(str); } @Override public ShapeGroup clone() { ShapeGroup copy = new ShapeGroup(); for (Shape shape : shapes) { copy.addShape(shape); } return copy; } @Override public Point2D getPosition() { // TODO Auto-generated method stub return null; } public int egal(ShapeGroup compare) { ArrayList<Shape> comp = compare.getShapes(); if(shapes.size() != comp.size()){ System.out.println("Failed: unequal size"); return 0; } for(int i = 0 ; i< shapes.size(); i++){ if(shapes.get(i) instanceof Rectangle && comp.get(i) instanceof Rectangle){ Rectangle test2 = (Rectangle) comp.get(i); Rectangle test = (Rectangle) shapes.get(i); if(test.egale(test2) != 1){ System.out.println("Failed:" + shapes.get(i) + "not equal to"+ comp.get(i)); return 0; } } if(shapes.get(i) instanceof Polygone && comp.get(i) instanceof Polygone){ Polygone test = (Polygone)shapes.get(i); Polygone test2 = (Polygone)comp.get(i); if(test.egale(test2) != 1){ System.out.println("Failed:" + shapes.get(i) + "not equal to"+ comp.get(i)); return 0; } } } return 1; } @Override public void notifier() { for (IShapeObserver observer : observeurs) { observer.update(); } for (Shape shape : shapes) { shape.notifier(); } } @Override public int egale(Shape s) { throw new UnsupportedOperationException(); } public void addObserveur(IShapeObserver obs){ observeurs.add(obs); for (Shape shape : shapes) { shape.addObserveur(obs); } } @Override public int putId() { this.id = controller.Controller.id; return this.id; } @Override public int getId() { return id; } @Override public void setCouleur(Color couleur) { for (Shape shape : shapes) { shape.setCouleur(couleur); } } public void supprimerGroup(){ for (Shape shape : shapes) { this.shapes.remove(shape); } parent = null; id =-1; } public void degroup(){ for (Shape shape : shapes) { ShapeGroup tmp = (ShapeGroup)this.parent; tmp.addShape(shape); } this.supprimerGroup(); } @Override public void setParent(Shape s) { parent = s; } @Override public Shape getParent() { return this.parent; } @Override public Color getCouleur() { // TODO Auto-generated method stub return null; } }
true
4d0e0370b6dd585d7b7e5515f73cdd8de9cdab9e
Java
dimaskiddo/training-telkom-dta-backend
/src/main/java/co/id/telkom/digitalent/jwt/JWTAuthentication.java
UTF-8
3,054
2.296875
2
[]
no_license
package co.id.telkom.digitalent.jwt; import co.id.telkom.digitalent.model.JWTModel; import co.id.telkom.digitalent.response.WriteResponse; import co.id.telkom.digitalent.response.DataResponse; import co.id.telkom.digitalent.utils.SecurityUtils; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.User; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Date; public class JWTAuthentication extends UsernamePasswordAuthenticationFilter { private AuthenticationManager authenticationManager; public JWTAuthentication(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; // Set Login URL setFilterProcessesUrl(SecurityUtils.SIGN_IN_URL); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { String email = request.getParameter("email"); String password = request.getParameter("password"); return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(email, password, new ArrayList<>())); } catch (Exception e) { WriteResponse.responseUnauthorized(response, e.getMessage().toUpperCase()); throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { String token = JWT.create() .withSubject(((User) authResult.getPrincipal()).getUsername()) .withExpiresAt(new Date(System.currentTimeMillis() + SecurityUtils.EXPIRATION_TIME)) .sign(Algorithm.HMAC256(SecurityUtils.SECRET)); JWTModel jwtModel = new JWTModel(); DataResponse<JWTModel> dataResponse = new DataResponse<>(); jwtModel.setToken(token); dataResponse.setCode(HttpServletResponse.SC_OK); dataResponse.setData(jwtModel); WriteResponse.responseSuccessWithData(response, dataResponse); } @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { WriteResponse.responseInternalServerError(response, ""); } }
true
e3f34dff2d328187acc561feae5002312fa8f582
Java
teamFeeder/main
/src/main/java/seedu/address/logic/parser/CliSyntax.java
UTF-8
918
2.03125
2
[ "MIT" ]
permissive
package seedu.address.logic.parser; /** * Contains Command Line Interface (CLI) syntax definitions common to multiple commands */ public class CliSyntax { /* Prefix definitions */ public static final Prefix PREFIX_NAME = new Prefix("n/"); public static final Prefix PREFIX_PHONE = new Prefix("p/"); public static final Prefix PREFIX_EMAIL = new Prefix("e/"); public static final Prefix PREFIX_ADDRESS = new Prefix("a/"); public static final Prefix PREFIX_SCHEDULE = new Prefix("s/"); public static final Prefix PREFIX_TAG = new Prefix("t/"); public static final Prefix PREFIX_MEDICAL_RECORD = new Prefix("mr/"); public static final Prefix PREFIX_DATE = new Prefix("d/"); public static final Prefix PREFIX_MEDICAL_DEPARTMENT = new Prefix("md/"); public static final Prefix PREFIX_NRIC = new Prefix("ic/"); public static final Prefix PREFIX_ROLE = new Prefix("r/"); }
true
a51fa38b6d19a61591df8f6ffd0079f93701ed33
Java
qreal/wmp
/editor-service/src/main/java/com/qreal/wmp/editor/common/auth/OAuth2UserDetailsLoaderImpl.java
UTF-8
4,963
2.34375
2
[ "Apache-2.0" ]
permissive
package com.qreal.wmp.editor.common.auth; import com.qreal.wmp.editor.database.exceptions.AbortedException; import com.qreal.wmp.editor.database.exceptions.ErrorConnectionException; import com.qreal.wmp.editor.database.exceptions.NotFoundException; import com.qreal.wmp.editor.database.users.client.UserService; import com.qreal.wmp.editor.database.users.model.User; import com.qreal.wmp.editor.database.users.model.UserRole; import com.racquettrack.security.oauth.OAuth2UserDetailsLoader; import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import java.util.*; import java.util.stream.Collectors; /** Handles requests for user operations from OAuth authentication points.*/ @Component public class OAuth2UserDetailsLoaderImpl implements OAuth2UserDetailsLoader<UserDetails, String> { public static final String ROLE_USER = "ROLE_USER"; private static final Logger logger = LoggerFactory.getLogger(OAuth2UserDetailsLoaderImpl.class); private final UserService userService; @Autowired public OAuth2UserDetailsLoaderImpl(UserService userService) { this.userService = userService; } /** * Finds user using userService for OAuth authentication point. * If user was found point will authenticate session of this user. * If user was not found point will create new user. */ @Override public UserDetails getUserByUserId(String id) { logger.trace("OAuth passed user {} for authentication", id); UserDetails userDetails = null; try { User user = userService.getUser(id); userDetails = convert(user); logger.trace("User {} was found", id); } catch (NotFoundException e) { logger.trace("User {} was not found", id); } catch (ErrorConnectionException e) { //TODO what to do in that case? logger.error("Fatal error: must find user but can't because of connection error with user service", id); } catch (TException e) { logger.error("TException was not translated", e); } return userDetails; } /** Updates user retrieved from OAuth authentication point. Not used right now.*/ @Override public UserDetails updateUser(UserDetails userDetails, Map<String, Object> userInfo) { logger.trace("OAuth tried to updateUser user {}", userDetails.getUsername()); logger.trace("No actual updating was performed for user {}.", userDetails.getUsername()); return userDetails; } /** * Creates user retrieved from OAuth authentication point. User will be created if no user with this id was * found previously. */ @Override public UserDetails createUser(String id, Map<String, Object> userInfo) { logger.trace("OAuth passed user {} for creation.", id); User user = createUserFromId(id); try { userService.saveUser(user); } catch (AbortedException e) { //TODO what to do in that case? logger.error("Fatal error: must create user but can't because operation was aborted."); } catch (ErrorConnectionException e) { //TODO what to do in that case? logger.error("Fatal error: must create user but can't because of connection error with user service."); } catch (TException e) { logger.error("TException was not translated", e); } UserDetails userDetails = convert(user); logger.trace("User {} was created.", id); return userDetails; } /** Tells if user with such info allowed to register.*/ @Override public boolean isCreatable(Map<String, Object> userInfo) { return true; } private User createUserFromId(String username) { User user = new User(username, username, true); Set<UserRole> roles = new HashSet<>(); UserRole userRole = new UserRole(user, ROLE_USER); roles.add(userRole); user.setRoles(roles); return user; } private org.springframework.security.core.userdetails.User convert(User user) { return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, buildUserAuthority(user.getRoles())); } private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) { Set<GrantedAuthority> setAuths = userRoles.stream().map(userRole -> new SimpleGrantedAuthority(userRole.getRole())).collect(Collectors.toSet()); return new ArrayList<>(setAuths); } }
true
327703f626e598b5805b87648d4b9ab528e510ea
Java
deathmock5/BrewersConstruct
/bconstruct/common/blocks/templates/BConstructBlock.java
UTF-8
692
2.09375
2
[ "MIT" ]
permissive
package bconstruct.common.blocks.templates; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.registry.LanguageRegistry; import bconstruct.BConstruct; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; public class BConstructBlock extends Block { public BConstructBlock(int id, Material material, float hardness, String tex) { super(id, material); this.setHardness(hardness); this.setUnlocalizedName(tex.replace(" ", "").toLowerCase()); LanguageRegistry.addName(this, tex); } }
true
c85e7932c2749aedc643548686c8a172e342b6f8
Java
BarakHirsch/BasicWeb
/Trivia/src/java/servlets/StartGameServlet.java
UTF-8
1,726
2.4375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package servlets; import enums.*; import java.io.IOException; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import logic.Manager; import logic.TriviaGame; import helpers.ParseHelper; public class StartGameServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HandleRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HandleRequest(request, response); } public void HandleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { HashMap<Category, Difficulty> categoriesToPlay = new HashMap<>(); for (Category cat : Category.values()) { if (request.getParameter("checkBox" + cat) != null) { categoriesToPlay.put(cat, ParseHelper.parseDifficulty(request.getParameter("radioButton" + cat))); } } TriviaGame currentGame = Manager.getInsance().startGame(categoriesToPlay); request.getSession().setAttribute("currGame", currentGame); response.sendRedirect("PlayServlet"); } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
cf8e4cbf15cf858037431e3245b10a70917ed3b6
Java
ryouichi0618/Java-Lesson
/UdemyJava/src/exday4/SampleEx401.java
UTF-8
373
2.6875
3
[]
no_license
package exday4; public class SampleEx401 { public static void main(String[] args) { CellPhone cp = new CellPhone("hoge@email.com","090-1234-5678"); cp.call("011-123-4567"); cp.sendMail("fuga@email.com"); IPhone phone = (IPhone)cp; phone.call("011-987-6543"); IEmail mail = (IEmail)cp; mail.sendMail("bar@email.com"); } }
true
31e1e05705c7e6d5b8d8a4ee6a3fbcf263b4c019
Java
J-Wass/LeBot
/LeBotCommandCore.java
WINDOWS-1252
4,114
2.421875
2
[]
no_license
import org.pircbotx.PircBotX; import org.pircbotx.hooks.ListenerAdapter; import org.pircbotx.hooks.events.MessageEvent; import static org.pircbotx.ReplyConstants.*; import org.pircbotx.exception.IrcException; import org.pircbotx.exception.NickAlreadyInUseException; import org.pircbotx.hooks.CoreHooks; import org.pircbotx.hooks.Event; import org.pircbotx.hooks.Listener; import org.pircbotx.hooks.events.*; import org.pircbotx.hooks.managers.GenericListenerManager; import org.pircbotx.hooks.managers.ListenerManager; import org.pircbotx.hooks.managers.ThreadedListenerManager; import org.pircbotx.User; import org.pircbotx.Channel; import java.util.Date; import java.util.Random; public class LeBotCommandCore extends ListenerAdapter { public void onMessage(MessageEvent event) { Channel channel = event.getChannel(); //help command if((event.getMessage().toLowerCase().contains("lcbot") && event.getMessage().toLowerCase().contains("help")) || event.getMessage().equalsIgnoreCase("!help")) { event.respond("I currently support !time, !help, !joke, !about, !ping and some other stuff."); } //owner command if (event.getMessage().equalsIgnoreCase("!owner") || (event.getMessage().toLowerCase().contains("who") && event.getMessage().toLowerCase().contains("owner"))) { event.respond("The bot owner is " + Values.owner); } //time command if (event.getMessage().equalsIgnoreCase("!time")) { event.respond("The current time is " + new Date()); } //ping command if (event.getMessage().equalsIgnoreCase("!ping")) { event.respond("Pong!"); } //joke command if (event.getMessage().equalsIgnoreCase("!joke")) { String[] jokes = { "Energizer Bunny was arrested, charged with battery.", "I usually take steps to avoid elevators.", "Schrodinger's Cat: Wanted dead and alive.", "If at first you don't succeed; call it version 1.0", "CONGRESS.SYS Corrupted: Re-boot Washington D.C (Y/n)?", "We live in a society where pizza gets to your house before the police.", "Light travels faster than sound. This is why some people appear bright until you hear them speak.", "Evening news is where they begin with 'Good evening', and then proceed to tell you why it isn't.", "You do not need a parachute to skydive. You only need a parachute to skydive twice.", "When in doubt, mumble.", "War does not determine who is right only who is left...", "I wondered why the frisbee was getting bigger - then it hit me.", "Never argue with a fool, they will lower you to their level, and then beat you with experience.", "There are 3 kinds of people in the world: Those who can count and those who can't.", "Never hit a man with glasses. Hit him with a baseball bat instead.", "Nostalgia isn't what it used to be." }; Random randJoke = new Random(); event.respond(jokes[randJoke.nextInt(jokes.length)]); } //about command if(event.getMessage().equalsIgnoreCase("!about")) { event.respond("LegendCraft is an open sourced minecraft classic software that is based off of 800Craft and fCraft. It is developed by LeChosenOne and DingusBungus. For more information, visit http://www.legendcraft.webuda.com"); } } }
true
da4c69fa9ae1266b07ce18088da6294f7909c2a8
Java
brzaskun/NetBeansProjects
/kadry/src/main/java/view/RodzajenieobecnosciView.java
UTF-8
1,858
2.03125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import comparator.Rodzajnieobecnoscicomparator; import dao.RodzajnieobecnosciFacade; import entity.Rodzajnieobecnosci; import java.io.Serializable; import java.util.Collections; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import msg.Msg; /** * * @author Osito */ @Named @ViewScoped public class RodzajenieobecnosciView implements Serializable { private static final long serialVersionUID = 1L; @Inject private RodzajnieobecnosciFacade rodzajnieobecnosciFacade; private Rodzajnieobecnosci selectedlista; private List<Rodzajnieobecnosci> lista; @PostConstruct private void init() { lista = rodzajnieobecnosciFacade.findAll(); Collections.sort(lista, new Rodzajnieobecnoscicomparator()); } public void zachowaj() { rodzajnieobecnosciFacade.editList(lista); Msg.msg("Zmiany zachowane"); } public void edytuj(Rodzajnieobecnosci rodzajnieobecnosci) { if (rodzajnieobecnosci!=null) { rodzajnieobecnosciFacade.edit(rodzajnieobecnosci); Msg.msg("Naniesiono zmiany"); } else { Msg.msg("e","Wystąpił błąd"); } } public Rodzajnieobecnosci getSelectedlista() { return selectedlista; } public void setSelectedlista(Rodzajnieobecnosci selectedlista) { this.selectedlista = selectedlista; } public List<Rodzajnieobecnosci> getLista() { return lista; } public void setLista(List<Rodzajnieobecnosci> lista) { this.lista = lista; } }
true
de896eae206b09c60fc7ab7fbc4309f63105b842
Java
jamiehjmills/codingInterview
/src/COSC250/Challenge1.java
UTF-8
953
3.34375
3
[]
no_license
package COSC250; import java.util.*; import static java.lang.Math.abs; public class Challenge1 { public static void main(String[] args){ int[] test = {0,1,2,4,3,5}; System.out.println(flatlandSpaceStations(6, test)); } public static int flatlandSpaceStations(int n, int[] c) { Arrays.sort(c); //List<Integer> temp = new ArrayList<>(); List<Integer> finalList = new ArrayList<>(); int i = 0; int min = 0; while(i < n){ for(int j = 0; j < c.length; j++){ if(j == 0 ) min = (abs(c[j]-i)); if ( min > (abs(c[j]-i))){ min = min = (abs(c[j]-i)); } } finalList.add(min); //temp.clear(); i++; //System.out.println(temp); // System.out.println(finalList); } return Collections.max(finalList); } }
true
3e83e6815480f49996a9f900e0fe62da9fcf9eb6
Java
cxlin007/commons
/refreshview/src/main/java/com/common/refreshview/PullToRefreshTouchManager.java
UTF-8
10,293
2.25
2
[]
no_license
package com.common.refreshview; import android.support.v4.view.MotionEventCompat; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.widget.AbsListView; import android.widget.Scroller; /** * 下拉刷新触摸管理器 * Created by chenxunlin_91 on 2015/4/20. */ public class PullToRefreshTouchManager { private static final int INVALID_POINTER = -1; private int mDurationToCloseHeader = 1000; private int mActivePointerId; private PullToRefreshView mPullToRefreshView; private PullToRefreshIndicator mPullToRefreshIndicator; private MotionEvent mLastMoveEvent; private boolean mHasSendCancelEvent = false; /** * 处理放开手指后的动画 */ private ScrollChecker mScrollChecker; public PullToRefreshTouchManager(PullToRefreshView pullToRefreshView,PullToRefreshIndicator pullToRefreshIndicator){ this.mPullToRefreshView = pullToRefreshView; mPullToRefreshIndicator = pullToRefreshIndicator; mScrollChecker = new ScrollChecker(); } public boolean dispatchTouchEvent(MotionEvent ev){ final int action = MotionEventCompat.getActionMasked(ev); switch (action) { case MotionEvent.ACTION_DOWN: { int index = 0; mActivePointerId = MotionEventCompat.getPointerId(ev, index); float x = MotionEventCompat.getX(ev, index); float y = MotionEventCompat.getY(ev, index); mPullToRefreshIndicator.onPressDown(x, y); mScrollChecker.abortIfWorking(); //判断是否要传给子视图 if (mPullToRefreshIndicator.hasStartPosition()) { // do nothing, intercept child event } else { mPullToRefreshView.dispatchTouchEventSupper(ev); } return true; } case MotionEvent.ACTION_MOVE: { mLastMoveEvent = ev; if (mActivePointerId == INVALID_POINTER) { return mPullToRefreshView.dispatchTouchEventSupper(ev); } final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId); if (index < 0) { return mPullToRefreshView.dispatchTouchEventSupper(ev); } //判断是否要移动整个布局还是子布局自身移动 float x = MotionEventCompat.getX(ev, index); float y = MotionEventCompat.getY(ev, index); mPullToRefreshIndicator.onMove(x,y); float offsetX = mPullToRefreshIndicator.getOffsetX(); float offsetY = mPullToRefreshIndicator.getOffsetY(); boolean moveDown = offsetY > 0; boolean moveUp = !moveDown; boolean canMoveUp = mPullToRefreshIndicator.hasStartPosition(); //判断是否要移动整个布局还是子布局自身移动 if(moveDown && canChildScrollUp(mPullToRefreshView.mContent)){ return mPullToRefreshView.dispatchTouchEventSupper(ev); } if ((moveUp && canMoveUp) || moveDown) { movePos(offsetY); return true; } break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mActivePointerId = -1; mPullToRefreshIndicator.onRelease(); if(mPullToRefreshIndicator.hasStartPosition()){ mPullToRefreshView.onRelease(); } if (mPullToRefreshIndicator.hasMovedAfterPressedDown()) { sendCancelEvent(); return true; } break; case MotionEventCompat.ACTION_POINTER_DOWN: mHasSendCancelEvent = false; final int pointerIndex = MotionEventCompat.getActionIndex(ev); mActivePointerId = MotionEventCompat.getPointerId(ev, pointerIndex); float x = MotionEventCompat.getX(ev, pointerIndex); float y = MotionEventCompat.getY(ev, pointerIndex); mPullToRefreshIndicator.onPressDown(x, y); mScrollChecker.abortIfWorking(); break; case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } return mPullToRefreshView.dispatchTouchEventSupper(ev); } private void movePos(float deltaY){ //已经到顶部 if(deltaY<0 && mPullToRefreshIndicator.isInStartPosition()){ return; } int to = mPullToRefreshIndicator.getCurrentPosY() + (int)deltaY; //over top if(mPullToRefreshIndicator.willOverTop(to)){ to = mPullToRefreshIndicator.POS_START; } mPullToRefreshIndicator.setCurrentPos(to); int change = to - mPullToRefreshIndicator.getLastPosY(); updatePos(change); } private void updatePos(int change){ if(change == 0){ return; } boolean isUnderTouch = mPullToRefreshIndicator.isUnderTouch(); if(isUnderTouch && !mHasSendCancelEvent && mPullToRefreshIndicator.hasMovedAfterPressedDown()){ mHasSendCancelEvent = true; sendCancelEvent(); } // back to initiated position if(mPullToRefreshIndicator.hasJustBackToStartPosition()){ // recover event to children if (isUnderTouch) { sendDownEvent(); } } mPullToRefreshView.mContent.offsetTopAndBottom(change); mPullToRefreshView.mHeaderView.offsetTopAndBottom(change); mPullToRefreshView.invalidate(); } private void sendCancelEvent() { MotionEvent last = mLastMoveEvent; MotionEvent e = MotionEvent.obtain(last.getDownTime(), last.getEventTime() + ViewConfiguration.getLongPressTimeout(), MotionEvent.ACTION_CANCEL, last.getX(), last.getY(), last.getMetaState()); mPullToRefreshView.dispatchTouchEventSupper(e); } private void sendDownEvent() { final MotionEvent last = mLastMoveEvent; MotionEvent e = MotionEvent.obtain(last.getDownTime(), last.getEventTime(), MotionEvent.ACTION_DOWN, last.getX(), last.getY(), last.getMetaState()); mPullToRefreshView.dispatchTouchEventSupper(e); } /** * 设置第二个触摸点移开后的操作 * * @param ev */ private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); float x = MotionEventCompat.getX(ev, newPointerIndex); float y = MotionEventCompat.getY(ev, newPointerIndex); mPullToRefreshIndicator.onPressDown(x, y); } } private boolean canChildScrollUp(View view){ if(android.os.Build.VERSION.SDK_INT < 14){ if (view instanceof AbsListView) { final AbsListView absListView = (AbsListView) view; return absListView.getChildCount() > 0 && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0) .getTop() < absListView.getPaddingTop()); } else { return view.getScrollY() > 0; } }else{ return view.canScrollVertically(-1); } } void tryToScrollTo(int to,int duration){ mScrollChecker.tryToScrollTo(to,duration); } void tryScrollBackToTop(){ if(!mPullToRefreshView.mPullToRefreshIndicator.isUnderTouch()){ mPullToRefreshView.mPullToRefreshTouchManager.tryToScrollTo(PullToRefreshIndicator.POS_START, mDurationToCloseHeader); } } boolean isRunning(){ return mScrollChecker.mIsRunning; } class ScrollChecker implements Runnable { private Scroller mScroller; private int mLastFlingY; private boolean mIsRunning = false; private int mStart; private int mTo; public ScrollChecker(){ mScroller = new Scroller(mPullToRefreshView.getContext()); } @Override public void run() { boolean finish = !mScroller.computeScrollOffset() || mScroller.isFinished(); int curY = mScroller.getCurrY(); int deltaY = curY - mLastFlingY; if(!finish){ mLastFlingY = curY; movePos(deltaY); mPullToRefreshView.post(this); }else{ finish(); } } private void finish(){ onScrollFinish(); reset(); } private void reset(){ mIsRunning = false; mLastFlingY = 0; mPullToRefreshView.removeCallbacks(this); } public void abortIfWorking(){ if(mIsRunning){ if(!mScroller.isFinished()){ mScroller.forceFinished(true); } } onScrollAbort(); reset(); } private void onScrollAbort(){ } private void onScrollFinish(){ } public void tryToScrollTo(int to,int duration){ if(mPullToRefreshIndicator.isAlreadyHere(to)){ return; } mStart = mPullToRefreshIndicator.getCurrentPosY(); mTo = to; int distance = to - mStart; mPullToRefreshView.removeCallbacks(this); mLastFlingY = 0; if(!mScroller.isFinished()){ mScroller.forceFinished(true); } mScroller.startScroll(0,0,0,distance,duration); mPullToRefreshView.post(this); mIsRunning = true; } } }
true
4f239abf747ae11865a00d7c60eb9a3a1552113d
Java
ptngmbjr/SchoolApp
/app/src/main/java/com/baseschoolapp/schoolapp/models/Student/AllMonthsAttendanceDataModel.java
UTF-8
891
2.421875
2
[]
no_license
package com.baseschoolapp.schoolapp.models.Student; public class AllMonthsAttendanceDataModel { public String getMonthName() { return monthName; } public void setMonthName(String monthName) { this.monthName = monthName; } public String getPresent_val() { return present_val; } public void setPresent_val(String present_val) { this.present_val = present_val; } public String getPercentage() { return percentage; } public void setPercentage(String percentage) { this.percentage = percentage; } String monthName; String present_val; String percentage; public AllMonthsAttendanceDataModel(String monthName, String present_val, String percentage) { this.monthName = monthName; this.present_val = present_val; this.percentage = percentage; } }
true
66298e413cb10613fd8390b463aa91c4eeb2d9a2
Java
52North/sos-for-geoevent
/sos-transport/src/main/java/net/opengis/gml/FeatureMember.java
UTF-8
644
1.96875
2
[]
no_license
package net.opengis.gml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import net.opengis.sa.x10.SamplingPoint; /** * * @author <a href="mailto:s.drost@52north.org">Sebastian Drost</a> * */ @XmlAccessorType(XmlAccessType.FIELD) public class FeatureMember { @XmlElement(name="SamplingPoint",namespace="http://www.opengis.net/sampling/1.0") private SamplingPoint samplingPoint; public SamplingPoint getSamplingPoint(){ return samplingPoint; } public void setSamplingPoint(SamplingPoint samplingPoint) { this.samplingPoint = samplingPoint; } }
true
03840157504dd7a73cf96241f48304c4f44fbdb9
Java
mboina/liveorderboard
/src/main/java/com/sbm/orders/liveorderboard/domain/OrderSummary.java
UTF-8
1,858
2.875
3
[]
no_license
package com.sbm.orders.liveorderboard.domain; import com.google.common.base.Preconditions; /** * Represents an {@link Order}, used for generating Order Summary. */ public class OrderSummary { private final OrderQuantity orderQuantity; private final OrderType orderType; private final UnitPrice unitPrice; public OrderSummary(OrderQuantity orderQuantity, UnitPrice unitPrice, OrderType orderType) { this.orderQuantity = orderQuantity; this.unitPrice = unitPrice; this.orderType = orderType; } public OrderQuantity getOrderQuantity() { return orderQuantity; } public UnitPrice getUnitPrice() { return unitPrice; } public OrderType getOrderType() { return orderType; } public OrderSummary merge(OrderSummary that) { OrderUnit thisOrderUnit = this.getOrderQuantity().getOrderUnit(); OrderUnit thatOrderUnit = that.getOrderQuantity().getOrderUnit(); Preconditions.checkArgument(thisOrderUnit == thatOrderUnit, "Cannot merge as order units do not match [" + thisOrderUnit + "] != [" + thisOrderUnit + "]"); Preconditions.checkArgument(this.getUnitPrice().equals(that.getUnitPrice()), "Cannot merge as unit prices do not match [" + this.getOrderType() + "] != [" + that.getOrderType() + "]"); Preconditions.checkArgument(this.getOrderType() == that.getOrderType(), "Cannot merge as order types do not match [" + this.getOrderType() + "] != [" + that.getOrderType() + "]"); OrderQuantity orderQuantity = new OrderQuantity(this.orderQuantity.getQuantity().add(that.getOrderQuantity().getQuantity()), thisOrderUnit); return new OrderSummary(orderQuantity, that.getUnitPrice(), that.getOrderType()); } }
true
3f5e796aa873934e93ad7f8371f0779e22b0f300
Java
simba1949/gof23
/src/main/java/top/simba1949/adapter/TFCard.java
UTF-8
275
2.03125
2
[ "Apache-2.0" ]
permissive
package top.simba1949.adapter; /** * @author anthony * @datetime 2023/7/20 22:10 */ public interface TFCard { /** * 读 TF * * @return */ String readTF(); /** * 写 TF * * @param msg */ void writeTF(String msg); }
true
d2336dad68b7823551eb48db0608281eadfc1ae3
Java
jefersonf/garupa.com
/Simulator/src/Entities/ClientServer.java
UTF-8
2,105
3.015625
3
[]
no_license
package Entities; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import eduni.simjava.*; public class ClientServer extends Sim_entity { private Sim_port in, out; private double delay; private String serverState; private Queue < String > queue1, queue2; private Random numGen; public ClientServer(String name, double delay) { super(name); this.delay = delay; serverState = "Empty"; queue1 = new LinkedList < String >(); queue2 = new LinkedList < String >(); numGen = new Random(); // Port for receiving events from the Scheduler in = new Sim_port("In"); // Port for sending events to Scheduler out = new Sim_port("Out"); add_port(in); add_port(out); } public void body() { while (Sim_system.running()) { Sim_event e = new Sim_event(); sim_get_next(e); sim_process(delay); sim_completed(e); if (e.get_tag() == 1) { sim_trace(1, "Tipo de evento: Chegada, Momento do evento: " + Sim_system.clock()); if (serverState.compareTo("Empty") != 0) queue1.add((String) e.get_data()); else { serverState = (String) e.get_data(); sim_schedule(out, numGen.nextInt(5) + 3, 3); } } else if (e.get_tag() == 2) { sim_trace(1, "Tipo de evento: Chegada, Momento do evento: " + Sim_system.clock()); if (serverState.compareTo("Empty") != 0) queue2.add((String) e.get_data()); else { serverState = (String) e.get_data(); sim_schedule(out, numGen.nextInt(5) + 3, 3); } } else { sim_trace(1, "Tipo de evento: Saída, Momento do evento: " + Sim_system.clock()); if (!queue1.isEmpty()) { serverState = queue1.poll(); sim_schedule(out, numGen.nextInt(5) + 3, 3); } else if (!queue2.isEmpty()) { serverState = queue2.poll(); sim_schedule(out, numGen.nextInt(5) + 3, 3); } else serverState = "Empty"; } sim_trace(1, "Elementos na Fila 1: " + queue1.toString()); sim_trace(1, "Elementos na Fila 2: " + queue2.toString()); sim_trace(1, "Elemento no serviço: " + serverState); sim_trace(1, ""); } } }
true
734fa312fb6280ef76b867147e9ac7389ada3334
Java
LyschevIvan/Lab7-server
/Application/Commands/RemoveGrKey.java
UTF-8
1,556
2.921875
3
[]
no_license
package com.company.Application.Commands; import com.company.Application.Data; import java.io.IOException; import java.net.Socket; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; /** * remove if key is greater */ class RemoveGrKey extends AbstractCommand { public RemoveGrKey(ControllersProvider controllersProvider) { super(controllersProvider); } @Override public ArrayList<Data> execute(Data data, String login) { ArrayList<Data> responses = new ArrayList<>(); Integer key = Integer.valueOf(data.getMessage()[1]); try{ controllersProvider.getDbController().removeGrKey(key, login); Iterator<Integer> keyIterator = controllersProvider.getTreeMapController().getKeyIterator(); while (keyIterator.hasNext()){ Integer k = keyIterator.next(); if(k>key) keyIterator.remove(); } responses.add(new Data("Продукт успешно удален!")) ; } catch (SQLException throwables) { throwables.printStackTrace(); System.out.println("Ошибка при удалении!"); responses.add(new Data("Ошибка при удалении!")); } return responses; } @Override public String getInfo() { return "remove_greater_key key : удалить из коллекции все элементы, ключ которых превышает заданный"; } }
true
f432ab49a44b3b49408151bdb3b35832eda7f464
Java
lishashalyt/JingDong_Lss
/app/src/main/java/com/bawei/jingdong_lss/model/ZiProductModel.java
UTF-8
1,226
2.15625
2
[]
no_license
package com.bawei.jingdong_lss.model; import com.bawei.jingdong_lss.bean.ZiProduct; import com.bawei.jingdong_lss.net.OnNetListener; import com.bawei.jingdong_lss.net.RetrofitHelper; import com.bawei.jingdong_lss.net.ServerApi; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class ZiProductModel implements IZiProductModel { @Override public void getZiProduct(final OnNetListener<ZiProduct> onNetListener, String pid) { ServerApi serverApi = RetrofitHelper.getServerApi(); serverApi.ziproduct(pid) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<ZiProduct>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { onNetListener.onFailure((Exception) e); } @Override public void onNext(ZiProduct ziProduct) { onNetListener.onSuccess(ziProduct); } }); } }
true
df5a592dd5ffca1af69d11355cf02a9da2e9536d
Java
P79N6A/icse_20_user_study
/methods/Method_36798.java
UTF-8
64
1.632813
2
[]
no_license
public BaseCell getCell(View view){ return vmMap.get(view); }
true
78b195767ebeaad3d84f0089e42a25199c4b6114
Java
jpaulo02/GymAgenda
/app/src/main/java/com/brogrammers/paulo/gymagenda/SpotifyEndpoints.java
UTF-8
452
2.359375
2
[]
no_license
package com.brogrammers.paulo.gymagenda; /** * Created by paulo on 4/13/17. */ public enum SpotifyEndpoints { GET_CURRENTLY_PLAYING("https://api.spotify.com/v1/me/player/currently-playing"), GET_USER_PLAYLISTS("https://api.spotify.com/v1/users/{user_id}/playlists"); private final String value; private SpotifyEndpoints(String s) { value = s; } public String getStringValue() { return this.value; } }
true
6c402fce1e1bf5366f62f846f4571e14d5838582
Java
zhangyufeng12/Basis
/src/main/day14/ProducerConsumerDemo2.java
UTF-8
3,401
3.453125
3
[]
no_license
package main.day14; /* jdk1.5以后将同步和锁封装成了对象。 并将操作锁的隐式方式定义到了该对象中, 将隐式动作变成了显示动作。 Lock接口: 出现替代了同步代码块或者同步函数。将同步的隐式锁操作变成现实锁操作。 同时更为灵活。可以一个锁上加上多组监视器。 lock():获取锁。 unlock():释放锁,通常需要定义finally代码块中。 Condition接口:出现替代了Object中的wait notify notifyAll方法。 将这些监视器方法单独进行了封装,变成Condition监视器对象。 可以任意锁进行组合。 await(); signal(); signalAll(); */ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* *@author zhangyufeng *@data 2018/7/19 下午12:38 */ class Resource6 { private String name; private int count = 1; private boolean flag = false; // 创建一个锁对象。 Lock lock =new ReentrantLock(); //通过已有的锁获取该锁上的监视器对象。 // Condition con = lock.newCondition(); //通过已有的锁获取两组监视器,一组监视生产者,一组监视消费者。 Condition producer_con = lock.newCondition(); Condition consumer_con = lock.newCondition(); public void set(String name) { lock.lock(); try { while (flag) { try { producer_con.await(); } catch (InterruptedException e) { e.printStackTrace(); } } this.name =name; count++; System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name+count); flag=true; // notifyAll(); consumer_con.signal(); } finally { lock.unlock(); } } public void out() { lock.lock(); try { while (!flag) { try { consumer_con.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name+count); flag = false; // notifyAll(); producer_con.signal(); } finally { lock.unlock(); } } } class Producer1 implements Runnable { Resource6 r; Producer1(Resource6 r) { this.r=r; } @Override public void run() { while (true) { r.set("哈哈"); } } } class Consumer1 implements Runnable { Resource6 r; Consumer1(Resource6 r) { this.r=r; } @Override public void run() { while (true) { r.out(); } } } public class ProducerConsumerDemo2 { public static void main( String[] args ) { Resource6 r= new Resource6(); Producer1 p1= new Producer1(r); Consumer1 con1 = new Consumer1(r); Thread t0 = new Thread(p1); Thread t1 = new Thread(p1); Thread t2 = new Thread(con1); Thread t3 = new Thread(con1); t0.start(); t1.start(); t2.start(); t3.start(); } }
true
9f3616a5d20ba90b9dfca0ed825c62857ae01485
Java
oceanbhardwaj/LeetcodeJulyChallenge
/ConstructBinaryTreefromInorderandPostorderTraversal.java
UTF-8
1,117
2.75
3
[]
no_license
class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { int len=inorder.length; return Helper(inorder,postorder,0,len-1,0,len-1); } static TreeNode Helper(int[] inorder,int[]postorder,int instart,int inend,int poststart,int postend) { if(instart>inend) return null; int rootval=postorder[postend]; TreeNode root=new TreeNode(rootval); int rootindex=instart; for(;rootindex<=inend;rootindex++) { if(inorder[rootindex]==rootval) break; } int leftheight=rootindex-instart; int rightheight=inend-rootindex; root.left=Solution.Helper( inorder, postorder,instart,rootindex-1,poststart,poststart+leftheight-1); root.right=Solution.Helper( inorder, postorder,rootindex+1,inend,postend-rightheight,postend-1); return root; } }
true
b89d8f42bf0b9b53f6c81d99628ff19b3f03e089
Java
Atikasoft/protteus2
/proteus-web/src/main/java/ec/com/atikasoft/proteus/controlador/helper/TramiteRevisionHelper.java
UTF-8
985
1.734375
2
[]
no_license
/* * TramiteValidacionHelper.java * Proteus V 2.0 $Revision 1.0 $ * * Todos los derechos reservados. All rights reserved. * This software is the confidential and proprietary information of Proteus * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into * with Proteus. * * Proteus * Quito - Ecuador * * * 07/12/2012 * */ package ec.com.atikasoft.proteus.controlador.helper; import ec.com.atikasoft.proteus.controlador.helper.base.AtencionHelper; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; /** * Helper de Revision Validacion. * * @author Victor Quimbiamba <victor.quimbiamba@atikasoft.com.ec> */ @ManagedBean(name = "tramiteRevisionHelper") @SessionScoped public class TramiteRevisionHelper extends AtencionHelper { /** * Constructor por defecto. */ public TramiteRevisionHelper() { super(); } }
true
c12a857e80a1e01828b5c4af04164cd37d70289c
Java
JayWebDevCom/Supermarket
/src/tests/ThreeForTwoTest.java
UTF-8
2,124
2.84375
3
[]
no_license
package tests; import models.Basket; import models.Product; import models.Saving; import models.offers.ThreeForTwo; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; public class ThreeForTwoTest { private ThreeForTwo tft; private Product juice; private Basket basket; @Before public void setUp() throws Exception { juice = new Product("Juice", 1.99); tft = new ThreeForTwo("Three For Two", juice.getName()); basket = new Basket(juice, juice, juice, juice, juice); } @Test public void addOffer(){ Product yoghurt = new Product("Yoghurt", 1.49); tft.addProduct(yoghurt.getName()); assertEquals(2, tft.getIncludedProducts().size()); } @Test public void removeOffer(){ tft.removeProduct(juice.getName()); assertEquals(0, tft.getIncludedProducts().size()); } @Test public void applyToBasketAddsOneSavingForThree() throws Exception { Basket basket = new Basket(juice, juice, juice); List<Saving> savings = tft.generateSavings(basket.getProducts()); assertEquals(1, savings.size()); assertEquals(-1 * juice.getPrice(), savings.get(0).getSaving(), 0.001); } @Test public void applyToBasketAddsOneSavingForFive() throws Exception { List<Saving> savings = tft.generateSavings(basket.getProducts()); assertEquals(1, savings.size()); assertEquals(-1 * juice.getPrice(), savings.get(0).getSaving(), 0.001); } @Test public void applyToBasketAddsTwoSavingForSix() throws Exception { basket.add(juice); List<Saving> savings = tft.generateSavings(basket.getProducts()); assertEquals(2, savings.size()); assertEquals(-1 * juice.getPrice(), savings.get(0).getSaving(), 0.001); } @Test public void applyToBasketNoSavingsWhenProductNotIncluded() throws Exception { tft.removeProduct(juice.getName()); List<Saving> savings = tft.generateSavings(basket.getProducts()); assertEquals(0, savings.size()); } }
true
5f3fdcbfa48e03bff22b047de8c2d7e639d805fd
Java
unsamdev/plataforma1
/src/plataforma1/wicket/SetFocusBehavior.java
UTF-8
653
2.328125
2
[]
no_license
package plataforma1.wicket; import org.apache.wicket.Component; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; public class SetFocusBehavior extends Behavior { @Override public void bind(Component component) { component.setOutputMarkupId(true); } @Override public void renderHead(Component component, IHeaderResponse response) { super.renderHead(component, response); response.render(OnDomReadyHeaderItem.forScript("document.getElementById('" + component.getMarkupId() + "').focus()")); } }
true
a6f376f0f2719da73c9dcf49e0999712ec8ed5d8
Java
MarianaOnica/OOP
/Lab4/src/com/mariana/practica/Practica2/practice_3.java
UTF-8
720
3.59375
4
[]
no_license
package com.mariana.practica.Practica2; public class practice_3 { public static void main(String[] args) { // Employee e1 = new Employee(); // e1.name = "Ionica"; SimpleEmployee s1 = new SimpleEmployee(5); s1.name = "Grisha"; } } class Employee { public String name; public double salary; Employee(){ System.out.println("Employee constructor called"); } } class SimpleEmployee extends Employee{ SimpleEmployee(){ System.out.println("SimpleEmployee constructor called"); } SimpleEmployee(int a){ this(); System.out.println("SimpleEmployee constructor with paremeter "); System.out.println(a); } }
true
123638c5cbc66444d50c91476991eff4775fd034
Java
kothsada/ace_member_android
/app/src/main/java/com/ace/member/main/me/payment_history/PaymentHistoryActivity.java
UTF-8
6,381
1.914063
2
[]
no_license
package com.ace.member.main.me.payment_history; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.AppCompatImageView; import android.text.TextUtils; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.PopupWindow; import android.widget.TextView; import com.ace.member.R; import com.ace.member.base.BaseActivity; import com.ace.member.bean.PaymentHistoryBean; import com.ace.member.main.third_party.edc.detail.EdcHistoryDetailActivity; import com.ace.member.main.third_party.wsa.detail.WsaHistoryDetailActivity; import com.ace.member.popup_window.DatePickerPopWindow; import com.ace.member.toolbar.ToolBarConfig; import com.ace.member.utils.AppGlobal; import com.og.component.CustomSlidingRefreshListView; import com.og.utils.DateUtils; import com.og.utils.FileUtils; import com.og.utils.Utils; import java.util.ArrayList; import javax.inject.Inject; import butterknife.BindView; public class PaymentHistoryActivity extends BaseActivity implements PaymentHistoryContract.PaymentHistoryView, CustomSlidingRefreshListView.IXListViewListener { @Inject PaymentHistoryPresenter mPaymentHistoryPresenter; @BindView(R.id.lv_payment) CustomSlidingRefreshListView mLVPaymentHistory; @BindView(R.id.iv_menu) AppCompatImageView mIvMenu; @BindView(R.id.tv_condition) TextView mTvCondition; public PaymentHistoryListAdapter mAdapter; private int mPage = 1; private String mDateStart; private String mDateEnd; private String mSelectedType; private ArrayList<String> mTypeList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DaggerPaymentHistoryComponent.builder() .paymentHistoryPresenterModule(new PaymentHistoryPresenterModule(this, this)) .build() .inject(this); initActivity(); } @Override protected int getContentViewID() { return R.layout.activity_payment_history; } public void initActivity() { ToolBarConfig.builder(this, null) .setTvTitleRes(R.string.payment_history) .setIvMenuRes(R.drawable.ic_filter) .setMenuType(ToolBarConfig.MenuType.MENU_IMAGE) .setEnableMenu(true) .build(); setTypeList(); initListener(); mLVPaymentHistory.setPullLoadEnable(false); mLVPaymentHistory.setXListViewListener(this); mLVPaymentHistory.setRefreshTime(DateUtils.getFormatDataTime()); mLVPaymentHistory.hideLoadMore(); mLVPaymentHistory.setPullRefreshEnable(true); mDateStart = DateUtils.getToday(); mDateEnd = DateUtils.getToday(); setTvCondition(); mPaymentHistoryPresenter.getList(mDateStart, mDateEnd, mSelectedType, mPage); setItemListener(); } private void setTypeList() { if (mTypeList == null) { mTypeList = new ArrayList<>(); mTypeList.add("All"); mTypeList.add("Electricity"); mTypeList.add("Water"); } } private void initListener() { mIvMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DatePickerPopWindow datePickerPopWin = new DatePickerPopWindow.Builder(PaymentHistoryActivity.this, mDateStart, mDateEnd, mSelectedType, new DatePickerPopWindow.OnDatePickedListener() { @Override public void onDatePickCompleted(String dateStart, String dateEnd, String selectedType) { mDateStart = dateStart; mDateEnd = dateEnd; if ("All".equals(selectedType)) { selectedType = ""; } mSelectedType = selectedType; mPaymentHistoryPresenter.getList(mDateStart, mDateEnd, mSelectedType, mPage); setTvCondition(); } }).setSearchList(mTypeList).setCurrencyWidth(Utils.getDimenPx(R.dimen.width100)).build(); datePickerPopWin.showPopWin(PaymentHistoryActivity.this); datePickerPopWin.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 1f; getWindow().setAttributes(lp); } }); WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.7f; getWindow().setAttributes(lp); } }); } private void setTvCondition() { String type; if (TextUtils.isEmpty(mSelectedType)) { type = "All Type"; } else { type = mSelectedType; } mTvCondition.setText(type + " / " + mDateStart + " to " + mDateEnd); } @Override public void onRefresh() { mPage = 1; mPaymentHistoryPresenter.getList(mDateStart, mDateEnd, mSelectedType, mPage); } @Override public void onLoadMore() { if (mPage > 0) { mPaymentHistoryPresenter.getList(mDateStart, mDateEnd, mSelectedType, mPage); } } private void onLoad() { mLVPaymentHistory.stopRefresh(); mLVPaymentHistory.stopLoadMore(); } @Override public void showList(int nextPage, boolean isHint) { try { mPage = nextPage; mLVPaymentHistory.setRefreshTime(DateUtils.getFormatDataTime()); int len = mPaymentHistoryPresenter.getData().size(); if (len > 0 && isHint) { mLVPaymentHistory.setPullLoadEnable(true); mLVPaymentHistory.showLoadMore(); } else { mLVPaymentHistory.setPullLoadEnable(false); mLVPaymentHistory.hideLoadMore(); if (len == 0) Utils.showToast(R.string.no_data); } mAdapter = new PaymentHistoryListAdapter(mPaymentHistoryPresenter.getData()); mLVPaymentHistory.setAdapter(mAdapter); onLoad(); } catch (Exception e) { FileUtils.addErrorLog(e); e.printStackTrace(); } } @Override public void showNextList(int nextPage) { try { if (nextPage == 0) { mLVPaymentHistory.hideLoadMore(); mLVPaymentHistory.setPullLoadEnable(false); return; } mPage = nextPage; mAdapter.notifyDataSetChanged(); onLoad(); } catch (Exception e) { e.printStackTrace(); } } public void setItemListener() { mLVPaymentHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //list view 的索引是从1开始的 PaymentHistoryBean bean = mPaymentHistoryPresenter.getData().get(position - 1); Intent intent = new Intent(PaymentHistoryActivity.this, bean.getType() == AppGlobal.PAYMENT_TYPE_1_EDC ? EdcHistoryDetailActivity.class : WsaHistoryDetailActivity.class); intent.putExtra("id", bean.getId()); startActivity(intent); } }); } }
true
9be3a157a200250b61ebc8f417b9fe7ef711c50c
Java
IESJacaranda/FranArroyo1DAW
/Coronavirus/src/es/iesjacaranda/corona/Coronavirus.java
UTF-8
2,309
2.6875
3
[]
no_license
package es.iesjacaranda.corona; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.time.LocalDate; import java.util.ArrayList; import com.google.gson.Gson; //gettersetterconstructorhashset //fechaconformato public class Coronavirus { String fecha; private int contagiados; private int fallecidos; private int curados; public Coronavirus(String fecha, int contagiados, int fallecidos, int curados) { super(); this.fecha = fecha; this.contagiados = contagiados; this.fallecidos = fallecidos; this.curados = curados; } public Coronavirus() { super(); } ArrayList solucion=new ArrayList<Coronavirus>(); public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public int getContagiados() { return contagiados; } public void setContagiados(int contagiados) { this.contagiados = contagiados; } public int getFallecidos() { return fallecidos; } public void setFallecidos(int fallecidos) { this.fallecidos = fallecidos; } public ArrayList getSolucion() { return solucion; } public int getCurados() { return curados; } public void setCurados(int curados) { this.curados = curados; } public ArrayList MostrarDia() { String linea; StringBuilder resul = new StringBuilder(); try { FileReader flujoLectura=new FileReader("./ficheros/casos_diagnosticados_de_c.json"); BufferedReader filtroLectura=new BufferedReader(flujoLectura); linea=filtroLectura.readLine(); while ( linea!=null) { resul.append(linea); linea=filtroLectura.readLine(); } filtroLectura.close(); flujoLectura.close(); } catch(FileNotFoundException e){ } catch(IOException e){ } Gson gson = new Gson(); LecturaJson l = gson.fromJson(resul.toString(), LecturaJson.class); long menor=0; String dias=""; for (ClaseMetrica aux : l.getDatos().getMetrica()) { for (Informacion inf : aux.getDatos()) { System.out.println(inf.getValor()-inf.getValor()); if (menor<inf.getValor()) { menor=inf.getValor(); String[] dia=inf.getPeriodo().split(" ", 2); Coronavirus c=new Coronavirus(dia[1], (int) inf.getValor(), 0, 0); solucion.add(c); } } } return solucion; } }
true
8b654afd75ed2464b78e99afca8fdbc6c08a4256
Java
hongLev/-
/pinyougou-manage-web/src/main/java/com/pinyougou/manager/controller/ItemCatController.java
UTF-8
2,007
2.078125
2
[]
no_license
package com.pinyougou.manager.controller; import java.util.List; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.dubbo.config.annotation.Reference; import com.pinyougou.pojo.TbItemCat; import com.pinyougou.sellergoods.service.ItemCatService; import entity.JSONResult; @RestController @RequestMapping("/ItemCat") public class ItemCatController { @Reference private ItemCatService itemCatService; /** * 根据父类id获取商品分类 * @param id * @return */ @RequestMapping("/select") public List<TbItemCat> getItemCatByParenId(Long id){ return this.itemCatService.getItemCatByparenId(id); } /** * 新增 或者修改 * @param itemCat */ @RequestMapping("/addOrupdata") public JSONResult addOrupdata(@RequestBody TbItemCat itemCat){ JSONResult json = new JSONResult(); try { this.itemCatService.addOrupdata(itemCat); json.setSuccess(true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); json.setMessage("保存失败"); json.setSuccess(false); } return json; } /** * 根据主键id查找 * @param id * @return */ @RequestMapping("/findOne") public TbItemCat findOne(Long id){ return this.itemCatService.findOne(id); } /** * 根据主键id依此删除 * @param id * @return */ @RequestMapping("/deleteById") public JSONResult deleteById(Long[] id){ JSONResult json = new JSONResult(); try { this.itemCatService.deleteItemCatById(id); json.setSuccess(true); json.setMessage("删除成功"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); json.setMessage("删除失败"); json.setSuccess(false); } return json; } /** * 查找全部 * @return */ @RequestMapping("/selectAll") public List<TbItemCat> selectAll(){ return this.itemCatService.findAll(); } }
true
508f9c548d9c7b963635a451a6e2a5d1f80c5fa4
Java
andreysher/study
/3k-1s/architecture/laba4/benchit/kernel/numerical/elementary/Java/0/0/sincostan/KernelMain.java
UTF-8
11,057
2.421875
2
[]
no_license
/******************************************************************** * BenchIT - Performance Measurement for Scientific Applications * Contact: developer@benchit.org * * $Id: KernelMain.java 1 2009-09-11 12:26:19Z william $ * $URL: svn+ssh://william@rupert.zih.tu-dresden.de/svn-base/benchit-root/BenchITv6/kernel/numerical/elementary/Java/0/0/sincostan/KernelMain.java $ * For license details see COPYING in the package base directory *******************************************************************/ /* Kernel: Execution time of mathematical operations * SINUS / COSINUS / TANGENT addict to input value *******************************************************************/ import java.util.Date; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** This class is the Interface between the measured algorithm and BenchIT. * @author Robert Wloch, wloch@zhr.tu-dresden.de */ public class KernelMain implements BIJavaKernel { /* if it is static it has to be calculated just one time */ private static double timeroverhead = 0.0; /** * Here we define a minimum time that our kernel needs * we do this to avoid a divide by zero. */ private static double MINTIME = 5.0e-6; /* attributes */ /** * These variables will help us to keep the overview over the arrays * we access for our functions/data. */ /** * Number of different ways an algorithm will be measured. * sin, cos, tan -> n_of_works=3; */ private int n_of_works; /** * Number of fixed functions we have per measurement. * Example: execution time and MFLOPS are measured for each loop order * -> n_of_sure_funcs_per_work=2 */ private int n_of_sure_funcs_per_work; private int num_funcs = 0; private int bi_angle_start, bi_angle_stop, bi_angle_increment; private BIEnvHash rwe = null; /** * The constructor. */ public KernelMain() { rwe = BIEnvHash.getInstance(); } /** * The implementation of the bi_getinfo from the BenchIT interface. * Here the info is filled with informations about the kernel. * @param info An Object to hold the info about the kernel. */ public int bi_getinfo( InfoObject info ) { evaluate_environment(); info.codesequence = "for( a=0; a<LOOPS; a++) do the mathematical operation; "; info.xaxistext = "Angle (degree)"; info.log_xaxis = 0; info.base_xaxis = 0; info.maxproblemsize = (bi_angle_stop-bi_angle_start+1)/bi_angle_increment; if ((bi_angle_stop-bi_angle_start+1) % bi_angle_increment != 0) info.maxproblemsize++; info.kernel_execs_mpi1 = 0; info.kernel_execs_mpi2 = 0; info.kernel_execs_pvm = 0; info.kernel_execs_omp = 0; info.kernel_execs_pthreads = 0; info.kernel_execs_javathreads = 0; /* B ########################################################*/ n_of_works = 3; /* number versions of this algorithm sin,cos,tan = 3 */ n_of_sure_funcs_per_work = 1; /* FLOPS */ /*########################################################*/ num_funcs = n_of_works * n_of_sure_funcs_per_work; info.numfunctions = num_funcs; /* allocating memory for y axis texts and properties */ info.yaxistexts = new String[info.numfunctions]; info.selected_result = new int[info.numfunctions]; info.legendtexts = new String[info.numfunctions]; info.log_yaxis = new int[info.numfunctions]; info.base_yaxis = new int[info.numfunctions]; /* setting up y axis texts and properties */ for ( int j = 0; j < n_of_works; j++ ) { /* B ########################################################*/ int index1 = 0 * n_of_works + j; info.yaxistexts[index1] = "Op/s"; info.selected_result[index1] = 0; info.log_yaxis[index1] = 0; info.base_yaxis[index1] = 0; /*########################################################*/ switch ( j ) { /* B ########################################################*/ case 0: // 1th version legend text info.legendtexts[index1] = "sinus"; break; case 1: // 2th version legend text info.legendtexts[index1] = "cosinus"; break; case 2: // 3th version legend text info.legendtexts[index1] = "tangent"; break; default: System.out.println( "Error: corrupte n_of_works" ); System.exit( 127 ); /*########################################################*/ } } return 0; } /** * Implementation of the bi_init of the BenchIT interface. */ public Object bi_init( int problemsizemax ) { if ( problemsizemax > bi_angle_stop ) { System.out.println( "Kernel: Illegal problem size!" ); System.exit( 127 ); } DataObject dataObject = new DataObject(); return (Object)dataObject; } /** * The central function within each kernel. This function * is called for each measurment step seperately. * @param dObject an Object to the attributes initialized in bi_init, * it is the Object bi_init returns * @param problemsize the actual problemsize * @param results an array of doubles, the * size of the array depends on the number * of functions, there are #functions+1 * doubles * @return 0 if the measurment was sucessfull, something * else in the case of an error */ public int bi_entry( Object dObject, int problemsize, double[] results ) { /* ts, te: the start and end time of the measurement */ /* timeinsecs: the time for a single measurement in seconds */ double ts = 0.0, te = 0.0, calloverhead = 0.0; double[] timeinsecs = new double[n_of_works]; double maxn = 0.0; long howManyRepeats = 1; double dummy; SinCosTan worker = new SinCosTan(); maxn = bi_angle_start + (problemsize-1) * bi_angle_increment; // System.out.println("problemsize: " + (int)maxn); /* convert degree to radian */ maxn = Math.toRadians((double)maxn); /* calculate overhead if it is not done yet */ if ( timeroverhead == 0.0 ) { timeroverhead = gettimeroverhead(); /* maybe we have a VERY fast timer ;-) * the /10000 is because we measure the timeroverhead with 10000 calls * to the timer. if this can't be measured with the timers resolution * 1 call has to be 10000 times faster than the resolution of the timer */ if ( timeroverhead == 0.0 ) timeroverhead = MINTIME/10000; } /* check wether the pointer to store the results in is valid or not */ if ( results == null ) return 1; do { for (int j=0; j<n_of_works; j++) { /* reset of reused values */ ts = 0.0; te = 0.0; timeinsecs[j] = 0.0; ts = JBI.bi_gettime(); dummy = worker.getOverhead(maxn, howManyRepeats); te = JBI.bi_gettime(); calloverhead = te - ts; /* choose version of algorithm */ switch ( j ) { case 0: // 1th version legend text /* take start time, do measurment, and take end time */ ts = JBI.bi_gettime(); dummy = worker.sin(maxn, howManyRepeats); te = JBI.bi_gettime(); break; case 1: // 2th version legend text /* take start time, do measurment, and take end time */ ts = JBI.bi_gettime(); dummy = worker.cos(maxn, howManyRepeats); te = JBI.bi_gettime(); break; case 2: // 3th version legend text /* take start time, do measurment, and take end time */ ts = JBI.bi_gettime(); dummy = worker.tan(maxn, howManyRepeats); te = JBI.bi_gettime(); break; default: System.out.println( "Error: corrupte n_of_works" ); System.exit( 127 ); } /* calculate the used time and FLOPS */ timeinsecs[j] = te - ts; timeinsecs[j] -= calloverhead; timeinsecs[j] -= timeroverhead; } howManyRepeats = howManyRepeats * 8; if( (timeinsecs[0]>MINTIME) && (timeinsecs[1]>MINTIME) && (timeinsecs[2]>MINTIME) ) { break; } } while(true); /* reset last multiplication on howManyRepeats */ howManyRepeats = (long)howManyRepeats / 8; /** * the index 0 always keeps the value for the x axis * the xaxis value needs to be stored only once! */ results[0] = (double)(bi_angle_start + (problemsize-1) * bi_angle_increment); /** * store the results in results[1], results[2], ... * [1] for the first function, [2] for the second function * and so on ... */ for (int j=0; j<n_of_works; j++) { results[j + 1] = howManyRepeats / timeinsecs[j]; } return(0); } /** * Tries to measure the timer overhead for a single call to bi_gettime(). * @return the calculated overhead in seconds */ private double gettimeroverhead() { int s; double ts, te, t; ts = JBI.bi_gettime(); for ( s = 0; s < 10000; s++ ) { t = JBI.bi_gettime(); } te = JBI.bi_gettime(); return ( te - ts ) / 10000.0; } /** * Reads the environment variables used by this kernel. */ private void evaluate_environment() { String s_bi_angle_start = null, s_bi_angle_stop = null, s_bi_angle_increment = null; int i_bi_angle_start = -1, i_bi_angle_stop = -1, i_bi_angle_increment = 500; s_bi_angle_start = rwe.bi_getEnv("BENCHIT_KERNEL_PROBLEMSIZE_MIN"); s_bi_angle_stop = rwe.bi_getEnv("BENCHIT_KERNEL_PROBLEMSIZE_MAX"); s_bi_angle_increment = rwe.bi_getEnv("BENCHIT_KERNEL_PROBLEMSIZE_INCREMENT"); if ((s_bi_angle_start == null) || (s_bi_angle_stop == null) || (s_bi_angle_increment == null)) { i_bi_angle_start = 1; i_bi_angle_stop = 360; i_bi_angle_increment = 1; } try { i_bi_angle_start = (new Integer(s_bi_angle_start)).intValue(); i_bi_angle_stop = (new Integer(s_bi_angle_stop)).intValue(); i_bi_angle_increment = (new Integer(s_bi_angle_increment)).intValue(); } catch ( NumberFormatException nfe ) { i_bi_angle_start = 1; i_bi_angle_stop = 360; i_bi_angle_increment = 1; } bi_angle_start = i_bi_angle_start; bi_angle_stop = i_bi_angle_stop; bi_angle_increment = i_bi_angle_increment; } }
true
95410c88e5deb8f30b24566cfd15197a806d60a1
Java
yuanyisheng/yys_springboot
/yys-springboot-freemarker-templateDirectiveModel/src/main/java/com/yys/freemarker/BaseDirective.java
UTF-8
490
2.03125
2
[]
no_license
package com.yys.freemarker; import freemarker.ext.beans.BeansWrapper; import freemarker.ext.beans.BeansWrapperBuilder; import freemarker.template.Configuration; import freemarker.template.TemplateDirectiveModel; /** * 自定义标签父类 * Directive * @author yys */ public abstract class BaseDirective implements TemplateDirectiveModel { public static BeansWrapper getBeansWrapper(){ return new BeansWrapperBuilder(Configuration.VERSION_2_3_21).build(); } }
true
ced5a58ae6afa58ff054e342a0b88aa6aa044338
Java
micha1981/SpringRest
/src/main/java/pl/org/rudnicki/service/CarService.java
UTF-8
947
2.296875
2
[]
no_license
package pl.org.rudnicki.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.org.rudnicki.dao.CarDao; import pl.org.rudnicki.model.Car; @Service public class CarService { private final CarDao carDao; @Autowired public CarService(CarDao carDao) { super(); this.carDao = carDao; } public Boolean saveCar(Car car) { return carDao.saveCar(car); } public Car getCarById(Integer id) { return carDao.getCarById(id); } public List<Car> getCarList(){ return carDao.getCarList(); } public Boolean deleteCar(Integer id) { try { carDao.deleteCar(id); return true; } catch (Exception e) { return false; } } public Boolean updateCar(Car car) { try { carDao.updateCar(car); return true; } catch (Exception e) { return false; } } }
true
7409b125b599cfb65175e1b6f9cdd703c3ef8590
Java
victoria12345/padsof
/nuevaguiaverquetal/src/paneles/ElegirRolPanel.java
ISO-8859-10
2,785
2.890625
3
[]
no_license
package paneles; import java.awt.*; import java.awt.event.*; import javax.swing.*; import app.Sistema; /** * Descripcion de la clase ElegirRolPanel * @author Victoria Pelayo e Ignacio Rabunnal * */ public class ElegirRolPanel extends JPanel { private static final long serialVersionUID = 1L; private JLabel labelModo = new JLabel("Elija el modo que desea usar"); private JLabel labelCont = new JLabel("Nueva Contrasea:"); private JTextField campoCont = new JTextField(30); private JButton bOfertante = new JButton("Ofertante"); private JButton bDemandante = new JButton("Demandante"); private JButton bAdministrador = new JButton("Administrador"); private JButton bSalir = new JButton("Salir"); private JButton bCont = new JButton("Cambiar contrasenna"); private Sistema sist; /** * Constructor del panel de elegir rol * @param sist sistema con los datos y funciones pertinentes */ public ElegirRolPanel(Sistema sist) { this.sist = sist; GridBagLayout layout = new GridBagLayout(); GridBagConstraints cons = new GridBagConstraints(); this.setLayout(layout); cons.fill = GridBagConstraints.NONE; cons.anchor = GridBagConstraints.WEST; cons.gridx = 1; cons.gridy = 0; layout.setConstraints(bOfertante, cons); cons.gridy = 1; layout.setConstraints(bAdministrador, cons); cons.gridy = 2; layout.setConstraints(bDemandante, cons); cons.gridy = 3; layout.setConstraints(bSalir, cons); cons.gridx = 0; cons.gridy = 0; JPanel p4 = new JPanel(); p4.add(labelCont); p4.add(campoCont); cons.gridy = 1; layout.setConstraints(bCont, cons); cons.gridx = 0; cons.gridy = 7; JPanel p5 = new JPanel(); p4.add(labelModo); this.add(p4); this.add(p5); this.add(bCont); this.add(bOfertante); this.add(bDemandante); this.add(bAdministrador); this.add(bSalir); } public JTextField getCampoCont() { return campoCont; } public JButton getbOfertante() { return bOfertante; } public JButton getbDemandante() { return bDemandante; } public JButton getbAdministrador() { return bAdministrador; } public JButton getbSalir() { return bSalir; } public JButton getbCont() { return bCont; } public Sistema getSist() { return sist; } public void setSist(Sistema sist) { this.sist = sist; } /** * Establece un controlador para el panel * @param a1 controlador del panel */ public void setControlador(ActionListener al) { this.bOfertante.addActionListener(al); this.bAdministrador.addActionListener(al); this.bDemandante.addActionListener(al); this.bSalir.addActionListener(al); this.bCont.addActionListener(al); } }
true
3605f9c6f6181e877d53da8e8ce4617b29515f63
Java
iamjones/msc-cs-project
/src/main/java/domain/stopwords/StopWords.java
UTF-8
2,352
3.328125
3
[]
no_license
package domain.stopwords; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * This class holds all the stop words a provided methods to * do some processing with the stored list of stop words. */ public class StopWords { public String[] stopwords = { "a","about","above","after","again","against","all","am","an","and","any","are","arent","as","at","be", "because","been","before","being","below","between","both","but","by","cant","cannot","could","couldnt", "did","didnt","do","does","doesnt","doing","dont","down","during","each","few","for","from","further", "had","hadnt","has","hasnt","have","havent","having","he","hed","hell","hes","her","here","heres", "hers","herself","him","himself","his","how","hows","i","id","ill","im","ive","if","in","into","is", "isnt","it","its","its","itself","lets","me","more","most","mustnt","my","myself","no","nor", "of","off","on","once","only","or","other","ought","our","ours","ourselves","out","over","own","same", "shant","she","shed","shell","shes","should","shouldnt","so","some","such","than","that","thats","the", "their","theirs","them","themselves","then","there","theres","these","they","theyd","theyll","theyre", "theyve","this","those","through","to","too","under","until","up","very","was","wasnt","we","wed","well", "were","weve","were","werent","what","whats","when","whens","where","wheres","which","while","who", "whos","whom","why","whys","with","wont","would","wouldnt","you","youd","youll","youre","youve","your", "yours","yourself","yourselves" }; private List<String> stopwordsList; public StopWords() { this.stopwordsList = Arrays.asList(this.stopwords); } /** * Takes a document and removes all the stop words that it contains. * Returns a list of words that are not found in our stop word list. * * @param document String * @return List<String> */ public List<String> removeStopWords(List<String> document) { List<String> nonStopWords = new ArrayList<>(); for (String word : document) { if (!this.stopwordsList.contains(word.toLowerCase())) { nonStopWords.add(word); } } return nonStopWords; } }
true
edd1d815288200ace6d0e61feb62929f0d9a1287
Java
Toolanto/akkaExperience
/src/main/java/com/simpleapp/becomeUnbecome/StartSystem.java
UTF-8
387
1.90625
2
[]
no_license
package com.simpleapp.becomeUnbecome; import com.google.inject.Guice; import com.google.inject.Injector; import com.simpleapp.guice.AkkaModule; public class StartSystem { public static Injector injector; public static void main(String[] args) throws Exception { injector = Guice.createInjector(new AkkaModule()); injector.getInstance(BecomeUnbecomeApp.class).run(); } }
true
e8f96e2ec3527d7e45544382eb30a1116cc56eed
Java
zhongxingyu/Seer
/Diff-Raw-Data/11/11_04200917365973f40989c10c811f968182b0f2a8/Client/11_04200917365973f40989c10c811f968182b0f2a8_Client_t.java
UTF-8
3,290
3.296875
3
[]
no_license
/* Client Handles the client-side of communications - display messages sent from the server and accept messages sent from the user and forward them to the server. Still needs: - Exception handling - More, I'm sure, but I can't think of it right now. */ import java.io.*; // Provides for system input and output through data // streams, serialization and the file system import java.net.*; // Provides the classes for implementing networking // applications Lemons // TCP Client class class Client { public static void main(String argv[]) { int lisPort; String hostname; if(argv.length == 2) { hostname = argv[0]; lisPort = Integer.parseInt(argv[1]); connect(hostname, lisPort); } else { System.out.println("Please specify a hostname and port number."); } } public static void connect(String hostname, int port) { BufferedReader servIn; PrintWriter servOut; BufferedReader userIn; Protocol protocol = new Protocol(); Socket clientSocket; String userPkt = ""; String serverPkt = ""; String serverString = ""; String userString = ""; boolean isLogged = false; // THIS IS A HACK. char[] data; int dataLength; String cmd_type; userIn = new BufferedReader(new InputStreamReader(System.in)); try { // Create the socket and connect. clientSocket = new Socket(hostname, port); // Set up communication channels. servOut = new PrintWriter(clientSocket.getOutputStream(), true); servIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // PROTOCOL while(serverString != "END") { while(userString.equals("") && serverPkt.equals("")) { // Poll for input from either the user or the server continually. if(userIn.ready()) userString = userIn.readLine(); else if(servIn.ready()) serverPkt = servIn.readLine(); } if(userString.equals("")) { // The server sent us something ; display it. dataLength = protocol.getLength(serverPkt); data = new char[dataLength]; servIn.read(data, 0, dataLength); serverString = new String(data); System.out.println(serverString); } else if(userString != null) { if(userString.indexOf(" ") != -1 && userString.indexOf(" ") != userString.length()) { cmd_type = userString.substring(0, userString.indexOf(" ")); userString = userString.substring(userString.indexOf(" ") + 1); } else { if(isLogged) cmd_type = userString; else { cmd_type = "LOGIN"; isLogged = true; } } userPkt = protocol.makePacket(userString, cmd_type); // The user typed something - send it to the server. servOut.println(userPkt); } serverPkt = ""; userPkt = ""; userString = ""; serverString = ""; } // PROTOCOL clientSocket.close(); } catch(SocketException se) { System.out.println("There has been an issue with the socket. Please check your hostname and port #, and try again."); } catch(Exception e) { System.out.println("Something has gone terribly wrong..."); } } }
true
1f97c1d39c91a70fd723f9f185b77f73b83190d7
Java
quyetdv155214/a7-Quyet-ci-Session1
/Session7 HomeWork/src/controllers/manangers/EnemyControllerManager.java
UTF-8
1,609
2.90625
3
[]
no_license
package controllers.manangers; import controllers.Controller; import controllers.GameSetting; import controllers.GameVector; import controllers.PlaneController; import controllers.enemies.EnemyController; import controllers.enemies.EnemyType; import java.util.Random; /** * Created by apple on 12/10/16. */ public class EnemyControllerManager extends ControllerManager { public static final EnemyControllerManager enemyControllerManager = new EnemyControllerManager(); int counter; @Override public void run() { super.run(); counter++; if (counter == 100) { spawn(); counter = 0; } } private int enemyCount; private void spawn() { //1: Create enemy enemyCount++; EnemyController enemyController = null; // Random ran = new Random(); int x = ran.nextInt(GameSetting.instance.getWidth() - 200) + 100; if (enemyCount % 2 == 0) { enemyController = EnemyController.create(x, 0, EnemyType.WHITE); } else { enemyController = EnemyController.create(x, 0, EnemyType.BROWN); } //2: Add new enemy to vector this.controllers.add(enemyController); } public void destroyInScope(int scope){ for (Controller c : this.controllers) { GameVector dVector = c.getModel().subtract(PlaneController.instance.getModel()); double lengh = dVector.getLength(); if (lengh <= scope) { c.decHp(100); } } } }
true
509bdb98be1c454b486cd494b115affd83c508fd
Java
Karavanych/DraziwGLesEngine
/src/draziw/simple/physics/Collision.java
UTF-8
1,665
3.109375
3
[]
no_license
package draziw.simple.physics; public class Collision { // direction x = left, right - + // direction y = bottom, top - + // direction z = forward, back - + public static final int NO_COLLISION=0x0000; public static final int X_INCR=0x0001; public static final int X_DECR=0x0002; public static final int Y_INCR=0x0004; public static final int Y_DECR=0x0008; public static final int Z_INCR=0x0010; public static final int Z_DECR=0x0020; public float xIncrCol; public float xDecrCol; public float yIncrCol; public float yDecrCol; public float zIncrCol; public float zDecrCol; public int colDirection; public void clearCollisions() { xIncrCol=-Float.MAX_VALUE; yIncrCol=-Float.MAX_VALUE; zIncrCol=-Float.MAX_VALUE; xDecrCol=Float.MAX_VALUE; yDecrCol=Float.MAX_VALUE; zDecrCol=Float.MAX_VALUE; colDirection=NO_COLLISION; } public void add(int direction,float position) { colDirection|=direction; switch (direction) { case X_INCR: xIncrCol=Math.max(xIncrCol, position); break; case X_DECR: xDecrCol=Math.min(xDecrCol, position); break; case Y_INCR: yIncrCol=Math.max(yIncrCol, position); break; case Y_DECR: yDecrCol=Math.min(xDecrCol, position); break; case Z_INCR: zIncrCol=Math.max(zIncrCol, position); break; case Z_DECR: zDecrCol=Math.min(zDecrCol, position); break; } } public void add(int direction) { colDirection|=direction; } public boolean isCollision(int direction) { return (colDirection & direction)==direction; } }
true
3807f42b6011d0142576e57f58f6a9d6d2e445b1
Java
er-rousy/meet-andoid
/app/src/main/java/com/yuejian/meet/bean/DateHead.java
UTF-8
163
1.5
2
[]
no_license
package com.yuejian.meet.bean; /** * Created by zh02 on 2017/8/22. */ public class DateHead { public int year; public int month; public int day; }
true
a5f279e7828d44d95e6bb1aa2560d16b1a859484
Java
abdulkashif/Project
/javaAdv/Day1/Assignment10a/EmployeeGrade.java
UTF-8
1,094
3.3125
3
[]
no_license
package javaAdv.Day1.Assignment10a; public class EmployeeGrade{ private int employeeNo; private String employeeName; private float customer1Feedback; private float customer2Feedback; private float customer3Feedback; private float averageFeedback; private char grade; public EmployeeGrade(){ this.employeeNo = 101; this.employeeName = "Ram"; this.customer1Feedback = 4.1f; this.customer2Feedback = 4.5f; this.customer3Feedback = 4.3f; } public void calculateAverageFeedback(){ this.averageFeedback = (this.customer1Feedback+this.customer2Feedback+this.customer3Feedback)/3; } public void calculateGrade(){ if(this.averageFeedback<2.5) this.grade = 'C'; else if(this.averageFeedback>=2.5 && this.averageFeedback<4.0) this.grade = 'B'; else this.grade = 'A'; } public void displayInfo(){ System.out.println("Employee ID " + this.employeeNo); System.out.println("Employee Name " + this.employeeName); System.out.println("Average feedback " + this.averageFeedback); System.out.println("Grade " + this.grade); } }
true
c7b24a66c1393687890c7d06fcd9e6bba8c5a1b7
Java
nagyist/splunk-shuttl
/src/java/com/splunk/shuttl/server/mbeans/rest/ArchiveBucketEndpoint.java
UTF-8
5,445
1.851563
2
[ "Apache-2.0" ]
permissive
// Copyright (C) 2011 Splunk Inc. // // Splunk Inc. licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.splunk.shuttl.server.mbeans.rest; import static com.splunk.shuttl.ShuttlConstants.*; import static com.splunk.shuttl.archiver.LogFormatter.*; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.IOException; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import com.splunk.shuttl.archiver.archive.ArchiveConfiguration; import com.splunk.shuttl.archiver.archive.BucketFormat; import com.splunk.shuttl.archiver.archive.BucketShuttler; import com.splunk.shuttl.archiver.archive.BucketShuttlerFactory; import com.splunk.shuttl.archiver.archive.recovery.ArchiveBucketLocker; import com.splunk.shuttl.archiver.model.BucketFactory; import com.splunk.shuttl.archiver.model.FileNotDirectoryException; import com.splunk.shuttl.archiver.model.LocalBucket; import com.splunk.shuttl.server.mbeans.rest.ShuttlBucketEndpoint.BucketModifier; import com.splunk.shuttl.server.mbeans.rest.ShuttlBucketEndpoint.ShuttlProvider; @Path(ENDPOINT_ARCHIVER + ENDPOINT_BUCKET_ARCHIVE) public class ArchiveBucketEndpoint { private static Logger logger = Logger.getLogger(ArchiveBucketEndpoint.class); @POST @Produces(MediaType.TEXT_PLAIN) public void archiveBucket(@FormParam("path") String path, @FormParam("index") String index) { try { ArchiveConfiguration config = ArchiveConfiguration.getSharedInstance(); if (isPathReplicatedBucketWithRawdataOnly(path)) { try { deletePath(path, index); } catch (IOException e) { logDeleteException(path, index, e); } } else { ShuttlBucketEndpointHelper.shuttlBucket(path, index, new BucketArchiverProvider(), ConfigProviderForBothNormalAndReplicatedBuckets.create(config), new RenamesReplicatedBucketAsNormalBucket(), new ArchiveBucketLocker()); } } catch (Throwable t) { logger.error(did("Tried archiving bucket", t, "to archive the bucket", "path", path, "index", index)); throw new RuntimeException(t); } } private boolean isPathReplicatedBucketWithRawdataOnly(String path) throws FileNotFoundException, FileNotDirectoryException { LocalBucket localBucket = new LocalBucket(new File(path), "doesNotMatter", BucketFormat.UNKNOWN); if (localBucket.isReplicatedBucket()) if (listFilesThatAreNotRawdataDirNorDotFiles(localBucket).length == 0) return true; return false; } private File[] listFilesThatAreNotRawdataDirNorDotFiles( LocalBucket localBucket) { return localBucket.getDirectory().listFiles(new FileFilter() { @Override public boolean accept(File f) { if (isRawdataOrDotFile(f.getName())) return false; return true; } private boolean isRawdataOrDotFile(String fileName) { return fileName.equals("rawdata") || fileName.startsWith("."); } }); } private void deletePath(String path, String index) throws IOException { logReason(path, index); FileUtils.deleteDirectory(new File(path)); } private void logReason(String path, String index) { logger.warn(warn( "Tried shuttling a replicted bucket that only contained rawdata", "Will not Shuttl this bucket, because Shuttl does not support rawdata only" + " buckets.", "Will delete bucket. But don't worry, searchable copies and the " + "original bucket will still be Shuttled, by the other indexers. " + "You have Shuttl installed at all indexers, don't you?", "bucket_path", path, "index", index)); } private void logDeleteException(String path, String index, IOException e) { logger .error(did( "Tried deleting bucket path", e, "To delete it. It will be deleted next retry, unless an Exception is thrown", "bucket_path", path, "index", index)); } private static class BucketArchiverProvider implements ShuttlProvider { @Override public BucketShuttler createWithConfig(ArchiveConfiguration config) { return BucketShuttlerFactory.createWithConfig(config); } } private static class RenamesReplicatedBucketAsNormalBucket implements BucketModifier { @Override public LocalBucket modifyLocalBucket(LocalBucket bucket) { return getNormalizedBucket(bucket); } private LocalBucket getNormalizedBucket(LocalBucket bucket) { if (bucket.isReplicatedBucket()) return getBucketWithNormalBucketName(bucket); else return bucket; } private LocalBucket getBucketWithNormalBucketName(LocalBucket b) { String normalizedBucketName = b.getName().replaceFirst("rb", "db"); return BucketFactory.createBucketWithIndexDirectoryBucketNameAndSize( b.getIndex(), new File(b.getPath()), normalizedBucketName, b.getFormat(), b.getSize()); } } }
true
d5bb395a9ce13c71b35cf6a94aa640e46c5f1e92
Java
ssk910/Head-First-Design-Patterns
/src/practice/designpatterns/abstractfactory/TabletDevice.java
UTF-8
409
2.640625
3
[]
no_license
package practice.designpatterns.abstractfactory; public class TabletDevice extends Device { ModuleFactory module; public TabletDevice(ModuleFactory module) { this.module = module; } @Override void prepare() { System.out.println("preparing " + name); graphic = module.createGraphic(); gps = module.createGPS(); wifi = module.createWIFI(); } }
true
0268eff092b0962dfd589857191ae07b098dc4b9
Java
tsuzcx/qq_apk
/com.tencent.mm/classes.jar/com/google/android/gms/iid/zzak.java
UTF-8
8,731
1.851563
2
[]
no_license
package com.google.android.gms.iid; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; import com.tencent.matrix.trace.core.AppMethodBeat; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Set; public final class zzak { private SharedPreferences zzcz; private final zzn zzda; private final Map<String, zzo> zzdb; private Context zzk; public zzak(Context paramContext) { this(paramContext, new zzn()); AppMethodBeat.i(2503); AppMethodBeat.o(2503); } private zzak(Context paramContext, zzn paramzzn) { AppMethodBeat.i(2504); this.zzdb = new androidx.b.a(); this.zzk = paramContext; this.zzcz = paramContext.getSharedPreferences("com.google.android.gms.appid", 0); this.zzda = paramzzn; paramContext = new File(androidx.core.content.a.ac(this.zzk), "com.google.android.gms.appid-no-backup"); if (!paramContext.exists()) { try { if ((paramContext.createNewFile()) && (!isEmpty())) { InstanceIDListenerService.zzd(this.zzk, this); } AppMethodBeat.o(2504); return; } catch (IOException paramContext) { if (Log.isLoggable("InstanceID/Store", 3)) { paramContext = String.valueOf(paramContext.getMessage()); if (paramContext.length() != 0) { "Error creating file in no backup dir: ".concat(paramContext); AppMethodBeat.o(2504); return; } new String("Error creating file in no backup dir: "); } } } AppMethodBeat.o(2504); } private static String zzd(String paramString1, String paramString2, String paramString3) { AppMethodBeat.i(2506); paramString1 = String.valueOf(paramString1).length() + 4 + String.valueOf(paramString2).length() + String.valueOf(paramString3).length() + paramString1 + "|T|" + paramString2 + "|" + paramString3; AppMethodBeat.o(2506); return paramString1; } static String zzh(String paramString1, String paramString2) { AppMethodBeat.i(2515); paramString1 = String.valueOf(paramString1).length() + 3 + String.valueOf(paramString2).length() + paramString1 + "|S|" + paramString2; AppMethodBeat.o(2515); return paramString1; } final String get(String paramString) { try { AppMethodBeat.i(2507); paramString = this.zzcz.getString(paramString, null); AppMethodBeat.o(2507); return paramString; } finally { paramString = finally; throw paramString; } } public final boolean isEmpty() { AppMethodBeat.i(2505); boolean bool = this.zzcz.getAll().isEmpty(); AppMethodBeat.o(2505); return bool; } public final void zzd(String paramString1, String paramString2, String paramString3, String paramString4, String paramString5) { try { AppMethodBeat.i(2511); paramString1 = zzd(paramString1, paramString2, paramString3); paramString2 = this.zzcz.edit(); paramString2.putString(paramString1, paramString4); paramString2.putString("appVersion", paramString5); paramString2.putString("lastToken", Long.toString(System.currentTimeMillis() / 1000L)); paramString2.commit(); AppMethodBeat.o(2511); return; } finally { paramString1 = finally; throw paramString1; } } public final String zze(String paramString1, String paramString2, String paramString3) { try { AppMethodBeat.i(2510); paramString1 = zzd(paramString1, paramString2, paramString3); paramString1 = this.zzcz.getString(paramString1, null); AppMethodBeat.o(2510); return paramString1; } finally { paramString1 = finally; throw paramString1; } } public final void zzf(String paramString1, String paramString2, String paramString3) { try { AppMethodBeat.i(2512); paramString1 = zzd(paramString1, paramString2, paramString3); paramString2 = this.zzcz.edit(); paramString2.remove(paramString1); paramString2.commit(); AppMethodBeat.o(2512); return; } finally { paramString1 = finally; throw paramString1; } } public final void zzi(String paramString) { try { AppMethodBeat.i(2508); SharedPreferences.Editor localEditor = this.zzcz.edit(); Iterator localIterator = this.zzcz.getAll().keySet().iterator(); while (localIterator.hasNext()) { String str = (String)localIterator.next(); if (str.startsWith(paramString)) { localEditor.remove(str); } } localEditor.commit(); } finally {} AppMethodBeat.o(2508); } /* Error */ public final zzo zzj(String paramString) { // Byte code: // 0: aload_0 // 1: monitorenter // 2: sipush 2513 // 5: invokestatic 29 com/tencent/matrix/trace/core/AppMethodBeat:i (I)V // 8: aload_0 // 9: getfield 41 com/google/android/gms/iid/zzak:zzdb Ljava/util/Map; // 12: aload_1 // 13: invokeinterface 219 2 0 // 18: checkcast 221 com/google/android/gms/iid/zzo // 21: astore_2 // 22: aload_2 // 23: ifnull +13 -> 36 // 26: sipush 2513 // 29: invokestatic 32 com/tencent/matrix/trace/core/AppMethodBeat:o (I)V // 32: aload_0 // 33: monitorexit // 34: aload_2 // 35: areturn // 36: aload_0 // 37: getfield 55 com/google/android/gms/iid/zzak:zzda Lcom/google/android/gms/iid/zzn; // 40: aload_0 // 41: getfield 43 com/google/android/gms/iid/zzak:zzk Landroid/content/Context; // 44: aload_1 // 45: invokevirtual 224 com/google/android/gms/iid/zzn:zze (Landroid/content/Context;Ljava/lang/String;)Lcom/google/android/gms/iid/zzo; // 48: astore_2 // 49: aload_0 // 50: getfield 41 com/google/android/gms/iid/zzak:zzdb Ljava/util/Map; // 53: aload_1 // 54: aload_2 // 55: invokeinterface 228 3 0 // 60: pop // 61: sipush 2513 // 64: invokestatic 32 com/tencent/matrix/trace/core/AppMethodBeat:o (I)V // 67: goto -35 -> 32 // 70: astore_1 // 71: aload_0 // 72: monitorexit // 73: aload_1 // 74: athrow // 75: astore_2 // 76: aload_0 // 77: getfield 43 com/google/android/gms/iid/zzak:zzk Landroid/content/Context; // 80: aload_0 // 81: invokestatic 84 com/google/android/gms/iid/InstanceIDListenerService:zzd (Landroid/content/Context;Lcom/google/android/gms/iid/zzak;)V // 84: aload_0 // 85: getfield 55 com/google/android/gms/iid/zzak:zzda Lcom/google/android/gms/iid/zzn; // 88: aload_0 // 89: getfield 43 com/google/android/gms/iid/zzak:zzk Landroid/content/Context; // 92: aload_1 // 93: invokevirtual 230 com/google/android/gms/iid/zzn:zzf (Landroid/content/Context;Ljava/lang/String;)Lcom/google/android/gms/iid/zzo; // 96: astore_2 // 97: goto -48 -> 49 // Local variable table: // start length slot name signature // 0 100 0 this zzak // 0 100 1 paramString String // 21 34 2 localzzo1 zzo // 75 1 2 localzzp zzp // 96 1 2 localzzo2 zzo // Exception table: // from to target type // 2 22 70 finally // 26 32 70 finally // 36 49 70 finally // 49 67 70 finally // 76 97 70 finally // 36 49 75 com/google/android/gms/iid/zzp } final void zzk(String paramString) { AppMethodBeat.i(2514); try { this.zzdb.remove(paramString); zzn.zzg(this.zzk, paramString); zzi(String.valueOf(paramString).concat("|")); AppMethodBeat.o(2514); return; } finally { AppMethodBeat.o(2514); } } public final void zzx() { try { AppMethodBeat.i(2509); this.zzdb.clear(); zzn.zzi(this.zzk); this.zzcz.edit().clear().commit(); AppMethodBeat.o(2509); return; } finally { localObject = finally; throw localObject; } } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes7.jar * Qualified Name: com.google.android.gms.iid.zzak * JD-Core Version: 0.7.0.1 */
true
33a2844fb107b299fa1211cd0974fbaa910f3197
Java
jetlinks/jetlinks-community
/jetlinks-manager/notify-manager/src/main/java/org/jetlinks/community/notify/manager/subscriber/SubscriberProviders.java
UTF-8
716
2.3125
2
[ "Apache-2.0" ]
permissive
package org.jetlinks.community.notify.manager.subscriber; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; public class SubscriberProviders { private final static Map<String, SubscriberProvider> providers = new ConcurrentHashMap<>(); public static void register(SubscriberProvider provider) { providers.put(provider.getId(), provider); } public static List<SubscriberProvider> getProviders() { return new ArrayList<>(providers.values()); } public static Optional<SubscriberProvider> getProvider(String id) { return Optional.ofNullable(providers.get(id)); } }
true
e5a382c18eb43909b8085e556a1ac2417ea1a8cd
Java
rominamartinez99/Parcial_DDS_2021
/Implementacion/src/main/java/Dominio/Utils/Exceptions/MailNoEnviadoException.java
UTF-8
397
2.359375
2
[]
no_license
package Dominio.Utils.Exceptions; import Dominio.Usuarios.MediosContacto.Notificacion; import Dominio.Usuarios.Usuario; public class MailNoEnviadoException extends RuntimeException{ public MailNoEnviadoException(Notificacion mensaje, Usuario usuario){ super("no se pudo enviar a la cuenta "+usuario.getMail()+ " el mensaje ["+mensaje.getAsunto()+"] "+mensaje.getCuerpo()); } }
true
e0acb5f02df533761d23eb5f57beca068d6eebf9
Java
canyinghao/CanOkHttp
/canokhttp/src/main/java/com/canyinghao/canokhttp/threadpool/SingleJob.java
UTF-8
100
1.742188
2
[ "Apache-2.0" ]
permissive
package com.canyinghao.canokhttp.threadpool; public interface SingleJob<O,T> { T run(O o); }
true
dd289bb9b408f4303d423aa5291d7372fa4b9c6e
Java
chl-123/traced
/src/Country.java
UTF-8
656
2.578125
3
[]
no_license
public class Country { private String countryName; private String quarantine_data; private Location[] location; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getQuarantine_data() { return quarantine_data; } public void setQuarantine_data(String quarantine_data) { this.quarantine_data = quarantine_data; } public Location[] getLocation() { return location; } public void setLocation(Location[] location) { this.location = location; } }
true
3253eaee00c939f83e1a16946aafb7c095476895
Java
mohammadul/addondev
/addondev/plugins/org.addondev.ui/src/org/addondev/ui/editor/javascript/JavaScriptPartitionScanner.java
UTF-8
1,241
2.296875
2
[]
no_license
package org.addondev.ui.editor.javascript; import java.util.ArrayList; import org.eclipse.jface.text.rules.EndOfLineRule; import org.eclipse.jface.text.rules.IPredicateRule; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.MultiLineRule; import org.eclipse.jface.text.rules.RuleBasedPartitionScanner; import org.eclipse.jface.text.rules.SingleLineRule; import org.eclipse.jface.text.rules.Token; public class JavaScriptPartitionScanner extends RuleBasedPartitionScanner { public final static String JS_COMMENT = "__js_comment"; public final static String JS_STRING = "__js_string"; public JavaScriptPartitionScanner(){ ArrayList<IPredicateRule> rules = new ArrayList<IPredicateRule>(); IToken comment = new Token(JS_COMMENT); //rules.add(new MultiLineRule("/*" , "*/" ,comment)); rules.add(new MultiLineRule("/*", "*/", comment, (char) 0, true)); rules.add(new EndOfLineRule("//", comment)); IToken string = new Token(JS_STRING); rules.add(new SingleLineRule("\"", "\"", string, '\\')); rules.add(new SingleLineRule("\'", "\'", string, '\\')); setPredicateRules(rules.toArray(new IPredicateRule[rules.size()])); //setRules(rules); } }
true
74830d79dbf7d207c8ebb9f8765dcce5a443b245
Java
shashimoto1028/yohh
/src/main/java/com/example/test/controller/LogoutController.java
UTF-8
844
2.171875
2
[]
no_license
package com.example.test.controller; import java.util.Locale; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class LogoutController { private static final Logger logger = LoggerFactory.getLogger(LogoutController.class); @Autowired HttpSession session; @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(Locale locale, Model model) { logger.info("Welcome logout! The client locale is {}.", locale); session.invalidate(); return "forward:/"; } }
true
d542560ab499769a55d2a9bf04c7bba992f0a0b8
Java
AvishkaShyaman/SIMS_
/src/com/sims/control/AdminNoticeAddController.java
UTF-8
4,231
2.0625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sims.control; import com.sims.model.Notice; import com.sims.model.NoticeDOA; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.stage.Stage; /** * FXML Controller class * * @author acer */ public class AdminNoticeAddController implements Initializable { @FXML private TextField txt_notice_title; @FXML private TextArea txt_notice_content; @FXML private Button btn_notice_add; private Notice notice_ = null; @FXML private TextField txt_notice_ID; private String publiser = "Admin"; AdminDashboardController admindash; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML private void btn_notice_addActionhandel(ActionEvent event) throws IOException { Notice notice = new Notice(); notice.setID(txt_notice_ID.getText()); notice.setTitle(txt_notice_title.getText()); notice.setContent(txt_notice_content.getText()); NoticeDOA noticedoa = new NoticeDOA(); if (notice_ == null) { notice.setPublisher(publiser); if (noticedoa.saveNotice(notice)) { System.out.println("Add"); alertINFORMATION("Succesfully added"); done(); } else { alertError("Adding Error"); System.out.println("Add Error"); } } else { notice.setPublisher(notice_.getPublisher()); if (noticedoa.updateNotice(notice)) { alertINFORMATION("Succesfully Updated"); System.out.println("Updated"); done(); } else { alertError("Updating Error"); System.out.println("Update Error"); } } } public void setAddScene(String publiser, AdminDashboardController admindash) { this.publiser = publiser; this.admindash = admindash; } public void setUpdateScene(Notice notice_, AdminDashboardController admindash) { this.admindash = admindash; this.notice_ = notice_; txt_notice_ID.setText(notice_.getID()); txt_notice_content.setText(notice_.getContent()); txt_notice_title.setText(notice_.getTitle()); publiser = notice_.getPublisher(); btn_notice_add.setText("Update Notice"); btn_notice_add.setStyle("-fx-background-color: #EDD817;"); } private void done() throws IOException { // Stage primaryStage = new Stage(); // FXMLLoader loder = new FXMLLoader(getClass().getResource("/com/sims/view/AdminDash.fxml")); // Parent root = loder.load(); // AdminDashboardController admindash = loder.getController(); // admindash.setUserID(publiser); // Scene scene = new Scene(root); // primaryStage.setScene(scene); // primaryStage.show(); admindash.settable(); Stage stage = (Stage) btn_notice_add.getScene().getWindow(); stage.close(); } private void alertINFORMATION(String msg) { Alert a1 = new Alert(Alert.AlertType.INFORMATION); a1.setTitle("Done"); a1.setContentText(msg); a1.setHeaderText(null); a1.showAndWait(); } private void alertError(String msg) { Alert a1 = new Alert(Alert.AlertType.ERROR); a1.setTitle("Error"); a1.setContentText(msg); a1.setHeaderText(null); a1.showAndWait(); } }
true
0e0b3ad461b80b39a22d114903a76e5d060a0e2b
Java
hycomsa/mokka
/src/mokka/src/integration-test/java/pl/hycom/mokka/emulator/mock/MockConfigurationControllerIT.java
UTF-8
6,338
1.765625
2
[]
no_license
package pl.hycom.mokka.emulator.mock; import com.github.tomakehurst.wiremock.WireMockServer; import io.restassured.RestAssured; import io.restassured.response.Response; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import pl.hycom.mokka.Application; import wiremock.com.jayway.jsonpath.JsonPath; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * @author adam.misterski@hycom.pl */ @DirtiesContext @ActiveProfiles("test") @AutoConfigureMockMvc @AutoConfigureTestDatabase @SpringBootTest(classes = Application.class, properties = {"wiremock.enabled = true"}) public class MockConfigurationControllerIT { @Autowired private MockMvc mvc; @Autowired private WireMockServer wm; private static final String name = "test"; private static final String httpMethod = "GET"; private static final int status = 303; private static final String path = "path"; private static final String slash = "/"; @BeforeEach public void setUp() { RestAssured.port = wm.port(); } @Test @WithMockUser(roles="ADMIN") public void create_mock() throws Exception { String id = createMock(true); Response response = RestAssured.get("/__admin/mappings/" + convertIDtoUUID(id)); assertEquals(name, response.jsonPath().get("name")); assertEquals(slash + path, response.jsonPath().get("request.urlPathPattern")); assertEquals(httpMethod, response.jsonPath().get("request.method")); } @Test @WithMockUser(roles="ADMIN") public void update_mock() throws Exception { String id = createMock(true); String testChange = "test_change"; String requestBody = "{\"status\":" + status + ",\"httpMethod\":\"" + httpMethod + "\",\"path\":\""+path+"\",\"id\":"+id+",\"description\":\"test\",\"pattern\":null,\"name\":\"" + testChange + "\",\"enabled\":true,\"proxyBaseUrl\":null,\"timeout\":0,\"order\":0,\"configurationContent\":{\"string\":{\"value\":\"d\"}},\"updated\":\"2020-03-18T01:44:39.089+0000\",\"errors\":null,\"changes\":null,\"showChanges\":false,\"showConfiguration\":true,\"type\":\"string\"}"; mvc.perform(asyncRequest(put("/configuration")).contentType(MediaType.APPLICATION_JSON).with(csrf()) .content(requestBody)) .andExpect(status().isOk()); Response response = RestAssured.get("/__admin/mappings/" + convertIDtoUUID(id)); assertEquals(testChange, response.jsonPath().get("name")); assertEquals(slash + path, response.jsonPath().get("request.urlPathPattern")); assertEquals(httpMethod, response.jsonPath().get("request.method")); } @Test @WithMockUser(roles="ADMIN") public void disable_mock() throws Exception { String id = createMock(true); mvc.perform(asyncRequest(post("/configuration/{id}/disable", id)).contentType(MediaType.APPLICATION_JSON).with(csrf())) .andExpect(status().isOk()); Response response = RestAssured.get("/__admin/mappings/" + convertIDtoUUID(id)); assertEquals(response.getStatusCode(), HttpStatus.NOT_FOUND.value()); } @Test @WithMockUser(roles="ADMIN") public void enable_mock() throws Exception { String id = createMock(false); mvc.perform(asyncRequest(post("/configuration/{id}/enable", id)).contentType(MediaType.APPLICATION_JSON).with(csrf())) .andExpect(status().isOk()); Response response = RestAssured.get("/__admin/mappings/" + convertIDtoUUID(id)); assertEquals(name, response.jsonPath().get("name")); assertEquals(slash + path, response.jsonPath().get("request.urlPathPattern")); assertEquals(httpMethod, response.jsonPath().get("request.method")); } @Test public void remove_mock() throws Exception { String id = createMock(true); mvc.perform(asyncRequest(delete("/configuration/"+ id)).contentType(MediaType.APPLICATION_JSON).with(csrf())) .andExpect(status().isOk()); Response response = RestAssured.get("/__admin/mappings" + convertIDtoUUID(id)); assertEquals(response.getStatusCode(), HttpStatus.NOT_FOUND.value()); } private MockHttpServletRequestBuilder asyncRequest(MockHttpServletRequestBuilder builder) { return builder.header("x-requested-with", "XMLHttpRequest"); } private String createMock(boolean enable) throws Exception { String requestBody = "{\"status\":\"" + status + "\",\"httpMethod\":\"" + httpMethod + "\",\"path\":\"" + path + "\",\"name\":\"" + name + "\",\"enabled\":\"" + enable + "\",\"type\":\"string\",\"configurationContent\":{\"string\":{\"value\":\"test\"}}}\n"; String createMock = mvc.perform(asyncRequest(put("/configuration")).contentType(MediaType.APPLICATION_JSON).with(csrf()) .content(requestBody)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); return JsonPath.parse(createMock).read("$['id']").toString(); } private String convertIDtoUUID(String id){ return UUID.nameUUIDFromBytes(id.getBytes()).toString(); } }
true
a76cb077e1c2267888eed77bff51452af232e5e6
Java
nudefingers/practices
/src/com/ifmo/jjd/practice7/school/ForStudy.java
UTF-8
108
1.757813
2
[]
no_license
package com.ifmo.jjd.practice7.school; public interface ForStudy { void toStudy(int knowledgeCount); }
true
924247d15c6130728d7cf0e8370a32e8721c66d0
Java
jonny-ddns/web-project-movie
/myProject_movie6_board/src/mvc/command/member/MemberCommand_memberDelete.java
UTF-8
542
2.40625
2
[]
no_license
package mvc.command.member; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import mvc.db.dao.MemberDao; public class MemberCommand_memberDelete implements MemberCommand{ @Override public void execute(HttpServletRequest request, HttpServletResponse response) { System.out.println(">>MemberCommand_memberDelete()"); String id = request.getParameter("id"); MemberDao mdao = MemberDao.getInstance(); mdao.memberDelete(id); System.out.println("MemberCommand_memberDelete() end"); } }
true
88a4183d367d19b0144b13542cf9a406e6f7f973
Java
kennedyzt/spring-demo
/src/main/java/com/kennedy/springdemo/config/websocket/WebSocketConfig.java
UTF-8
924
2.109375
2
[]
no_license
package com.kennedy.springdemo.config.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import com.kennedy.springdemo.beans.common.interceptor.WebSocketHandshakeInterceptor; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(marcoHandler(), "/marco").addInterceptors(new WebSocketHandshakeInterceptor()); } @Bean public SystemWebSocketHandler marcoHandler() { return new SystemWebSocketHandler(); } }
true
3ce554099e7af3e900fa021b04288bca88046fb6
Java
jomof/CppBuildCacheWorkInProgress
/agp-7.1.0-alpha01/tools/base/build-system/integration-test/application/src/test/java/com/android/build/gradle/integration/testing/SeparateTestWithMinificationButNoObfuscationTest.java
UTF-8
1,159
1.828125
2
[ "Apache-2.0" ]
permissive
package com.android.build.gradle.integration.testing; import com.android.build.gradle.integration.common.fixture.GradleTestProject; import com.android.build.gradle.options.BooleanOption; import java.io.IOException; import org.junit.Rule; import org.junit.Test; /** * Test for a separate test module that has minification turned on but no obfuscation (no * mapping.txt file produced) */ public class SeparateTestWithMinificationButNoObfuscationTest { @Rule public GradleTestProject project = GradleTestProject.builder() // http://b/149978740 .addGradleProperties( BooleanOption.INCLUDE_DEPENDENCY_INFO_IN_APKS.getPropertyName() + "=" + false) .fromTestProject("separateTestWithMinificationButNoObfuscation") .create(); @Test public void testBuilding() throws IOException, InterruptedException { // just building fine is enough to test the regression. project.execute("clean"); project.executor().run("assemble"); } }
true
75f12f68cb58ce91c8d00ed1b580db1e43f0695b
Java
spotinst/spotinst-sdk-java
/src/main/java/com/spotinst/sdkjava/model/bl/ocean/ecs/ClusterLaunchSpecification.java
UTF-8
9,115
1.695313
2
[ "Apache-2.0", "EPL-2.0", "MIT" ]
permissive
package com.spotinst.sdkjava.model.bl.ocean.ecs; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.HashSet; import java.util.List; import java.util.Set; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class ClusterLaunchSpecification { @JsonIgnore private Set<String> isSet; private List<ClusterAttributes> attributes; private LaunchSpecAutoScaleSpecification autoScale; private List<LaunchSpecBlockDeviceMappings> blockDeviceMappings; private LaunchSpecIamInstanceProfileSpecification iamInstanceProfile; private String imageId; private LaunchSpecInstanceMetadataOptions instanceMetadataOptions; private String name; private String oceanId; private Boolean restrictScaleDown; private List<String> securityGroupIds; private List<String> subnetIds; private List<LaunchSpecTagsSpecification> tags; private String userData; private String id; private ClusterLaunchSpecification() { isSet = new HashSet<>(); } public Set<String> getIsSet() { return isSet; } public void setIsSet(Set<String> isSet) { this.isSet = isSet; } public List<ClusterAttributes> getAttributes() { return attributes; } public void setAttributes(List<ClusterAttributes> attributes) { isSet.add("attributes"); this.attributes = attributes; } public LaunchSpecAutoScaleSpecification getAutoScale() { return autoScale; } public void setAutoScale(LaunchSpecAutoScaleSpecification autoScale) { isSet.add("autoScale"); this.autoScale = autoScale; } public List<LaunchSpecBlockDeviceMappings> getBlockDeviceMappings() { return blockDeviceMappings; } public void setBlockDeviceMappings(List<LaunchSpecBlockDeviceMappings> blockDeviceMappings) { isSet.add("blockDeviceMappings"); this.blockDeviceMappings = blockDeviceMappings; } public LaunchSpecIamInstanceProfileSpecification getIamInstanceProfile() { return iamInstanceProfile; } public void setIamInstanceProfile(LaunchSpecIamInstanceProfileSpecification iamInstanceProfile) { isSet.add("iamInstanceProfile"); this.iamInstanceProfile = iamInstanceProfile; } public String getImageId() { return imageId; } public void setImageId(String imageId) { isSet.add("imageId"); this.imageId = imageId; } public LaunchSpecInstanceMetadataOptions getInstanceMetadataOptions() { return instanceMetadataOptions; } public void setInstanceMetadataOptions(LaunchSpecInstanceMetadataOptions instanceMetadataOptions) { isSet.add("instanceMetadataOptions"); this.instanceMetadataOptions = instanceMetadataOptions; } public String getName() { return name; } public void setName(String name) { isSet.add("name"); this.name = name; } public String getOceanId() { return oceanId; } public void setOceanId(String oceanId) { isSet.add("oceanId"); this.oceanId = oceanId; } public Boolean getRestrictScaleDown() { return restrictScaleDown; } public void setRestrictScaleDown(Boolean restrictScaleDown) { isSet.add("restrictScaleDown"); this.restrictScaleDown = restrictScaleDown; } public List<String> getSecurityGroupIds() { return securityGroupIds; } public void setSecurityGroupIds(List<String> securityGroupIds) { isSet.add("securityGroupIds"); this.securityGroupIds = securityGroupIds; } public List<String> getSubnetIds() { return subnetIds; } public void setSubnetIds(List<String> subnetIds) { isSet.add("subnetIds"); this.subnetIds = subnetIds; } public List<LaunchSpecTagsSpecification> getTags() { return tags; } public void setTags(List<LaunchSpecTagsSpecification> tags) { isSet.add("tags"); this.tags = tags; } public String getUserData() { return userData; } public void setUserData(String userData) { isSet.add("userData"); this.userData = userData; } public String getId() { return id; } public void setId(String id) { isSet.add("id"); this.id = id; } public static class Builder { private ClusterLaunchSpecification launchspec; private Builder() { this.launchspec = new ClusterLaunchSpecification(); } public static Builder get() { return new Builder(); } public Builder setAttributes(final List<ClusterAttributes> attributes) { launchspec.setAttributes(attributes); return this; } public Builder setAutoScale(final LaunchSpecAutoScaleSpecification autoScale) { launchspec.setAutoScale(autoScale); return this; } public Builder setBlockDeviceMappings(final List<LaunchSpecBlockDeviceMappings> blockDeviceMappings) { launchspec.setBlockDeviceMappings(blockDeviceMappings); return this; } public Builder setIamInstanceProfile(final LaunchSpecIamInstanceProfileSpecification iamInstanceProfile) { launchspec.setIamInstanceProfile(iamInstanceProfile); return this; } public Builder setName(final String name) { launchspec.setName(name); return this; } public Builder setOceanId(final String oceanId) { launchspec.setOceanId(oceanId); return this; } public Builder setImageId(final String imageId) { launchspec.setImageId(imageId); return this; } public Builder setRestrictScaleDown(final Boolean restrictScaleDown) { launchspec.setRestrictScaleDown(restrictScaleDown); return this; } public Builder setSecurityGroupIds(final List<String> securityGroupIds) { launchspec.setSecurityGroupIds(securityGroupIds); return this; } public Builder setSubnetIds(final List<String> subnetIds) { launchspec.setSubnetIds(subnetIds); return this; } public Builder setTags(final List<LaunchSpecTagsSpecification> tags) { launchspec.setTags(tags); return this; } public Builder setId(final String id) { launchspec.setId(id); return this; } public Builder setUserData(final String userData) { launchspec.setUserData(userData); return this; } public Builder setInstanceMetadataOptions(final LaunchSpecInstanceMetadataOptions instanceMetadataOptions) { launchspec.setInstanceMetadataOptions(instanceMetadataOptions); return this; } public ClusterLaunchSpecification build() { return launchspec; } } @JsonIgnore public boolean isAttributesSet() { return isSet.contains("attributes"); } @JsonIgnore public boolean isIdSet() { return isSet.contains("id"); } @JsonIgnore public boolean isAutoScaleSet() { return isSet.contains("autoScale"); } @JsonIgnore public boolean isBlockDeviceMappingsSet() { return isSet.contains("blockDeviceMappings"); } @JsonIgnore public boolean isIamInstanceProfileSet() { return isSet.contains("iamInstanceProfile"); } @JsonIgnore public boolean isImageIdSet() { return isSet.contains("imageId"); } @JsonIgnore public boolean isInstanceMetadataOptionsSet() { return isSet.contains("instanceMetadataOptions"); } @JsonIgnore public boolean isNameSet() { return isSet.contains("name"); } @JsonIgnore public boolean isOceanIdSet() { return isSet.contains("oceanId"); } @JsonIgnore public boolean isRestrictScaleDownSet() { return isSet.contains("restrictScaleDown"); } @JsonIgnore public boolean isSecurityGroupIdsSet() { return isSet.contains("securityGroupIds"); } @JsonIgnore public boolean isSubnetIdsSet() { return isSet.contains("subnetIds"); } @JsonIgnore public boolean isTagsSet() { return isSet.contains("tags"); } @JsonIgnore public boolean isUserDataSet() { return isSet.contains("userData"); } }
true
5fe4c86c2deb21865838a346ae84bbe63126d3eb
Java
heylichen/AlgorithmsLab
/src/main/java/algorithms/fundamentals/sub3_collection/exercises/linkedlist/CircularLinkedListQueue.java
UTF-8
2,962
3.625
4
[]
no_license
package algorithms.fundamentals.sub3_collection.exercises.linkedlist; import edu.princeton.cs.algs4.StdOut; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Consumer; /** * Created by lichen2 on 2017/1/13. */ public class CircularLinkedListQueue<T> implements Iterable<T> { private Node<T> last; private int count; public void enqueue(T item) { Node<T> t = new Node(); t.item = item; count++; if (last == null) { last = t; t.next = last; } else { Node<T> next = last.next; last.next = t; t.next = next; last = t; } } public void reverseEnqueue(T item) { Node<T> t = new Node(); t.item = item; count++; if (last == null) { last = t; t.next = last; } else { Node<T> next = last.next; last.next = t; t.next = next; } } public T dequeue() { if (last == null) { return null; } count--; T item = last.next.item; if (last.next == last) { last = null; return item; } Node<T> next = last.next.next; last.next.next = null; last.next = next; return item; } public boolean isEmpty() { return count == 0; } public int size() { return count; } @Override public Iterator<T> iterator() { return new QueueIterator(); } private class QueueIterator implements Iterator<T> { private int currentCount = 0; private Node<T> current = last == null ? null : last.next; @Override public void remove() { } @Override public void forEachRemaining(Consumer<? super T> action) { } @Override public boolean hasNext() { return currentCount < count; } @Override public T next() { T item = current.item; current = current.next; currentCount++; return item; } } private class Node<T> { private T item; private Node<T> next; public Node() { } public Node(T item, Node next) { this.item = item; this.next = next; } } public CircularLinkedListQueue<T> reverse(CircularLinkedListQueue<T> queue) { //initialize count = 0; last = null; // for (T t : queue) { reverseEnqueue(t); } return this; } public static void main(String[] args) { CircularLinkedListQueue<Integer> queue = new CircularLinkedListQueue<>(); for (int i = 0; i < 100; i++) { queue.enqueue(i); } for (Integer i : queue) { StdOut.printf("%s ", i); } StdOut.print("\n"); List<Integer> list = new ArrayList<>(); while (!queue.isEmpty()) { StdOut.printf("%s ", queue.dequeue()); } StdOut.print("\n"); StdOut.printf("isEmpty: %s ", queue.isEmpty()); } }
true
44fe08fb6db2d45a5bca49d5de529826fdb980d1
Java
copperdong/servletjsp2
/chapter16/javamailweb/src/java/model/FetchResponse.java
UTF-8
1,149
2.046875
2
[]
no_license
package model; import java.util.List; public class FetchResponse { private long messageCount; private String folder = "INBOX"; private MessageBean messageBean; private List<MessageBean> messageBeans; private List<FolderBean> folderBeans; public long getMessageCount() { return messageCount; } public void setMessageCount(long messageCount) { this.messageCount = messageCount; } public String getFolder() { return folder; } public void setFolder(String folder) { this.folder = folder; } public MessageBean getMessageBean() { return messageBean; } public void setMessageBean(MessageBean messageBean) { this.messageBean = messageBean; } public List<MessageBean> getMessageBeans() { return messageBeans; } public void setMessageBeans(List<MessageBean> messageBeans) { this.messageBeans = messageBeans; } public List<FolderBean> getFolders() { return folderBeans; } public void setFolders(List<FolderBean> folderBeans) { this.folderBeans = folderBeans; } }
true
2ce006a67f85b2a385ffb86c4918e77dda5d396f
Java
Nalin28/chatApp
/src/main/java/com/chatx/back/service/ChatService.java
UTF-8
678
1.992188
2
[]
no_license
package com.chatx.back.service; import com.chatx.back.model.Chat; import com.chatx.back.repository.ChatDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import java.util.List; @EnableMongoRepositories(basePackageClasses = ChatDao.class) @Configuration public class ChatService { @Autowired private ChatDao chatDao; public List<Chat> saveChat(Chat chat){ chatDao.save(chat); return chatDao.findAll(); } public List<Chat> getChat(){ return chatDao.findAll(); } }
true
833529758cc8c6609801ab215d04078ae4bad9d3
Java
levchafx/LibraryJDBC
/LibraryJDBCServlets/src/main/java/dao/MessageDaoImpl.java
UTF-8
1,451
2.703125
3
[]
no_license
package dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import model.Message; public class MessageDaoImpl extends AbstractCrudDao<Message> { @Override protected Message resultSetMapper(ResultSet rs) throws SQLException { Message m = new Message(); m.setId(rs.getInt("id")); m.setUserId(rs.getInt("user_id")); m.setMessage(rs.getString("message")); return m; } @Override protected void updateMapper(PreparedStatement ps, Message value) throws SQLException { ps.setInt(1, value.getUserId()); ps.setString(2, value.getMessage()); ps.setInt(3, value.getId()); ps.executeUpdate(); } @Override protected void byIdMapper(PreparedStatement ps, int id) throws SQLException { ps.setInt(1, id); } @Override protected void createMapper(PreparedStatement ps, Message t) throws SQLException { ps.setInt(1, t.getUserId()); ps.setString(2, t.getMessage()); ps.executeUpdate(); } @Override protected String allQuery() { return "select*from message"; } @Override protected String byIdQuery() { return "select*from message where id =?"; } @Override protected String updateQuery() { return "update message set user_id=?,message =? where id=?"; } @Override protected String deleteQuery() { return "delete from message where id=?"; } @Override protected String createQuery() { return "insert into message (user_id,message) values(?,?)"; } }
true
6afc4ec1cc1ef4add252041dbf4cb3f8586d6bf4
Java
youngasimov/Yo-Simce
/src/com/dreamer8/yosimce/server/hibernate/pojo/AplicacionXUsuarioTipoXPermiso.java
UTF-8
1,390
1.953125
2
[]
no_license
package com.dreamer8.yosimce.server.hibernate.pojo; // Generated 16-08-2013 05:13:17 AM by Hibernate Tools 3.4.0.CR1 /** * AplicacionXUsuarioTipoXPermiso generated by hbm2java */ public class AplicacionXUsuarioTipoXPermiso implements java.io.Serializable { private Integer id; private AplicacionXUsuarioTipo aplicacionXUsuarioTipo; private Permiso permiso; private Boolean acceso; public AplicacionXUsuarioTipoXPermiso() { } public AplicacionXUsuarioTipoXPermiso(Integer id) { this.id = id; } public AplicacionXUsuarioTipoXPermiso(Integer id, AplicacionXUsuarioTipo aplicacionXUsuarioTipo, Permiso permiso, Boolean acceso) { this.id = id; this.aplicacionXUsuarioTipo = aplicacionXUsuarioTipo; this.permiso = permiso; this.acceso = acceso; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public AplicacionXUsuarioTipo getAplicacionXUsuarioTipo() { return this.aplicacionXUsuarioTipo; } public void setAplicacionXUsuarioTipo( AplicacionXUsuarioTipo aplicacionXUsuarioTipo) { this.aplicacionXUsuarioTipo = aplicacionXUsuarioTipo; } public Permiso getPermiso() { return this.permiso; } public void setPermiso(Permiso permiso) { this.permiso = permiso; } public Boolean getAcceso() { return this.acceso; } public void setAcceso(Boolean acceso) { this.acceso = acceso; } }
true
b5e1021b466ad76d0c9568fc7bbfcc66ace87b9e
Java
xicalango/fuzzy-robot-utils
/btw2009-lib/src/xx/btw2009/beans/Direktkandidat.java
UTF-8
772
2.1875
2
[]
no_license
package xx.btw2009.beans; import xx.btw2009.beans.factory.ReferenceSetter; import xx.btw2009.beans.factory.Setter; public class Direktkandidat implements BTW2009Bean { private String vorname; private String nachname; private Partei partei; public String getVorname() { return vorname; } @Setter("vorname") public void setVorname(String vorname) { this.vorname = vorname; } public String getNachname() { return nachname; } @Setter("nachname") public void setNachname(String nachname) { this.nachname = nachname; } public Partei getPartei() { return partei; } @ReferenceSetter(refClass = Partei.class, column="partei_id") public void setPartei(Partei partei) { this.partei = partei; } }
true
8ee11fb9d44bbed42a0d32275f6fa2edbc4b7806
Java
karmelosng/TheKsimulator3
/src/com/karmelos/ksimulator/model/SimState.java
UTF-8
5,432
2.03125
2
[]
no_license
package com.karmelos.ksimulator.model; //TODO use proper code format conventions (readable property and variable names etc) and other Java conventions import java.io.Serializable; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Stack; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; @Entity public class SimState extends Observable implements Serializable { private static final long serialVersionUID = -505800887487595246L; private Long id; private String description; private double score; private boolean globalAccessFlag; private boolean readWriteFlag; private Date savedAt; private SimUser simUser; private List<SimComponent> availableComponents; private Map<SimComponent,SimPoint> placedComponents = new LinkedHashMap(); private Map<SimComponent,SimPoint> usedComponents= new LinkedHashMap(); private List<SimComponent> undo; private Date timerStart; private Long timerDuration; private boolean timed; private String level; // until drag and drop starts @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Lob public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean getGlobalAccessFlag() { return globalAccessFlag; } public void setGlobalAccessFlag(boolean globalAccessFlag) { this.globalAccessFlag = globalAccessFlag; } public boolean getReadWriteFlag() { return readWriteFlag; } public void setReadWriteFlag(boolean readWriteFlag) { this.readWriteFlag = readWriteFlag; } @Temporal(TemporalType.TIMESTAMP) public Date getSavedAt() { return savedAt; } public void setSavedAt(Date savedAt) { this.savedAt = savedAt; } @ManyToOne public SimUser getSimUser() { return simUser; } public void setSimUser(SimUser simUser) { this.simUser = simUser; } @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL) @JoinTable(name = "Placed_Components") public Map<SimComponent, SimPoint> getPlacedComponents() { return placedComponents; } public void setPlacedComponents(Map<SimComponent, SimPoint> placedComponents) { this.placedComponents = placedComponents; } @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL) @JoinTable(name = "Available_Components") public List<SimComponent> getAvailableComponents() { return availableComponents; } public void setAvailableComponents(List<SimComponent> availableComponents) { this.availableComponents = new Stack(); if(availableComponents != null) { this.availableComponents.addAll(availableComponents); } } @ManyToMany(fetch = FetchType.LAZY) @JoinTable(name = "Used_Components") public Map<SimComponent, SimPoint> getUsedComponents() { return usedComponents; } public void setUsedComponents(Map<SimComponent,SimPoint> usedComponents) { this.usedComponents = usedComponents; } @Transient public List<SimComponent> getUndo() { return undo; } public void setUndo(List<SimComponent> undo) { this.undo = undo; } @Override public void setChanged() { super.setChanged(); } @Override public String toString() { String paddedString; int lengthOfString = description.trim().length(); if(lengthOfString >=20){ paddedString = description.substring(0,15);} else{ int pad = 20-lengthOfString; paddedString =String.format("%-"+pad+"s", description); } return paddedString+"||" + savedAt; } @Temporal(TemporalType.TIMESTAMP) public Date getTimerStart() { return timerStart; } public void setTimerStart(Date timerStart) { this.timerStart = timerStart; } public Long getTimerDuration() { return timerDuration; } public void setTimerDuration(Long timerDuration) { this.timerDuration = timerDuration; } public boolean isTimed() { return timed; } public void setTimed(boolean timed) { this.timed = timed; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } }
true
0d4e41fd77a3516530bb05f586e118315915f6aa
Java
InfinityZ25/FakeEntityLib
/src/main/java/uk/lewdev/entitylib/utils/SimpleLock.java
UTF-8
840
3.1875
3
[]
no_license
package uk.lewdev.entitylib.utils; import java.util.concurrent.locks.ReentrantLock; /** * Syntactic Sugar for Try, Finally Blocks When Used in Safe Locking * * @author Lewys Davies (Lew_) */ public class SimpleLock { private final ReentrantLock lock = new ReentrantLock(); /** * Obtains the read lock and executes the functional executor [Use lambda :)]<br> * This will block the current thread until the lock is obtained<br> * For safety, the lock will always be released, even after an exception * * @param executor */ public final void lockOrWait(FunctionalExecutor executor) { this.lock.lock(); try { executor.execute(); } finally { this.lock.unlock(); } } public interface FunctionalExecutor { void execute(); } }
true
3c2aab704de84c8b8f4cecd0cc8e2cf179b5e82e
Java
csoda/MoreInventoryMod
/src/main/java/moreinventory/client/gui/GuiPotionHolder.java
UTF-8
1,389
2.203125
2
[]
no_license
package moreinventory.client.gui; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import moreinventory.container.ContainerPotionHolder; import moreinventory.inventory.InventoryPotionHolder; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; @SideOnly(Side.CLIENT) public class GuiPotionHolder extends GuiContainer { private static final ResourceLocation potionHolderGuiTexture = new ResourceLocation("textures/gui/container/dispenser.png"); public GuiPotionHolder(InventoryPlayer inventory, InventoryPotionHolder holderInventory) { super(new ContainerPotionHolder(inventory, holderInventory)); this.xSize = 176; this.ySize = 190; } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { fontRendererObj.drawString(I18n.format("item.potionholder.name"), 8, 6, 4210752); fontRendererObj.drawString(I18n.format("container.inventory"), 8, ySize - 120 + 2, 4210752); } @Override protected void drawGuiContainerBackgroundLayer(float ticks, int mouseX, int mouseY) { mc.getTextureManager().bindTexture(potionHolderGuiTexture); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize); } }
true
dc5ff470c417dc934aada592346fb3d4765a15a9
Java
yanggali/RecommenderSystem
/src/main/java/doubantest.java
UTF-8
14,118
2.78125
3
[]
no_license
/** * Created by Yangjiali on 2017/4/11 0011. * Version 1.0 */ import algorithms.BayesScoring; import algorithms.ItemSimilarity; import structure.UserRecord; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 在豆瓣读书数据集上测试 */ public class doubantest { public static Map<String, UserRecord> userRecordMap = new HashMap<>(); public static void main(String[] args) { //初始化 initialData(); userRecordMap = BayesScoring.getUsermap(1); recommendByTag(); } public static void recommendV2(int startNum,int endNum,int shift) { System.out.println("加权混合方法"); for (int recommendcount = startNum;recommendcount <= endNum;recommendcount+=shift) { System.out.println("推荐数:"+recommendcount); float avgprecision = 0, avgrecall = 0, avgfmeasure = 0; long starttime = System.currentTimeMillis(); float totalNum = 0; for (Map.Entry<String, UserRecord> entry : userRecordMap.entrySet()) { float percentage = (float) (entry.getValue().getItemTags().size() - 1) / 1247; //System.out.println(percentage); float cfNum = percentage * recommendcount; Map<String, Float> itemtagmap = sortByValue(BayesScoring.getItemTagsScore(entry.getKey(),7.9f)); //Map<String, Float> tagmap = sortByValue(BayesScoring.getItemscoreByTag(entry.getKey())); Map<String, Float> itemmap = ItemSimilarity.getItemMap(entry.getKey()); //将两种结果合并 Map<String, Float> allmap = new HashMap<>(); Stream<Map.Entry<String, Float>> entryStreamCf = itemtagmap.entrySet().stream(); Stream<Map.Entry<String, Float>> entryStreamItem = itemmap.entrySet().stream(); Set<String> allRecItems = new HashSet<>(); allRecItems.addAll(entryStreamCf.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .limit((int)cfNum) .map(e->e.getKey()) .collect(Collectors.toSet())); if (itemmap != null){ allRecItems.addAll(entryStreamItem.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .limit(recommendcount - (int) cfNum) .map(e -> e.getKey()) .collect(Collectors.toSet())); } int recNum = allRecItems.size(); allRecItems.retainAll(entry.getValue().getItems().keySet()); //System.out.println("用户"+entry.getKey()+"的命中数:"+allRecItems.size()); float precision = 0,recall = 0,fmeasure = 0; if (allRecItems.size() > 0) { precision = (float) allRecItems.size()/recNum; recall = (float) allRecItems.size() / entry.getValue().getItems().size(); fmeasure = (float) 2 * precision * recall / (precision + recall); } else { precision = 0; recall = 0; fmeasure = 0; } avgprecision += precision; avgrecall += recall; avgfmeasure += fmeasure; } long endtime = System.currentTimeMillis(); System.out.println("计算的时间为:"+(endtime-starttime)/1000+"秒"); System.out.println("计算的用户数:" + userRecordMap.size()); System.out.println("avgprecision:"+avgprecision); float averageP = avgprecision / userRecordMap.size(); float averageR = avgrecall / userRecordMap.size(); float avgF = avgfmeasure / userRecordMap.size(); System.out.println("平均准确率:" + averageP + " 平均召回率:" + averageR + " 平均F-Measure:" + avgF); } } public static void recommend(int startNum,int endNum,int shift) { System.out.println("加权混合方法"); for (int recommendcount = startNum;recommendcount <= endNum;recommendcount+=shift) { System.out.println("推荐数:"+recommendcount); //根据物品标签对寻找用户和物品 for (float temp = 1;temp <= 10;temp++) { System.out.println("取每个用户的"+temp/10+"推荐"); float avgprecision = 0, avgrecall = 0,avgfmeasure = 0; int usercounts = 0; //标签数大于阈值的用户才推荐 long starttime = System.currentTimeMillis(); float totalNum = 0; for (String user : userRecordMap.keySet()) { float num = userRecordMap.get(user).getItemTags().size() * (temp / 10); totalNum+=num; usercounts++; Map<String, Float> itemtagmap = sortByValue(BayesScoring.getItemTagsScore(user,7.9f,temp/10)); // Map<String, Float> tagmap = sortByValue(BayesScoring.getItemscoreByTag(user)); // Iterator<Map.Entry<String,Float>> tagIt = tagmap.entrySet().iterator(); Map<String,Float> itemmap = ItemSimilarity.getItemMap(user,temp/10); //将两种结果合并 Map<String,Float> allmap = new HashMap<>(); float cfNum = (float) recommendcount * (temp / 10); int cfCount = 0; for (Map.Entry<String, Float> entry : itemtagmap.entrySet()) { if (cfCount++ > cfNum) break; allmap.put(entry.getKey(),entry.getValue()); } int contentCount = 0; for (Map.Entry<String, Float> entry : itemmap.entrySet()) { if (contentCount++ > recommendcount-cfNum) break; allmap.put(entry.getKey(),entry.getValue()); } Iterator<Map.Entry<String, Float>> it = allmap.entrySet().iterator(); Map<String, Double> ur = userRecordMap.get(user).getItems(); int hitcounts = 0, count = 0; while (it.hasNext()) { if (++count > recommendcount) break; Map.Entry<String, Float> entry = it.next(); if (ur.containsKey(entry.getKey())) hitcounts++; } float precision, recall,fmeasure; if (hitcounts != 0) { precision = Float.valueOf(hitcounts) / (float)allmap.size(); recall = Float.valueOf(hitcounts) / (ur.size() * (temp / 10)); fmeasure = 2 * precision * recall / (precision + recall); } else { precision = 0; recall = 0; fmeasure = 0; } avgprecision += precision; avgrecall += recall; avgfmeasure += fmeasure; } System.out.println("一共根据"+totalNum+"条记录推荐"); long endtime = System.currentTimeMillis(); System.out.println("取每个用户的" + temp / 10 + "推荐所需时间为:" + (endtime - starttime) / 1000 + "秒"); System.out.println("计算的用户数:" + usercounts); float averageP = avgprecision / usercounts; float averageR = avgrecall / usercounts; float averageF = avgfmeasure / usercounts; System.out.println("平均准确率:" + averageP + " 平均召回率:" + averageR +" 平均F-Measure:"+averageF); } } } public static void recommendByTag() { for (int recommendcount = 100;recommendcount<=100;recommendcount+=50) { System.out.println("推荐数:"+recommendcount); for (float temp = 10;temp <= 10;temp++) { System.out.println("根据用户记录的"+temp/10+"推荐"); float avgprecision = 0, avgrecall = 0; int usercounts = 0; //标签数大于阈值的用户才推荐 for (String user : userRecordMap.keySet()) { float num = userRecordMap.get(user).getItemTags().size()*(temp/10); usercounts++; Map<String,Float> itemtagmap = sortByValue(BayesScoring.getItemscoreByTag(user,temp/10)); Iterator<Map.Entry<String, Float>> it = itemtagmap.entrySet().iterator(); Map<String,Double> ur = userRecordMap.get(user).getItems(); int hitcounts = 0,count = 0; while (it.hasNext()) { if (++count > recommendcount) break; Map.Entry<String, Float> entry = it.next(); if (ur.containsKey(entry.getKey())) hitcounts++; } float precision, recall; if (hitcounts != 0) { precision = (float)hitcounts / (float) itemtagmap.size(); recall = (float) hitcounts / (float) ur.size(); } else { precision = 0; recall = 0; } avgprecision += precision; avgrecall += recall; System.out.println("用户推荐数:"+itemtagmap.size()+";"+user+"的准确率:"+precision+";召回率:"+recall); } System.out.println("计算的用户数:"+usercounts); System.out.println("平均准确率:"+avgprecision/usercounts+" 平均召回率:"+avgrecall/usercounts); } } } /** * 根据item-tag/tag推荐 */ public static void recommendByItemTag(int startNum,int endNum,int shift) { for (int recommendcount = startNum; recommendcount <= endNum; recommendcount += shift) { int resUserCount = 0; System.out.println("推荐数:" + recommendcount); for (float temp = 1; temp <= 10; temp ++) { float avgprecision = 0, avgrecall = 0; int usercounts = 0; //标签数大于阈值的用户才推荐 //根据物品标签对寻找用户和物品 for (String user : userRecordMap.keySet()) { float num = userRecordMap.get(user).getItemTags().size() * (temp / 10); usercounts++; Map<String, Float> itemtagmap = BayesScoring.getItemTagsScore(user,7.9f); if (itemtagmap.size() == 0) { continue; } //被推荐的用户数 resUserCount++; Map<String, Float> sortmap = sortByValue(itemtagmap); Map<String, Double> ur = userRecordMap.get(user).getItems(); int hitcounts = 0, count = 0; for (Map.Entry<String, Float> resIt : sortmap.entrySet()) { if (++count > recommendcount) break; if (ur.containsKey(resIt.getKey())) hitcounts++; } float precision, recall; if (hitcounts != 0) { precision = (float) hitcounts / count; recall = (float) hitcounts / ur.size(); } else { precision = 0; recall = 0; } avgprecision += precision; avgrecall += recall; } System.out.println("被推荐的用户数:" + usercounts); float averageP = avgprecision / usercounts; float averageR = avgrecall / usercounts; System.out.println("平均准确率:" + averageP + " 平均召回率:" + averageR + " 平均F-Measure:" + 2 * averageP * averageR / (averageR + averageP)); } } } //初始化数据 public static void initialData() { String pathname = "E:\\ADA_Project\\RecommenderSystem\\src\\main\\resources\\doubanset\\tags.dat"; String pathname1 = "E:\\ADA_Project\\RecommenderSystem\\src\\main\\resources\\doubanset\\rates.dat"; String itemscorepath = "E:\\ADA_Project\\RecommenderSystem\\src\\main\\resources\\doubanset\\bookscore.dat"; //String itemtagpath = "E:\\ADA_Project\\RecommenderSystem\\src\\main\\resources\\doubanset\\books.dat"; //初始化book_tag信息 //ItemSimilarity.initialBookTags(itemtagpath); //初始化所有物品的评分 BayesScoring.initialBookScore(itemscorepath); //初始化用户的item-tag记录 BayesScoring.initialUserItemTagMap1(pathname); //初始化用户的阅读评分记录 BayesScoring.initialUserRatingMap(pathname1); } //对map根据value排序 public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map ) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( map.entrySet() ); Collections.sort( list, new Comparator<Map.Entry<K, V>>() { public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) { return -(o1.getValue()).compareTo( o2.getValue() ); } } ); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { result.put( entry.getKey(), entry.getValue() ); } return result; } }
true
3d8559a0e337151972cd0a4334f6be33646651b2
Java
tirro-s/Chess-Java
/core/src/com/chess/game/engine/player/Player.java
UTF-8
3,585
2.84375
3
[]
no_license
package com.chess.game.engine.player; import com.chess.game.engine.Alliance; import com.chess.game.engine.board.Board; import com.chess.game.engine.board.Move; import com.chess.game.engine.pieces.King; import com.chess.game.engine.pieces.Piece; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import java.util.ArrayList; import java.util.Collection; import java.util.List; public abstract class Player { protected final Board board; protected final King playerKing; protected final Collection<Move> legalMoves; private final boolean isInChack; Player(Board board, Collection<Move> legalMoves, Collection<Move> opponentMoves) { this.board = board; this.playerKing = establishKing(); this.legalMoves = ImmutableList.copyOf(Iterables.concat(legalMoves, calculateKingCastle(legalMoves, opponentMoves))); this.isInChack = !Player.calculateAttacksOnTile(this.playerKing.getPiecePosition(), opponentMoves).isEmpty(); } public King getPlayerKing() { return this.playerKing; } public Collection<Move> getLegalMoves() { return this.legalMoves; } protected static Collection<Move> calculateAttacksOnTile(int piecePosition, Collection<Move> moves) { final List<Move> attackMoves = new ArrayList<>(); for(final Move move : moves) { if(piecePosition == move.getDestinationCoordinate()) { attackMoves.add(move); } } return ImmutableList.copyOf(attackMoves); } private King establishKing() { for(final Piece piece : getActivePieces()) { if (piece.getPieceType().isKing()) { return (King) piece; } } throw new RuntimeException("Не валидная доска"); } public boolean isMoveLegal(final Move move) { return this.legalMoves.contains(move); } public boolean isInCheck(){ return this.isInChack; } public boolean isInCheckMate(){ //ПРОВЕРИТЬ И СРАВНИТЬ С ПАТОМ return this.isInChack && !hasEscapeMoves(); } public boolean isInStaleMate(){ //ПРОВЕРИТЬ return !this.isInChack && !hasEscapeMoves(); } protected boolean hasEscapeMoves() { for(final Move move : this.legalMoves) { final MoveTransition transition = makeMove(move); if (transition.getMoveStatus().isDone()) { return true; } } return false; } public boolean isCastled(){ return false; } public MoveTransition makeMove(final Move move){ if (!isMoveLegal(move)) { return new MoveTransition(this.board, move, MoveStatus.ILLIGAL_MOVE); } final Board transitionBoard = move.execute(); final Collection<Move> kinhAttacks = Player.calculateAttacksOnTile(transitionBoard.currentPlayer().getOpponent().getPlayerKing().getPiecePosition(), transitionBoard.currentPlayer().getLegalMoves()); if (!kinhAttacks.isEmpty()) { return new MoveTransition(this.board, move, MoveStatus.LEAVES_PLAYER_IN_CHECK); } return new MoveTransition(transitionBoard, move, MoveStatus.DONE); } public abstract Collection<Piece> getActivePieces(); public abstract Alliance getAlliance(); public abstract Player getOpponent(); protected abstract Collection<Move> calculateKingCastle(Collection<Move> playerLegals, Collection<Move> opponentLegals); }
true
50dd3fd139595d0b03a74e5c5f09dc9032b70396
Java
Mehvix/competitive-programming
/Leetcode/reconstructQueue.java
UTF-8
766
2.9375
3
[]
no_license
import sun.plugin.javascript.navig.Array; import java.util.*; class Solution { public int[][] reconstructQueue(int[][] people) { Arrays.sort(people, new Comparator<int[]>() { @Override public int compare(int[] i, int[] j) { return i[0] == j[0] ? i[1] - j[1] : j[0] - i[0]; } }); ArrayList<int[]> lst = new ArrayList<>(); for (int[] person : people) { lst.add(person[1], person); } return lst.toArray(new int[0][]); } public static void main(String[] args) { Solution obj = new Solution(); System.out.println(Arrays.deepToString(obj.reconstructQueue(new int[][]{{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}}))); } }
true
e6bc6f399d08ea8a706a3b65eef51b062ecf722c
Java
albinaTheUnicorn/myFirstRepository
/src/main/java/com/bb/core/repository/AddressRepository.java
UTF-8
450
1.945313
2
[]
no_license
package com.bb.core.repository; import com.bb.core.domain.AddressDomain; import com.bb.core.dto.Address; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface AddressRepository extends CrudRepository<AddressDomain,Long> { List<AddressDomain> findAll(); Optional<AddressDomain> findByAddressId(Long id); }
true
44a366718ebcb43d58964659c71dc4c964a09e54
Java
promegalex/finartz
/src/main/java/com/finartz/ticket/model/User.java
UTF-8
462
1.882813
2
[]
no_license
package com.finartz.ticket.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; import java.util.List; /** * Created by promegalex on 11.03.2020 18:31 */ @Data @AllArgsConstructor @NoArgsConstructor public class User { private UserId id; private List<Ticket> tickets; private String phoneNumber; private String address; private Date birthDate; private Gender gender; }
true
7dd7f4870e571e6efca52c3b6146b119c1ce755c
Java
tan-yukun/design-patterns
/src/main/java/com/tan/yukun/command/achieves/LightOnCommand.java
UTF-8
376
2.453125
2
[]
no_license
package com.tan.yukun.command.achieves; import com.tan.yukun.command.interfaces.Command; import com.tan.yukun.command.interfaces.Light; /** * @author tan_y */ public class LightOnCommand implements Command { Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.on(); } }
true
196714b364583b1cc9607627ffac4e88921af65f
Java
makewheels/AnalyzeBusDex
/src/main/java/com/amap/api/p015a/by.java
UTF-8
527
1.648438
2
[]
no_license
package com.amap.api.p015a; import android.graphics.PointF; import java.util.ArrayList; import java.util.List; /* compiled from: TrafSegment */ /* renamed from: com.amap.api.a.by */ class by { /* renamed from: a */ private int f964a; /* renamed from: b */ private List<PointF> f965b = new ArrayList(); /* renamed from: a */ public List<PointF> m1575a() { return this.f965b; } /* renamed from: b */ public int m1576b() { return this.f964a; } }
true
ab3bfff497d903a3d2fdd5b19cac8766a2d266a2
Java
SuneethaGudise/git-practice
/TestNgPractice/src/loan/DebitAccount.java
UTF-8
444
2.109375
2
[]
no_license
package loan; import org.testng.annotations.Test; //@listener(packagename.classname) public class DebitAccount { @Test(groups={"Regression"}) public void debtDetails() { System.out.println("Enter the debit details"); } @Test public void depAmount() { System.out.println("Deposit the amount"); } @Test public void withdraw() { System.out.println("Amount withdraw"); } @Test public void balance() { System.out.println("Balance amount"); } }
true
bfb8fd9a8cf0fd80eaafc84256d0374c9b98ebcb
Java
ShaviSuri/BharatBankBackendJavaSpring
/Bank/src/main/java/com/training/bank/repo/CustomerRepo.java
UTF-8
390
1.71875
2
[]
no_license
package com.training.bank.repo; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Repository; import com.training.bank.model.Customer; public interface CustomerRepo extends JpaRepository<Customer, Long>{ // void delete(Optional<Customer> c); }
true
8c23aaab5344f561bad36934203fce28a26b8610
Java
ypg0112/OOP
/ConsoleApplication/src/com/personal/passbyvalue/array/ArrayByValue.java
UTF-8
715
3.875
4
[]
no_license
package com.personal.passbyvalue.array; public class ArrayByValue { public static void main(String[] args) { int array1[] = {2, 4}; int[] array2 = {3}; System.out.println("Before swap : \narray1 = "); print(array1); System.out.println("array2 = "); print(array2); swapValue(array1, array2); System.out.println("After swap : \narray1 = "); print(array1); System.out.println("array2 = "); print(array2); } private static void swapValue(int[] first, int[] second) { int temp[] = first; first = second; second = temp; } private static void print(int[] array) { for(int i : array) { System.out.println(i); } } }
true
689ddcfddd766dbc64ea029a12c2272164924241
Java
bannerxu/sureme
/service/src/main/java/top/banner/service/order/OrderCmsService.java
UTF-8
8,638
2.078125
2
[]
no_license
package top.banner.service.order; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specifications; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import top.banner.common.exception.MessageCodes; import top.banner.common.exception.ValidationException; import top.banner.common.utils.*; import top.banner.models.commodity.CommodityBanner; import top.banner.models.commodity.CommodityBannerDao; import top.banner.models.commodity.CommodityDao; import top.banner.models.commodity.StockKeepingUnitDao; import top.banner.models.logistics.LogisticsRecord; import top.banner.models.logistics.LogisticsRecordDao; import top.banner.models.moneywater.MoneyWater; import top.banner.models.moneywater.MoneyWaterType; import top.banner.models.order.*; import top.banner.service.RedisKeyPrefix; import top.banner.service.order.cms.OrderCmsResultVO; import top.banner.service.order.cms.OrderSendParamVO; import top.banner.service.order.web.OrderItemVO; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.math.BigDecimal; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static top.banner.common.utils.ExcelHelper.WEBAPP_EXPORT_EXCEL; /** * @author jinguoguo */ @Service public class OrderCmsService { private static final Logger logger = LoggerFactory.getLogger(OrderCmsService.class); @Resource private OrderDao orderDao; @Resource private OrderItemDao orderItemDao; @Resource private CommodityDao commodityDao; @Resource private CommodityBannerDao commodityBannerDao; @Resource private LogisticsRecordDao logisticsRecordDao; @Resource private StockKeepingUnitDao stockKeepingUnitDao; @Resource private CommonSpecUtil<Order> commonSpecUtil; @Resource private StringRedisTemplate stringRedisTemplate; @Resource private LogisticsUtil logisticsUtil; /** * 分页查询订单 * * @param orderStatus 订单状态 * @param pageable 分页信息 * @return 分页订单 */ public Page<OrderCmsResultVO> findPage(OrderStatusEnum orderStatus, Pageable pageable) { Specification<Order> specification = commonSpecUtil.equal("orderStatus", orderStatus); Specification<Order> deleted = commonSpecUtil.equal("deleted", false); Specifications<Order> specifications = null; if (ObjectUtils.isEmpty(orderStatus)) { specifications = Specifications.where(deleted); } else { specifications = Specifications.where(specification).and(deleted); } Page<Order> orders = orderDao.findAll(specifications, pageable); return orders.map(this::convertOrderToVO); } /** * 查询单个订单 * * @param orderId 订单id * @return 订单结果 */ public OrderCmsResultVO getOrder(Integer orderId) { Order order = orderDao.getOne(orderId); if (ObjectUtils.isEmpty(order)) { logger.error("调用订单单个查询业务:id{}对应的订单不存在", orderId); throw new ValidationException(MessageCodes.CMS_ORDER_NOT_EXIST, "订单不存在"); } return convertOrderToVO(order); } /** * 订单转VO * * @param order 订单 * @return VO */ private OrderCmsResultVO convertOrderToVO(Order order) { OrderCmsResultVO vo = new OrderCmsResultVO(); BeanUtils.copyNonNullProperties(order, vo); Integer orderId = order.getOrderId(); List<OrderItemVO> orderItems = orderItemDao.findByOrderIdIs(orderId).stream().map(orderItem -> { OrderItemVO orderItemVO = new OrderItemVO(); BeanUtils.copyNonNullProperties(orderItem, orderItemVO); Integer commodityId = orderItem.getCommodityId(); List<CommodityBanner> commodityBanners = commodityBannerDao.findByCommodityIdIsAndDeletedIsFalse(commodityId); orderItemVO.setCommodityBanners(commodityBanners); return orderItemVO; }).collect(Collectors.toList()); vo.setOrderItems(orderItems); return vo; } /** * 删除订单(只能删除用户已经取消的) * * @param orderId 订单id */ public void deleteOrder(Integer orderId) { Order order = orderDao.getOne(orderId); OrderStatusEnum orderStatus = order.getOrderStatus(); // 只有订单为已退款、已退货时,才执行删除 if (orderStatus.equals(OrderStatusEnum.ORDER_RETURNED) || orderStatus.equals(OrderStatusEnum.ORDER_REFUNDED)) { order.setDeleted(true); orderDao.saveAndFlush(order); } else { logger.warn("订单目前状态非可删除,导致删除订单失败"); } } /** * 发货 * * @param orderId 订单id * @param vo 物流信息 */ public void send(Integer orderId, OrderSendParamVO vo) { Date date = new Date(); // 发货时,修改发货时间,订单状态 Order order = orderDao.getOne(orderId); if (ObjectUtils.isEmpty(order) || order.getDeleted()) { logger.error("订单发货失败:订单{} 不存在", orderId); throw new ValidationException(MessageCodes.CMS_ORDER_NOT_EXIST); } // 判断:只有在订单是已支付状态才能发货 OrderStatusEnum orderStatus = order.getOrderStatus(); if (!orderStatus.equals(OrderStatusEnum.ORDER_WAITING_SEND)) { throw new ValidationException(MessageCodes.ORDER_STATUS_NOT_MATCH); } String logisticsNumber = vo.getLogisticsNumber(); order.setLogisticsNumber(logisticsNumber); order.setLogisticsCompany(vo.getLogisticsCompany()); order.setOrderStatus(OrderStatusEnum.ORDER_SENT); order.setSendTime(date); orderDao.saveAndFlush(order); } /** * 获取物流信息 * * @param orderId 订单id * @return 物流信息 */ public String getLogisticsInfo(Integer orderId) { Order order = orderDao.getOne(orderId); String logisticsNumber = order.getLogisticsNumber(); String logisticsCompany = order.getLogisticsCompany(); ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue(); String logisticsInfo = valueOperations.get(RedisKeyPrefix.logisticsInfo(orderId)); if (StringUtils.isEmpty(logisticsInfo)) { String info = logisticsUtil.getLogisticsInfo(logisticsCompany, logisticsNumber); // 存入redis valueOperations.set(RedisKeyPrefix.logisticsInfo(orderId), info, 1, TimeUnit.HOURS); LogisticsRecord logisticsRecord = logisticsRecordDao.findByOrderIdIs(orderId); if (ObjectUtils.isEmpty(logisticsRecord)) { logisticsRecord = new LogisticsRecord(); logisticsRecord.setOrderId(orderId); logisticsRecord.setLogisticsNumber(logisticsNumber); logisticsRecord.setLogisticsInfo(info); logisticsRecord.setLogisticsCompany(logisticsCompany); logisticsRecordDao.saveAndFlush(logisticsRecord); } return info; } return logisticsInfo; } public void excel(HttpServletResponse response) throws Exception { List<MoneyWater> list = new ArrayList<>(); MoneyWater moneyWater = new MoneyWater(); moneyWater.setMoney(BigDecimal.TEN); moneyWater.setDeleted(false); moneyWater.setTime(new Date()); moneyWater.setType(MoneyWaterType.PAY); moneyWater.setMoneyWaterId(1); moneyWater.setUserId(1); moneyWater.setOrderId(1); list.add(moneyWater); List<String> titles = Arrays.asList("金钱", "是否删除", "时间", "时间", "时间", "时间", "时间"); ExcelHelper.writeExcel("1.xls",list,MoneyWater.class,new ArrayList<>(1),titles); ExportUtil.exportToClient(response, "multipart/form-data", WEBAPP_EXPORT_EXCEL, "1.xls"); } }
true
6edfe3a4b38f086921e1ee919c9f04ac238bdc86
Java
snowjak88/rays3d
/rays3d/core/src/main/java/org/rays3d/message/SamplerRequestMessage.java
UTF-8
1,128
2.046875
2
[ "MIT" ]
permissive
package org.rays3d.message; import java.io.Serializable; public class SamplerRequestMessage implements Serializable { private static final long serialVersionUID = 2458491555780152549L; private long renderId; private int filmWidth; private int filmHeight; private String samplerName; private int samplesPerPixel; public long getRenderId() { return renderId; } public void setRenderId(long renderId) { this.renderId = renderId; } public int getFilmWidth() { return filmWidth; } public void setFilmWidth(int filmWidth) { this.filmWidth = filmWidth; } public int getFilmHeight() { return filmHeight; } public void setFilmHeight(int filmHeight) { this.filmHeight = filmHeight; } public String getSamplerName() { return samplerName; } public void setSamplerName(String samplerName) { this.samplerName = samplerName; } public int getSamplesPerPixel() { return samplesPerPixel; } public void setSamplesPerPixel(int samplesPerPixel) { this.samplesPerPixel = samplesPerPixel; } }
true
2fa6bb1e76ceec4a24caba90f71057f91bf0ec99
Java
mion00/ClassroomFinder
/src/init/InizializzaDati.java
UTF-8
5,541
2.5
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package init; import Database.Dipartimento; import Network.DownloadDati; import Network.MultiThreadHTTP; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONValue; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * * @author creamcodifier */ class Corso { String id; String nome; Dipartimento dipartimento; Corso(String id,String nome) { this.id=id; this.nome=nome; } @Override public String toString() { return "NOME: " + nome + " ID: " + id + " | " + dipartimento.toString(); } } public class InizializzaDati { private final String urlBase="http://webapps.unitn.it/Orari/it/Web/CalendarioCds"; private final String urlPost = "http://webapps.unitn.it/Orari/it/Web/AjaxCds"; private Document doc; private String annoSelected; final void checkConfigDir() { File config = new File("config"); if (!config.exists()) { config.mkdir(); } } private void DownloadBaseHTML() { try { doc = Jsoup.connect(urlBase).get(); } catch (IOException ex) { System.out.println("Unable to download HTML page"); } } private String CalcolaAnnoAccademico() { Elements options = doc.getElementsByAttributeValue("name", "id"); Elements anni = options.get(0).getElementsByTag("option"); Elements annoselected = anni.get(0).getElementsByAttributeValue("selected", "selected"); String anno_id= annoselected.get(0).attributes().get("value"); return anno_id; } List<Dipartimento> OttieniDipartimenti() { List<Dipartimento> indirizzi = new ArrayList<>(); Elements labels = doc.getElementsByAttributeValue("name", "id2"); Elements dipartimenti = labels.get(0).getElementsByTag("option"); annoSelected = CalcolaAnnoAccademico(); for (int i = 1; i<dipartimenti.size(); i++) { Element elem = dipartimenti.get(i); String value = elem.attributes().get("value"); String name = elem.html(); Dipartimento dip = new Dipartimento(); dip.id = i-1; dip.setNome(name); dip.setAnno(annoSelected); dip.setUrlCorso(value); indirizzi.add(dip); } // DEBUG // for (int i = 0; i< indirizzi.size(); i++) { // System.out.println(indirizzi.get(i)); // } return indirizzi; } void SalvaDipartimenti() { try { FileWriter writer = new FileWriter("config/dipartimenti.json"); List<Dipartimento> list = OttieniDipartimenti(); JSONArray array = new JSONArray(); BufferedWriter buff = new BufferedWriter(writer); for (int i=0; i<list.size(); i++) { Dipartimento dip = list.get(i); Map obj = new LinkedHashMap(); obj.put("id", dip.id); obj.put("name", dip.getNome()); obj.put("urlCorse", dip.getUrlCorso()); obj.put("accademicYear", dip.getAnno()); array.add(JSONValue.toJSONString(obj)); } buff.write(array.toString()); buff.close(); } catch (IOException ex) { System.out.println("Unable to write file"); } } void OttieniCorsi(List<Dipartimento> list_dip) { List<String> parameters = new ArrayList<>(); List<String> courses = new ArrayList<>(); for (Dipartimento dip : list_dip) { String parameter = "id="+annoSelected+"&id2="+dip.id; parameters.add(parameter); } //// DEBUG // for (int i=0; i < parameters.size(); i++){ // System.out.println(parameters.get(i)); // } MultiThreadHTTP downloader = new MultiThreadHTTP(); courses = downloader.PostfFromParameters(urlPost, parameters); for (int i=0; i<courses.size();i++) { System.out.println(courses.get(i)); } } public InizializzaDati () { checkConfigDir(); DownloadBaseHTML(); SalvaDipartimenti(); // List<Dipartimento> list_dip = OttieniDipartimenti(); // OttieniCorsi(list_dip); //chiama la funzione OttieniIdDipartimenti() che ritorna una lista di stringhe //passa la lista di dipartimenti alla funzione OttieniIdCorsi(List<String> dipartimenti) che ritorna una lista di stringhe (metodo post) //viene chiamata la funzione OttieniEventi che riceve la lista di corsi e ritorna una hashmap che associa ad ogni corso i relativi url di eventi //ad ogni evento di ogni corso viene mandata una richesta per ottenere le aule e l'edificio relativo all'evento per costruire 2 map che associano edificio e aule ed edificio e corsi } }
true
7283bb7fcce00f5311c9e4af7e3f412539c39f5e
Java
Aaron216/MobileAppDevelopment-Assignment
/src/main/java/au/edu/curtin/madassignment/Database/AreaCursor.java
UTF-8
1,124
2.515625
3
[]
no_license
package au.edu.curtin.madassignment.Database; import android.database.Cursor; import android.database.CursorWrapper; import java.util.UUID; import au.edu.curtin.madassignment.Model.Area; import au.edu.curtin.madassignment.Database.GameSchema.AreaTable; public class AreaCursor extends CursorWrapper { public AreaCursor(Cursor cursor) { super(cursor); } public Area getArea() { UUID areaID = UUID.fromString(getString(getColumnIndex(AreaTable.Cols.ID))); int rowLocation = getInt(getColumnIndex(AreaTable.Cols.ROW_LOCATION)); int colLocation = getInt(getColumnIndex(AreaTable.Cols.COL_LOCATION)); boolean town = Boolean.valueOf(getString(getColumnIndex(AreaTable.Cols.IS_TOWN))); String description = getString(getColumnIndex(AreaTable.Cols.DESCRIPTION)); boolean starred = Boolean.valueOf(getString(getColumnIndex(AreaTable.Cols.IS_STARRED))); boolean explored = Boolean.valueOf(getString(getColumnIndex(AreaTable.Cols.IS_EXPLORED))); return new Area(areaID, rowLocation, colLocation, town, description, starred, explored); } }
true
28bcd3cd2bff521588702acb22619b3ea6b6876c
Java
keGoep/Demo1
/Day18/Handling_copy.java
UTF-8
1,945
2.859375
3
[]
no_license
package Day18; import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * @Author LinQ * Date:2020/12/9 * Weather:Windy */ public class Handling_copy { public static void main(String[] args) { copy(); } public static void copy() { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { File inFile = new File("C:\\Users\\86181\\Pictures\\Saved Pictures\\a.jpg"); File outFile = new File("E:\\e.jpg"); fileInputStream = new FileInputStream(inFile); fileOutputStream = new FileOutputStream(outFile); byte[] buf = new byte[1024]; int length = 0; while ((length = fileInputStream.read(buf)) != -1) { fileOutputStream.write(buf, 0, length); } } catch (IOException e) { System.out.println("拷贝图片出错"); throw new RuntimeException(e); } finally { //关闭资源 try { if(fileInputStream!=null) fileInputStream.close(); System.out.println("关闭输入流对象成功"); }catch(IOException e){ System.out.println("关闭输入流对象成功"); throw new RuntimeException(e); }finally { if(fileOutputStream!=null) { try { fileOutputStream.close(); System.out.println("关闭输出流对象成功"); } catch (IOException e) { System.out.println("关闭输出流对象失败.."); throw new RuntimeException(e); } } } } } }
true
4b9970bcc1a012899ab3337d117dc6705b7f1f7e
Java
taoistcard/zeus
/zeus.live/src/main/java/zeus/live/server/BusinessUtil.java
UTF-8
6,557
1.90625
2
[]
no_license
package zeus.live.server; import java.io.IOException; import java.text.ParseException; import javax.persistence.EntityManager; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.i5i58.clubTask.ClubTaskUtils; import com.i5i58.data.channel.ChannelAuth; import com.i5i58.data.channel.ChannelWatchingRecord; import com.i5i58.data.channel.WeekOffer; import com.i5i58.userTask.TaskUtil; import com.i5i58.util.AuthVerify; import com.i5i58.util.ChannelUtils; import com.i5i58.util.Constant; import com.i5i58.util.DateUtils; import com.i5i58.util.JedisUtils; import com.i5i58.util.JsonUtils; import com.i5i58.util.MountPresentUtil; import zeus.live.data.HotDaoDelegate; import zeus.live.data.PriDaoDelegate; import zeus.live.data.SecDaoDelegate; @Component public class BusinessUtil { private static Logger logger = Logger.getLogger(BusinessUtil.class); private static LiveDataService liveDataService; private static PriDaoDelegate priDaoDelegate; private static SecDaoDelegate secDaoDelegate; private static HotDaoDelegate hotDaoDelegate; private static EntityManager entityManager; private static JedisUtils jedisUtils; private static AuthVerify<ChannelAuth> channelAdminAuthVerify; private static JsonUtils jsonUtil; private static MountPresentUtil mountPresentUtil; private static ChannelUtils channelUtils; private static TaskUtil taskUtil; private static ClubTaskUtils clubTaskUtils; public static boolean beforeServerStart() { liveDataService = LiveDataService.getInstance(); priDaoDelegate = liveDataService.getPriDaoDelegate(); secDaoDelegate = liveDataService.getSecDaoDelegate(); hotDaoDelegate = liveDataService.getHotDaoDelegate(); entityManager = liveDataService.getEntityManager(); jedisUtils = liveDataService.getJedisUtils(); channelAdminAuthVerify = liveDataService.getChannelAdminAuthVerify(); jsonUtil = liveDataService.getJsonUtil(); mountPresentUtil = liveDataService.getMountPresentUtil(); channelUtils = liveDataService.getChannelUtils(); taskUtil = liveDataService.getTaskUtil(); clubTaskUtils = liveDataService.getClubTaskUtils(); return true; } public static void addSessionId(String accId, String sessionId) { liveDataService.getJedisUtils().hset(Constant.HOT_USERDATA + accId, Constant.SUB_USERDATA_VIRTUAL_SESSION_ID, sessionId); logger.info(String.format("add virtual session id accId %s, sessionId %s", accId, sessionId)); } public static String getSessionId(String accId) { return liveDataService.getJedisUtils().hget(Constant.HOT_USERDATA + accId, Constant.SUB_USERDATA_VIRTUAL_SESSION_ID); } public static void delSessionId(String accId) { liveDataService.getJedisUtils().hdel(Constant.HOT_USERDATA + accId, Constant.SUB_USERDATA_VIRTUAL_SESSION_ID); logger.info(String.format("delete virtual session id accId %s", accId)); } public static void channelWatchingStart(String cId, String accId) throws ParseException { long nowTime = DateUtils.getNowTime(); ChannelWatchingRecord todayWatchingTime = liveDataService.getPriDaoDelegate().getChannelWatchingRecordPriDao() .findOne(cId + "_" + accId); if (todayWatchingTime == null) { todayWatchingTime = new ChannelWatchingRecord(); todayWatchingTime.setId(cId + "_" + accId); todayWatchingTime.setAccId(accId); todayWatchingTime.setcId(cId); todayWatchingTime.setStartTime(nowTime); } else { try { long dayDiff; dayDiff = DateUtils.getDayInterval(todayWatchingTime.getStartTime(), nowTime); if (dayDiff != 0) {// 重置过期值 todayWatchingTime.setStartTime(nowTime); todayWatchingTime.setFinishTime(0L); todayWatchingTime.setDuration(0L); } todayWatchingTime.setStartTime(nowTime); } catch (java.text.ParseException e) { e.printStackTrace(); } } liveDataService.getPriDaoDelegate().getChannelWatchingRecordPriDao().save(todayWatchingTime); } /** * 获取娱乐积分对应的等级 * * @return * @author frank */ public static int getRichScoreLevel(long richScore) { richScore = richScore / 100; if (richScore <= 10) { return 1; } if (richScore <= 100) { return 2; } if (richScore <= 200) { return 3; } if (richScore <= 500) { return 4; } if (richScore <= 800) { return 5; } if (richScore <= 2000) { return 6; } if (richScore <= 5000) { return 7; } if (richScore <= 10000) { return 8; } if (richScore <= 20000) { return 9; } if (richScore <= 50000) { return 10; } if (richScore <= 100000) { return 11; } if (richScore <= 200000) { return 12; } if (richScore <= 300000) { return 13; } if (richScore <= 400000) { return 14; } if (richScore <= 500000) { return 15; } if (richScore <= 600000) { return 16; } if (richScore <= 800000) { return 17; } if (richScore <= 1000000) { return 18; } if (richScore <= 2000000) { return 19; } if (richScore <= 3000000) { return 20; } return 20; } public static long addWeekOffer(String cId, String accId, final long amount, String name, String faceSmallUrl, final int vip, final int guardLevel, final long richScore) { long offer = 0; System.out.println(amount); Double score = liveDataService.getJedisUtils().zscore(Constant.HOT_CHANNEL_WEEKOFFER_SSET_KEY + cId, accId); if (score == null) { offer = amount; } else { System.out.println(score); offer = score.longValue() + amount; } System.out.println(offer); liveDataService.getJedisUtils().zadd(Constant.HOT_CHANNEL_WEEKOFFER_SSET_KEY + cId, offer, accId);// redis排序集合记录周榜排名 // jedisUtils.hset(Constant.HOT_CHANNEL_WEEKOFFER_HSET_KEY + cId, accId, // Long.toString(offer)); WeekOffer weekOffer = new WeekOffer(); weekOffer.setAccId(accId); weekOffer.setOffer(offer); weekOffer.setName(name); weekOffer.setFaceSmallUrl(faceSmallUrl); weekOffer.setVip(vip); weekOffer.setGuardLevel(guardLevel); weekOffer.setRichScore(richScore); try { String value = liveDataService.getJsonUtil().toJson(weekOffer); System.out.println(value); liveDataService.getJedisUtils().hset(Constant.HOT_CHANNEL_WEEKOFFER_HSET_KEY + cId, accId, value);// redis // hash集合存放周榜用户对象json } catch (IOException e) { logger.error("", e); } return offer; } public static boolean giftAnmiCondition(int count, int continuous, int condition) { if (condition == 0) { return true; } if (count == condition) { return true; } return false; } }
true
f949e423b1fb265127b0efa7c090aa6934d87830
Java
hanqunfeng/springbootchapter
/chapter36/cas-overlay-template-6.2.2/src/main/java/com/cas/controller/CaptchaController.java
UTF-8
8,041
2.265625
2
[ "Apache-2.0", "MIT" ]
permissive
package com.cas.controller; import com.cas.utils.AesUtil; import io.swagger.annotations.Api; import io.swagger.v3.oas.annotations.Operation; import org.apereo.cas.configuration.CasConfigurationProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.util.WebUtils; import javax.annotation.Nullable; import javax.imageio.ImageIO; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Random; /** * <p>验证码</p> * Created by hanqf on 2020/9/11 11:54. */ @Api(tags = {"验证码控制器"}) //@Tag(name = "验证码控制器") @Controller public class CaptchaController extends BaseController { public static final int WIDTH = 120;//生成图片的宽度 public static final int HEIGHT = 55;//生成图片的高度 public static final int WORDS_NUMBER = 4;//验证码中字符的个数 public static final String CHECK_CODE_NAME = "CHECK_CODE";//验证码session中的名称 //CaptchaConfiguration中注入进来的 @Autowired private CasConfigurationProperties casConfigurationProperties; //@ApiOperation(value = "生成验证码",notes = "4位长度,字母或数字") @Operation(summary = "生成验证码",description = "4位长度,字母或数字") @RequestMapping("/checkcode/bimage") public void creatImageCode(HttpServletRequest req, HttpServletResponse resp) throws IOException { // TODO Auto-generated method stub String createTypeFlag = req.getParameter("createTypeFlag");//接收客户端传递的createTypeFlag标识 //在内存中创建一张图片 BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR); //得到图片 Graphics g = bi.getGraphics(); //设置图片的背景色 setBackGround(g); //设置图片的边框 setBorder(g); //在图片上画干扰线 drawRandomLine(g); //在图片上放上随机字符 String randomString = this.drawRandomNum(g, createTypeFlag); //将随机数存在session中 //req.getSession(true).setAttribute(CHECK_CODE_NAME, randomString); WebUtils.setSessionAttribute(req, CHECK_CODE_NAME, randomString); //http访问时获取session的值为null,所以这里使用cookie再存储一份,取的时候,先判断session是否存在,不存在就读取cookie,cookie的值最好加密处理 Cookie cookie = new Cookie(CHECK_CODE_NAME, AesUtil.encrypt(randomString)); //当maxAge属性为负数,则表示该Cookie只是一个临时Cookie,不会被持久化,仅在本浏览器窗口或者本窗口打开的子窗口中有效,关闭浏览器后该Cookie立即失效。 cookie.setMaxAge(-1); resp.addCookie(cookie); //设置响应头通知浏览器以图片的形式打开 resp.setContentType("image/jpeg"); //设置响应头控制浏览器不要缓存 resp.setDateHeader("expries", -1); resp.setHeader("Cache-Control", "no-cache"); resp.setHeader("Pragma", "no-cache"); //将图片传给浏览器 ImageIO.write(bi, "jpg", resp.getOutputStream()); } //@ApiOperation(value = "比对验证码",notes = "判断验证码是否有效") @Operation(summary = "比对验证码",description = "判断验证码是否有效") @RequestMapping("/checkcode/check") @ResponseBody public Map<String, Object> checkCode(@Nullable String code, HttpServletRequest req) { //返回值 Map<String, Object> map = new HashMap<String, Object>(); if (!StringUtils.hasText(code)) { map.put("error", true); map.put("msg", getMessage("login.checkcode.check.null")); } else { //String checkcode = (String) req.getSession(true).getAttribute(CHECK_CODE_NAME); String checkcode = (String) WebUtils.getSessionAttribute(req, CHECK_CODE_NAME); if (checkcode == null) { Cookie cookie = WebUtils.getCookie(req, CHECK_CODE_NAME); if (cookie != null) { checkcode = AesUtil.decrypt(cookie.getValue()); } } if (code.trim().equalsIgnoreCase(checkcode)) { map.put("error", false); map.put("msg", getMessage("login.checkcode.check.success")); } else { map.put("error", true); map.put("msg", getMessage("login.checkcode.check.fail") + checkcode); } } return map; } //设置图片背景色 //@param g private void setBackGround(Graphics g) { //设置颜色 g.setColor(Color.WHITE); //填充区域 g.fillRect(0, 0, WIDTH, HEIGHT); } /* * 设置图片的边框 * @param g * */ private void setBorder(Graphics g) { //设置边框颜色 g.setColor(Color.BLUE); //边框区域 g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2); } /* * 在图片上画随机线条 * @param g * */ private void drawRandomLine(Graphics g) { //设置颜色 g.setColor(Color.GREEN); //设置线条个数并画线 for (int i = 0; i < 3; i++) { int x1 = new Random().nextInt(WIDTH); int y1 = new Random().nextInt(HEIGHT); int x2 = new Random().nextInt(WIDTH); int y2 = new Random().nextInt(HEIGHT); g.drawLine(x1, y1, x2, y2); } } /* * 在图片上画随机字符 * @param g * @param createTypeFlag * @return String * */ private String drawRandomNum(Graphics g, String createTypeFlag) { //设置颜色 g.setColor(Color.RED); g.setFont(new Font("宋体", Font.BOLD, 30)); //数字字母的组合,为了避免数字0和字母O混淆,所以去掉了 String baseNumLetter = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ"; String baseNum = "123456789"; String baseLetter = "ABCDEFGHJKLMNPQRSTUVWXYZ"; if (createTypeFlag != null && createTypeFlag.length() > 0) { if ("nl".equals(createTypeFlag)) { //截取数字和字母的组合 return createRandomChar((Graphics2D) g, baseNumLetter); } else if ("n".equals(createTypeFlag)) { //截取数字的组合 return createRandomChar((Graphics2D) g, baseNum); } else if ("l".equals(createTypeFlag)) { //截取字母的组合 return createRandomChar((Graphics2D) g, baseLetter); } } else { //截取数字和字母的组合 return createRandomChar((Graphics2D) g, baseNumLetter); } return ""; } /* * 创建随机字符 * @param g * @param baseChar * @return String * */ private String createRandomChar(Graphics2D g, String baseChar) { StringBuffer b = new StringBuffer(); int x = 5; String ch = ""; for (int i = 0; i < WORDS_NUMBER; i++) { //设置字体的旋转角度 int degree = new Random().nextInt() % 30; ch = baseChar.charAt(new Random().nextInt(baseChar.length())) + ""; b.append(ch); //正向角度 g.rotate(degree * Math.PI / 180, x, 40); g.drawString(ch, x, 40); //反向角度 g.rotate(-degree * Math.PI / 180, x, 40); x += 30; } return b.toString(); } }
true
6186ace75568dd5b827bc362f6dd1334616f7736
Java
WangMin219/workspace
/lqb/src/com/zt/s5/T1.java
UTF-8
219
2.6875
3
[]
no_license
package com.zt.s5; public class T1 { public static void main(String[] args) { for(int a=4;a<20;a++) { for(int b=4;b<20;b++) { if((a*b==(a+b)*6)&&a!=b) { System.out.println(a+" "+b); } } } } }
true
e04d4d3f1cb24197ab432356035282dccad3e198
Java
aravind24u/Tree_Strucutres
/ChaseInteg/src/com/medicalmine/charm/store/chase/bean/response/InquiryRespType.java
UTF-8
44,803
1.585938
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.09.12 at 06:20:23 PM IST // package com.medicalmine.charm.store.chase.bean.response; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for inquiryRespType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="inquiryRespType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="IndustryType" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="MessageType" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="MerchantID" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="TerminalID" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="CardBrand" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="AccountNum" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="OrderID" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="TxRefNum" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="TxRefIdx" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="ProcStatus" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="ApprovalStatus" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="RespCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="AVSRespCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="CVV2RespCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="AuthCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="RecurringAdviceCd" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="CAVVRespCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="StatusMsg" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="RespMsg" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="HostRespCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="HostAVSRespCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="HostCVV2RespCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="CustomerRefNum" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="CustomerName" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="ProfileProcStatus" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="CustomerProfileMessage" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="BillerReferenceNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="MBStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="MBMicroPaymentDaysLeft" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="MBMicroPaymentDollarsLeft" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="RespTime" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="PartialAuthOccurred" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="RequestedAmount" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="RedeemedAmount" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="RemainingBalance" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="CountryFraudFilterStatus" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="IsoCountryCode" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="FraudScoreProcStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="FraudScoreProcMsg" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="FraudAnalysisResponse" type="{}fraudAnalysisRespType" minOccurs="0"/> * &lt;element name="CTIAffluentCard" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CTICommercialCard" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CTIDurbinExemption" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CTIHealthcareCard" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CTILevel3Eligible" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CTIPayrollCard" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CTIPrepaidCard" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CTIPINlessDebitCard" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CTISignatureDebitCard" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="CTIIssuingCountry" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EUDDCountryCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EUDDBankSortCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EUDDRibCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EUDDBankBranchCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EUDDIBAN" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EUDDBIC" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EUDDMandateSignatureDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EUDDMandateID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="EUDDMandateType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="TokenAssuranceLevel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="DPANAccountStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "inquiryRespType", propOrder = { "industryType", "messageType", "merchantID", "terminalID", "cardBrand", "accountNum", "orderID", "txRefNum", "txRefIdx", "procStatus", "approvalStatus", "respCode", "avsRespCode", "cvv2RespCode", "authCode", "recurringAdviceCd", "cavvRespCode", "statusMsg", "respMsg", "hostRespCode", "hostAVSRespCode", "hostCVV2RespCode", "customerRefNum", "customerName", "profileProcStatus", "customerProfileMessage", "billerReferenceNumber", "mbStatus", "mbMicroPaymentDaysLeft", "mbMicroPaymentDollarsLeft", "respTime", "partialAuthOccurred", "requestedAmount", "redeemedAmount", "remainingBalance", "countryFraudFilterStatus", "isoCountryCode", "fraudScoreProcStatus", "fraudScoreProcMsg", "fraudAnalysisResponse", "ctiAffluentCard", "ctiCommercialCard", "ctiDurbinExemption", "ctiHealthcareCard", "ctiLevel3Eligible", "ctiPayrollCard", "ctiPrepaidCard", "ctipiNlessDebitCard", "ctiSignatureDebitCard", "ctiIssuingCountry", "euddCountryCode", "euddBankSortCode", "euddRibCode", "euddBankBranchCode", "euddiban", "euddbic", "euddMandateSignatureDate", "euddMandateID", "euddMandateType", "tokenAssuranceLevel", "dpanAccountStatus" }) public class InquiryRespType { @XmlElement(name = "IndustryType", required = true) protected String industryType; @XmlElement(name = "MessageType", required = true) protected String messageType; @XmlElement(name = "MerchantID", required = true) protected String merchantID; @XmlElement(name = "TerminalID", required = true) protected String terminalID; @XmlElement(name = "CardBrand", required = true) protected String cardBrand; @XmlElement(name = "AccountNum", required = true) protected String accountNum; @XmlElement(name = "OrderID", required = true) protected String orderID; @XmlElement(name = "TxRefNum", required = true) protected String txRefNum; @XmlElement(name = "TxRefIdx", required = true) protected String txRefIdx; @XmlElement(name = "ProcStatus", required = true) protected String procStatus; @XmlElement(name = "ApprovalStatus", required = true) protected String approvalStatus; @XmlElement(name = "RespCode", required = true) protected String respCode; @XmlElement(name = "AVSRespCode", required = true) protected String avsRespCode; @XmlElement(name = "CVV2RespCode", required = true) protected String cvv2RespCode; @XmlElement(name = "AuthCode", required = true) protected String authCode; @XmlElement(name = "RecurringAdviceCd", required = true) protected String recurringAdviceCd; @XmlElement(name = "CAVVRespCode", required = true) protected String cavvRespCode; @XmlElement(name = "StatusMsg", required = true) protected String statusMsg; @XmlElement(name = "RespMsg", required = true) protected String respMsg; @XmlElement(name = "HostRespCode", required = true) protected String hostRespCode; @XmlElement(name = "HostAVSRespCode", required = true) protected String hostAVSRespCode; @XmlElement(name = "HostCVV2RespCode", required = true) protected String hostCVV2RespCode; @XmlElement(name = "CustomerRefNum", required = true) protected String customerRefNum; @XmlElement(name = "CustomerName", required = true) protected String customerName; @XmlElement(name = "ProfileProcStatus", required = true) protected String profileProcStatus; @XmlElement(name = "CustomerProfileMessage", required = true) protected String customerProfileMessage; @XmlElement(name = "BillerReferenceNumber") protected String billerReferenceNumber; @XmlElement(name = "MBStatus") protected String mbStatus; @XmlElement(name = "MBMicroPaymentDaysLeft") protected String mbMicroPaymentDaysLeft; @XmlElement(name = "MBMicroPaymentDollarsLeft") protected String mbMicroPaymentDollarsLeft; @XmlElement(name = "RespTime", required = true) protected String respTime; @XmlElement(name = "PartialAuthOccurred", required = true) protected String partialAuthOccurred; @XmlElement(name = "RequestedAmount", required = true) protected String requestedAmount; @XmlElement(name = "RedeemedAmount", required = true) protected String redeemedAmount; @XmlElement(name = "RemainingBalance", required = true) protected String remainingBalance; @XmlElement(name = "CountryFraudFilterStatus", required = true) protected String countryFraudFilterStatus; @XmlElement(name = "IsoCountryCode", required = true) protected String isoCountryCode; @XmlElement(name = "FraudScoreProcStatus") protected String fraudScoreProcStatus; @XmlElement(name = "FraudScoreProcMsg") protected String fraudScoreProcMsg; @XmlElement(name = "FraudAnalysisResponse") protected FraudAnalysisRespType fraudAnalysisResponse; @XmlElement(name = "CTIAffluentCard") protected String ctiAffluentCard; @XmlElement(name = "CTICommercialCard") protected String ctiCommercialCard; @XmlElement(name = "CTIDurbinExemption") protected String ctiDurbinExemption; @XmlElement(name = "CTIHealthcareCard") protected String ctiHealthcareCard; @XmlElement(name = "CTILevel3Eligible") protected String ctiLevel3Eligible; @XmlElement(name = "CTIPayrollCard") protected String ctiPayrollCard; @XmlElement(name = "CTIPrepaidCard") protected String ctiPrepaidCard; @XmlElement(name = "CTIPINlessDebitCard") protected String ctipiNlessDebitCard; @XmlElement(name = "CTISignatureDebitCard") protected String ctiSignatureDebitCard; @XmlElement(name = "CTIIssuingCountry") protected String ctiIssuingCountry; @XmlElement(name = "EUDDCountryCode") protected String euddCountryCode; @XmlElement(name = "EUDDBankSortCode") protected String euddBankSortCode; @XmlElement(name = "EUDDRibCode") protected String euddRibCode; @XmlElement(name = "EUDDBankBranchCode") protected String euddBankBranchCode; @XmlElement(name = "EUDDIBAN") protected String euddiban; @XmlElement(name = "EUDDBIC") protected String euddbic; @XmlElement(name = "EUDDMandateSignatureDate") protected String euddMandateSignatureDate; @XmlElement(name = "EUDDMandateID") protected String euddMandateID; @XmlElement(name = "EUDDMandateType") protected String euddMandateType; @XmlElement(name = "TokenAssuranceLevel") protected String tokenAssuranceLevel; @XmlElement(name = "DPANAccountStatus") protected String dpanAccountStatus; /** * Gets the value of the industryType property. * * @return * possible object is * {@link String } * */ public String getIndustryType() { return industryType; } /** * Sets the value of the industryType property. * * @param value * allowed object is * {@link String } * */ public void setIndustryType(String value) { this.industryType = value; } /** * Gets the value of the messageType property. * * @return * possible object is * {@link String } * */ public String getMessageType() { return messageType; } /** * Sets the value of the messageType property. * * @param value * allowed object is * {@link String } * */ public void setMessageType(String value) { this.messageType = value; } /** * Gets the value of the merchantID property. * * @return * possible object is * {@link String } * */ public String getMerchantID() { return merchantID; } /** * Sets the value of the merchantID property. * * @param value * allowed object is * {@link String } * */ public void setMerchantID(String value) { this.merchantID = value; } /** * Gets the value of the terminalID property. * * @return * possible object is * {@link String } * */ public String getTerminalID() { return terminalID; } /** * Sets the value of the terminalID property. * * @param value * allowed object is * {@link String } * */ public void setTerminalID(String value) { this.terminalID = value; } /** * Gets the value of the cardBrand property. * * @return * possible object is * {@link String } * */ public String getCardBrand() { return cardBrand; } /** * Sets the value of the cardBrand property. * * @param value * allowed object is * {@link String } * */ public void setCardBrand(String value) { this.cardBrand = value; } /** * Gets the value of the accountNum property. * * @return * possible object is * {@link String } * */ public String getAccountNum() { return accountNum; } /** * Sets the value of the accountNum property. * * @param value * allowed object is * {@link String } * */ public void setAccountNum(String value) { this.accountNum = value; } /** * Gets the value of the orderID property. * * @return * possible object is * {@link String } * */ public String getOrderID() { return orderID; } /** * Sets the value of the orderID property. * * @param value * allowed object is * {@link String } * */ public void setOrderID(String value) { this.orderID = value; } /** * Gets the value of the txRefNum property. * * @return * possible object is * {@link String } * */ public String getTxRefNum() { return txRefNum; } /** * Sets the value of the txRefNum property. * * @param value * allowed object is * {@link String } * */ public void setTxRefNum(String value) { this.txRefNum = value; } /** * Gets the value of the txRefIdx property. * * @return * possible object is * {@link String } * */ public String getTxRefIdx() { return txRefIdx; } /** * Sets the value of the txRefIdx property. * * @param value * allowed object is * {@link String } * */ public void setTxRefIdx(String value) { this.txRefIdx = value; } /** * Gets the value of the procStatus property. * * @return * possible object is * {@link String } * */ public String getProcStatus() { return procStatus; } /** * Sets the value of the procStatus property. * * @param value * allowed object is * {@link String } * */ public void setProcStatus(String value) { this.procStatus = value; } /** * Gets the value of the approvalStatus property. * * @return * possible object is * {@link String } * */ public String getApprovalStatus() { return approvalStatus; } /** * Sets the value of the approvalStatus property. * * @param value * allowed object is * {@link String } * */ public void setApprovalStatus(String value) { this.approvalStatus = value; } /** * Gets the value of the respCode property. * * @return * possible object is * {@link String } * */ public String getRespCode() { return respCode; } /** * Sets the value of the respCode property. * * @param value * allowed object is * {@link String } * */ public void setRespCode(String value) { this.respCode = value; } /** * Gets the value of the avsRespCode property. * * @return * possible object is * {@link String } * */ public String getAVSRespCode() { return avsRespCode; } /** * Sets the value of the avsRespCode property. * * @param value * allowed object is * {@link String } * */ public void setAVSRespCode(String value) { this.avsRespCode = value; } /** * Gets the value of the cvv2RespCode property. * * @return * possible object is * {@link String } * */ public String getCVV2RespCode() { return cvv2RespCode; } /** * Sets the value of the cvv2RespCode property. * * @param value * allowed object is * {@link String } * */ public void setCVV2RespCode(String value) { this.cvv2RespCode = value; } /** * Gets the value of the authCode property. * * @return * possible object is * {@link String } * */ public String getAuthCode() { return authCode; } /** * Sets the value of the authCode property. * * @param value * allowed object is * {@link String } * */ public void setAuthCode(String value) { this.authCode = value; } /** * Gets the value of the recurringAdviceCd property. * * @return * possible object is * {@link String } * */ public String getRecurringAdviceCd() { return recurringAdviceCd; } /** * Sets the value of the recurringAdviceCd property. * * @param value * allowed object is * {@link String } * */ public void setRecurringAdviceCd(String value) { this.recurringAdviceCd = value; } /** * Gets the value of the cavvRespCode property. * * @return * possible object is * {@link String } * */ public String getCAVVRespCode() { return cavvRespCode; } /** * Sets the value of the cavvRespCode property. * * @param value * allowed object is * {@link String } * */ public void setCAVVRespCode(String value) { this.cavvRespCode = value; } /** * Gets the value of the statusMsg property. * * @return * possible object is * {@link String } * */ public String getStatusMsg() { return statusMsg; } /** * Sets the value of the statusMsg property. * * @param value * allowed object is * {@link String } * */ public void setStatusMsg(String value) { this.statusMsg = value; } /** * Gets the value of the respMsg property. * * @return * possible object is * {@link String } * */ public String getRespMsg() { return respMsg; } /** * Sets the value of the respMsg property. * * @param value * allowed object is * {@link String } * */ public void setRespMsg(String value) { this.respMsg = value; } /** * Gets the value of the hostRespCode property. * * @return * possible object is * {@link String } * */ public String getHostRespCode() { return hostRespCode; } /** * Sets the value of the hostRespCode property. * * @param value * allowed object is * {@link String } * */ public void setHostRespCode(String value) { this.hostRespCode = value; } /** * Gets the value of the hostAVSRespCode property. * * @return * possible object is * {@link String } * */ public String getHostAVSRespCode() { return hostAVSRespCode; } /** * Sets the value of the hostAVSRespCode property. * * @param value * allowed object is * {@link String } * */ public void setHostAVSRespCode(String value) { this.hostAVSRespCode = value; } /** * Gets the value of the hostCVV2RespCode property. * * @return * possible object is * {@link String } * */ public String getHostCVV2RespCode() { return hostCVV2RespCode; } /** * Sets the value of the hostCVV2RespCode property. * * @param value * allowed object is * {@link String } * */ public void setHostCVV2RespCode(String value) { this.hostCVV2RespCode = value; } /** * Gets the value of the customerRefNum property. * * @return * possible object is * {@link String } * */ public String getCustomerRefNum() { return customerRefNum; } /** * Sets the value of the customerRefNum property. * * @param value * allowed object is * {@link String } * */ public void setCustomerRefNum(String value) { this.customerRefNum = value; } /** * Gets the value of the customerName property. * * @return * possible object is * {@link String } * */ public String getCustomerName() { return customerName; } /** * Sets the value of the customerName property. * * @param value * allowed object is * {@link String } * */ public void setCustomerName(String value) { this.customerName = value; } /** * Gets the value of the profileProcStatus property. * * @return * possible object is * {@link String } * */ public String getProfileProcStatus() { return profileProcStatus; } /** * Sets the value of the profileProcStatus property. * * @param value * allowed object is * {@link String } * */ public void setProfileProcStatus(String value) { this.profileProcStatus = value; } /** * Gets the value of the customerProfileMessage property. * * @return * possible object is * {@link String } * */ public String getCustomerProfileMessage() { return customerProfileMessage; } /** * Sets the value of the customerProfileMessage property. * * @param value * allowed object is * {@link String } * */ public void setCustomerProfileMessage(String value) { this.customerProfileMessage = value; } /** * Gets the value of the billerReferenceNumber property. * * @return * possible object is * {@link String } * */ public String getBillerReferenceNumber() { return billerReferenceNumber; } /** * Sets the value of the billerReferenceNumber property. * * @param value * allowed object is * {@link String } * */ public void setBillerReferenceNumber(String value) { this.billerReferenceNumber = value; } /** * Gets the value of the mbStatus property. * * @return * possible object is * {@link String } * */ public String getMBStatus() { return mbStatus; } /** * Sets the value of the mbStatus property. * * @param value * allowed object is * {@link String } * */ public void setMBStatus(String value) { this.mbStatus = value; } /** * Gets the value of the mbMicroPaymentDaysLeft property. * * @return * possible object is * {@link String } * */ public String getMBMicroPaymentDaysLeft() { return mbMicroPaymentDaysLeft; } /** * Sets the value of the mbMicroPaymentDaysLeft property. * * @param value * allowed object is * {@link String } * */ public void setMBMicroPaymentDaysLeft(String value) { this.mbMicroPaymentDaysLeft = value; } /** * Gets the value of the mbMicroPaymentDollarsLeft property. * * @return * possible object is * {@link String } * */ public String getMBMicroPaymentDollarsLeft() { return mbMicroPaymentDollarsLeft; } /** * Sets the value of the mbMicroPaymentDollarsLeft property. * * @param value * allowed object is * {@link String } * */ public void setMBMicroPaymentDollarsLeft(String value) { this.mbMicroPaymentDollarsLeft = value; } /** * Gets the value of the respTime property. * * @return * possible object is * {@link String } * */ public String getRespTime() { return respTime; } /** * Sets the value of the respTime property. * * @param value * allowed object is * {@link String } * */ public void setRespTime(String value) { this.respTime = value; } /** * Gets the value of the partialAuthOccurred property. * * @return * possible object is * {@link String } * */ public String getPartialAuthOccurred() { return partialAuthOccurred; } /** * Sets the value of the partialAuthOccurred property. * * @param value * allowed object is * {@link String } * */ public void setPartialAuthOccurred(String value) { this.partialAuthOccurred = value; } /** * Gets the value of the requestedAmount property. * * @return * possible object is * {@link String } * */ public String getRequestedAmount() { return requestedAmount; } /** * Sets the value of the requestedAmount property. * * @param value * allowed object is * {@link String } * */ public void setRequestedAmount(String value) { this.requestedAmount = value; } /** * Gets the value of the redeemedAmount property. * * @return * possible object is * {@link String } * */ public String getRedeemedAmount() { return redeemedAmount; } /** * Sets the value of the redeemedAmount property. * * @param value * allowed object is * {@link String } * */ public void setRedeemedAmount(String value) { this.redeemedAmount = value; } /** * Gets the value of the remainingBalance property. * * @return * possible object is * {@link String } * */ public String getRemainingBalance() { return remainingBalance; } /** * Sets the value of the remainingBalance property. * * @param value * allowed object is * {@link String } * */ public void setRemainingBalance(String value) { this.remainingBalance = value; } /** * Gets the value of the countryFraudFilterStatus property. * * @return * possible object is * {@link String } * */ public String getCountryFraudFilterStatus() { return countryFraudFilterStatus; } /** * Sets the value of the countryFraudFilterStatus property. * * @param value * allowed object is * {@link String } * */ public void setCountryFraudFilterStatus(String value) { this.countryFraudFilterStatus = value; } /** * Gets the value of the isoCountryCode property. * * @return * possible object is * {@link String } * */ public String getIsoCountryCode() { return isoCountryCode; } /** * Sets the value of the isoCountryCode property. * * @param value * allowed object is * {@link String } * */ public void setIsoCountryCode(String value) { this.isoCountryCode = value; } /** * Gets the value of the fraudScoreProcStatus property. * * @return * possible object is * {@link String } * */ public String getFraudScoreProcStatus() { return fraudScoreProcStatus; } /** * Sets the value of the fraudScoreProcStatus property. * * @param value * allowed object is * {@link String } * */ public void setFraudScoreProcStatus(String value) { this.fraudScoreProcStatus = value; } /** * Gets the value of the fraudScoreProcMsg property. * * @return * possible object is * {@link String } * */ public String getFraudScoreProcMsg() { return fraudScoreProcMsg; } /** * Sets the value of the fraudScoreProcMsg property. * * @param value * allowed object is * {@link String } * */ public void setFraudScoreProcMsg(String value) { this.fraudScoreProcMsg = value; } /** * Gets the value of the fraudAnalysisResponse property. * * @return * possible object is * {@link FraudAnalysisRespType } * */ public FraudAnalysisRespType getFraudAnalysisResponse() { return fraudAnalysisResponse; } /** * Sets the value of the fraudAnalysisResponse property. * * @param value * allowed object is * {@link FraudAnalysisRespType } * */ public void setFraudAnalysisResponse(FraudAnalysisRespType value) { this.fraudAnalysisResponse = value; } /** * Gets the value of the ctiAffluentCard property. * * @return * possible object is * {@link String } * */ public String getCTIAffluentCard() { return ctiAffluentCard; } /** * Sets the value of the ctiAffluentCard property. * * @param value * allowed object is * {@link String } * */ public void setCTIAffluentCard(String value) { this.ctiAffluentCard = value; } /** * Gets the value of the ctiCommercialCard property. * * @return * possible object is * {@link String } * */ public String getCTICommercialCard() { return ctiCommercialCard; } /** * Sets the value of the ctiCommercialCard property. * * @param value * allowed object is * {@link String } * */ public void setCTICommercialCard(String value) { this.ctiCommercialCard = value; } /** * Gets the value of the ctiDurbinExemption property. * * @return * possible object is * {@link String } * */ public String getCTIDurbinExemption() { return ctiDurbinExemption; } /** * Sets the value of the ctiDurbinExemption property. * * @param value * allowed object is * {@link String } * */ public void setCTIDurbinExemption(String value) { this.ctiDurbinExemption = value; } /** * Gets the value of the ctiHealthcareCard property. * * @return * possible object is * {@link String } * */ public String getCTIHealthcareCard() { return ctiHealthcareCard; } /** * Sets the value of the ctiHealthcareCard property. * * @param value * allowed object is * {@link String } * */ public void setCTIHealthcareCard(String value) { this.ctiHealthcareCard = value; } /** * Gets the value of the ctiLevel3Eligible property. * * @return * possible object is * {@link String } * */ public String getCTILevel3Eligible() { return ctiLevel3Eligible; } /** * Sets the value of the ctiLevel3Eligible property. * * @param value * allowed object is * {@link String } * */ public void setCTILevel3Eligible(String value) { this.ctiLevel3Eligible = value; } /** * Gets the value of the ctiPayrollCard property. * * @return * possible object is * {@link String } * */ public String getCTIPayrollCard() { return ctiPayrollCard; } /** * Sets the value of the ctiPayrollCard property. * * @param value * allowed object is * {@link String } * */ public void setCTIPayrollCard(String value) { this.ctiPayrollCard = value; } /** * Gets the value of the ctiPrepaidCard property. * * @return * possible object is * {@link String } * */ public String getCTIPrepaidCard() { return ctiPrepaidCard; } /** * Sets the value of the ctiPrepaidCard property. * * @param value * allowed object is * {@link String } * */ public void setCTIPrepaidCard(String value) { this.ctiPrepaidCard = value; } /** * Gets the value of the ctipiNlessDebitCard property. * * @return * possible object is * {@link String } * */ public String getCTIPINlessDebitCard() { return ctipiNlessDebitCard; } /** * Sets the value of the ctipiNlessDebitCard property. * * @param value * allowed object is * {@link String } * */ public void setCTIPINlessDebitCard(String value) { this.ctipiNlessDebitCard = value; } /** * Gets the value of the ctiSignatureDebitCard property. * * @return * possible object is * {@link String } * */ public String getCTISignatureDebitCard() { return ctiSignatureDebitCard; } /** * Sets the value of the ctiSignatureDebitCard property. * * @param value * allowed object is * {@link String } * */ public void setCTISignatureDebitCard(String value) { this.ctiSignatureDebitCard = value; } /** * Gets the value of the ctiIssuingCountry property. * * @return * possible object is * {@link String } * */ public String getCTIIssuingCountry() { return ctiIssuingCountry; } /** * Sets the value of the ctiIssuingCountry property. * * @param value * allowed object is * {@link String } * */ public void setCTIIssuingCountry(String value) { this.ctiIssuingCountry = value; } /** * Gets the value of the euddCountryCode property. * * @return * possible object is * {@link String } * */ public String getEUDDCountryCode() { return euddCountryCode; } /** * Sets the value of the euddCountryCode property. * * @param value * allowed object is * {@link String } * */ public void setEUDDCountryCode(String value) { this.euddCountryCode = value; } /** * Gets the value of the euddBankSortCode property. * * @return * possible object is * {@link String } * */ public String getEUDDBankSortCode() { return euddBankSortCode; } /** * Sets the value of the euddBankSortCode property. * * @param value * allowed object is * {@link String } * */ public void setEUDDBankSortCode(String value) { this.euddBankSortCode = value; } /** * Gets the value of the euddRibCode property. * * @return * possible object is * {@link String } * */ public String getEUDDRibCode() { return euddRibCode; } /** * Sets the value of the euddRibCode property. * * @param value * allowed object is * {@link String } * */ public void setEUDDRibCode(String value) { this.euddRibCode = value; } /** * Gets the value of the euddBankBranchCode property. * * @return * possible object is * {@link String } * */ public String getEUDDBankBranchCode() { return euddBankBranchCode; } /** * Sets the value of the euddBankBranchCode property. * * @param value * allowed object is * {@link String } * */ public void setEUDDBankBranchCode(String value) { this.euddBankBranchCode = value; } /** * Gets the value of the euddiban property. * * @return * possible object is * {@link String } * */ public String getEUDDIBAN() { return euddiban; } /** * Sets the value of the euddiban property. * * @param value * allowed object is * {@link String } * */ public void setEUDDIBAN(String value) { this.euddiban = value; } /** * Gets the value of the euddbic property. * * @return * possible object is * {@link String } * */ public String getEUDDBIC() { return euddbic; } /** * Sets the value of the euddbic property. * * @param value * allowed object is * {@link String } * */ public void setEUDDBIC(String value) { this.euddbic = value; } /** * Gets the value of the euddMandateSignatureDate property. * * @return * possible object is * {@link String } * */ public String getEUDDMandateSignatureDate() { return euddMandateSignatureDate; } /** * Sets the value of the euddMandateSignatureDate property. * * @param value * allowed object is * {@link String } * */ public void setEUDDMandateSignatureDate(String value) { this.euddMandateSignatureDate = value; } /** * Gets the value of the euddMandateID property. * * @return * possible object is * {@link String } * */ public String getEUDDMandateID() { return euddMandateID; } /** * Sets the value of the euddMandateID property. * * @param value * allowed object is * {@link String } * */ public void setEUDDMandateID(String value) { this.euddMandateID = value; } /** * Gets the value of the euddMandateType property. * * @return * possible object is * {@link String } * */ public String getEUDDMandateType() { return euddMandateType; } /** * Sets the value of the euddMandateType property. * * @param value * allowed object is * {@link String } * */ public void setEUDDMandateType(String value) { this.euddMandateType = value; } /** * Gets the value of the tokenAssuranceLevel property. * * @return * possible object is * {@link String } * */ public String getTokenAssuranceLevel() { return tokenAssuranceLevel; } /** * Sets the value of the tokenAssuranceLevel property. * * @param value * allowed object is * {@link String } * */ public void setTokenAssuranceLevel(String value) { this.tokenAssuranceLevel = value; } /** * Gets the value of the dpanAccountStatus property. * * @return * possible object is * {@link String } * */ public String getDPANAccountStatus() { return dpanAccountStatus; } /** * Sets the value of the dpanAccountStatus property. * * @param value * allowed object is * {@link String } * */ public void setDPANAccountStatus(String value) { this.dpanAccountStatus = value; } }
true
04b7d99855c9175b7bc187bc913ecc18de1e1689
Java
smis394/12-04-ReShapeUp
/src/Rectangle.java
UTF-8
1,470
3.640625
4
[]
no_license
// A Rectangle object represents a rectangle defined by an origin point (bottom left corner), plus width and height. import java.lang.Math; public class Rectangle { private Point origin; private int width; private int height; public Rectangle() { origin=new Point(); width=0; height=0; } public Rectangle (Point a , Point m) { origin=a; height=m.getY()-a.getY(); width=m.getX()-a.getY(); } public Rectangle(Point a, int x, int y) { origin=a; width=a.getX()-x; height=a.getY()-y; } public Point getBottomLeft() { return origin; } public Point getTopRight() { Point b=new Point(); b.setX(origin.getX()+width); b.setY(origin.getY()+height); return b; } public int getHeight() { return height; } public int getWidth() { return width; } public double area() { return height*width; } public double diagonal() { return Math.sqrt((height*height)+(width*width)); } public int perimeter() { return (2*width)+(2*height); } public boolean isSquare() { if(width!=height) { return false; } else { return true; } } public String toString() { return "["+origin.toString()+","+getTopRight().toString()+"]"; } public void translate(int x, int y) { origin.setX(origin.getX()+x); origin.setY(origin.getY()+y); } public void scale (int dx, int dy) { width+=dx; height+=dy; } }
true
a2383cb2ff3a101c3669b1991313d1e9569f98f2
Java
shahzaib38/EcoApp
/java/imagetrack/app/View/HistoryActivity.java
UTF-8
4,228
2.0625
2
[]
no_license
package imagetrack.app.View; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.myapplication.R; import java.util.List; import imagetrack.app.HistoryDatabase.HistoryBean; import imagetrack.app.HistoryDatabase.HistoryDatabase; import imagetrack.app.HistoryDatabase.HistoryLiveDatabase; import imagetrack.app.HistoryDatabase.HistoryRecyclerViewAdapter; import io.reactivex.Observable; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; public class HistoryActivity extends AppCompatActivity { String TAG=HistoryActivity.class.getSimpleName(); CompositeDisposable compositeDisposable; private RecyclerView recyclerView; private List<HistoryBean> myHistoryArray; private HistoryRecyclerViewAdapter historyRecyclerViewAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.historyactivity); compositeDisposable =new CompositeDisposable(); recyclerView = (RecyclerView) findViewById(R.id.recyclerview); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); itemTouchHelper.attachToRecyclerView(recyclerView); recyclerView.addItemDecoration(new DividerItemDecoration(HistoryActivity.this,DividerItemDecoration.VERTICAL)); recyclerView.setLayoutManager(new LinearLayoutManager(this,RecyclerView.VERTICAL,false)); init(); } private void init() { HistoryLiveDatabase historyLiveDatabase =new HistoryLiveDatabase(this.getApplication()); Observable<List<HistoryBean>> observable= historyLiveDatabase.getHistoryList(); observable.subscribe(new io.reactivex.Observer<List<HistoryBean>>() { @Override public void onSubscribe(Disposable d) { compositeDisposable.add(d); } @Override public void onNext(List<HistoryBean> historyBeans) { myHistoryArray = historyBeans; historyRecyclerViewAdapter =new HistoryRecyclerViewAdapter(historyBeans); historyRecyclerViewAdapter.notifyDataSetChanged(); recyclerView.setAdapter(historyRecyclerViewAdapter); } @Override public void onError(Throwable e) { Log.i(TAG, "onError: "+e.getMessage()); } @Override public void onComplete() { compositeDisposable.clear(); Log.i(TAG, "onComplete: "); } }); } ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(final RecyclerView.ViewHolder viewHolder, int swipeDir) { CardView cardView= viewHolder.itemView.findViewById(R.id.cardview); cardView.setRadius(12.2f); viewHolder.itemView.setBackgroundColor(getColor(R.color.colorAccent)); int position = viewHolder.getAdapterPosition(); final HistoryBean historyBean= myHistoryArray.get(position); myHistoryArray.remove(position); new Thread(new Runnable() { @Override public void run() { HistoryDatabase historyDatabase =HistoryDatabase.getInstance(HistoryActivity.this); historyDatabase.userDao().delete(historyBean); } }).start(); historyRecyclerViewAdapter.notifyDataSetChanged(); } }; }
true
5e256b6983d45704205d2e48ae9dda459c3ab6d0
Java
scalecube/scalecube-third-party-benchmarks
/chronicle-map-benchmarks/src/main/java/io/scalecube/benchmarks/storages/chronicle/ChronicleMapStorageReadAndWriteBenchmark.java
UTF-8
558
2.140625
2
[]
no_license
package io.scalecube.benchmarks.storages.chronicle; import io.scalecube.benchmarks.BenchmarkSettings; import io.scalecube.benchmarks.storages.common.ReadAndWriteScenario; import io.scalecube.benchmarks.storages.common.StorageState; public class ChronicleMapStorageReadAndWriteBenchmark { /** * Runs benchmark with the read scenario. * * @param args args */ public static void main(String[] args) { ReadAndWriteScenario.runWith( args, (BenchmarkSettings settings) -> new StorageState(settings, ChronicleMapStorage::new)); } }
true
7bd8b9c2fc7ec8af4b3c1167e75920aa5058c195
Java
Nazul/MSC-BDA
/BankSimulator-v1/src/main/java/mx/iteso/msc/bda/banksimulator/entities/Transfer.java
UTF-8
2,734
2.296875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Mario Contreras - marioc@nazul.net. * * 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 mx.iteso.msc.bda.banksimulator.entities; import java.math.BigDecimal; /** * * @author Mario Contreras - marioc@nazul.net */ public class Transfer extends Entity { private String source; private String destination; private BigDecimal value; private TransferStatus status; private long lastModified; public Transfer(String id, String source, String destination, BigDecimal value) { super(id); this.source = source; this.destination = destination; this.value = value; this.status = TransferStatus.INITIAL; this.lastModified = System.currentTimeMillis(); } public Transfer(String id, String source, String destination, BigDecimal value, String status, long lastModified) { this(id, source, destination, value); try { this.status = TransferStatus.valueOf(status); } catch (Exception ex) { this.status = TransferStatus.ERROR; } this.lastModified = lastModified; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public BigDecimal getValue() { return value; } public void setValue(BigDecimal value) { this.value = value; } public long getLastModified() { return lastModified; } public void setLastModified(long lastModified) { this.lastModified = lastModified; } public TransferStatus getStatus() { return status; } public void setStatus(TransferStatus status) { this.status = status; this.lastModified = System.currentTimeMillis(); } @Override public String toString() { return "{ id: \"" + getId() + "\", source: \"" + source + "\", destination: \"" + destination + "\", value: " + value + ", status: \"" + status.name() + "\", lastModified: " + lastModified + " }"; } } // EOF
true