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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
119f237e6eb3c57bd3068a52a817e31d2ec4fb7d | Java | svgreensoft/sportlogger | /src/main/java/org/sversh/sportlogger/service/impl/PressureServiceImpl.java | UTF-8 | 825 | 2.125 | 2 | [] | no_license | package org.sversh.sportlogger.service.impl;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.sversh.sportlogger.model.dao.api.PressureDao;
import org.sversh.sportlogger.model.domain.Pressure;
import org.sversh.sportlogger.service.api.PressureService;
/**
*
* @author Sergey Vershinin
*
*/
@Service
public class PressureServiceImpl implements PressureService {
@Autowired
private PressureDao pressureDao;
@Transactional
public void addPressure(Short sys, Short dias) {
Pressure entity = new Pressure();
entity.setDate(new Date());
entity.setDias(dias);
entity.setSys(sys);
pressureDao.save(entity );
}
}
| true |
163bb02279f52473f51387ce9610cbc2defe06f1 | Java | retor/VKNewsClient | /vklib/src/main/java/com/retor/vklib/parsers/AttachParser.java | UTF-8 | 1,994 | 2.578125 | 3 | [] | no_license | package com.retor.vklib.parsers;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.retor.vklib.model.Attachments;
import com.retor.vklib.model.attachments.AttachModel;
import com.retor.vklib.model.attachments.Document;
import com.retor.vklib.model.attachments.Photo;
import java.lang.reflect.Type;
/**
* Created by retor on 02.09.2015.
*/
public class AttachParser implements JsonDeserializer<Attachments<AttachModel>> {
@Override
public Attachments<AttachModel> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
JsonArray array = json.getAsJsonArray();
Attachments<AttachModel> out = null;
for (JsonElement element : array) {
String type = element.getAsJsonObject().get("type").getAsString();
if (type.equals("photo")) {
JsonObject photo = element.getAsJsonObject().getAsJsonObject("photo");
Photo ph = getPhoto(photo.toString());
out = new Attachments<>((AttachModel) ph);
}
if (type.equals("doc")) {
JsonObject document = element.getAsJsonObject().getAsJsonObject("doc");
Document doc = getDoc(document.toString());
out = new Attachments<>((AttachModel) doc);
}
}
return out;
}
private Document getDoc(String input) {
Type listType = new TypeToken<Document>() {
}.getType();
return new Gson().fromJson(input, listType);
}
private Photo getPhoto(String input) {
Type listType = new TypeToken<Photo>() {
}.getType();
return new Gson().fromJson(input, listType);
}
}
| true |
7d63c288698bc60645c417908da0e493e3d3b040 | Java | supermanxkq/projects | /car/src/com/paySystem/ic/bean/buss/MerApplyRecord.java | UTF-8 | 3,093 | 2.171875 | 2 | [] | no_license | package com.paySystem.ic.bean.buss;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 商户活动信息关联bean
* @ClassName:MerPromotion
* @Description:商户活动信息关联
* @date: 2014-8-18 上午08:29:36
* @author: luckygoup
* @version: V1.0
*/
@Entity
@Table(name = "B_MerApplyRecord")
public class MerApplyRecord implements Serializable {
private static final long serialVersionUID = 1L;
/**申请记录编号*/
private Integer recordId;
/**活动信息ID*/
private Integer proid;
/**商户编号*/
private String merid;
/**状态
1:未审核
2:审核通过
3:审核不通过
9:清退
*/
private String status;
/**审核意见*/
private byte[] descr;
/**创建时间*/
private Date createTime;
/**更新时间*/
private Date updateTime;
/**操作人Id*/
private String operatorId;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public Integer getRecordId() {
return this.recordId;
}
public void setRecordId(Integer recordId) {
this.recordId = recordId;
}
@Column(name="proid", nullable=false)
public Integer getProid() {
return this.proid;
}
public void setProid(Integer proid) {
this.proid = proid;
}
@Column(name="merid", nullable=false, length=15)
public String getMerid() {
return this.merid;
}
public void setMerid(String merid) {
this.merid = merid;
}
@Lob
@Basic(fetch=FetchType.LAZY)
@Column(name = "descr",columnDefinition="BLOB")
public byte[] getDescr() {
return this.descr;
}
public void setDescr(byte[] descr) {
this.descr = descr;
}
@Temporal(TemporalType.DATE)
@Column(name="createTime", nullable=false, length=10)
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Temporal(TemporalType.DATE)
@Column(name="updateTime", nullable=false, length=10)
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Column(name="operatorId", nullable=false, length=30)
public String getOperatorId() {
return this.operatorId;
}
public void setOperatorId(String operatorId) {
this.operatorId = operatorId;
}
@Column(name="status", nullable=false, length=1)
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
}
| true |
7d56baae6b0f0297307f0c63c607d46c85b0efdc | Java | uethackathon/uethackathon2015_team11 | /main/src/team/hidro/highschoolsupport/dao/impl/ParentDaoImpl.java | UTF-8 | 2,029 | 2.3125 | 2 | [] | no_license | package team.hidro.highschoolsupport.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import org.springframework.stereotype.Repository;
import team.hidro.highschoolsupport.dao.AutoWireJdbcDaoSupport;
import team.hidro.highschoolsupport.dao.ParentDao;
import team.hidro.highschoolsupport.entities.ParentDetail;
import team.hidro.highschoolsupport.entities.StudentDetail;
@Repository
public class ParentDaoImpl extends AutoWireJdbcDaoSupport implements ParentDao {
@Override
public List<ParentDetail> getList() {
// TODO Auto-generated method stub
return null;
}
@Override
public ParentDetail getById(Integer id) {
Connection conn = null;
PreparedStatement smt = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
String sql = "Select parent.*, student.user_id, user.username from parent inner join student on parent.student_user_id = student.user_id inner join user on student.user_id = user.id where parent.user_id = ?";
smt = conn.prepareStatement(sql);
smt.setInt(1, id);
rs = smt.executeQuery();
if (rs.next()) {
int id1 = rs.getInt("parent.user_id");
String name = rs.getString("parent.name");
String email = rs.getString("parent.email");
int childId = rs.getInt("student.user_id");
String childName = rs.getString("user.username");
ParentDetail parent = new ParentDetail(id1, name, email, childId, childName);
return parent;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(smt);
DbUtils.closeQuietly(conn);
}
return null;
}
@Override
public boolean save(ParentDetail item) {
// TODO Auto-generated method stub
return false;
}
@Override
public void remove(Integer id) {
// TODO Auto-generated method stub
}
@Override
public boolean update(ParentDetail item) {
// TODO Auto-generated method stub
return false;
}
}
| true |
4e3a7fb06db18d5a2f586659dbc7cb7e522a6eab | Java | GomgomKim/mobileGov_v3 | /app_sample_support_test/src/main/java/kr/go/mobile/iff/sample/NativeActivity.java | UTF-8 | 11,361 | 2.015625 | 2 | [] | no_license | package kr.go.mobile.iff.sample;
import android.content.Intent;
import android.os.Environment;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.sds.BizAppLauncher.gov.util.CertiticationUtil;
import com.sds.mobile.servicebrokerLib.ServiceBrokerLib;
import com.sds.mobile.servicebrokerLib.event.ResponseEvent;
import com.sds.mobile.servicebrokerLib.event.ResponseListener;
import org.json.JSONException;
import java.util.ArrayList;
public class NativeActivity extends AppCompatActivity {
private RecognitionListener listener = new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle bundle) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override public void onRmsChanged(float rmsdB) {
// TODO Auto-generated method stub
}
@Override
public void onBufferReceived(byte[] bytes) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int i) {
}
@Override
public void onResults(Bundle bundle) {
String key = ""; key = SpeechRecognizer.RESULTS_RECOGNITION;
ArrayList<String> mResult = bundle.getStringArrayList(key);
final String[] rs = new String[mResult.size()];
mResult.toArray(rs);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(NativeActivity.this, rs[0], Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onPartialResults(Bundle bundle) {
}
@Override
public void onEvent(int i, Bundle bundle) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_native);
String dn = getIntent().getStringExtra("dn");
String cn = getIntent().getStringExtra("cn");
String ou = getIntent().getStringExtra("ou");
StringBuilder sb = new StringBuilder();
sb.append("이름: ").append(cn);
sb.append("\n소속기관: ").append(ou);
sb.append("\n(").append(dn).append(")");
TextView txtView = (TextView) findViewById(R.id.txtUesrInfo);
txtView.setText(sb.toString());
makeServiceBrokerList();
makeDocViewerList();
}
private void makeServiceBrokerList() {
// 서비스 브로커 기능
ServiceBrokerListAdapter adapter = new ServiceBrokerListAdapter();
adapter.addServiceVO("IF_MSERVICE", "", new ResponseListener() {
@Override
public void receive(ResponseEvent responseevent) {
int code = responseevent.getResultCode();
String message = responseevent.getResultData();
StringBuilder sb = new StringBuilder();
sb.append("Result :: ")
.append("code = ").append(code)
.append(", result = ").append(message);
Log.d("Result : ", sb.toString());
Toast.makeText(getBaseContext(), sb.toString(), Toast.LENGTH_LONG).show();
}
});
adapter.addServiceVO("IF_MSERVICE", "req=big", new ResponseListener() {
@Override
public void receive(ResponseEvent responseevent) {
int code = responseevent.getResultCode();
String message = responseevent.getResultData();
StringBuilder sb = new StringBuilder();
sb.append("Result :: ")
.append("code = ").append(code)
.append(", result = ").append(message);
Log.d("Result : ", sb.toString());
Toast.makeText(getBaseContext(), sb.toString(), Toast.LENGTH_LONG).show();
}
});
ListView listview = (ListView) findViewById(R.id.listServiceBroker) ;
listview.setVisibility(View.GONE);
listview.setAdapter(adapter) ;
}
private void makeDocViewerList() {
// 문서 뷰어 기능
// 운영 : 10.180.12.216:65535
// TB : 10.180.22.77:65535
DocViewerListAdapter adapter = new DocViewerListAdapter();
adapter.addDocViewerVO("sample.pdf", "http://10.180.22.77:65535/MOI_API/file/sample.pdf", "");
adapter.addDocViewerVO("sample1.pdf", "http://10.180.22.77:65535/MOI_API/file/sample1.pdf", "");
adapter.addDocViewerVO("sample.xlsx", "http://10.180.22.77:65535/MOI_API/file/sample.xlsx", "");
adapter.addDocViewerVO("sample.pptx", "http://10.180.22.77:65535/MOI_API/file/sample.pptx", "");
adapter.addDocViewerVO("sample.pdf", "http://10.180.12.216:65535/MOI_API/file/sample.pdf", "");
adapter.addDocViewerVO("sample.xlsx", "http://10.180.12.216:65535/MOI_API/file/sample.xlsx", "");
adapter.addDocViewerVO("sample.pptx", "http://10.180.12.216:65535/MOI_API/file/sample.pptx", "");
adapter.addDocViewerVO("sample.hwp", "http://10.180.12.216:65535/MOI_API/file/sample.hwp", "");
ListView listview = (ListView) findViewById(R.id.listDocumentViewer) ;
listview.setVisibility(View.GONE);
listview.setAdapter(adapter) ;
}
public void onClickUserInfo(View view) {
ServiceBrokerLib brokerLib = new ServiceBrokerLib(NativeActivity.this,
new ServiceBrokerLib.ServiceBrokerCB() {
@Override
public void onServiceBrokerResponse(String retMsg) {
try {
CertiticationUtil certUtil = CertiticationUtil.parse(retMsg);
final StringBuilder sb = new StringBuilder();
sb.append("====== 사용자 정보 획득 ======\n");
sb.append("nickname : ").append(certUtil.getInfo(CertiticationUtil.KEY_NICKNAME)).append("\n");
sb.append("cn : ").append(certUtil.getInfo(CertiticationUtil.KEY_CN)).append("\n");
sb.append("ou : ").append(certUtil.getInfo(CertiticationUtil.KEY_OU)).append("\n");
sb.append("ou code : ").append(certUtil.getInfo(CertiticationUtil.KEY_OU_CODE)).append("\n");
sb.append("department : ").append(certUtil.getInfo(CertiticationUtil.KEY_DEPARTMENT)).append("\n");
sb.append("department number : ").append(certUtil.getInfo(CertiticationUtil.KEY_DEPARTMENT_NUMBER)).append("\n");
sb.append("========================");
Log.d("사용자 정보", sb.toString());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(NativeActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
Intent intent = new Intent();
intent.putExtra(ServiceBrokerLib.KEY_SERVICE_ID, ServiceBrokerLib.SERVICE_GET_INFO);
CertiticationUtil cert = new CertiticationUtil();
cert.setRequestData(CertiticationUtil.KEY_NICKNAME);
cert.setRequestData(CertiticationUtil.KEY_CN);
cert.setRequestData(CertiticationUtil.KEY_OU);
cert.setRequestData(CertiticationUtil.KEY_OU_CODE);
cert.setRequestData(CertiticationUtil.KEY_DEPARTMENT);
cert.setRequestData(CertiticationUtil.KEY_DEPARTMENT_NUMBER);
intent.putExtra(ServiceBrokerLib.KEY_PARAMETER, cert.toRequestData());
brokerLib.request(intent);
}
public void onClickServiceBroker(View view) {
ListView listview = (ListView) findViewById(R.id.listServiceBroker) ;
switch (listview.getVisibility()) {
case View.VISIBLE:
listview.setVisibility(View.GONE);
break;
case View.GONE:
listview.setVisibility(View.VISIBLE);
break;
default:
break;
};
}
public void onClickDocViewer(View view) {
ListView listview = (ListView) findViewById(R.id.listDocumentViewer) ;
switch (listview.getVisibility()) {
case View.VISIBLE:
listview.setVisibility(View.GONE);
break;
case View.GONE:
listview.setVisibility(View.VISIBLE);
break;
default:
break;
};
}
public void onClickDocViewerCustom(View view) {
Toast.makeText(this, "미구현", Toast.LENGTH_SHORT).show();
/*
Intent _intent = new Intent(this, CustomDocActivity.class);
startActivity(_intent);
*/
// TODO 구현 완료 시 주석 해제
/*
String uploadPath = "http://10.180.22.77:65535/MOI_API/upload";
String srcPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmp.jpg";
String extraParam = "";
Intent intent = new Intent();
intent.putExtra("sCode", "upload");
intent.putExtra("filePath", srcPath);
intent.putExtra("parameter", "url=" + uploadPath + ";" + extraParam);
ServiceBrokerLib lib = new ServiceBrokerLib(NativeActivity.this, new ResponseListener() {
@Override
public void receive(ResponseEvent responseEvent) {
final int resultCode = responseEvent.getResultCode();
String resultData = responseEvent.getResultData();
Log.i("fileUploadSB", "File Upload API 호출 결과");
Log.d("fileUploadSB", "resultCode = " + resultCode);
Log.d("fileUploadSB", "resultData = " + resultData);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(NativeActivity.this, "resultCode = " + resultCode, Toast.LENGTH_SHORT).show();
}
});
}
});
lib.request(intent);
*/
}
public void onClickTSS(View view) {
Log.d("@@@", "음성인식 시작");
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ko-KR");
SpeechRecognizer mRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mRecognizer.setRecognitionListener(listener);
mRecognizer.startListening(i);
}
}
| true |
bee0c882cc889ef2834e0c0817ed23363b0476c2 | Java | sesepok/TP | /src/Section4.java | WINDOWS-1251 | 8,659 | 3.40625 | 3 | [] | no_license | import java.util.ArrayList;
public class Section4 extends AbstractSection
{
public static void start(int task)
{
System.out.println("===============================");
System.out.println(" 4. " + task);
switch(task)
{
case 1:
task1();
break;
case 2:
task2();
break;
case 3:
task3();
break;
case 4:
task4();
break;
case 5:
task5();
break;
case 6:
task6();
break;
case 7:
task7();
break;
case 8:
task8();
break;
case 9:
task9();
break;
case 10:
task10();
break;
}
}
public static void task1()
{
while (true)
{
int n = readInt("N (- ) ( )");
int k = readInt("k ( )");
String input = readString("");
System.out.println(": ");
System.out.println(essay(n, k, input));
if (!continuePrompt()) break;
}
}
public static String essay(int words, int lineWidth, String str)
{
String[] lines = str.split(" ");
String res = "";
int currentLine = 0;
for (String line: lines)
{
if (line.length() + currentLine <= lineWidth)
{
if (res.length() > 0) res += " ";
res += line;
currentLine += line.length();
}
else
{
res += "\n" + line;
currentLine = line.length();
}
}
return res;
}
public static void task2()
{
while (true)
{
String input = readString("");
System.out.println(": ");
printArray(split(input));
if (!continuePrompt()) break;
}
}
public static String[] split(String str)
{
ArrayList<String> res = new ArrayList<String>();
int opened = 0;
int start = 0;
int end = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == '(')
opened++;
else
opened--;
if (opened == 0)
{
end = i + 1;
res.add(str.substring(start, end));
start = end;
}
}
return res.toArray(new String[0]);
}
public static void task3()
{
while (true)
{
String input = readString("");
System.out.println("toCamelCase: " + toCamelCase(input));
System.out.println("toSnakeCase: " + toSnakeCase(input));
if (!continuePrompt()) break;
}
}
public static String toCamelCase(String str)
{
String[] words = str.split("_");
String res = words[0];
for (int i = 1; i < words.length; i++)
{
res += words[i].substring(0, 1).toUpperCase() + words[i].substring(1);
}
return res;
}
public static String toSnakeCase(String str)
{
String res = "";
int start = 0;
int end = 0;
for (int i = 0; i < str.length(); i++)
{
if (Character.isUpperCase(str.charAt(i)))
{
end = i;
if (start == 0)
res += str.substring(start, end);
else
res += "_" + Character.toLowerCase(str.charAt(start)) + str.substring(start + 1, end);
start = end;
}
}
if (start != 0) res += "_";
res += Character.toLowerCase(str.charAt(start)) + str.substring(start + 1);
return res;
}
public static void task4()
{
while (true)
{
double[] input = readDoubleArray(" ");
System.out.println(": " + overTime(input));
if (!continuePrompt()) break;
}
}
public static String overTime(double[] input)
{
double start = input[0];
double end = input[1];
double perHour = input[2];
double multiplier = input[3];
double earned = 0;
if (start < 17 && end <= 17)
earned = (end - start) * perHour;
else if (start >= 17 && end > 17)
earned = (end - start) * perHour * multiplier;
else
earned = ((17 - start) + (end - 17) * multiplier) * perHour;
int dollars = (int)earned;
int cents = (int)Math.round((earned % 1) * 100);
return "$" + dollars + "." + cents + ((cents == 0 ? "0" : ""));
}
public static void task5()
{
while (true)
{
String weight = readString(" ( . )");
String height = readString(" ( . )");
System.out.println(": " + BMI(weight, height));
if (!continuePrompt()) break;
}
}
public static String BMI(String weight, String height)
{
double w = Double.parseDouble(weight.split(" ")[0]);
if (weight.endsWith("pounds"))
w *= 0.45359237;
double h = Double.parseDouble(height.split(" ")[0]);
if (height.endsWith("inches"))
h *= 0.0254;
double index = w / (h*h);
System.out.println(index);
index = Math.round(index * 10) / 10.0;
String category = "";
if (index < 18.5)
category = "Underweight";
else if (index < 25)
category = "Normal weight";
else category = "Overweight";
return index + " " + category;
}
public static void task6()
{
while (true)
{
int input = readInt("");
System.out.println(": " + bugger(input));
if (!continuePrompt()) break;
}
}
public static int bugger(int n)
{
int count = 0;
while (n > 10)
{
int temp = n;
int product = 1;
while (temp > 0)
{
product *= (temp % 10);
temp /= 10;
}
n = product;
count++;
}
return count;
}
public static void task7()
{
while (true)
{
String input = readString("");
System.out.println(": " + toStarShorthand(input));
if (!continuePrompt()) break;
}
}
public static String toStarShorthand(String str)
{
String res = "";
char lastChar = ' ';
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == lastChar)
count++;
else
{
if (lastChar != ' ')
{
if (count > 1)
res += lastChar + "*" + count;
else
res += lastChar;
}
lastChar = str.charAt(i);
count = 1;
}
}
if (count > 1)
res += lastChar + "*" + count;
else
res += lastChar;
return res;
}
public static void task8()
{
while (true)
{
String a = readString(" ");
String b = readString(" ");
System.out.println(": " + doesRhyme(a, b));
if (!continuePrompt()) break;
}
}
public static boolean doesRhyme(String a, String b)
{
String lastA = a.substring(a.lastIndexOf(" ") + 1).toUpperCase();
String lastB = b.substring(b.lastIndexOf(" ") + 1).toUpperCase();
String vowelsA = "";
String vowelsB = "";
for (int i = 0; i < lastA.length(); i++)
if ("AEIOUY".contains(lastA.substring(i, i+1)))
vowelsA += lastA.charAt(i);
for (int i = 0; i < lastB.length(); i++)
if ("AEIOUY".contains(lastB.substring(i, i+1)))
vowelsB += lastB.charAt(i);
return vowelsA.equals(vowelsB);
}
public static void task9()
{
while (true)
{
long a = readLong(" ");
long b = readLong(" ");
System.out.println(": " + trouble(a, b));
if (!continuePrompt()) break;
}
}
public static boolean trouble(long a, long b)
{
String strA = Long.toString(a);
String strB = Long.toString(b);
int[] repeatsA = new int[10];
int[] repeatsB = new int[10];
for (int i = 0; i < strA.length(); i++)
repeatsA[Integer.parseInt(strA.substring(i, i+1))]++;
for (int i = 0; i < strB.length(); i++)
repeatsB[Integer.parseInt(strB.substring(i, i+1))]++;
for (int i = 0; i < 10; i++)
if (repeatsA[i] == 3 && repeatsB[i] == 2)
return true;
return false;
}
public static void task10()
{
while (true)
{
String str = readString("");
char c = readChar("");
System.out.println(": " + countUniqueBooks(str, c));
if (!continuePrompt()) break;
}
}
public static int countUniqueBooks(String str, char c)
{
boolean bookOpen = false;
String uniqueChars = "";
String currentBook = "";
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == c)
{
if (bookOpen)
uniqueChars += currentBook;
bookOpen = !bookOpen;
}
else
{
if (bookOpen)
if (!uniqueChars.contains(str.substring(i, i+1))
&& !currentBook.contains(str.substring(i, i+1)))
uniqueChars += str.charAt(i);
}
}
return uniqueChars.length();
}
}
| true |
c21aecdeb30fd5e1cea8bfba12e9cf41d3460f71 | Java | iantal/AndroidPermissions | /apks/obfuscation_and_logging/de_number26_android/source/com/google/android/gms/location/zzae.java | UTF-8 | 930 | 1.75 | 2 | [
"Apache-2.0"
] | permissive | package com.google.android.gms.location;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.internal.Hide;
import com.google.android.gms.internal.zzbgm;
import com.google.android.gms.internal.zzbgp;
@Hide
public final class zzae
extends zzbgm
{
public static final Parcelable.Creator<zzae> CREATOR = new zzaf();
private final String zza;
private final String zzb;
private final String zzc;
@Hide
zzae(String paramString1, String paramString2, String paramString3)
{
this.zzc = paramString1;
this.zza = paramString2;
this.zzb = paramString3;
}
public final void writeToParcel(Parcel paramParcel, int paramInt)
{
paramInt = zzbgp.zza(paramParcel);
zzbgp.zza(paramParcel, 1, this.zza, false);
zzbgp.zza(paramParcel, 2, this.zzb, false);
zzbgp.zza(paramParcel, 5, this.zzc, false);
zzbgp.zza(paramParcel, paramInt);
}
}
| true |
acfe313dd7a9b556b92f2cee84f910feed4a47ac | Java | igorsrajer123/Inzenjering-znanja-projekat2020 | /Case-Based Reasoning/src/ruleBasedReasoning/AddBolest.java | UTF-8 | 8,913 | 2.25 | 2 | [] | no_license | package ruleBasedReasoning;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import com.ugos.jiprolog.engine.JIPEngine;
import com.ugos.jiprolog.engine.JIPQuery;
import com.ugos.jiprolog.engine.JIPTerm;
import main.Main;
@SuppressWarnings("serial")
public class AddBolest extends JPanel{
@SuppressWarnings({ "rawtypes", "unchecked" })
public AddBolest() {
RbrPanel.podaciPanel4 = new JPanel();
RbrPanel.podaciPanel4.setBackground(new Color(204,153,255));
RbrPanel.podaciPanel4.setBorder(BorderFactory.createLineBorder(Color.black));
RbrPanel.podaciPanel4.setPreferredSize(new Dimension(1000,80));
RbrPanel.podaciPanel4.setMaximumSize(new Dimension(1000,80));
RbrPanel.podaciPanel4.setMinimumSize(new Dimension(1000,80));
RbrPanel.podaciPanel4.setLayout(new BoxLayout(RbrPanel.podaciPanel4, BoxLayout.X_AXIS));
RbrPanel.rbrPanel.add(RbrPanel.podaciPanel4);
JLabel simp = new JLabel(" Simptomi pacijenta: ");
simp.setPreferredSize(new Dimension(127,25));
simp.setMinimumSize(new Dimension(127,25));
simp.setMaximumSize(new Dimension(127,25));
Main.simpTxt2 = new JComboBox();
Main.simpTxt2.setBackground(new Color(204,153,255));
Main.simpTxt2.setModel(new DefaultComboBoxModel<String>(Main.simptomi2.toArray(new String[0])));
Main.simpTxt2.setPreferredSize(new Dimension(133,25));
Main.simpTxt2.setMinimumSize(new Dimension(133,25));
Main.simpTxt2.setMaximumSize(new Dimension(133,25));
JButton btnSimp = new JButton("Predložene bolesti>>");
btnSimp.setBackground(new Color(204,153,255));
btnSimp.setPreferredSize(new Dimension(153,25));
btnSimp.setMinimumSize(new Dimension(153,25));
btnSimp.setMaximumSize(new Dimension(153,25));
RbrPanel.combo = new JComboBox();
RbrPanel.combo.setBackground(new Color(204,153,255));
RbrPanel.combo.setPreferredSize(new Dimension(150,25));
RbrPanel.combo.setMinimumSize(new Dimension(150,25));
RbrPanel.combo.setMaximumSize(new Dimension(150,25));
RbrPanel.combo.setVisible(false);
RbrPanel.podaciPanel4.add(simp);
RbrPanel.podaciPanel4.add(Box.createHorizontalStrut(5));
RbrPanel.podaciPanel4.add(Main.simpTxt2);
RbrPanel.podaciPanel4.add(Box.createHorizontalStrut(2));
RbrPanel.podaciPanel4.add(btnSimp);
RbrPanel.podaciPanel4.add(Box.createHorizontalStrut(5));
RbrPanel.podaciPanel4.add(RbrPanel.combo);
//=================================================================================================================
//Dodavanje bolesti------------------------------------------------------------------------------------------------
btnSimp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(Main.polTxt2.getSelectedItem()=="" || RbrPanel.godTxt.getText().isEmpty() || Main.simpTxt2.getSelectedItem()== "") {
RbrPanel.combo.setVisible(false);
Main.bolesti2.clear();
JOptionPane.showMessageDialog(null, "Molimo Vas popunite odgovarajuća polja!");
}else {
Main.bolesti2.clear();
JIPEngine engine = new JIPEngine();
engine.consultFile("/rbr/lekovi.pl");
String s = Main.simpTxt2.getSelectedItem().toString();
String prosledjujem = "";
if(s.equals("Cough"))
prosledjujem = "cough";
else if(s.equals("Sore throat"))
prosledjujem = "sore_throat";
else if(s.equals("Difficulty breathing"))
prosledjujem = "difficulty_breathing";
else if(s.equals("Shortness of breath"))
prosledjujem = "shortness_of_breath";
else if(s.equals("Coryza"))
prosledjujem = "coryza";
else if(s.equals("Sharp chest pain"))
prosledjujem = "sharp_chest_pain";
else if(s.equals("Nasal congestion"))
prosledjujem = "nasal_congestion";
else if(s.equals("Coughing up sputum"))
prosledjujem = "coughing_up_sputum";
else if(s.equals("Headache"))
prosledjujem = "headache";
else if(s.equals("Chest tightness"))
prosledjujem = "chest_tightness";
else if(s.equals("Fever"))
prosledjujem = "fever";
JIPQuery query = engine.openSynchronousQuery("verovatnoca_za_dijagnozu(" + prosledjujem +",L)");
JIPTerm solution;
while ((solution = query.nextSolution()) != null) {
String solution1 = solution.toString();
String solution2 = solution1.replace("(", ")");
String solution3 = solution2.replace(")"," ");
String solution4 = solution3.replace("[]", "'.'");
String solution5 = solution4.replace("'.'", " ");
String[] delovi = solution5.split(",");
String prva = delovi[26];
String druga = delovi[23];
String treca = delovi[20];
String p1 = delovi[25];
String p2 = delovi[22];
String p3 = delovi[19];
String proc1 = p1.replace(" ", "");
String proc2 = p2.replace(" ", "");
String proc3 = p3.replace(" ", "");
if(prva.contains("asthma"))
prva = "Asthma";
if(prva.contains("pneumonia"))
prva = "Pneumonia";
if(prva.contains("acute_bronchitis"))
prva = "Acute bronchitis";
if(prva.contains("chronic_obstructive_pulmonary_disease"))
prva = "COPD";
if(prva.contains("pulmonary_fibrosis"))
prva = "Pulmonary fibrosis";
if(prva.contains("abscess_of_the_lung"))
prva = "Abscess of the lung";
if(prva.contains("pulmonary_hypertension"))
prva = "Pulmonary hypertension";
if(prva.contains("emphysema")) {
prva = "Emphysema";
}
if(prva.contains("pulmonary_embolism")) {
prva = "Pulmonary embolism";
}
if(prva.contains("sarcoidosis")) {
prva = "Sarcoidosis";
}
//------------------------------
if(druga.contains("asthma"))
druga = "Asthma";
if(druga.contains("pneumonia"))
druga = "Pneumonia";
if(druga.contains("acute_bronchitis"))
druga = "Acute bronchitis";
if(druga.contains("chronic_obstructive_pulmonary_disease"))
druga = "COPD";
if(druga.contains("pulmonary_fibrosis"))
druga = "Pulmonary fibrosis";
if(druga.contains("abscess_of_the_lung"))
druga = "Abscess of the lung";
if(druga.contains("pulmonary_hypertension"))
druga = "Pulmonary hypertension";
if(druga.contains("emphysema")) {
druga = "Emphysema";
}
if(druga.contains("pulmonary_embolism")) {
druga = "Pulmonary embolism";
}
if(druga.contains("sarcoidosis")) {
druga = "Sarcoidosis";
}
//--------------------------------------------
if(treca.contains("asthma"))
treca = "Asthma";
if(treca.contains("pneumonia"))
treca = "Pneumonia";
if(treca.contains("acute_bronchitis"))
treca = "Acute bronchitis";
if(treca.contains("chronic_obstructive_pulmonary_disease"))
treca = "COPD";
if(treca.contains("pulmonary_fibrosis"))
treca = "Pulmonary fibrosis";
if(treca.contains("abscess_of_the_lung"))
treca = "Abscess of the lung";
if(treca.contains("pulmonary_hypertension"))
treca = "Pulmonary hypertension";
if(treca.contains("emphysema")) {
treca = "Emphysema";
}
if(treca.contains("pulmonary_embolism")) {
treca = "Pulmonary embolism";
}
if(treca.contains("sarcoidosis")) {
treca = "Sarcoidosis";
}
Main.bolesti2.add(prva);
Main.bolesti2.add(druga);
Main.bolesti2.add(treca);
int p1I = Integer.parseInt(proc1);
int p2I = Integer.parseInt(proc2);
int p3I = Integer.parseInt(proc3);
if(p3I < 3)
Main.bolesti2.remove(treca);
if(p2I <3)
Main.bolesti2.remove(druga);
if(p1I < 3)
Main.bolesti2.remove(prva);
}
RbrPanel.combo.setModel(new DefaultComboBoxModel<String>(Main.bolesti2.toArray(new String[0])));
RbrPanel.combo.setVisible(true);
}
}
});
}
}
| true |
cce3065636ad4c8f47f1b14eeb9fbdb50a273817 | Java | LCPKU/leetcode | /LongestPalindrome409.java | GB18030 | 1,007 | 3.703125 | 4 | [] | no_license | package leetcode;
import java.util.HashMap;
/*
* ұhashmap
* оڸ
* ȻҰٶһ
* ʹASCIIķʽ
* Ϊż2ϣ2
* ǰСԭ
* ˵һ
* ֱӼ1
*/
public class LongestPalindrome409 {
public int longestPalindrome(String s) {
int [] str = new int[123];
for(int i=0;i<s.length();i++)
{
str[s.charAt(i)]++;
}
int sum=0;
for(int i=65;i<=122;i++)
{
sum=sum+str[i]/2;
}
sum=sum*2;
if(sum<s.length())
{
sum=sum+1;
}
return sum;
}
public static void main(String[] args) {
LongestPalindrome409 l=new LongestPalindrome409();
String s="zeusnilemacaronimaisanitratetartinasiaminoracamelinsuez";
int w=l.longestPalindrome(s);
System.out.println(w);
}
}
| true |
58722a5644f6b492ff5cee4b8049ba6b3143c1d2 | Java | streamblocks/streamblocks-graalvm | /language/src/main/java/ch/epfl/vlsc/truffle/cal/nodes/contorlflow/StmtFunctionBodyNode.java | UTF-8 | 1,650 | 2.40625 | 2 | [
"UPL-1.0"
] | permissive | package ch.epfl.vlsc.truffle.cal.nodes.contorlflow;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.NodeInfo;
import com.oracle.truffle.api.profiles.BranchProfile;
import ch.epfl.vlsc.truffle.cal.nodes.CALExpressionNode;
import ch.epfl.vlsc.truffle.cal.nodes.CALStatementNode;
import ch.epfl.vlsc.truffle.cal.runtime.CALNull;
@NodeInfo(shortName = "body")
public final class StmtFunctionBodyNode extends CALExpressionNode {
/**
* The body of the function.
*/
@Node.Child
private CALStatementNode bodyNode;
private final BranchProfile exceptionTaken = BranchProfile.create();
private final BranchProfile nullTaken = BranchProfile.create();
public StmtFunctionBodyNode(CALStatementNode bodyNode) {
this.bodyNode = bodyNode;
addRootTag();
}
@Override
public Object executeGeneric(VirtualFrame frame) {
try {
/* Execute the function body. */
bodyNode.executeVoid(frame);
} catch (ReturnException ex) {
/*
* In the interpreter, record profiling information that the function has an explicit
* return.
*/
exceptionTaken.enter();
/* The exception transports the actual return value. */
return ex.getResult();
}
/*
* In the interpreter, record profiling information that the function ends without an
* explicit return.
*/
nullTaken.enter();
/* Return the default null value. */
return CALNull.SINGLETON;
}
}
| true |
a71f173782c3e7c02ee25b7416656aa072625e75 | Java | Hereticked/Old-Code | /Java/CSC 1500/Semester1/Addition2.java | UTF-8 | 558 | 3.96875 | 4 | [] | no_license | // James Poulette CSC 1500 03
// Reads two integers and prints their sum.
import java.io.*;
class Addition2 {
public static void main (String[] args) throws IOException {
BufferedReader stdin = new BufferedReader
(new InputStreamReader(System.in));
int num1, num2;
System.out.println ("Enter a number:");
num1 = Integer.parseInt (stdin.readLine());
System.out.println ("Enter another number:");
num2 = Integer.parseInt (stdin.readLine());
System.out.println ("The sum is " + (num1 + num2));
} // method main
} // class Addition2
| true |
7016326231f9e860b7853824aaab3b9d79314715 | Java | rcr-81/UdL | /Universitat_Lleida_Alfresco_AMP/src/java/com/smile/webscripts/audit/AuditUdl.java | UTF-8 | 1,222 | 2.15625 | 2 | [] | no_license | package com.smile.webscripts.audit;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.repo.audit.AuditComponent;
import org.alfresco.repo.audit.model.AuditApplication;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.smile.webscripts.helper.ConstantsUdL;
public class AuditUdl implements ConstantsUdL{
private static final Log logger = LogFactory.getLog(AuditUdl.class);
public static void auditRecord(AuditComponent auditComponent, String username, String nodeRef,String action, String type, String site){
Map<String, Serializable> auditMap = new HashMap<String, Serializable>();
auditMap.put(AuditApplication.buildPath("/userName"), username);
auditMap.put(AuditApplication.buildPath("/action"), action);
auditMap.put(AuditApplication.buildPath("/noderef"), nodeRef);
auditMap.put(AuditApplication.buildPath("/type"), type);
auditMap.put(AuditApplication.buildPath("/site"), site);
auditComponent.recordAuditValues(AUDIT_APLICATION_PATH, auditMap);
if(logger.isDebugEnabled()){
logger.debug("Audit source = \n "+AUDIT_APLICATION_PATH);
logger.debug("Audit values = \n "+auditMap);
}
}
}
| true |
ac6f42e62ebc88af41f57edd57099645153fd596 | Java | JamesJi9277/Algorithm | /medium/535. Encode and Decode TinyURL .java | UTF-8 | 650 | 3.015625 | 3 | [] | no_license | class Codec {
List<String> urls = new ArrayList<String>();
Map<Integer, String> map = new HashMap<>();
int i=0;
public String encode(String longUrl) {
map.put(i,longUrl);
return "http://tinyurl.com/"+i++;
}
public String decode(String shortUrl) {
return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
}
}
public class Codec {
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
return longUrl;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return shortUrl;
}
}
| true |
b87a2971f12a7a30f7529330190f3d31db908e64 | Java | lfeniri/Spellmonger3 | /src/main/java/edu/insightr/spellmonger/VaultOverclocking.java | UTF-8 | 334 | 2.25 | 2 | [
"MIT"
] | permissive | package edu.insightr.spellmonger;
public class VaultOverclocking extends Card {
public VaultOverclocking() {
energyCost = 4;
}
@Override
public String toString() {
return "Vault Overclocking" + super.toString();
}
@Override
public String getName() {
return "VaultOver";
}
}
| true |
191d9116a8f39845725e77001dd7a6440e11c204 | Java | fairmonk/webdriver | /src/test/java/com/selenium/webdriver/user/interactions/SampleExercises.java | UTF-8 | 3,289 | 2.734375 | 3 | [] | no_license | package com.selenium.webdriver.user.interactions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.seleniumsimplified.webdriver.manager.Driver;
public class SampleExercises {
private static WebDriver driver;
@BeforeClass
public static void setupDriver()
{
driver = Driver.get("http://compendiumdev.co.uk/selenium/gui_user_interactions.html");
}
@Before
public void resetPage()
{
driver.navigate().refresh();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("canvas")));
wait.until(ExpectedConditions.elementToBeClickable(By.id("keyeventslist")));
//user interactions can be intermittent
//so click on the html to force focus to the page
driver.findElement(By.tagName("html")).click();
}
@Test
public void moveDrag1ToDrop1()
{
WebElement element1 = driver.findElement(By.cssSelector("#draggable1"));
WebElement element2 = driver.findElement(By.cssSelector("#droppable1"));
Action clickAndDrag = new Actions(driver).
dragAndDrop(element1, element2).
build();
clickAndDrag.perform();
String elText = driver.findElement(By.cssSelector("#droppable1")).getText();
String textOnElement2 = "Dropped!";
assertTrue("Dragging of draggable1 failed onto droppable1", elText.equals(textOnElement2));
}
@Test
public void dragAndDropDraggable2ToDroppable1()
{
WebElement element1 = driver.findElement(By.cssSelector("#draggable2"));
WebElement element2 = driver.findElement(By.cssSelector("#droppable1"));
Action clickAndDrag = new Actions(driver).
dragAndDrop(element1, element2).
build();
clickAndDrag.perform();
String elText = driver.findElement(By.cssSelector("#droppable1")).getText();
String textOnElement2 = "Get Off Me!";
assertTrue("Dragging of draggable2 failed onto droppable1", elText.equals(textOnElement2));
}
@Test
public void controlAndBwaHaHa()
{
/* when we issue a control + B draggable1 says "Bwa ha ha" */
WebElement draggable1 = driver.findElement(By.id("draggable1"));
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys("b").keyUp(Keys.CONTROL).perform();
assertEquals("Bwa! Ha! Ha!", draggable1.getText());
}
@Test
public void drawSomethingOnCanvas()
{
WebElement canvas = driver.findElement(By.id("canvas"));
WebElement eventList = driver.findElement(By.id("keyeventslist"));
int eventCount = eventList.findElements(By.tagName("li")).size();
new Actions(driver).
// click doesn't do it, need to click and hold
//click (canvas)
clickAndHold(canvas).
moveByOffset(10, 10).
release().
perform();
assertTrue("we should have had some draw events", eventCount < eventList.findElements(By.tagName("li")).size());
}
}
| true |
5d014647407386896f379b6f8e9b6a2a295da793 | Java | surban1974/neohort | /2018/neohort-base/src/main/java/neohort/log/log.java | UTF-8 | 2,260 | 2.1875 | 2 | [] | no_license | /**
* Creation date: (14/12/2005)
* @author: Svyatoslav Urbanovych surban@bigmir.net svyatoslav.urbanovych@gmail.com
*/
/********************************************************************************
*
* Copyright (C) 2005 Svyatoslav Urbanovych
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*********************************************************************************/
package neohort.log;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
private static final long serialVersionUID = -1L;
private static log_init logInit;
private static log_generator logG;
public void init() throws ServletException, UnavailableException {
logInit = new log_init();
logInit.init();
logG = new log_generator(logInit);
}
public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, UnavailableException {
}
private static void service_mountLog(){
logInit = new log_init();
logInit.init();
logG = new log_generator(logInit);
}
public static synchronized void writeLog(String msg, String level) {
try{
if(logG==null) service_mountLog();
logG.writeLog(msg,level);
}catch(Exception e){}
}
public static synchronized void writeLog(HttpServletRequest _request, String msg, String level){
try{
logG.writeLog(_request,msg,level);
}catch(Exception e){}
}
public static log_generator getLogG() {
return logG;
}
public static log_init getLogInit() {
return logInit;
}
}
| true |
df0d0d7a0822da8a3494f87a8250ffb029df2b05 | Java | taregbalola/spring0commerce | /ShopmeWebParent/ShopmeFrontEnd/src/main/resources/templates/CustomerService.java | UTF-8 | 670 | 2.15625 | 2 | [] | no_license | package com.shopme.customer;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shopme.common.entity.Country;
import com.shopme.common.entity.Customer;
import com.shopme.setting.CountryRepository;
@Service
public class CustomerService {
@Autowired private CountryRepository countryRepo;
@Autowired private CustomerRepository customerRepo;
public List<Country> listAllCountries() {
return countryRepo.findAllByOrderByNameAsc();
}
public boolean isEmailUnique(String email) {
Customer customer = customerRepo.findByEmail(email);
return customer == null;
}
}
| true |
a180d6a8146086d1dfc8fc8491d5f1e3b2a75d67 | Java | iantal/AndroidPermissions | /apks/comparison_qark/de.number26.android/classes_dex2jar/android/support/v4/media/session/e.java | UTF-8 | 1,797 | 1.773438 | 2 | [
"Apache-2.0"
] | permissive | package android.support.v4.media.session;
import android.media.session.PlaybackState;
import android.media.session.PlaybackState.CustomAction;
import android.os.Bundle;
import java.util.List;
class e
{
public static int a(Object paramObject)
{
return ((PlaybackState)paramObject).getState();
}
public static long b(Object paramObject)
{
return ((PlaybackState)paramObject).getPosition();
}
public static long c(Object paramObject)
{
return ((PlaybackState)paramObject).getBufferedPosition();
}
public static float d(Object paramObject)
{
return ((PlaybackState)paramObject).getPlaybackSpeed();
}
public static long e(Object paramObject)
{
return ((PlaybackState)paramObject).getActions();
}
public static CharSequence f(Object paramObject)
{
return ((PlaybackState)paramObject).getErrorMessage();
}
public static long g(Object paramObject)
{
return ((PlaybackState)paramObject).getLastPositionUpdateTime();
}
public static List<Object> h(Object paramObject)
{
return ((PlaybackState)paramObject).getCustomActions();
}
public static long i(Object paramObject)
{
return ((PlaybackState)paramObject).getActiveQueueItemId();
}
static final class a
{
public static String a(Object paramObject)
{
return ((PlaybackState.CustomAction)paramObject).getAction();
}
public static CharSequence b(Object paramObject)
{
return ((PlaybackState.CustomAction)paramObject).getName();
}
public static int c(Object paramObject)
{
return ((PlaybackState.CustomAction)paramObject).getIcon();
}
public static Bundle d(Object paramObject)
{
return ((PlaybackState.CustomAction)paramObject).getExtras();
}
}
}
| true |
60767a71c4483234e32922e8ffa7a0cb53a17911 | Java | cainiao22/qddata | /src/main/java/com/qding/bigdata/ds/controller/BuriedEventPositionMetaController.java | UTF-8 | 6,235 | 1.929688 | 2 | [] | no_license | package com.qding.bigdata.ds.controller;
import com.github.pagehelper.PageInfo;
import com.qding.bigdata.ds.common.Result;
import com.qding.bigdata.ds.model.DsMaidianEventPageRelationship;
import com.qding.bigdata.ds.model.DsMaidianParam;
import com.qding.bigdata.ds.model.Product;
import com.qding.bigdata.ds.service.MaidianEventPageRelationService;
import com.qding.bigdata.ds.service.ProductService;
import com.qding.bigdata.ds.util.DateUtil;
import com.qding.bigdata.ds.util.ExportExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author yanpf
* @date 2019/3/20 17:18
* @description
*/
@RequestMapping("buriedEventPosition")
@RestController
public class BuriedEventPositionMetaController extends BasicController {
@Autowired
MaidianEventPageRelationService relationService;
@Autowired
ProductService productService;
@RequestMapping("query")
public PageInfo<DsMaidianEventPageRelationship> query(DsMaidianEventPageRelationship param, Integer start, Integer length){
PageInfo<DsMaidianEventPageRelationship> pageInfo = relationService.list(param, start/length+1, length);
Map<Long, String> productMap = productService.getAll().stream().collect(Collectors.toMap(item -> item.getId(), item -> item.getName()));
pageInfo.getList().forEach(item -> item.setProductName(productMap.get(item.getProductId())));
return pageInfo;
}
@RequestMapping("saveOrUpdate")
public Result saveOrUpdate(DsMaidianEventPageRelationship param){
if(param.getId() == null){
relationService.add(param);
}else{
relationService.update(param);
}
return Result.success();
}
@RequestMapping("export")
public void export(DsMaidianEventPageRelationship param, HttpServletResponse response) throws Exception {
Map<Long, String> productMap = productService.getAll().stream().collect(Collectors.toMap(item -> item.getId(), item -> item.getName()));
response.setContentType("application/csv;charset=utf-8");
response.setHeader("Content-disposition",
"attachment;filename=" + DateUtil.formatDateToFullString(new Date()) + ".xlsx");
OutputStream os = response.getOutputStream();
PageInfo<DsMaidianEventPageRelationship> eventPageInfo = relationService.list(param, null, null);
eventPageInfo.getList().forEach(item -> item.setProductName(productMap.get(item.getProductId())));
List<Object[]> resultList = new ArrayList<>();
for (DsMaidianEventPageRelationship maidianEvent : eventPageInfo.getList()) {
Object[] item = new Object[11];
item[0] = maidianEvent.getId();
item[1] = maidianEvent.getEventCode();
item[2] = maidianEvent.getEventName();
item[3] = maidianEvent.getProductName();
item[4] = maidianEvent.getPageCode();
item[5] = maidianEvent.getPageName();
item[6] = maidianEvent.getAreaCode();
item[7] = maidianEvent.getAreaName();
item[8] = maidianEvent.getPositionId();
item[9] = maidianEvent.getPositionName();
item[10] = maidianEvent.getStatus();
resultList.add(item);
}
OutputStreamWriter writer = new OutputStreamWriter(os,"gbk");
SXSSFWorkbook workbook = ExportExcelUtil.writeNewExcel("sheet1", resultList);
workbook.write(os);
writer.flush();
os.flush();
writer.close();
os.close();
}
@RequestMapping("import")
public Result buriedEventPositionImport(MultipartFile excel) throws IOException, InvalidFormatException {
Workbook wookbook = WorkbookFactory.create(excel.getInputStream());
Sheet sheet = wookbook.getSheetAt(0);
List<DsMaidianEventPageRelationship> maidianParamList = new ArrayList<>();
int totalRowNum = sheet.getLastRowNum();
List<Product> productList = productService.getAll();
for(int i = 1 ; i <= totalRowNum ; i++)
{
DsMaidianEventPageRelationship param = new DsMaidianEventPageRelationship();
//获得第i行对象
Row row = sheet.getRow(i);
param.setEventCode(ExportExcelUtil.getCellValue(row.getCell(0)));
param.setEventName(ExportExcelUtil.getCellValue(row.getCell(1)));
for(int j=0; j<productList.size(); j++){
if(productList.get(j).getName().equals(ExportExcelUtil.getCellValue(row.getCell(2)))){
param.setProductId(productList.get(j).getId());
break;
}
}
param.setPageCode(ExportExcelUtil.getCellValue(row.getCell(3)));
param.setPageName(ExportExcelUtil.getCellValue(row.getCell(4)));
param.setAreaCode(ExportExcelUtil.getCellValue(row.getCell(5)));
param.setAreaName(ExportExcelUtil.getCellValue(row.getCell(6)));
param.setPositionId(ExportExcelUtil.getCellValue(row.getCell(7)));
param.setPositionName(ExportExcelUtil.getCellValue(row.getCell(8)));
param.setStatus(new Double(ExportExcelUtil.getCellValue(row.getCell(9))).intValue());
maidianParamList.add(param);
}
try {
relationService.batchInsert(maidianParamList);
}catch (Exception e){
e.printStackTrace();
return Result.failed(500, e.getMessage());
}
return Result.success();
}
}
| true |
206bed87b250ec3dce067c1fce29b1e78b658337 | Java | OMAleks/java-core-grom | /src/Lesson_02r/VariablesExample.java | UTF-8 | 3,518 | 3.984375 | 4 | [] | no_license | package Lesson_02r;
public class VariablesExample {
//Переменные - это некий контейнер, внутри которого содержатся данные.
//Переменные - это ячеки памяти, в которых содержатся данные.
//Тип переменных = классификация переменных по содержанию и количеству данных.
//Указывая копьютеру тип переменной, мы одновременно говорим ему о том, какой объем паяти
//нужно зарезервировать под эту переменную.
//Синтаксис: type - variable name - value
//!!Заглавная буква у переменной есть или нет имеет значение!!!!!!!! Заглавная буква - уже другая переменная!
public static void main(String[] args) {
byte a = 100; //Может содержать целые числа от -128 до +127 - 1 байт
short b = 20000; //Целые -32768 до 32767 - 2 байта
int c = 444; //Целые - 2 147 483 648 до 2 147 483 647 - 4 байта
long d = 3333333; //Целые -9 223 372 036 854 775 808 до 9 223....807 - 8 байт
double e = 3.54545; // Дробные - 8 байт (любое количество знаков после запятой)
float el = 3434.33333f; // В конце необходимо добавлять букву f !!
// Дробные - 4 байта (любое количество знаков после запятой)
char ch = 'd'; //Одна буква
char ch1 = '\u0001'; //может обозначаться через код буквы
boolean trueBul = true; //Логический тип. Может содержать только два значения: Правда и
boolean falseBul = false; //Ложь (верно-не верно).
//Негласный хороший стиль написания:
//Все переменные должны начинаться с маленькой буквы!! Второе слово (третье и так далее)
//пишем без пробела, но с Большой буквы: примерМногословнойПеременнойРусскимЯзыком.
//Введение переменной происходит в два этапа:
//1 declaration - Объявление переменной (определяе тип, имя, резервирует место в памяти)
int test;
//2 initialization - присвоение переменной определенного значение
test = 1500;
// 1 и 2 этапы можно писать как в две, так и в одну строку:
int test1 = 1500;
// Переменную можно перезаписывать (присваевать ей новое значение) любое количество раз:
test1 = 1200;
test1 = 12000;
test1 = 1;
int el1 = 3;
int el2 = 8;
if (el1 < el2 && el1 != 3) {
System.out.println("верно");
}
}
}
| true |
500a87463d322a290336c0961840bff78d38ef8c | Java | history-purge/LeaveHomeSafe-source-code | /com/facebook/imagepipeline/nativecode/NativeJpegTranscoder.java | UTF-8 | 6,985 | 1.648438 | 2 | [] | no_license | package com.facebook.imagepipeline.nativecode;
import e.e.e.d.b;
import e.e.e.d.d;
import e.e.k.b;
import e.e.k.c;
import e.e.l.e.e;
import e.e.l.e.f;
import e.e.l.k.d;
import e.e.l.q.a;
import e.e.l.q.b;
import e.e.l.q.c;
import e.e.l.q.e;
import java.io.InputStream;
import java.io.OutputStream;
@d
public class NativeJpegTranscoder implements c {
private boolean a;
private int b;
private boolean c;
static {
d.a();
}
public NativeJpegTranscoder(boolean paramBoolean1, int paramInt, boolean paramBoolean2) {
this.a = paramBoolean1;
this.b = paramInt;
this.c = paramBoolean2;
}
public static void a(InputStream paramInputStream, OutputStream paramOutputStream, int paramInt1, int paramInt2, int paramInt3) {
// Byte code:
// 0: invokestatic a : ()V
// 3: iconst_0
// 4: istore #6
// 6: iload_3
// 7: iconst_1
// 8: if_icmplt -> 17
// 11: iconst_1
// 12: istore #5
// 14: goto -> 20
// 17: iconst_0
// 18: istore #5
// 20: iload #5
// 22: invokestatic a : (Z)V
// 25: iload_3
// 26: bipush #16
// 28: if_icmpgt -> 37
// 31: iconst_1
// 32: istore #5
// 34: goto -> 40
// 37: iconst_0
// 38: istore #5
// 40: iload #5
// 42: invokestatic a : (Z)V
// 45: iload #4
// 47: iflt -> 56
// 50: iconst_1
// 51: istore #5
// 53: goto -> 59
// 56: iconst_0
// 57: istore #5
// 59: iload #5
// 61: invokestatic a : (Z)V
// 64: iload #4
// 66: bipush #100
// 68: if_icmpgt -> 77
// 71: iconst_1
// 72: istore #5
// 74: goto -> 80
// 77: iconst_0
// 78: istore #5
// 80: iload #5
// 82: invokestatic a : (Z)V
// 85: iload_2
// 86: invokestatic d : (I)Z
// 89: invokestatic a : (Z)V
// 92: iload_3
// 93: bipush #8
// 95: if_icmpne -> 106
// 98: iload #6
// 100: istore #5
// 102: iload_2
// 103: ifeq -> 109
// 106: iconst_1
// 107: istore #5
// 109: iload #5
// 111: ldc 'no transformation requested'
// 113: invokestatic a : (ZLjava/lang/Object;)V
// 116: aload_0
// 117: invokestatic a : (Ljava/lang/Object;)Ljava/lang/Object;
// 120: pop
// 121: aload_0
// 122: checkcast java/io/InputStream
// 125: astore_0
// 126: aload_1
// 127: invokestatic a : (Ljava/lang/Object;)Ljava/lang/Object;
// 130: pop
// 131: aload_0
// 132: aload_1
// 133: checkcast java/io/OutputStream
// 136: iload_2
// 137: iload_3
// 138: iload #4
// 140: invokestatic nativeTranscodeJpeg : (Ljava/io/InputStream;Ljava/io/OutputStream;III)V
// 143: return
}
public static void b(InputStream paramInputStream, OutputStream paramOutputStream, int paramInt1, int paramInt2, int paramInt3) {
// Byte code:
// 0: invokestatic a : ()V
// 3: iconst_0
// 4: istore #6
// 6: iload_3
// 7: iconst_1
// 8: if_icmplt -> 17
// 11: iconst_1
// 12: istore #5
// 14: goto -> 20
// 17: iconst_0
// 18: istore #5
// 20: iload #5
// 22: invokestatic a : (Z)V
// 25: iload_3
// 26: bipush #16
// 28: if_icmpgt -> 37
// 31: iconst_1
// 32: istore #5
// 34: goto -> 40
// 37: iconst_0
// 38: istore #5
// 40: iload #5
// 42: invokestatic a : (Z)V
// 45: iload #4
// 47: iflt -> 56
// 50: iconst_1
// 51: istore #5
// 53: goto -> 59
// 56: iconst_0
// 57: istore #5
// 59: iload #5
// 61: invokestatic a : (Z)V
// 64: iload #4
// 66: bipush #100
// 68: if_icmpgt -> 77
// 71: iconst_1
// 72: istore #5
// 74: goto -> 80
// 77: iconst_0
// 78: istore #5
// 80: iload #5
// 82: invokestatic a : (Z)V
// 85: iload_2
// 86: invokestatic c : (I)Z
// 89: invokestatic a : (Z)V
// 92: iload_3
// 93: bipush #8
// 95: if_icmpne -> 107
// 98: iload #6
// 100: istore #5
// 102: iload_2
// 103: iconst_1
// 104: if_icmpeq -> 110
// 107: iconst_1
// 108: istore #5
// 110: iload #5
// 112: ldc 'no transformation requested'
// 114: invokestatic a : (ZLjava/lang/Object;)V
// 117: aload_0
// 118: invokestatic a : (Ljava/lang/Object;)Ljava/lang/Object;
// 121: pop
// 122: aload_0
// 123: checkcast java/io/InputStream
// 126: astore_0
// 127: aload_1
// 128: invokestatic a : (Ljava/lang/Object;)Ljava/lang/Object;
// 131: pop
// 132: aload_0
// 133: aload_1
// 134: checkcast java/io/OutputStream
// 137: iload_2
// 138: iload_3
// 139: iload #4
// 141: invokestatic nativeTranscodeJpegWithExifOrientation : (Ljava/io/InputStream;Ljava/io/OutputStream;III)V
// 144: return
}
@d
private static native void nativeTranscodeJpeg(InputStream paramInputStream, OutputStream paramOutputStream, int paramInt1, int paramInt2, int paramInt3);
@d
private static native void nativeTranscodeJpegWithExifOrientation(InputStream paramInputStream, OutputStream paramOutputStream, int paramInt1, int paramInt2, int paramInt3);
public b a(d paramd, OutputStream paramOutputStream, f paramf, e parame, c paramc, Integer paramInteger) {
InputStream inputStream;
Integer integer = paramInteger;
if (paramInteger == null)
integer = Integer.valueOf(85);
f f1 = paramf;
if (paramf == null)
f1 = f.e();
int i = a.a(f1, parame, paramd, this.b);
f f2 = null;
paramf = f2;
try {
int j = e.a(f1, parame, paramd, this.a);
paramf = f2;
int k = e.a(i);
paramf = f2;
if (this.c)
j = k;
paramf = f2;
InputStream inputStream1 = paramd.u();
inputStream = inputStream1;
if (e.a.contains(Integer.valueOf(paramd.e()))) {
inputStream = inputStream1;
b(inputStream1, paramOutputStream, e.a(f1, paramd), j, integer.intValue());
} else {
inputStream = inputStream1;
a(inputStream1, paramOutputStream, e.b(f1, paramd), j, integer.intValue());
}
b.a(inputStream1);
j = 1;
return new b(j);
} finally {
b.a(inputStream);
}
}
public String a() {
return "NativeJpegTranscoder";
}
public boolean a(c paramc) {
return (paramc == b.a);
}
public boolean a(d paramd, f paramf, e parame) {
f f1 = paramf;
if (paramf == null)
f1 = f.e();
return (e.a(f1, parame, paramd, this.a) < 8);
}
}
/* Location: /home/yc/Downloads/LeaveHomeSafe.jar!/com/facebook/imagepipeline/nativecode/NativeJpegTranscoder.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ | true |
43098df9bd1502dbb3ea43d2cd66d238db7467a2 | Java | juneyoung-jo/Project_CODARY | /codary_backend/src/main/java/com/spring/web/dao/SearchPostDao.java | UTF-8 | 1,014 | 1.71875 | 2 | [] | no_license | package com.spring.web.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import com.spring.web.dto.BlogPostDto;
import com.spring.web.dto.HashtagDto;
import com.spring.web.dto.TestDto;
@Mapper
public interface SearchPostDao {
// public List<BlogPostDto> searchPost(SearchParam param) throws SQLException;
List<BlogPostDto> searchTitle() throws SQLException;
List<BlogPostDto> searchHash(String keyword) throws SQLException;
List<Integer> searchByHash(Map<String, Object> map) throws SQLException;
List<Integer> getCommentInfo(int blogContentsId) throws SQLException;
Map<String, String> getUserProfile(String blogId) throws SQLException;
List<BlogPostDto> getPostInfo(List<Integer> list) throws SQLException;
List<HashtagDto> getHashtagOfPost(int blogContentsId) throws SQLException;
List<TestDto> getHashtagOfPostNew(int blogContentsId) throws SQLException;
// List<Map<String, Object>> searchByTitle() throws SQLException;
}
| true |
c6aea5a774ec23f72a3c6c4c333b6ea036597249 | Java | fifadxj/myleetcode | /leetcode/editor/cn/[414]第三大的数.java | UTF-8 | 1,393 | 3.671875 | 4 | [] | no_license | //给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。
//
//
//
// 示例 1:
//
//
//输入:[3, 2, 1]
//输出:1
//解释:第三大的数是 1 。
//
// 示例 2:
//
//
//输入:[1, 2]
//输出:2
//解释:第三大的数不存在, 所以返回最大的数 2 。
//
//
// 示例 3:
//
//
//输入:[2, 2, 3, 1]
//输出:1
//解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
//此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。
//
//
//
// 提示:
//
//
// 1 <= nums.length <= 104
// -231 <= nums[i] <= 231 - 1
//
//
//
//
// 进阶:你能设计一个时间复杂度 O(n) 的解决方案吗?
// Related Topics 数组 排序
// 👍 231 👎 0
import java.util.Arrays;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int thirdMax(int[] nums) {
Arrays.sort(nums);
int sort = 0;
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] != nums[i + 1]) {
sort++;
}
if (sort == 2) {
return nums[i];
}
}
return nums[nums.length - 1];
}
}
//leetcode submit region end(Prohibit modification and deletion)
| true |
74027b3894f5f8548e1a658cfc3f564f4a16e801 | Java | Lewis614/LeetCode_Practice | /src/easy107/binaryTreeLevelOrderTraversalII/Solution.java | UTF-8 | 1,386 | 3.40625 | 3 | [] | no_license | package easy107.binaryTreeLevelOrderTraversalII;
//https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*
* 20141118 17:00
*/
import java.util.*;
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> reservedList = new ArrayList<List<Integer>>();
if (root == null) return reservedList;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> list = new ArrayList<List<Integer>>();
queue.add(root);
while (!queue.isEmpty()) {
ArrayList<TreeNode> innerList = new ArrayList<TreeNode>();
ArrayList<Integer> innerListValue = new ArrayList<Integer>();
while(!queue.isEmpty()) {
TreeNode node = queue.remove();
innerList.add(node);
innerListValue.add(node.val);
}
list.add(innerListValue);
for(int i = 0 ; i < innerList.size(); i++) {
TreeNode node = innerList.get(i);
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
for(int i = 0 ; i < list.size(); i++) {
reservedList.add(list.get(list.size()-1-i));
}
return reservedList;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
} | true |
24bf6b4b730ae3cce6b620b1471459ace3400284 | Java | xiuer121/creditcardm | /src/carss/action/admin/repayment/ClientAddAction.java | GB18030 | 7,444 | 1.695313 | 2 | [] | no_license | /**
* @
*/
package carss.action.admin.repayment;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import carss.constant.CardConstant;
import carss.constant.CreditRecConstant;
import carss.constant.DealInfoConstant;
import carss.po.BankCardInfo;
import carss.po.CardInfo;
import carss.po.CreditRecords;
import carss.po.DealInfo;
import carss.po.PostInfo;
import carss.po.auth.Admin;
import carss.service.BankCardInfoService;
import carss.service.CardInfoService;
import carss.service.CreditRecordsService;
import carss.service.DealInfoService;
import carss.service.PostInfoService;
import carss.service.perm.AdminService;
import carss.vo.LoginAdmin;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype")
@Results({ @Result(type = "redirectAction", location = "repayment-list"),
@Result(name = "repayment", location = "repayment-add.jsp"),
@Result(name = "cash", location = "cash-add.jsp") })
public class ClientAddAction extends ActionSupport {
private static final long serialVersionUID = 1L;
@Resource
private CardInfoService cardInfoService;
@Resource
private AdminService adminService;
@Resource
private DealInfoService dealInfoService;
@Resource
private BankCardInfoService bankCardInfoService;
@Resource
private CreditRecordsService creditRecordsService;
@Resource
private PostInfoService postInfoService;
private Integer id;
private Integer type;
private Integer bankId;
private String cardNo;
private String cardBank;
private String personName;
private String idNo;
private String phone;
private Double credits;
private Double money;
private Double rates;
private Boolean stayStates;
private String cardPassword;
private String queryPassword;
private List<BankCardInfo> bankList = new ArrayList<BankCardInfo>();
private List<PostInfo> postList = new ArrayList<PostInfo>();
/**
* @
*/
public String show() {
String str = "";
if (type == 10) {
bankList = bankCardInfoService.getList();
str = "repayment";
}
if (type == 20) {
String where = "order by o.postMaxMoney - postMoney desc";
postList = postInfoService.getList(where, null);
str = "cash";
}
return str;
}
@Override
public String execute() throws Exception {
LoginAdmin loginAdmin = (LoginAdmin) ActionContext.getContext()
.getSession().get("loginAdmin");
CardInfo one = new CardInfo();
Admin adminInfo = adminService.get(loginAdmin.getId());
one.setAdmin(adminInfo);
one.setCardBank(cardBank);
one.setCardNo(cardNo);
one.setCardType(CardConstant.CARD_TYPE_REPAYMENT);
one.setCredits(credits);
one.setEntrustDate(new Date());
one.setMoney(money);
one.setRates(rates);
one.setIdNo(idNo);
one.setPersonName(personName);
one.setPhone(phone);
one.setRepaymentStates(CardConstant.CARD_REPAYMENT_ALSO);
one.setStayStates(stayStates);
one.setRepaymentDate(new Date());
one.setCardStates(CardConstant.CARD_CANCEL_NO);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
cardInfoService.save(one);
if (stayStates) {
CardInfo next = new CardInfo();
next = one;
next.setRepaymentDate(calendar.getTime());
cardInfoService.clear();
cardInfoService.save(next);
}
// 滹¼
BankCardInfo bankInfo = bankCardInfoService.get(bankId);
CreditRecords crs = new CreditRecords();
crs.setBankInfo(bankInfo);
crs.setBrushType(CreditRecConstant.CREDITREC_REPAYMENT);
crs.setCardInfo(one);
crs.setBrushMoney(money);
crs.setBrushDate(new Date());
creditRecordsService.save(crs);
// ʱпĵջ
bankInfo.setBankMoney(bankInfo.getBankMoney() + money);
bankCardInfoService.update(bankInfo);
// һʼ¼
DealInfo dealInfo = new DealInfo();
dealInfo.setBankMoney(money);
dealInfo.setCardInfo(one);
dealInfo.setDealStates(DealInfoConstant.DEAL_STATES_PLUSH_REPAYMENT);
dealInfo.setCommitDate(new Date());
dealInfo.setNeedMoney(money);
dealInfo.setCheckState(DealInfoConstant.DEAL_CHECK_NO);
dealInfo.setFinshState(DealInfoConstant.DEAL_FINSH_NO);
dealInfo.setPostMoney(0d);
dealInfo.setAdminInfo(adminInfo);
dealInfoService.save(dealInfo);
return SUCCESS;
}
/**
* @
*/
@Override
public void validate() {
String where = " where o.cardInfo.cardNo = ? and o.dealStates = ? and finshState = ? ";
List<Object> params = new ArrayList<Object>();
params.add(cardNo);
params.add(DealInfoConstant.DEAL_STATES_PLUSH_REPAYMENT);
params.add(DealInfoConstant.DEAL_FINSH_NO);
List<DealInfo> deals = dealInfoService.getList(where, params.toArray());
if (deals.size() > 0) {
this.addActionError("Ѿһ");
}
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getCardBank() {
return cardBank;
}
public void setCardBank(String cardBank) {
this.cardBank = cardBank;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getBankId() {
return bankId;
}
public void setBankId(Integer bankId) {
this.bankId = bankId;
}
public Double getCredits() {
return credits;
}
public void setCredits(Double credits) {
this.credits = credits;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public Double getRates() {
return rates;
}
public void setRates(Double rates) {
this.rates = rates;
}
public Boolean getStayStates() {
return stayStates;
}
public void setStayStates(Boolean stayStates) {
this.stayStates = stayStates;
}
public List<BankCardInfo> getBankList() {
return bankList;
}
public void setBankList(List<BankCardInfo> bankList) {
this.bankList = bankList;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public List<PostInfo> getPostList() {
return postList;
}
public void setPostList(List<PostInfo> postList) {
this.postList = postList;
}
public String getCardPassword() {
return cardPassword;
}
public void setCardPassword(String cardPassword) {
this.cardPassword = cardPassword;
}
public String getQueryPassword() {
return queryPassword;
}
public void setQueryPassword(String queryPassword) {
this.queryPassword = queryPassword;
}
}
| true |
c624e5a8a93835c597fa0bb2d838c47d055f4643 | Java | lowZoom/LujGame | /game/src/main/java/lujgame/game/server/database/load/message/DbLoadObjRsp.java | UTF-8 | 540 | 2.375 | 2 | [] | no_license | package lujgame.game.server.database.load.message;
public class DbLoadObjRsp {
public DbLoadObjRsp(String cacheKey, Class<?> dbType, Object resultObject) {
_cacheKey = cacheKey;
_dbType = dbType;
_resultObject = resultObject;
}
public String getCacheKey() {
return _cacheKey;
}
public Class<?> getDbType() {
return _dbType;
}
public Object getResultObject() {
return _resultObject;
}
private final String _cacheKey;
private final Class<?> _dbType;
private final Object _resultObject;
}
| true |
3c4e82b4176aa695be3cf07ef357f104973298b1 | Java | AndriyDniproUA/Assignment_4 | /src/main/java/com/savytskyy/Lesson4/Phonebook/contacts/ContactsService.java | UTF-8 | 194 | 2 | 2 | [] | no_license | package com.savytskyy.Lesson4.Phonebook.contacts;
import java.util.List;
public interface ContactsService {
List<Contact> getAll();
void remove (int index);
void add(Contact c);
}
| true |
611cda11462d293565d1f7f266fa5e3481bf53c8 | Java | xiaoxian075/aten | /jewelry_admin/src/com/aten/model/orm/ShakeWinningRecord.java | UTF-8 | 1,831 | 2 | 2 | [] | no_license | package com.aten.model.orm;
import java.io.Serializable;
import java.util.Date;
public class ShakeWinningRecord implements Serializable {
private static final long serialVersionUID = 1L;
private String wr_id;
private String shake_id;
private String awards_id;
private String login_name;
private String account_id;
private String draw_time;
private String is_draw;
private String accept_time;
private String shake_name;
private String awards_name;
public String getShake_name() {
return shake_name;
}
public void setShake_name(String shake_name) {
this.shake_name = shake_name;
}
public String getAwards_name() {
return awards_name;
}
public void setAwards_name(String awards_name) {
this.awards_name = awards_name;
}
public String getWr_id() {
return wr_id;
}
public void setWr_id(String wr_id) {
this.wr_id = wr_id;
}
public String getShake_id() {
return shake_id;
}
public void setShake_id(String shake_id) {
this.shake_id = shake_id;
}
public String getAwards_id() {
return awards_id;
}
public void setAwards_id(String awards_id) {
this.awards_id = awards_id;
}
public String getLogin_name() {
return login_name;
}
public void setLogin_name(String login_name) {
this.login_name = login_name;
}
public String getAccount_id() {
return account_id;
}
public void setAccount_id(String account_id) {
this.account_id = account_id;
}
public String getDraw_time() {
return draw_time;
}
public void setDraw_time(String draw_time) {
this.draw_time = draw_time;
}
public String getIs_draw() {
return is_draw;
}
public void setIs_draw(String is_draw) {
this.is_draw = is_draw;
}
public String getAccept_time() {
return accept_time;
}
public void setAccept_time(String accept_time) {
this.accept_time = accept_time;
}
}
| true |
fac66d88d77a2503bc7ca669aa3b0cb7e4964a85 | Java | wangpiju/dh-prize | /dh-prize-util/src/main/java/com/hs3/utils/DateUtils.java | UTF-8 | 9,133 | 2.984375 | 3 | [] | no_license | package com.hs3.utils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
public static final String FORMAT_DATE_TIME = "yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_DATE = "yyyy-MM-dd";
public static final String FORMAT_TIME = "HH:mm:ss";
public static Date addDay(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(5, n);
return cal.getTime();
}
public static Date addHour(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(11, n);
return cal.getTime();
}
public static Date addMinute(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(12, n);
return cal.getTime();
}
public static Date AddSecond(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(13, n);
return cal.getTime();
}
public static String timeFormat(int time) {
Calendar cal = Calendar.getInstance();
cal.set(11, 0);
cal.set(12, 0);
cal.set(13, 0);
cal.set(14, 0);
cal.add(13, time);
String str = format(cal.getTime(), "HH:mm:ss");
int day = time / 86400;
if (day > 0) {
Integer h = Integer.valueOf(Integer.parseInt(str.substring(0, 2)) + day * 24);
str = h + str.substring(2);
}
return str;
}
public static Timestamp toTimestamp(String c)
throws ParseException {
Date d = toDate(c);
return new Timestamp(d.getTime());
}
public static boolean validateNormalFormat(String strDate) {
return validateNormalFormat(strDate, "yyyy-MM-dd HH:mm:ss");
}
public static boolean validateNormalFormat(String strDate, String formatStr) {
SimpleDateFormat format = new SimpleDateFormat(formatStr);
try {
format.parse(strDate);
} catch (ParseException e) {
return false;
}
return true;
}
public static String format(Date date) {
return format(date, "yyyy-MM-dd HH:mm:ss");
}
public static String formatDate(Date date) {
return format(date, "yyyy-MM-dd");
}
public static String format(Date date, String format) {
DateFormat fm = new SimpleDateFormat(format);
return fm.format(date);
}
public static Date toDateNull(String c) {
try {
return toDate(c);
} catch (Exception localException) {
}
return null;
}
public static Date toDateNull(String c, String format) {
try {
return toDate(c, format);
} catch (Exception localException) {
}
return null;
}
public static Date toDate(String c)
throws ParseException {
return toDate(c, "yyyy-MM-dd HH:mm:ss");
}
public static Date toDate(String c, String format)
throws ParseException {
DateFormat fm = new SimpleDateFormat(format);
return fm.parse(c);
}
public static Date getToDay(int day) {
Calendar cal = Calendar.getInstance();
cal.set(11, 0);
cal.set(12, 0);
cal.set(13, 0);
cal.set(14, 0);
cal.add(5, day);
return cal.getTime();
}
public static Date getToDay() {
return getToDay(0);
}
public static Date getDate(Date d) {
String date = formatDate(d);
Date rel = toDateNull(date, "yyyy-MM-dd");
return rel;
}
public static SimpleDateFormat returnSimpleDateFormat() {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return myFormatter;
}
public static String getTwotime(String sj1, String sj2) {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long time = 0L;
try {
Date date = myFormatter.parse(sj1);
Date mydate = myFormatter.parse(sj2);
time = (mydate.getTime() - date.getTime()) / 1000L;
} catch (Exception e) {
return "";
}
//jd-gui
//return time;
return (new StringBuilder(String.valueOf(time))).toString();
}
public static long getSecondBetween(Date minDate, Date maxDate) {
long ween = maxDate.getTime() - minDate.getTime();
ween /= 1000L;
return ween;
}
public static long getTwoDay(Date d1, Date d2) {
return getTwoDay(format(d1), format(d2));
}
public static long getTwoDay(String sj1, String sj2) {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
long day = 0L;
try {
Date date = myFormatter.parse(sj1);
Date mydate = myFormatter.parse(sj2);
day = (mydate.getTime() - date.getTime()) / 86400000L;
} catch (Exception e) {
return 0L;
}
return day;
}
public static String getPreTime(String sj1, int jj, int sign) {
/**jd-gui
* SimpleDateFormat format;
SimpleDateFormat format;
if (sign == 0)
{
format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
else
{
SimpleDateFormat format;
if (sign == 1) {
format = new SimpleDateFormat("yyyy-MM-dd");
} else {
format = new SimpleDateFormat("HH:mm:ss");
}
}
String mydate1 = "";
try
{
Date date1 = format.parse(sj1);
long Time = date1.getTime() / 1000L + jj;
date1.setTime(Time * 1000L);
mydate1 = format.format(date1);
}
catch (Exception localException) {}
return mydate1;*/
SimpleDateFormat format;
if (sign == 0)
format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
else if (sign == 1)
format = new SimpleDateFormat("yyyy-MM-dd");
else
format = new SimpleDateFormat("HH:mm:ss");
String mydate1 = "";
try {
Date date1 = format.parse(sj1);
long Time = date1.getTime() / 1000L + (long) jj;
date1.setTime(Time * 1000L);
mydate1 = format.format(date1);
} catch (Exception exception) {
}
return mydate1;
}
public static int getWeekOfDate(Date dt) {
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(7) - 1;
if (w == 0) {
w = 7;
}
return w;
}
public static Date getDayByOne(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(5);
if (day <= 15) {
cal.set(5, 1);
} else {
cal.set(5, 16);
}
int a = n / 2;
int b = n % 2;
if (a > 0) {
cal.add(2, a);
}
int day1 = cal.get(5);
if (b > 0) {
if (day1 == 1) {
cal.set(5, 16);
} else {
cal.add(2, b);
cal.set(5, 1);
}
}
return cal.getTime();
}
public static Date getDayBySecond(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(5, 1);
cal.add(2, n);
return cal.getTime();
}
public static Date getStartDateByOne(Date curDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(curDate);
int day = cal.get(5);
if (day >= 16) {
cal.set(5, 1);
} else {
cal.add(2, -1);
cal.set(5, 16);
}
cal.set(11, 0);
cal.set(12, 0);
cal.set(13, 0);
return cal.getTime();
}
public static Date getStartDateBySecond(Date curDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(curDate);
cal.add(5, -1);
cal.set(5, 1);
cal.set(11, 0);
cal.set(12, 0);
cal.set(13, 0);
return cal.getTime();
}
public static Date getEndDateByContract(Date curDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(curDate);
cal.add(5, -1);
cal.set(11, 23);
cal.set(12, 59);
cal.set(13, 59);
return cal.getTime();
}
public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 != null && cal2 != null) {
return cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6);
} else {
throw new IllegalArgumentException("The date must not be null");
}
}
public static int getDayNum(Date curDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(curDate);
return cal.get(5);
}
}
| true |
eebd2d8c9c75409346db5a25544851d030f69124 | Java | martinA85/AndroResto | /app/src/main/java/com/example/mallimonier2017/androresto/bddHelper/PlaceBddHelper.java | UTF-8 | 930 | 2.25 | 2 | [] | no_license | package com.example.mallimonier2017.androresto.bddHelper;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;
import com.example.mallimonier2017.androresto.contract.PlaceContract;
public class PlaceBddHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "AndroResto.db";
private final static int DATABASE_VERSION = 1;
public PlaceBddHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(PlaceContract.SQL_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(PlaceContract.SQL_DROP_TABLE);
onCreate(db);
}
}
| true |
f4844ac3376919cf07340a66821fb8e8412d13f6 | Java | saschabue/ExtraktionVonBpmnAusfuehrungspfadenInActiviti | /ExktraktionUnitTestsausBPMNProjekt/src/test/java/test/generatedUnitTests/ProcessTest_Test_CallActivityProcessesAndMultiInstance_JUnit.java | UTF-8 | 5,021 | 2.03125 | 2 | [] | no_license | package test.generatedUnitTests;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Assert;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import org.activiti.engine.test.ActivitiRule;
import org.junit.Rule;
import org.junit.Test;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
public class ProcessTest_Test_CallActivityProcessesAndMultiInstance_JUnit{
private String filename = "./src/main/resources/original/callingActivitiprocess.bpmn20.xml";
@Rule
public ActivitiRule activitiRule = new ActivitiRule();
@Test
public void executeProcess() throws Exception {
RepositoryService repositoryService = activitiRule.getRepositoryService();
RuntimeService runtimeService = activitiRule.getRuntimeService();
TaskService taskService = activitiRule.getTaskService();
IdentityService identityService = activitiRule.getIdentityService();
ProcessInstance processInstance =null;
Deployment deploy = repositoryService.createDeployment().addInputStream("callingActivitiprocess.bpmn20.xml",
new FileInputStream(filename)).deploy();
Map<String, Object> variableMap = new HashMap<String, Object>();
System.out.println("CallActivity Callactivititask1Name wird deployed");
Deployment deploy_called_process = repositoryService.createDeployment().addInputStream("called_process.bpmn20.xml",new FileInputStream("./src/main/resources/original/called_process.bpmn20.xml")).deploy();
identityService.setAuthenticatedUserId("kermit");
processInstance = runtimeService.startProcessInstanceByKey("callingActivitiprocess",variableMap);
//___User Task___
processInstance = runtimeService.createProcessInstanceQuery().processDefinitionKey("callingActivitiprocess").singleResult();
Task task_ut1 = (taskService.createTaskQuery().processInstanceId(processInstance.getId())).active()
.taskDefinitionKey("ut1").singleResult();
Assert.assertNotNull("Der Originalprozess wurde ver?ndert. Task nicht gefunden", task_ut1);
taskService.setAssignee(task_ut1.getId(),"kermit");
taskService.complete(task_ut1.getId(), variableMap);
//___User Task___
// Neues Start Element ausgef?hrt___
identityService.setAuthenticatedUserId("kermit");
//___User Task___
processInstance = runtimeService.createProcessInstanceQuery().processDefinitionKey("called_process").singleResult();
Task task_calledut10 = (taskService.createTaskQuery().processInstanceId(processInstance.getId())).active()
.taskDefinitionKey("calledut1").singleResult();
Assert.assertNotNull("Der Originalprozess wurde ver?ndert. Task nicht gefunden", task_calledut10);
taskService.setAssignee(task_calledut10.getId(),"sascha");
variableMap.put("nrOfActiveInstances", 1);
variableMap.put("loopCounter", 0);
variableMap.put("nrOfInstances", 3);
variableMap.put("nrOfCompletedInstances", 0);
taskService.complete(task_calledut10.getId(), variableMap);
//___User Task___
//___User Task___
processInstance = runtimeService.createProcessInstanceQuery().processDefinitionKey("called_process").singleResult();
Task task_calledut11 = (taskService.createTaskQuery().processInstanceId(processInstance.getId())).active()
.taskDefinitionKey("calledut1").singleResult();
Assert.assertNotNull("Der Originalprozess wurde ver?ndert. Task nicht gefunden", task_calledut11);
taskService.setAssignee(task_calledut11.getId(),"sascha");
variableMap.put("nrOfActiveInstances", 1);
variableMap.put("loopCounter", 1);
variableMap.put("nrOfInstances", 3);
variableMap.put("nrOfCompletedInstances", 1);
taskService.complete(task_calledut11.getId(), variableMap);
//___User Task___
//___User Task___
processInstance = runtimeService.createProcessInstanceQuery().processDefinitionKey("called_process").singleResult();
Task task_calledut12 = (taskService.createTaskQuery().processInstanceId(processInstance.getId())).active()
.taskDefinitionKey("calledut1").singleResult();
Assert.assertNotNull("Der Originalprozess wurde ver?ndert. Task nicht gefunden", task_calledut12);
taskService.setAssignee(task_calledut12.getId(),"sascha");
variableMap.put("nrOfActiveInstances", 1);
variableMap.put("loopCounter", 2);
variableMap.put("nrOfInstances", 3);
variableMap.put("nrOfCompletedInstances", 2);
taskService.complete(task_calledut12.getId(), variableMap);
//___User Task___
System.out.println("Teilprozess (2890019) wurde beendet");System.out.println("Teilprozess (2890009) wurde beendet");
//_____Testausf?hrung_beendet_____________________________________________
repositoryService.deleteDeployment(deploy.getId(),true);
repositoryService.deleteDeployment(deploy_called_process.getId(), true);
//_____Deployment_wird_gel?scht___________________________________________
}
} | true |
079160cb42be13aa9e19646b6652d1f15f26aa0c | Java | wwyywg/workspace | /AdapterPattern/src/motorAdapter/ElectricMotor.java | GB18030 | 153 | 2.640625 | 3 | [] | no_license | package motorAdapter;
public class ElectricMotor {
public void electricDrive() {
System.out.println("ܷ");
}
}
| true |
584a380078ae2d77a81f3bbdcff81199feda75a2 | Java | thistehneisen/cifra | /src/apk/com/fasterxml/jackson/core/a/c.java | UTF-8 | 9,927 | 2.015625 | 2 | [] | no_license | package com.fasterxml.jackson.core.a;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.e;
import com.fasterxml.jackson.core.e.a;
import com.fasterxml.jackson.core.e.h;
import com.fasterxml.jackson.core.g;
import java.io.IOException;
/* compiled from: ParserMinimalBase */
public abstract class c extends e {
/* renamed from: b reason: collision with root package name */
protected g f4175b;
protected c() {
}
public e G() throws IOException {
g gVar = this.f4175b;
if (gVar != g.START_OBJECT && gVar != g.START_ARRAY) {
return this;
}
int i2 = 1;
while (true) {
g F = F();
if (F == null) {
H();
return this;
} else if (F.e()) {
i2++;
} else if (F.d()) {
i2--;
if (i2 == 0) {
return this;
}
} else {
continue;
}
}
}
/* access modifiers changed from: protected */
public abstract void H() throws JsonParseException;
/* access modifiers changed from: protected */
public void I() throws JsonParseException {
StringBuilder sb = new StringBuilder();
sb.append(" in ");
sb.append(this.f4175b);
f(sb.toString());
throw null;
}
/* access modifiers changed from: protected */
public void J() throws JsonParseException {
f(" in a value");
throw null;
}
/* access modifiers changed from: protected */
public final void K() {
h.a();
throw null;
}
public boolean a(boolean z) throws IOException {
g gVar = this.f4175b;
if (gVar != null) {
boolean z2 = true;
switch (gVar.b()) {
case 6:
String trim = j().trim();
if ("true".equals(trim)) {
return true;
}
if (!"false".equals(trim) && !d(trim)) {
return z;
}
return false;
case 7:
if (h() == 0) {
z2 = false;
}
return z2;
case 9:
return true;
case 10:
case 11:
return false;
case 12:
Object f2 = f();
if (f2 instanceof Boolean) {
return ((Boolean) f2).booleanValue();
}
break;
}
}
return z;
}
/* access modifiers changed from: protected */
public void b(int i2, String str) throws JsonParseException {
if (!a(a.ALLOW_UNQUOTED_CONTROL_CHARS) || i2 > 32) {
char c2 = (char) i2;
StringBuilder sb = new StringBuilder();
sb.append("Illegal unquoted character (");
sb.append(b(c2));
sb.append("): has to be escaped using backslash to be included in ");
sb.append(str);
e(sb.toString());
throw null;
}
}
public String c(String str) throws IOException {
g gVar = this.f4175b;
if (gVar == g.VALUE_STRING || (gVar != null && gVar != g.VALUE_NULL && gVar.c())) {
return j();
}
return str;
}
public g d() {
return this.f4175b;
}
/* access modifiers changed from: protected */
public final void e(String str) throws JsonParseException {
throw b(str);
}
/* access modifiers changed from: protected */
public void f(String str) throws JsonParseException {
StringBuilder sb = new StringBuilder();
sb.append("Unexpected end-of-input");
sb.append(str);
e(sb.toString());
throw null;
}
public long h(long j2) throws IOException {
g gVar = this.f4175b;
if (gVar != null) {
switch (gVar.b()) {
case 6:
String j3 = j();
if (!d(j3)) {
j2 = com.fasterxml.jackson.core.b.g.a(j3, j2);
break;
} else {
return 0;
}
case 7:
case 8:
return i();
case 9:
return 1;
case 10:
case 11:
return 0;
case 12:
Object f2 = f();
if (f2 instanceof Number) {
return ((Number) f2).longValue();
}
break;
}
}
return j2;
}
/* access modifiers changed from: protected */
public boolean d(String str) {
return "null".equals(str);
}
/* access modifiers changed from: protected */
public void d(int i2) throws JsonParseException {
char c2 = (char) i2;
StringBuilder sb = new StringBuilder();
sb.append("Illegal character (");
sb.append(b(c2));
sb.append("): only regular white space (\\r, \\n, \\t) is allowed between tokens");
e(sb.toString());
throw null;
}
protected static final String b(int i2) {
char c2 = (char) i2;
String str = ")";
if (Character.isISOControl(c2)) {
StringBuilder sb = new StringBuilder();
sb.append("(CTRL-CHAR, code ");
sb.append(i2);
sb.append(str);
return sb.toString();
}
String str2 = "' (code ";
String str3 = "'";
if (i2 > 255) {
StringBuilder sb2 = new StringBuilder();
sb2.append(str3);
sb2.append(c2);
sb2.append(str2);
sb2.append(i2);
sb2.append(" / 0x");
sb2.append(Integer.toHexString(i2));
sb2.append(str);
return sb2.toString();
}
StringBuilder sb3 = new StringBuilder();
sb3.append(str3);
sb3.append(c2);
sb3.append(str2);
sb3.append(i2);
sb3.append(str);
return sb3.toString();
}
/* access modifiers changed from: protected */
public void c(int i2) throws JsonParseException {
a(i2, "Expected space separating root-level values");
throw null;
}
/* access modifiers changed from: protected */
public final void b(String str, Throwable th) throws JsonParseException {
throw a(str, th);
}
public int a(int i2) throws IOException {
g gVar = this.f4175b;
if (gVar != null) {
switch (gVar.b()) {
case 6:
String j2 = j();
if (!d(j2)) {
i2 = com.fasterxml.jackson.core.b.g.a(j2, i2);
break;
} else {
return 0;
}
case 7:
case 8:
return h();
case 9:
return 1;
case 10:
case 11:
return 0;
case 12:
Object f2 = f();
if (f2 instanceof Number) {
return ((Number) f2).intValue();
}
break;
}
}
return i2;
}
public double a(double d2) throws IOException {
g gVar = this.f4175b;
if (gVar != null) {
switch (gVar.b()) {
case 6:
String j2 = j();
if (!d(j2)) {
d2 = com.fasterxml.jackson.core.b.g.a(j2, d2);
break;
} else {
return 0.0d;
}
case 7:
case 8:
return e();
case 9:
return 1.0d;
case 10:
case 11:
return 0.0d;
case 12:
Object f2 = f();
if (f2 instanceof Number) {
return ((Number) f2).doubleValue();
}
break;
}
}
return d2;
}
/* access modifiers changed from: protected */
public void a(int i2, String str) throws JsonParseException {
if (i2 >= 0) {
StringBuilder sb = new StringBuilder();
sb.append("Unexpected character (");
sb.append(b(i2));
sb.append(")");
String sb2 = sb.toString();
if (str != null) {
StringBuilder sb3 = new StringBuilder();
sb3.append(sb2);
sb3.append(": ");
sb3.append(str);
sb2 = sb3.toString();
}
e(sb2);
throw null;
}
I();
throw null;
}
/* access modifiers changed from: protected */
public char a(char c2) throws JsonProcessingException {
if (a(a.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)) {
return c2;
}
if (c2 == '\'' && a(a.ALLOW_SINGLE_QUOTES)) {
return c2;
}
StringBuilder sb = new StringBuilder();
sb.append("Unrecognized character escape ");
sb.append(b(c2));
e(sb.toString());
throw null;
}
/* access modifiers changed from: protected */
public final JsonParseException a(String str, Throwable th) {
return new JsonParseException(str, b(), th);
}
}
| true |
f314fc9b2e56073537d3d70957ca1928bd929af4 | Java | tosswang/myGitPro | /ThreadTest/src/教程线程状态/学习1/MyThread.java | GB18030 | 404 | 3.359375 | 3 | [] | no_license | package ̳߳״̬.ѧϰ1;
public class MyThread extends Thread
{
public MyThread()
{
System.out.println("췽е״̬"+Thread.currentThread().getName()+"::"+Thread.currentThread().getState());
}
@Override
public void run()
{
System.out.println("run е״̬"+Thread.currentThread().getName()+"::"+Thread.currentThread().getState());
}
}
| true |
c380b8df39c9592043db90db1ccbba9f04369b4b | Java | 358Tcyf/Talk | /app/src/main/java/me/daylight/talk/presenter/InfoPresenter.java | UTF-8 | 8,677 | 1.679688 | 2 | [] | no_license | package me.daylight.talk.presenter;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.ImageView;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import me.daylight.talk.R;
import me.daylight.talk.app.GlideApp;
import me.daylight.talk.bean.User;
import me.daylight.talk.fragment.InfoFragment;
import me.daylight.talk.http.OnHttpCallBack;
import me.daylight.talk.http.RetResult;
import me.daylight.talk.model.InfoModel;
import me.daylight.talk.utils.DialogUtil;
import me.daylight.talk.utils.GlideEngine;
import me.daylight.talk.utils.GlobalField;
import me.daylight.talk.utils.SharedPreferencesUtil;
import me.daylight.talk.customview.GroupListView;
import me.daylight.talk.view.InfoView;
public class InfoPresenter extends BasePresenter<InfoView,InfoModel> {
private User user;
private List<EditText> editTextList;
private ImageView headView;
private QMUICommonListItemView gender;
public void initGroupListView(GroupListView groupListView) {
user=getModel().loadUserInfo();
initCustomView();
QMUICommonListItemView headImage = groupListView.createItemView("头像");
headImage.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
headImage.addAccessoryCustomView(headView);
QMUICommonListItemView phone=groupListView.createItemView("手机号码");
phone.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_NONE);
phone.setDetailText(user.getPhone());
QMUICommonListItemView name=groupListView.createItemView("姓名");
name.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
name.addAccessoryCustomView(editTextList.get(0));
QMUICommonListItemView nicName=groupListView.createItemView("昵称");
nicName.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
nicName.addAccessoryCustomView(editTextList.get(1));
gender=groupListView.createItemView("性别");
gender.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_NONE);
switch (user.getGender()){
case 0:
gender.setDetailText("请选择");
break;
case 1:
gender.setDetailText("男");
break;
case 2:
gender.setDetailText("女");
break;
}
QMUICommonListItemView signature=groupListView.createItemView("个性签名");
signature.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
signature.addAccessoryCustomView(editTextList.get(2));
QMUICommonListItemView address=groupListView.createItemView("地址");
address.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
address.addAccessoryCustomView(editTextList.get(3));
GroupListView.newSection(getView().getCurContext())
.addItemView(headImage, v ->
Matisse.from(getView().getFragment())
.choose(MimeType.ofAll())
.countable(false)
.maxSelectable(1)
.gridExpectedSize(QMUIResHelper.getAttrDimen(getView().getCurContext(),R.dimen.grid_expected_size))
.spanCount(3)
.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
.thumbnailScale(0.85f)
.imageEngine(new GlideEngine())
.capture(true)
.captureStrategy(new CaptureStrategy(true,"me.daylight.talk.fileprovider"))
.forResult(GlobalField.REQUEST_CODE_CHOOSE))
.addItemView(phone,null)
.addItemView(name,null)
.addItemView(nicName,null)
.addItemView(gender,v -> {
String[] items=new String[]{"请选择","男","女"};
new QMUIDialog.CheckableDialogBuilder(getView().getCurContext())
.setCheckedIndex(user.getGender())
.addItems(items,((dialog, which) -> {
user.setGender(which);
gender.setDetailText(items[which]);
dialog.dismiss();
}))
.create().show();
})
.addItemView(signature,null)
.addItemView(address,null)
.addTo(groupListView);
editable(false);
if (!user.getPhone().equals(SharedPreferencesUtil.getString(getView().getCurContext(),GlobalField.USER,GlobalField.ACCOUNT))){
headImage.setClickable(false);
getView().hideEditButton();
}
}
public void saveInfo() {
user.setName(editTextList.get(0).getText().toString());
user.setNicname(editTextList.get(1).getText().toString());
user.setSignature(editTextList.get(2).getText().toString());
user.setAddress(editTextList.get(3).getText().toString());
user.setUpdatetime(new Date().getTime());
getModel().saveUserInfo(user, new OnHttpCallBack<RetResult>() {
@Override
public void onSuccess(RetResult retResult) {
DialogUtil.showTipDialog(getView().getCurContext(), QMUITipDialog.Builder.ICON_TYPE_SUCCESS,
retResult.getMsg(),true);
editable(false);
SharedPreferencesUtil.putValue(getView().getCurContext(),GlobalField.USER,GlobalField.STATE,100);
}
@Override
public void onFailed(String errorMsg) {
DialogUtil.showTipDialog(getView().getCurContext(),QMUITipDialog.Builder.ICON_TYPE_FAIL,
errorMsg,true);
}
});
}
public void editable(boolean editable) {
getView().changeButtonStatus(editable);
for (int i = 0; i < 4; i++) {
editTextList.get(i).setFocusable(editable);
editTextList.get(i).setFocusableInTouchMode(editable);
}
gender.setClickable(editable);
}
private EditText createEditText(Context context){
EditText editText=new EditText(context);
editText.setWidth(QMUIDisplayHelper.dp2px(context,120));
editText.setGravity(Gravity.END);
editText.setTextSize(15);
editText.setTextColor(QMUIResHelper.getAttrColor(getView().getCurContext(),R.attr.qmui_config_color_gray_5));
editText.setBackgroundColor(context.getResources().getColor(R.color.transparent));
return editText;
}
private void initCustomView(){
editTextList=new ArrayList<>();
for (int i=0;i<4;i++){
editTextList.add(createEditText(getView().getCurContext()));
}
editTextList.get(0).setText(user.getName());
editTextList.get(1).setText(user.getNicname());
editTextList.get(2).setText(user.getSignature());
editTextList.get(3).setText(user.getAddress());
headView=new ImageView(getView().getCurContext());
setHeadImage(GlobalField.url+"user/headImage/"+user.getPhone()+"?time="+ user.getUpdatetime());
}
private void setHeadImage(String imageUrl){
GlideApp.with(getView().getCurContext()).load(imageUrl)
.override(QMUIDisplayHelper.dpToPx(48), QMUIDisplayHelper.dpToPx(48)).circleCrop().into(headView);
}
public InfoFragment.OnActivityResultCallback callback=uris-> getModel().uploadHeadImage(uris.get(0), new OnHttpCallBack<RetResult>() {
@Override
public void onSuccess(RetResult retResult) {
DialogUtil.showTipDialog(getView().getCurContext(),QMUITipDialog.Builder.ICON_TYPE_SUCCESS,retResult.getMsg(),true);
getModel().updateTime(user);
setHeadImage(GlobalField.url+"user/headImage/"+user.getPhone()+"?time="+new Date().getTime());
}
@Override
public void onFailed(String errorMsg) {
DialogUtil.showTipDialog(getView().getCurContext(),QMUITipDialog.Builder.ICON_TYPE_FAIL,errorMsg,true);
}
});
}
| true |
731784a876f02e642f89bc641525ada023492121 | Java | Eldivan/MavenJpa | /src/test/java/br/com/testejunit/TestePersistirProduto.java | UTF-8 | 1,359 | 2.421875 | 2 | [] | no_license | package br.com.testejunit;
import javax.persistence.EntityManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.jpa.EntityManagerUtil;
import br.com.modelo.Categoria;
import br.com.modelo.Marca;
import br.com.modelo.Produto;
public class TestePersistirProduto {
EntityManager em;
public TestePersistirProduto() {
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
em = EntityManagerUtil.getEntityManager();
}
@After
public void tearDown() throws Exception {
em.close();
}
@Test
public void test() {
boolean exception = false;
try {
Produto produto = new Produto();
produto.setNome("Teclado");
produto.setPreco(50.00);
produto.setQuantidadeEstoque(10);
produto.setDescricao("Teclado ergonomico");
produto.setMarca(em.find(Marca.class, 4));
produto.setCategoria(em.find(Categoria.class, 1));
em.getTransaction().begin();
em.persist(produto);
em.getTransaction().commit();
em.close();
}catch (Exception e) {
exception = true;
e.printStackTrace();
}
Assert.assertEquals(false, exception);
}
}
| true |
b6577cc82c92296df781b05b27ea051eb80a9b43 | Java | Ernestchang/J2EENote | /Base/src/com/wh/base/web/taglib/PermissionTag.java | UTF-8 | 1,160 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package com.wh.base.web.taglib;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import com.wh.base.bean.privilege.PrivilegeGroup;
import com.wh.base.bean.privilege.SystemPrivilege;
import com.wh.base.bean.privilege.SystemPrivilegePK;
import com.wh.base.bean.privilege.User;
import com.wh.base.utils.WebUtil;
public class PermissionTag extends TagSupport {
private static final long serialVersionUID = 2274050576698204851L;
private String module;
private String privilege;
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
public String getPrivilege() {
return privilege;
}
public void setPrivilege(String privilege) {
this.privilege = privilege;
}
@Override
public int doStartTag() throws JspException {
User user = WebUtil.getUser();
SystemPrivilege privilege = new SystemPrivilege(new SystemPrivilegePK(this.module, this.privilege));
for(PrivilegeGroup group : user.getGroups()){
if(group.getPrivileges().contains(privilege)){
return EVAL_BODY_INCLUDE;
}
}
return SKIP_BODY;
}
}
| true |
179b3eaa7941ab6942aed016ad40d3fe851dd35f | Java | dimitrkovalsky/soge | /src/main/java/com/liberty/soge/register/events/EventHandlersScanBeanDefinitionRegister.java | UTF-8 | 1,451 | 2.03125 | 2 | [] | no_license | package com.liberty.soge.register.events;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import com.liberty.soge.annotation.EventHandlersTypeScan;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EventHandlersScanBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
Class<?> clazz = null;
try {
clazz = Class.forName(importingClassMetadata.getClassName());
} catch (ClassNotFoundException e) {
log.error("error during initialization", e);
}
EventHandlersTypeScan eventHandlerTypesScan = clazz.getAnnotation(EventHandlersTypeScan.class);
if(eventHandlerTypesScan != null) {
String[] packages = eventHandlerTypesScan.packages();
BeanDefinition bd = new RootBeanDefinition(EventHandlersCandidateClassPathScanningComponentProvider.class);
bd.getPropertyValues().addPropertyValue("packages", packages);
registry.registerBeanDefinition("eventHandlersProvider", bd);
}
}
}
| true |
4f7fe83b8cd03da46203b4861245f0f26191deea | Java | renjunqu/joymove | /src/main/java/com/joymove/view/JOYUserController.java | UTF-8 | 18,030 | 1.867188 | 2 | [] | no_license | package com.joymove.view;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.futuremove.cacheServer.utils.Id5Utils;
import com.joymove.entity.JOYPayReqInfo;
import com.joymove.service.JOYPayReqInfoService;
import com.joymove.util.WeChatPay.WeChatPayUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;
import com.futuremove.cacheServer.utils.ConfigUtils;
import com.joymove.entity.JOYDynamicPws;
import com.joymove.entity.JOYUser;
import com.joymove.service.JOYDynamicPwsService;
import com.joymove.service.JOYUserService;
import com.joymove.util.zhifubao.ZhifubaoUtils;
import org.json.simple.parser.JSONParser;
@Controller("JOYUserController")
public class JOYUserController{
@Resource(name = "JOYUserService")
private JOYUserService joyUserService;
@Resource(name = "JOYDynamicPwsService")
private JOYDynamicPwsService joyDynamicPwsService;
@Resource(name = "JOYPayReqInfoService")
private JOYPayReqInfoService joyPayReqInfoService;
final static Logger logger = LoggerFactory.getLogger(JOYUserController.class);
/**
* @return
*/
@RequestMapping(value="usermgr/register",method=RequestMethod.POST)
public @ResponseBody JSONObject registration(HttpServletRequest req){
JSONObject jsonObject = new JSONObject();
jsonObject.put("result","10001");
try{
Hashtable<String, Object> jsonObj = (Hashtable<String, Object>)req.getAttribute("jsonArgs");
String mobileNo = (String)jsonObj.get("mobileNo");
String code = String.valueOf(jsonObj.get("code"));
//String username = (String)jsonObj.get("username");
String password = (String)jsonObj.get("password");
Map<String,Object> likeCondition = new HashMap<String, Object>();
JOYDynamicPws dynamicPwsFilter = new JOYDynamicPws();
dynamicPwsFilter.mobileNo = mobileNo;
List<JOYDynamicPws> dynamicPws = joyDynamicPwsService.getNeededList(dynamicPwsFilter,0,1,"DESC");
JOYUser user = new JOYUser();
if (password.length() <= 5 || password.length() >= 13) {
jsonObject.put("errMsg","密码格式不对");
}else{
JOYDynamicPws joyDynamicPws = dynamicPws.get(0);
Date time = joyDynamicPws.createTime;
if(joyDynamicPws.code.equals(code)){
if((System.currentTimeMillis() - time.getTime())/(60000) < 15){
user.mobileNo = mobileNo; //setMobileNo(mobileNo);
//user.setUserName(username);
user.userpwd = password; //setUserpwd(password);
joyUserService.insertRecord(user);
jsonObject.put("result","10000");
} else {
jsonObject.put("errMsg","验证码超时");
}
} else {
jsonObject.put("errMsg","验证码错误");
}
}
}catch(Exception e){
e.printStackTrace();
}
return jsonObject;
}
@RequestMapping(value="usermgr/login",method=RequestMethod.POST)
public @ResponseBody JSONObject userLogin(HttpServletRequest req) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("result","10001");
try{
Hashtable<String, Object> jsonObj = (Hashtable<String, Object>)req.getAttribute("jsonArgs");
String mobileNo = (String)jsonObj.get("mobileNo");
String password = (String)jsonObj.get("password");
JOYUser user = new JOYUser();
user.mobileNo = mobileNo; //setMobileNo(mobileNo);
List<JOYUser> joyUsers = joyUserService.getNeededList(user);
if (joyUsers.size() > 0) {
for (JOYUser joyUser : joyUsers) {
String userpwd = joyUser.userpwd; //getUserpwd();
if (password.equals(userpwd)) {
String authToken = joyUser.mobileNo /*getMobileNo()*/+"###"+String.valueOf(UUID.randomUUID());
joyUser.authToken = authToken; //setAuthToken(authToken);
joyUser.lastActiveTime = new Date(System.currentTimeMillis()); //setLastActiveTime(new Date(System.currentTimeMillis()));
joyUser.mobileNo = mobileNo; //setMobileNo(mobileNo);
joyUserService.updateRecord(joyUser, user);
jsonObject.put("result", "10000");
jsonObject.put("authToken", authToken);
}else{
jsonObject.put("errMsg","密码错误");
}
}
}else{
jsonObject.put("errMsg","用户名不存在");
}
}catch(Exception e){
e.printStackTrace();
}
return jsonObject;
}
@RequestMapping(value="usermgr/updatePwd",method=RequestMethod.POST)
public @ResponseBody JSONObject updatePwd(HttpServletRequest req){
JSONObject jsonObject = new JSONObject();
jsonObject.put("result","10001");
try{
Hashtable<String, Object> jsonObj = (Hashtable<String, Object>)req.getAttribute("jsonArgs");
String mobileNo = (String)jsonObj.get("mobileNo");
String passWord = (String)jsonObj.get("password");
String chPwd = (String) jsonObj.get("changepassword");
if (chPwd.length() <= 5 || chPwd.length() >= 13) {
jsonObject.put("errMsg","密码长度不能小于5位");
}else{
JOYUser joyUser = (JOYUser)req.getAttribute("cUser");
if (passWord.equals(joyUser.userpwd)) {
JOYUser userNew = new JOYUser();
userNew.userpwd = chPwd; //setUserpwd(chPwd);
joyUserService.updateRecord(userNew, joyUser);
jsonObject.put("result","10000");
}else{
jsonObject.put("errMsg","旧密码输入错误");
}
}
}catch(Exception e){
e.printStackTrace();
}
return jsonObject;
}
@RequestMapping(value="usermgr/resetPwd",method=RequestMethod.POST)
public @ResponseBody JSONObject resetPwd(HttpServletRequest req){
JSONObject jsonObject = new JSONObject();
jsonObject.put("result","10001");
try{
Hashtable<String, Object> jsonObj = (Hashtable<String, Object>)req.getAttribute("jsonArgs");
String mobileNo = (String)jsonObj.get("mobileNo");
String passWord = (String)jsonObj.get("password");
String code = String.valueOf(jsonObj.get("code"));
Map<String,Object> likeCondition = new HashMap<String, Object>();
JOYDynamicPws dynamicPwsFilter = new JOYDynamicPws();
dynamicPwsFilter.mobileNo = mobileNo;
List<JOYDynamicPws> dynamicPws = joyDynamicPwsService.getNeededList(dynamicPwsFilter,0,1,"DESC");
JOYDynamicPws joyDynamicPws = dynamicPws.get(0);
if(joyDynamicPws.code.equals(code) && ((System.currentTimeMillis() - joyDynamicPws.createTime.getTime())/(60000) < 15)){
if (passWord.length() <= 5 || passWord.length() >= 13) {
jsonObject.put("errMsg","验证码格式错误");
}else{
JOYUser joyUser = (JOYUser)req.getAttribute("cUser");
JOYUser userNew = new JOYUser();
userNew.userpwd = passWord; //setUserpwd(passWord);
joyUser.mobileNo = mobileNo; //setMobileNo(mobileNo);
joyUserService.updateRecord(userNew, joyUser);
jsonObject.put("result","10000");
}
} else {
jsonObject.put("errMsg","验证码错误");
}
}catch(Exception e){
e.printStackTrace();
}
return jsonObject;
}
@RequestMapping(value={"usermgr/viewBaseInfo"
,"usermgr/getCommonDestination"
,"usermgr/checkUserState"
,"usermgr/getBioLogicalInfo"
,"usermgr/updateUserIdInfo"},method=RequestMethod.POST)
public @ResponseBody JSONObject userInfo(HttpServletRequest req){
JSONObject Reobj = new JSONObject();
Reobj.put("result", "10001");
try{
Hashtable<String, Object> jsonObj = (Hashtable<String, Object>)req.getAttribute("jsonArgs");
String mobileNo = (String)jsonObj.get("mobileNo");
JOYUser joyUser = (JOYUser)req.getAttribute("cUser");
String URI = req.getRequestURI();
if(URI.contains("viewBaseInfo")) {
Reobj.put("username", joyUser.username);
Reobj.put("gender", joyUser.gender);
Reobj.put("mobileNo", joyUser.mobileNo);
Reobj.put("driverlicenseCertification", joyUser.authenticateDriver);
Reobj.put("deposit", joyUser.deposit);
Reobj.put("idNo",joyUser.idNo==null?"":joyUser.idNo);
Reobj.put("idName",joyUser.idName==null?"":joyUser.idName);
Reobj.put("result", "10000");
} else if (URI.contains("getCommonDestination")){
JSONObject homeAddr = new JSONObject();
JSONObject corpAddr = new JSONObject();
homeAddr.put("name", joyUser.homeAddr);
homeAddr.put("latitude", joyUser.homeLatitude);
homeAddr.put("longitude", joyUser.homeLongitude);
corpAddr.put("name", joyUser.corpAddr);
corpAddr.put("latitude", joyUser.corpLatitude);
corpAddr.put("longitude", joyUser.corpLongitude);
Reobj.put("home", homeAddr);
Reobj.put("corp", corpAddr);
Reobj.put("result", "10000");
} else if (URI.contains("checkUserState")){
Reobj.put("mobileAuthState", 1);
Reobj.put("id5PassFlag",joyUser.id5PassFlag);
Reobj.put("id5AuthState", joyUser.authenticateId);
Reobj.put("driverLicAuthState", joyUser.authenticateDriver);
BigDecimal deposit = joyUser.deposit;
if(deposit!=null && deposit.doubleValue() >=0.01) {
Reobj.put("depositState", 1);
} else {
Reobj.put("depositState", 0);
}
Reobj.put("result", "10000");
} else if(URI.contains("getBioLogicalInfo")) {
Reobj.put("face_info", joyUser.face_info);
Reobj.put("voice_info", joyUser.voice_info);
Reobj.put("result", "10000");
} else if(URI.contains("updateUserIdInfo")) {
String idNo = String.valueOf(jsonObj.get("idNo"));
String idName = String.valueOf(jsonObj.get("idName"));
if(idNo!=null && idName!=null) {
Map<String,String> id5Info = Id5Utils.Id5Check(idName,idNo);
JOYUser toModUser = new JOYUser();
toModUser.mobileNo = mobileNo;
if(id5Info!=null) {
toModUser.idNo = idNo;
toModUser.idName = idName;
toModUser.gender = String.valueOf(id5Info.get("sex"));
toModUser.id5PassFlag = JOYUser.auth_state_ok;
Reobj.put("result","10000");
} else {
toModUser.id5PassFlag = JOYUser.auth_state_pending;
}
joyUserService.updateRecord(toModUser, joyUser);
}
}
}catch(Exception e){
e.printStackTrace();
Reobj.put("result","10001");
Reobj.put("errMsg","发生未知错误");
}
return Reobj;
}
@RequestMapping(value={"usermgr/updateInfo","usermgr/updateBiologicalInfo"}, method=RequestMethod.POST)
public @ResponseBody JSONObject updateInfo(HttpServletRequest req){
JSONObject jsonObject = new JSONObject();
jsonObject.put("result","10001");
try{
Hashtable<String, Object> jsonObj = (Hashtable<String, Object>)req.getAttribute("jsonArgs");
String mobileNo = (String)jsonObj.get("mobileNo");
String URI = req.getRequestURI();
if(URI.contains("updateBiologicalInfo")) {
String face_info = (String) jsonObj.get("face_info");
String voice_info = (String) jsonObj.get("voice_info");
JOYUser joyUser = (JOYUser) req.getAttribute("cUser");
JOYUser userNew = new JOYUser();
userNew.face_info = face_info;
userNew.voice_info = voice_info;
joyUser.mobileNo = mobileNo;
joyUserService.updateRecord(userNew, joyUser);
jsonObject.put("result", "10000");
} else if (URI.contains("updateInfo")) {
String username = (String) jsonObj.get("username");
String gender = (String) jsonObj.get("gender");
JOYUser joyUser = (JOYUser) req.getAttribute("cUser");
JOYUser userNew = new JOYUser();
String[] settingProps = {"username", "gender"};
if(username!=null)
userNew.username = username;
if(gender!=null)
userNew.gender = gender;
joyUserService.updateRecord(userNew, joyUser);
jsonObject.put("result", "10000");
}
}catch(Exception e){
e.printStackTrace();
}
return jsonObject;
}
public static void main(String[] args){
JOYUser user = new JOYUser();
try {
BeanUtils.setProperty(user, "gender", "11111111");
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.trace(user.gender);
}
@RequestMapping(value="usermgr/depositRecharge",method=RequestMethod.POST)
public @ResponseBody JSONObject depositRecharge(HttpServletRequest req){
JSONObject Reobj = new JSONObject();
Reobj.put("result","10001");
try{
Hashtable<String, Object> jsonObj = (Hashtable<String, Object>)req.getAttribute("jsonArgs");
String mobileNo = (String)jsonObj.get("mobileNo");
Double balance = Double.valueOf(jsonObj.get("balance").toString());
String currTimeStr = System.currentTimeMillis()+"";
/* generate zhifubao's code **/
String zhifubao_code = ZhifubaoUtils.getPayInfo("depositRecharge", mobileNo, balance, currTimeStr+balance.toString().replace(".", "-"));
/** generate wx's code */
JOYPayReqInfo wxpayInfo = new JOYPayReqInfo();
JOYPayReqInfo zhifubaoPayInfo = new JOYPayReqInfo();
wxpayInfo.mobileNo = (mobileNo);
wxpayInfo.type = JOYPayReqInfo.type_wx;
zhifubaoPayInfo.type = JOYPayReqInfo.type_zhifubao;
zhifubaoPayInfo.mobileNo = mobileNo;
String wx_trade_no = "depositRecharge" + String.valueOf(System.currentTimeMillis());
wxpayInfo.out_trade_no = (wx_trade_no);
zhifubaoPayInfo.out_trade_no = currTimeStr+balance.toString().replace(".", "-");
wxpayInfo.totalFee = (Double.valueOf(balance));
zhifubaoPayInfo.totalFee = wxpayInfo.totalFee;
String wx_code = WeChatPayUtil.genePayStr(String.valueOf(Double.valueOf(balance*100).longValue()),wx_trade_no);
joyPayReqInfoService.insertRecord(wxpayInfo);
joyPayReqInfoService.insertRecord(zhifubaoPayInfo);
/**generate result **/
Reobj.put("result", "10000");
Reobj.put("zhifubao_code", zhifubao_code);
Reobj.put("wx_code",new JSONParser().parse(wx_code));
}catch(Exception e){
e.printStackTrace();
}
return Reobj;
}
@RequestMapping(value="usermgr/updateIma",method=RequestMethod.POST)
public @ResponseBody JSONObject userIma(HttpServletRequest req){
JSONObject jsonObject = new JSONObject();
jsonObject.put("result","10001");
try{
Hashtable<String, Object> jsonObj = (Hashtable<String, Object>)req.getAttribute("jsonArgs");
String mobileNo = (String)jsonObj.get("mobileNo");
String image = (String) jsonObj.get("image");
BASE64Decoder decode = new BASE64Decoder();
String imagePath = ConfigUtils.getPropValues("upload.images")+"/"+mobileNo+".jpg";
byte[] byteImage = decode.decodeBuffer(image);
OutputStream output = new BufferedOutputStream(new FileOutputStream(imagePath));
output.write(byteImage);
jsonObject.put("result","10000");
}catch(Exception e){
e.printStackTrace();
}
return jsonObject;
}
@RequestMapping(value="userImage/getIma",method=RequestMethod.GET)
public String getIma(HttpServletRequest req,HttpServletResponse res){
try{
String mobileNo = (String) req.getParameter("mobileNo");
byte[] bt = null;
String imagePath = ConfigUtils.getPropValues("upload.images")+"/"+mobileNo+".jpg";
File file = new File(imagePath);
InputStream inputStream = new FileInputStream(file);
bt = FileCopyUtils.copyToByteArray(inputStream);
res.setContentType("image/jpg");
OutputStream os = res.getOutputStream();
os.write(bt);
os.flush();
os.close();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
@RequestMapping(value="usermgr/checkUserMobileNo",method=RequestMethod.POST)
public @ResponseBody JSONObject checkUserMobileNo(HttpServletRequest req){
JSONObject jsonObject = new JSONObject();
//if the user exists , it will be filtered by the interceptor
jsonObject.put("result","10000");
return jsonObject;
}
@RequestMapping(value="usermgr/updateCommonDestination",method=RequestMethod.POST)
public @ResponseBody JSONObject updateCommonDestination(HttpServletRequest req){
JSONObject Reobj = new JSONObject();
Reobj.put("result","10001");
try{
Hashtable<String,Object> jsonObj = (Hashtable<String, Object>) req.getAttribute("jsonArgs");
JOYUser user = (JOYUser)req.getAttribute("cUser");
JOYUser userNew = new JOYUser();
JSONObject homeAddr = (JSONObject)jsonObj.get("home");
JSONObject corpAddr = (JSONObject)jsonObj.get("corp");
if(homeAddr!=null){
userNew.homeAddr = (String)homeAddr.get("name");
userNew.homeLatitude = BigDecimal.valueOf(Double.valueOf(String.valueOf(homeAddr.get("latitude"))));
userNew.homeLongitude = (BigDecimal.valueOf(Double.valueOf(String.valueOf(homeAddr.get("longitude")))));
}
if(corpAddr!=null) {
userNew.corpAddr = ((String)corpAddr.get("name"));
userNew.corpLatitude = (BigDecimal.valueOf(Double.valueOf(String.valueOf(corpAddr.get("latitude")))));
userNew.corpLongitude = (BigDecimal.valueOf(Double.valueOf(String.valueOf(corpAddr.get("longitude")))));
}
joyUserService.updateRecord(userNew,user);
Reobj.put("result","10000");
}catch(Exception e){
e.printStackTrace();
}
return Reobj;
}
}
| true |
a0553151c313954dd0de72fbbc57a6d3d1e3bfcd | Java | veryriskyrisk/r8 | /src/test/java/com/android/tools/r8/utils/codeinspector/Subject.java | UTF-8 | 631 | 1.75 | 2 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright (c) 2018, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.utils.codeinspector;
import com.android.tools.r8.errors.Unimplemented;
public abstract class Subject {
public abstract boolean isPresent();
public abstract boolean isRenamed();
public abstract boolean isSynthetic();
public boolean isCompilerSynthesized() {
throw new Unimplemented(
"Predicate not yet supported on Subject: " + getClass().getSimpleName());
}
}
| true |
6d214fa22014c57f52e70ddd00c641ebf9596038 | Java | YuliyaKhilko/pvt_course | /Task2/Task2_9.java | UTF-8 | 1,313 | 3.984375 | 4 | [] | no_license | // 9. найти номер минимального-максимального элементов и вывести
package core;
import java.util.Arrays;
import java.util.Scanner;
public class Task2_9 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter array length:");
int size = scanner.nextInt();
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10);
}
int max = array[0];
int min = array[0];
System.out.println("Generated array: " + Arrays.toString(array));
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
for (int i = 0; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.print("Max elements numbers: ");
for (int i = 0; i < array.length; i++) { // added this for as there could be more than one element with the same max value
if (array[i] == max) {
System.out.print((i + 1) + " ");
}
}
System.out.print("\n" + "Min elements numbers: "); // added this for as there could be several elements with the same min value
for (int i = 0; i < array.length; i++) {
if (array[i] == min) {
System.out.print((i + 1) + " ");
}
}
scanner.close();
}
}
| true |
e43da2600b264e9731d7bbe8e8def8edfb854593 | Java | chibitopoochan/soqlexecutor | /src/test/java/com/gmail/chibitopoochan/soqlexec/soap/mock/SalesforceConnectionFactoryMock.java | UTF-8 | 3,045 | 2.25 | 2 | [
"MIT"
] | permissive | package com.gmail.chibitopoochan.soqlexec.soap.mock;
import com.gmail.chibitopoochan.soqlexec.soap.SalesforceConnectionFactory;
import com.gmail.chibitopoochan.soqlexec.soap.wrapper.ConnectionWrapper;
public class SalesforceConnectionFactoryMock extends SalesforceConnectionFactory {
private ConnectionWrapper partner;
private boolean login;
private boolean logout;
private boolean error;
private String authEndPoint;
private String username;
private String password;
private String proxyHost;
private int proxyPort;
private String proxyUser;
private String proxyPass;
public void setLoginError(boolean error) {
this.error = error;
}
/* (非 Javadoc)
* @see com.gmail.chibitopoochan.soqlexec.soap.SalesforceConnectionFactory#setParameter(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public void setParameter(String authEndPoint, String username, String password, boolean tool, String local) {
this.authEndPoint = authEndPoint;
this.username = username;
this.password = password;
}
public String getAuthEndPoint() {
return authEndPoint;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
/* (非 Javadoc)
* @see com.gmail.chibitopoochan.soqlexec.soap.SalesforceConnectionFactory#login()
*/
@Override
public boolean login() {
if(error) {
login = false;
} else {
login = true;
}
return login;
}
/* (非 Javadoc)
* @see com.gmail.chibitopoochan.soqlexec.soap.SalesforceConnectionFactory#isLogin()
*/
@Override
public boolean isLogin() {
return login;
}
/* (非 Javadoc)
* @see com.gmail.chibitopoochan.soqlexec.soap.SalesforceConnectionFactory#logout()
*/
@Override
public boolean logout() {
if(error) {
logout = false;
} else {
logout = true;
}
return logout;
}
public boolean isLogout() {
return logout;
}
/* (非 Javadoc)
* @see com.gmail.chibitopoochan.soqlexec.soap.SalesforceConnectionFactory#getPartnerConnection()
*/
@Override
public ConnectionWrapper getPartnerConnection() {
return partner;
}
public void setPartnerConnection(ConnectionWrapper partner) {
this.partner = partner;
}
/* (非 Javadoc)
* @see com.gmail.chibitopoochan.soqlexec.soap.SalesforceConnectionFactory#setProxyParameter(java.lang.String, int, java.lang.String, java.lang.String)
*/
@Override
public void setProxyParameter(String host, int port, String username, String password) {
proxyHost = host;
proxyPort = port;
proxyUser = username;
proxyPass = password;
}
/**
* @return proxyHost
*/
public String getProxyHost() {
return proxyHost;
}
/**
* @return proxyPort
*/
public int getProxyPort() {
return proxyPort;
}
/**
* @return proxyUser
*/
public String getProxyUser() {
return proxyUser;
}
/**
* @return proxyPass
*/
public String getProxyPass() {
return proxyPass;
}
}
| true |
8ef2ea7b03e1b8646ad61372d0ddbf4a7487343f | Java | llllJokerllll/Programacion | /Trimestre2/BoletinColecciones/src/com/acarballeira/exercicios/clases/exercicio7/App.java | ISO-8859-1 | 2,847 | 3.6875 | 4 | [
"MIT"
] | permissive | /*
* @Author Jose Manuel Sabars Garca
*/
package com.acarballeira.exercicios.clases.exercicio7;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// TODO: Auto-generated Javadoc
/**
* The Class App.
*/
public class App {
/** The d 1. */
private Diccionario d1 = new Diccionario();
/** The br. */
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
/**
* The main method.
*
* @param args the arguments
* @throws IOException Signals that an I/O exception has occurred.
*/
public static void main(String[] args) throws IOException {
int opcion = 0;
App app = new App();
do {
opcion = app.menu();
app.opcionEscollida(opcion);
} while (opcion != 5);
}
/**
* Menu.
*
* @return the int
*/
public int menu() {
System.out.print("DICCIONARIO\n-----------\n1. Consultar traduccin\n2. Aadir traduccin\n3. Vaciar diccionario\n4. Aadir datos de prueba\n5. Salir\nIntroduzca la opcion a usar: ");
try {
return Integer.parseInt(br.readLine());
} catch (IOException e) {
System.out.println("Opcin no vlida");
return 0;
} catch (NumberFormatException e) {
System.out.println("Error indicando opcin");
return 0;
}
}
/**
* Crear terminos prueba.
*
* @throws IOException Signals that an I/O exception has occurred.
*/
public void crearTerminosPrueba() throws IOException {
d1.engadirTermo("Uno", "One");
d1.engadirTermo("Dos", "Two");
d1.engadirTermo("Tres", "Three");
d1.engadirTermo("Cuatro", "Four");
d1.engadirTermo("Cinco", "Five");
d1.engadirTermo("Seis", "Six");
d1.engadirTermo("Siete", "Seven");
d1.engadirTermo("Ocho", "Eight");
d1.engadirTermo("Nueve", "Nine");
d1.engadirTermo("Diez", "Ten");
System.out.println("Los trminos de prueba han sido aadidos correctamente.");
}
/**
* Opcion escollida.
*
* @param opcion the opcion
* @throws IOException Signals that an I/O exception has occurred.
*/
public void opcionEscollida(int opcion) throws IOException {
String esp;
String ing;
switch(opcion) {
case 1:
System.out.print("Introduzca el trmino que quiera traducir: ");
esp = br.readLine();
System.out.println(d1.traducir(esp));
break;
case 2:
System.out.print("Introduzca el trmino: ");
esp = br.readLine();
System.out.print("Introduzca la traduccin: ");
ing = br.readLine();
d1.engadirTermo(esp, ing);
break;
case 3:
d1.baleirar();
break;
case 4:
crearTerminosPrueba();
break;
case 5:
System.out.println("Hasta otra!");
break;
default:
System.out.println("ERROR, opcin no vlida");
}
}
}
| true |
d8cf295083d64d2b029429e76ac3ca0eddc96371 | Java | ThiagoSouzaCardoso/TwitterTopic | /TwitterTopic/src/br/com/fiap/app/Main.java | UTF-8 | 624 | 2.453125 | 2 | [] | no_license | package br.com.fiap.app;
import twitter4j.Query;
public class Main {
public static void main(String[] args) {
try {
Query query = new Query("#java8");
query.setSince("2016-05-15");
query.setUntil("2016-05-22");
System.out.println("Executando...");
new FiltraTwitter(query).imprimeQtdTweetsPorDia()
.imprimeQtdRetweetsPorDia().imprimeQtdFavoritosPorDia()
.imprimeDataMaisRecente().imprimeDataMenosRecente()
.imprimePrimeiroUsuarioDaLista().imprimeUltimoUsuarioDaLista().sendTwitter();
System.out.println("Executado com sucesso");
} catch (Exception e) {
e.printStackTrace();
}
}
} | true |
25aa13042350ae4de4cd58b530aa070ec4c984b5 | Java | JohnDuq/Docker | /driven-adapters/model/src/main/java/co/com/bancolombia/model/deposit/request/listplans/ListPlansRequest.java | UTF-8 | 355 | 1.59375 | 2 | [] | no_license | package co.com.bancolombia.model.deposit.request.listplans;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class ListPlansRequest {
private List<Pagination> list;
}
| true |
486411f2073c77f4a606bf8c63de650369f2afe2 | Java | bargyoon/mm_project | /src/mm/common/filter/ValidatorFilter.java | UTF-8 | 3,280 | 2.125 | 2 | [] | no_license | package mm.common.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mm.common.code.ErrorCode;
import mm.common.exception.HandlableException;
import mm.member.validator.JoinForm;
import mm.member.validator.ModifyPassword;
/**
* Servlet Filter implementation class ValidatorFilter
*/
public class ValidatorFilter implements Filter {
/**
* Default constructor.
*/
public ValidatorFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String[] uriArr = httpRequest.getRequestURI().split("/");
if (uriArr.length != 0) {
String redirectURI = null;
switch (uriArr[1]) {
case "member":
redirectURI = memberValidation(httpRequest, httpResponse, uriArr);
break;
default:
break;
}
if (redirectURI != null) {
httpResponse.sendRedirect(redirectURI);
return;
}
}
chain.doFilter(request, response);
}
private String memberValidation(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String[] uriArr)
throws IOException, ServletException {
String redirectURI = null;
JoinForm joinForm = null;
ModifyPassword modifyPw = null;
String persistToken = null;
switch (uriArr[2]) {
case "join-mentee":
joinForm = new JoinForm(httpRequest);
if (!joinForm.test()) {
redirectURI = "/member/join-form-mentee?err=1";
}
break;
case "join-mentor":
joinForm = new JoinForm(httpRequest);
if (!joinForm.test()) {
redirectURI = "/member/join-form-mentor?err=1";
}
break;
case "modify-password":
modifyPw = new ModifyPassword(httpRequest);
if (!modifyPw.test()) {
redirectURI = "/member/mypage?err=1";
}
break;
case "change-password":
modifyPw = new ModifyPassword(httpRequest);
if (!modifyPw.test()) {
redirectURI = "/member/password-impla?err=1";
}
break;
case "join-impl":
persistToken = httpRequest.getParameter("persist-token");
if (!persistToken.equals(httpRequest.getSession().getAttribute("persist-token"))) {
throw new HandlableException(ErrorCode.AUTHENTICATION_FAILED_ERROR);
}
break;
case "password-impl":
persistToken = httpRequest.getParameter("persist-token");
if (!persistToken.equals(httpRequest.getSession().getAttribute("persist-token"))) {
throw new HandlableException(ErrorCode.AUTHENTICATION_FAILED_ERROR);
}
break;
default:
break;
}
return redirectURI;
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
| true |
4a8ee9446f744be3909f2092327e5e2cc18119ec | Java | anasabuhussein/emulator-api | /src/main/java/com/jbielak/emulatorapi/socket/EmulatorClient.java | UTF-8 | 3,271 | 2.609375 | 3 | [
"MIT"
] | permissive | package com.jbielak.emulatorapi.socket;
import com.jbielak.emulatorapi.dto.LightweightSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
@Component
public class EmulatorClient implements ClientApi {
private static final Logger LOGGER = LoggerFactory.getLogger(EmulatorClient.class);
@Value("${socket.emulator.address}")
private String LOCALHOST;
@Value("${socket.emulator.port}")
private Integer ANDROID_EMULATOR_PORT;
private Socket socket;
private PrintWriter printWriter = null;
private BufferedReader bufferedReader = null;
private String currentAddress = null;
private Integer currentPort = null;
@Override
@PostConstruct
public LightweightSocket openConnection() {
return openConnection(LOCALHOST, ANDROID_EMULATOR_PORT);
}
@Override
public LightweightSocket openConnection(String address, Integer port) {
if (address == null && port == null) {
currentAddress = LOCALHOST;
currentPort = ANDROID_EMULATOR_PORT;
} else {
currentAddress = address;
currentPort = port;
}
try {
socket = new Socket(address, port);
printWriter = new PrintWriter(socket.getOutputStream(), true);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
LOGGER.info(String.format("Connection with %s, on port %s established.", currentAddress, currentPort));
return new LightweightSocket(currentAddress, currentPort);
} catch (IOException e) {
LOGGER.error(String.format("Could not open Connection to %s on %s. Check if target machine is running",
currentAddress, currentPort), e);
}
return new LightweightSocket();
}
@Override
@PreDestroy
public LightweightSocket closeConnection() {
LightweightSocket socketToClose = new LightweightSocket(currentAddress, currentPort);
try {
printWriter.close();
bufferedReader.close();
socket.shutdownOutput();
socket.shutdownInput();
socket.close();
LOGGER.info(String.format("Socket connection with Android Emulator on %s, port %s closed.",
currentAddress, currentPort));
currentAddress = null;
currentPort = null;
return socketToClose;
} catch (IOException e) {
LOGGER.error(String.format("Could not close Connection socket connection"
+ "to Android Emulator on %s, port %s.",
currentAddress, currentPort), e);
}
return new LightweightSocket();
}
@Override
public PrintWriter getPrintWriter() {
return this.printWriter;
}
@Override
public BufferedReader getBufferedReader() {
return this.bufferedReader;
}
}
| true |
9a2446ade83b05208c2740107ccbcbcc3e4be5dc | Java | pietrocaselani/MiniAndroidPlayground | /SimpleJavaSTDLib/src/main/java/io/github/pietrocaselani/simplejava/stdlib/Action0.java | UTF-8 | 165 | 1.5625 | 2 | [] | no_license | package io.github.pietrocaselani.simplejava.stdlib;
/**
* Created by Pietro Caselani
* On 03/09/14
* newjava
*/
public interface Action0 extends Action {
void call();
} | true |
24222c4613fd8df3254c36a976efc323104b5d00 | Java | mishra123/Reading-XML-using-Grammer | /Slot.java | UTF-8 | 547 | 2.328125 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Date;
/**
*
* @author Lucho
*/
public class Slot {
private String startTime;
private String endTime;
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getEndTime() {
return endTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getStartTime() {
return startTime;
}
}
| true |
b2141547228c7773f73035dbf907ba0baeaf4c61 | Java | F2020-ECSE223/ecse223-group-project-p4 | /ca.mcgill.ecse.flexibook/src/main/java/ca/mcgill/ecse223/flexibook/controller/TOService.java | UTF-8 | 2,116 | 2.125 | 2 | [] | no_license | /*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.30.1.5099.60569f335 modeling language!*/
package ca.mcgill.ecse223.flexibook.controller;
// line 12 "../../../../../FlexiBookTransferObjects.ump"
public class TOService
{
//------------------------
// MEMBER VARIABLES
//------------------------
//TOService Attributes
private String serviceName;
private int serviceDur;
private int downtimeDur;
private int downtimeDurStart;
//------------------------
// CONSTRUCTOR
//------------------------
public TOService(String aServiceName, int aServiceDur, int aDowntimeDur, int aDowntimeDurStart)
{
serviceName = aServiceName;
serviceDur = aServiceDur;
downtimeDur = aDowntimeDur;
downtimeDurStart = aDowntimeDurStart;
}
//------------------------
// INTERFACE
//------------------------
public boolean setServiceName(String aServiceName)
{
boolean wasSet = false;
serviceName = aServiceName;
wasSet = true;
return wasSet;
}
public boolean setServiceDur(int aServiceDur)
{
boolean wasSet = false;
serviceDur = aServiceDur;
wasSet = true;
return wasSet;
}
public boolean setDowntimeDur(int aDowntimeDur)
{
boolean wasSet = false;
downtimeDur = aDowntimeDur;
wasSet = true;
return wasSet;
}
public boolean setDowntimeDurStart(int aDowntimeDurStart)
{
boolean wasSet = false;
downtimeDurStart = aDowntimeDurStart;
wasSet = true;
return wasSet;
}
public String getServiceName()
{
return serviceName;
}
public int getServiceDur()
{
return serviceDur;
}
public int getDowntimeDur()
{
return downtimeDur;
}
public int getDowntimeDurStart()
{
return downtimeDurStart;
}
public void delete()
{}
public String toString()
{
return super.toString() + "["+
"serviceName" + ":" + getServiceName()+ "," +
"serviceDur" + ":" + getServiceDur()+ "," +
"downtimeDur" + ":" + getDowntimeDur()+ "," +
"downtimeDurStart" + ":" + getDowntimeDurStart()+ "]";
}
} | true |
8aa70b095359505c0d8000fbc77947726a34c646 | Java | BarnaBotond96/GreatHopesNetBank | /GreatHopesNetbank/src/hu/javamiddle/ghnb/db/resultsetreader/transaction/FullTransactionResultSetReader.java | UTF-8 | 1,538 | 2.484375 | 2 | [] | no_license | package hu.javamiddle.ghnb.db.resultsetreader.transaction;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import hu.javamiddle.ghnb.db.entity.Transaction;
import hu.javamiddle.ghnb.db.resultsetreader.ResultSetReader;
public class FullTransactionResultSetReader implements ResultSetReader<Transaction> {
@Override
public List<Transaction> read(ResultSet resultSet) throws SQLException {
List<Transaction> results = new ArrayList<>();
while (resultSet.next()) {
long transactionId = resultSet.getLong("transaction_id");
String fromBankAccountNumber = resultSet.getString("from_bank_account_number");
String toBankAccountNumber = resultSet.getString("to_bank_account_number");
String beneficiaryName = resultSet.getString("beneficiary_name");
LocalDateTime transactionDate = resultSet.getTimestamp("transaction_date").toLocalDateTime();
long amount = resultSet.getLong("amount");
String transactionComment = resultSet.getString("transaction_comment");
Transaction transaction = Transaction.builder()
.withTransactionId(transactionId)
.withFromBankAccountNumber(fromBankAccountNumber)
.withToBankAccountNumber(toBankAccountNumber)
.withBeneficiaryName(beneficiaryName)
.withTransactionDate(transactionDate)
.withAmount(amount)
.withTransactionComment(transactionComment)
.build();
results.add(transaction);
}
return results;
}
} | true |
0aa827d264a9e6421bead6834024345e9aea9295 | Java | tbette1/hw6 | /Track.java | UTF-8 | 3,879 | 3.234375 | 3 | [] | no_license | package cs3500.music.model;
import java.util.*;
public class Track implements Song {
private List <Note> notes;
/**
* Constructs a new Track object with an empty set of notes.
*/
public Track() {
notes = new ArrayList<Note>();
}
@Override
public void addNote(Note n, List<Attribute> attributes, int startBeat) {
int ind = notes.indexOf(n);
if (ind == -1) {
ArrayList<Attribute> toAddActions = new ArrayList<Attribute>();
for (int i = 0; i < startBeat; i++) {
toAddActions.add(Attribute.Rest);
}
for (int i = 0; i < attributes.size(); i++) {
toAddActions.add(startBeat + i, attributes.get(i));
}
n.actions = toAddActions;
}
else {
Note temp = notes.get(ind);
int diff = startBeat - temp.getPlayLength();
if (diff > 0) {
for (int i = 0; i < diff; i++) {
temp.actions.add(Attribute.Rest);
}
for (int i = 0; i < attributes.size(); i++) {
temp.actions.add(attributes.get(i));
}
}
else {
for (int i = 0; i < attributes.size() - diff; i++) {
temp.actions.add(Attribute.Rest);
}
int i = startBeat;
for (Attribute a : attributes) {
if (!a.equals(Attribute.Rest)) {
temp.actions.set(i, a);
i++;
}
}
}
}
}
@Override
public ArrayList<Note> getNotes() {
return new ArrayList(this.notes);
}
@Override
public ArrayList<Note> getAllNotesInRange() {
ArrayList<Note> fullList = new ArrayList<Note>();
fullList.add(this.firstNote());
while (!fullList.get(fullList.size() - 1).equals(this.lastNote())) {
Note n = fullList.get(fullList.size() - 1).getHalfStepUp();
if (this.notes.contains(n)) {
fullList.add(this.notes.get(this.notes.indexOf(n)));
}
else {
fullList.add(n);
}
}
return fullList;
}
@Override
public ArrayList<String> getNoteNames(ArrayList<Note> noteList) {
ArrayList<String> nameList = new ArrayList<String>();
for (Note n : noteList) {
nameList.add(n.toString());
}
return nameList;
}
@Override
public void delete(Note n, ArrayList<Integer> beats) throws IllegalArgumentException {
int ind = notes.indexOf(n);
if (ind == -1) {
throw new IllegalArgumentException("The given note is not contained in this track.");
}
else {
for (int i : beats) {
notes.get(ind).actions.set(i, Attribute.Rest);
}
}
}
@Override
public int getLength() {
int longest = 0;
for (Note n : this.notes) {
if (n.getPlayLength() > longest) {
longest = n.getPlayLength();
}
}
return longest;
}
@Override
public Note firstNote() {
int earliestBeat = 10000;
Note first = null;
for (Note n : this.notes) {
if (n.getFirstPlay() < earliestBeat && n.getFirstPlay() > -1) {
first = n;
earliestBeat = n.getFirstPlay();
}
}
return first;
}
@Override
public Note lastNote() {
int longest = 0;
Note last = null;
for (Note n : this.notes) {
if (n.getPlayLength() > longest) {
longest = n.getPlayLength();
last = n;
}
}
return last;
}
}
| true |
f201f8443092018bf84729a450bc60362da1df0a | Java | TJChangD/BigInteger-in-Java | /BigInteger/src/lab3and4_1406398_2si4/HugeInteger.java | UTF-8 | 13,908 | 3.328125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lab3and4_1406398_2si4;
import java.util.Random;
/**
*
* @author Darren
*/
public class HugeInteger {
private int size;
private int numArray[];
public HugeInteger(String val){
size = val.length();
int num[] = new int[size];
for (int i = 0; i < size; i++)
{
num[i] = (int)val.charAt(i) - 48;
}
numArray = num;
}
public HugeInteger(int n) throws IndexOutOfBoundsException{
size = n;
if(n<1){
throw new IndexOutOfBoundsException("Argument is invalid!");
}
else{
int rNum;
int num[] = new int[n];
Random r = new Random();
for(int i = 0;i<n;i++){
rNum = r.nextInt(9)+1;
num[i] = rNum;
}
numArray = num;
}
}
public HugeInteger add(HugeInteger h){
boolean flag = false, flag2 = false, neg = false;
if (this.numArray[0] == -3 && h.numArray[0] != -3) {
flag = true;
this.strip();
if(this.compareTo(h) == 0){
HugeInteger s = new HugeInteger("0");
return s;
}
if (this.compareTo(h) > 0){
neg = true;
h.complement(this);
}
else{
this.complement(h);
}
}
if (this.numArray[0] != -3 && h.numArray[0] == -3) {
flag2 = true;
h.strip();
if(this.compareTo(h) == 0){
HugeInteger s = new HugeInteger("0");
return s;
}
if (h.compareTo(this) > 0) {
neg = true;
this.complement(h);
}
else{
h.complement(this);
}
}
if (this.numArray[0] == -3 && h.numArray[0] == -3){
this.strip();
h.strip();
neg = true;
}
int i = this.size - 1, j = h.size - 1, k = 0, c = 0, num, carry = 0;
if (i == j) {
int tempsize = i + 1;
int sum[] = new int[tempsize];
while (i >= 0) {
num = this.numArray[i] + h.numArray[j];
num = num + carry;
if (num > 9) {
carry = 1;
} else {
carry = 0;
}
if (i == 0) {
sum[k] = num;
} else {
num = num % 10;
sum[k] = num;
}
i--; j--; k++; c++;
}
this.size = c;
this.numArray = sum;
this.numArray = this.reverse(numArray);
}
else if(j > i){
int tempsize = j + 1, zeros = (j + 1) - (i + 1), m = 0;
int sum[] = new int[tempsize], tempArray[] = new int[tempsize];
for (int l = 0;l < j+1; l++){
if(l < zeros){
tempArray[l] = 0;
}
else{
tempArray[l] = this.numArray[m];
m++;
}
}
while (j >= 0) {
num = tempArray[j] + h.numArray[j];
num = num + carry;
if (num > 9) {
carry = 1;
} else {
carry = 0;
}
if (j == 0) {
sum[k] = num;
} else {
num = num % 10;
sum[k] = num;
}
j--; k++; c++;
}
this.size = c;
this.numArray = sum;
this.numArray = this.reverse(numArray);
}
else{
int tempsize = i + 1, zeros = (i + 1) - (j + 1), m = 0;
int sum[] = new int[tempsize], tempArray[] = new int[tempsize];
for (int l = 0;l < i+1; l++){
if(l < zeros){
tempArray[l] = 0;
}
else{
tempArray[l] = h.numArray[m];
m++;
}
}
while (i >= 0) {
num = tempArray[i] + this.numArray[i];
num = num + carry;
if (num > 9) {
carry = 1;
} else {
carry = 0;
}
if (i == 0) {
sum[k] = num;
} else {
num = num % 10;
sum[k] = num;
}
i--; k++; c++;
}
this.size = c;
this.numArray = sum;
this.numArray = this.reverse(numArray);
}
if (flag2 == true || flag == true){
this.numArray[0] = this.numArray[0] % 10;
HugeInteger s = new HugeInteger("1");
this.add(s);
}
if (neg == true){
this.negative();
}
return this;
}
public HugeInteger subtract(HugeInteger h){
if(this.numArray[0] != -3 && h.numArray[0] != -3){
h.negative();
return this.add(h);
}
if(this.numArray[0] != -3 && h.numArray[0] == -3){
h.strip();
return this.add(h);
}
if(this.numArray[0] == -3 && h.numArray[0] != -3){
h.negative();
return this.add(h);
}
if(this.numArray[0] == -3 && h.numArray[0] == -3){
h.strip();
return this.add(h);
}
return this;
}
public HugeInteger multiply(HugeInteger h) {
String mul;
boolean neg = false;
int carry = 0, pow = 0, sum, num1[], num2[];
if (this.numArray[0] == -3 && h.numArray[0] != -3) {
this.strip();
neg = true;
}
if (this.numArray[0] != -3 && h.numArray[0] == -3) {
h.strip();
neg = true;
}
if (this.numArray[0] == -3 && h.numArray[0] == -3) {
h.strip();
this.strip();
neg = false;
}
if (this.size > h.size) {
num1 = this.numArray;
num2 = h.numArray;
} else {
num2 = this.numArray;
num1 = h.numArray;
}
HugeInteger a, b = new HugeInteger("0");
for (int i = num2.length - 1; i >= 0; i--) {
mul = "";
for (int j = num1.length - 1; j >= 0; j--) {
int temp = num1[j] * num2[i] + carry;
carry = (int)(temp / 10);
sum = temp % 10;
mul = sum + mul;
}
if (carry != 0) {
mul = carry + mul;
carry = 0;
}
for (int k = pow; k > 0; k--) {
mul = mul + "0";
}
a = new HugeInteger(mul);
b = b.add(a);
pow++;
}
if (neg == true) {
return b.negative();
} else {
return b;
}
}
public int compareTo(HugeInteger h){
int i = this.size, j = h.size, c = 0;
if(i == j){
for(int l = 0; l < i ; l++ ){
if(this.numArray[l] == h.numArray[l]){
c++;
}
}
if(c == i){
return 0;
}
}
if(this.numArray[0] == -3 && h.numArray[0] != -3){
return -1;
}
else if(this.numArray[0] != -3 && h.numArray[0] == -3){
return 1;
}
else if(this.numArray[0] == -3 && h.numArray[0] == -3){
if(i<j){
return 1;
}
else if(j<i){
return -1;
}
else{
for(int k = 0;k < i + 1; k++){
if(this.numArray[k] > h.numArray[k]){
return -1;
}
if(this.numArray[k] < h.numArray[k]){
return 1;
}
}
}
}
else{
if(i>j){
return 1;
}
else if(j>i){
return -1;
}
else{
for(int k = 0;k < i + 1; k++){
if(this.numArray[k] > h.numArray[k]){
return 1;
}
if(this.numArray[k] < h.numArray[k]){
return -1;
}
}
return 0;
}
}
return 0;
}
public HugeInteger strip(){
int num[] = new int[this.size - 1];
for (int i = 0; i < this.size - 1; i++){
num[i] = this.numArray[i+1];
}
this.size = this.size - 1;
this.numArray = num;
return this;
}
public HugeInteger negative(){
int num[] = new int[this.size + 1];
num[0] = -3;
for (int i = 0; i < this.size; i++){
num[i + 1] = this.numArray[i];
}
this.size = this.size + 1;
this.numArray = num;
return this;
}
public HugeInteger complement(HugeInteger h){
int num[] = new int[h.size];
for (int i = 0; i < h.size ; i++){
num[i] = 9;
}
int c = 0, arraysize = this.size;
for (int i = h.size - 1 ; c < arraysize ; i--){
num[i] = num[i] - this.numArray[this.size-1];
this.size--;
c++;
}
this.size = num.length;
this.numArray = num;
return this;
}
public int[] reverse(int[] array){
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
return array;
}
public int getSize(){
return size;
}
@Override
public String toString() {
String str = "";
if (numArray[0] == -3) {
str = "-";
for (int i = 1; i < size; i++) {
str = str + numArray[i];
}
} else {
for (int i = 0; i < size; i++) {
str = str + numArray[i];
}
}
return str;
}
public void RunTime(int n) {
AddTime(n);
SubTime(n);
MulTime(n);
CompTime(n);
}
public void AddTime(int n) {
int MAXNUMINTS = 1000, MAXRUN = 100;
HugeInteger h1, h2, h3;
long startTime, endTime;
double runTime = 0.0;
for (int i = 0; i < MAXNUMINTS; i++) {
h1 = new HugeInteger(n);
h2 = new HugeInteger(n);
startTime = System.currentTimeMillis();
for (int j = 0; j < MAXRUN; j++) {
h3 = h1.add(h2);
}
endTime = System.currentTimeMillis();
runTime += (double) (endTime - startTime) / ((double) MAXRUN);
}
runTime = runTime / ((double) (MAXNUMINTS));
System.out.println(runTime);
}
public void SubTime(int n) {
int MAXNUMINTS = 1000, MAXRUN = 100;
HugeInteger h1, h2, h3;
long startTime, endTime;
double runTime = 0.0;
for (int i = 0; i < MAXNUMINTS; i++) {
h1 = new HugeInteger(n);
h2 = new HugeInteger(n);
startTime = System.currentTimeMillis();
for (int j = 0; j < MAXRUN; j++) {
h3 = h1.subtract(h2);
}
endTime = System.currentTimeMillis();
runTime += (double) (endTime - startTime) / ((double) MAXRUN);
}
runTime = runTime / ((double) (MAXNUMINTS));
System.out.println(runTime);
}
public void MulTime(int n) {
int MAXNUMINTS = 1000, MAXRUN = 100;
HugeInteger h1, h2, h3;
long startTime, endTime;
double runTime = 0.0;
for (int i = 0; i < MAXNUMINTS; i++) {
h1 = new HugeInteger(n);
h2 = new HugeInteger(n);
startTime = System.currentTimeMillis();
for (int j = 0; j < MAXRUN; j++) {
h3 = h1.multiply(h2);
}
endTime = System.currentTimeMillis();
runTime += (double) (endTime - startTime) / ((double) MAXRUN);
}
runTime = runTime / ((double) (MAXNUMINTS));
System.out.println(runTime);
}
public void CompTime(int n) {
int MAXNUMINTS = 1000, MAXRUN = 100;
HugeInteger h1, h2;
long startTime, endTime;
double runTime = 0.0;
for (int i = 0; i < MAXNUMINTS; i++) {
h1 = new HugeInteger(n);
h2 = new HugeInteger(n);
startTime = System.currentTimeMillis();
for (int j = 0; j < MAXRUN; j++) {
h1.compareTo(h2);
}
endTime = System.currentTimeMillis();
runTime += (double) (endTime - startTime) / ((double) MAXRUN);
}
runTime = runTime / ((double) (MAXNUMINTS));
System.out.println(runTime);
}
}
| true |
13aac88e2a4731fd234fea6a73958d89e8850d44 | Java | brugienis/Capstone-Project | /app/src/main/java/au/com/kbrsolutions/melbournepublictransport/fragments/FavoriteStopsFragment.java | UTF-8 | 16,209 | 1.898438 | 2 | [] | no_license | package au.com.kbrsolutions.melbournepublictransport.fragments;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import au.com.kbrsolutions.melbournepublictransport.R;
import au.com.kbrsolutions.melbournepublictransport.adapters.FavoriteStopsAdapter;
import au.com.kbrsolutions.melbournepublictransport.data.LatLngDetails;
import au.com.kbrsolutions.melbournepublictransport.data.MptContract;
import au.com.kbrsolutions.melbournepublictransport.data.StopDetails;
/**
* Handles favorite train stops.
*
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link FavoriteStopsFragment.OnFavoriteStopsFragmentInteractionListener} interface
* to handle interaction events.
*/
@SuppressWarnings("ALL")
public class FavoriteStopsFragment
extends BaseFragment
implements LoaderManager.LoaderCallbacks<Cursor> {
private NestedScrollingListView mListView;
private List<StopDetails> mStopDetailsList;
private TextView mEmptyView;
private View mRootView;
private boolean isVisible;
private FavoriteStopsAdapter mFavoriteStopDetailAdapter;
private OnFavoriteStopsFragmentInteractionListener mListener;
private boolean mIsInSettingsActivityFlag;
private int mCursorRowCnt;
private View mCurrentSelectedView;
private int mCurrentSelectedRow;
private int selectableViewsCnt = 3;
private int selectedViewNo = -1;
private boolean mDatabaseIsEmpty;
private boolean mIsShowOptionsMenu;
private int loaderId;
private static final String ASCENDING_SORT_ORDER = " ASC";
private static final String DOT = ".";
private static final int STOP_DETAILS_LOADER = 0;
private static final String[] STOP_DETAILS_COLUMNS = {
MptContract.StopDetailEntry.TABLE_NAME + DOT + MptContract.StopDetailEntry._ID,
MptContract.StopDetailEntry.COLUMN_ROUTE_TYPE,
MptContract.StopDetailEntry.COLUMN_STOP_ID,
MptContract.StopDetailEntry.COLUMN_LOCATION_NAME,
MptContract.StopDetailEntry.COLUMN_LATITUDE,
MptContract.StopDetailEntry.COLUMN_LONGITUDE,
MptContract.StopDetailEntry.COLUMN_FAVORITE
};
// These indices are tied to stop_details columns specified above.
public static final int COL_STOP_DETAILS_ID = 0;
public static final int COL_STOP_DETAILS_ROUTE_TYPE = 1;
public static final int COL_STOP_DETAILS_STOP_ID = 2;
public static final int COL_STOP_DETAILS_LOCATION_NAME = 3;
public static final int COL_STOP_DETAILS_LATITUDE = 4;
public static final int COL_STOP_DETAILS_LONGITUDE = 5;
public static final int COL_STOP_DETAILS_FAVORITE = 6;
private final String TAG = ((Object) this).getClass().getSimpleName();
public FavoriteStopsFragment() {
// Required empty public constructor
}
/**
*
* Call invalidateOptionsMenu() to change the available menu options.
*
*/
public void hideView() {
isVisible = false;
if (mRootView != null) {
mRootView.setVisibility(View.INVISIBLE);
}
if (mListener != null) {
((Activity) mListener).invalidateOptionsMenu();
}
}
/**
*
* Call invalidateOptionsMenu() to change the available menu options.
*
*/
public void showView() {
isVisible = true;
if (mRootView != null) {
mRootView.setVisibility(View.VISIBLE);
}
if (mListener != null) {
((Activity) mListener).invalidateOptionsMenu();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
isVisible = true;
}
public void databaseIsEmpty(boolean databaseIsEmpty) {
mDatabaseIsEmpty = databaseIsEmpty;
setEmptyViewText("databaseIsEmpty");
}
private void setEmptyViewText(String source) {
if (mDatabaseIsEmpty) {
mEmptyView.setText(getActivity().getResources().getString(R.string.database_is_empty));
} else {
if (mIsInSettingsActivityFlag) {
mEmptyView.setText(getActivity().getResources().getString(R.string.no_favorite_stops_selected_in_settings));
} else {
mEmptyView.setText(getActivity().getResources().getString(R.string.no_favorite_stops_selected));
}
}
}
public void setShowOptionsMenuFlg(boolean showOptionsMenuFlg) {
if (mIsShowOptionsMenu != showOptionsMenuFlg) {
mIsShowOptionsMenu = showOptionsMenuFlg;
if (mListener != null) {
((Activity) mListener).invalidateOptionsMenu();
}
}
}
private void clearEmptyViewText() {
mEmptyView.setText("");
}
/**
*
* Followed henry74918's advice of how to navigate between items on a list's row.
*
* see:
*
* http://stackoverflow.com/questions/14392356/how-to-use-d-pad-navigate-switch-between-listviews-row-and-its-decendants-goo
*
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mFavoriteStopDetailAdapter = new FavoriteStopsAdapter(
getActivity().getApplicationContext(),
mListener,
mIsInSettingsActivityFlag);
// Inflate the layout for this fragment
mRootView = inflater.inflate(R.layout.fragment_favorite_stops, container, false);
if (mStopDetailsList == null) {
mStopDetailsList = new ArrayList<>();
}
mListView = (NestedScrollingListView) mRootView.findViewById(R.id.favoriteStopsListView);
mListView.setAdapter(mFavoriteStopDetailAdapter);
mListView.setNestedScrollingEnabled(true);
mListView.setItemsCanFocus(true);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
handleRowSelected(adapterView, position);
}
});
mListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
handleItemSelected(view, position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mEmptyView = (TextView) mRootView.findViewById(R.id.emptyFavoriteStopsView);
return mRootView;
}
/**
* This is called when D-pad navigation keys are used.
*
* @param view
* @param position
*/
private void handleItemSelected(View view, int position) {
if (view.getTag() != null) {
mCurrentSelectedView = view;
mCurrentSelectedRow = position;
selectedViewNo = 0;
FavoriteStopsAdapter.ViewHolder holder = (FavoriteStopsAdapter.ViewHolder)
mCurrentSelectedView.getTag();
mListView.clearFocus();
holder.departuresImageId.setFocusable(true);
holder.departuresImageId.requestFocus();
}
}
public boolean handleVerticalDpadKeys(boolean upKeyPressed) {
if (upKeyPressed && mCurrentSelectedRow == 0 ||
!upKeyPressed && mCurrentSelectedRow == mCursorRowCnt - 1) {
} else {
mCurrentSelectedView.setFocusable(true);
mCurrentSelectedView.requestFocus();
}
return false;
}
/**
*
* Based on henry74918
*
* http://stackoverflow.com/questions/14392356/how-to-use-d-pad-navigate-switch-between-listviews-row-and-its-decendants-goo
*
* @param rightKeyPressed
* @return
*/
public boolean handleHorizontalDpadKeys(boolean rightKeyPressed) {
boolean resultOk = false;
if (mCurrentSelectedView != null && mCurrentSelectedView.hasFocus()) {
int prevSelectedViewNo = selectedViewNo;
if (rightKeyPressed) {
selectedViewNo = selectedViewNo == (selectableViewsCnt - 1) ? 0 : selectedViewNo + 1;
} else {
selectedViewNo = selectedViewNo < 1 ? selectableViewsCnt - 1 : selectedViewNo - 1;
}
FavoriteStopsAdapter.ViewHolder holder = (FavoriteStopsAdapter.ViewHolder)
mCurrentSelectedView.getTag();
mListView.clearFocus();
switch (selectedViewNo) {
case 0:
holder.departuresImageId.setFocusable(true);
holder.departuresImageId.requestFocus();
break;
case 1:
holder.mapImageId.setFocusable(true);
holder.mapImageId.requestFocus();
break;
case 2:
holder.garbageInfoImage.setFocusable(true);
holder.garbageInfoImage.requestFocus();
break;
default:
throw new RuntimeException(TAG + ".handleHorizontalDpadKeys - case '" +
selectedViewNo + "' not handled");
}
resultOk = true;
}
return resultOk;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(STOP_DETAILS_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
// This is called when a new Loader needs to be created. Sort order: Ascending, by
// location_name.
loaderId = i;
String sortOrder = MptContract.StopDetailEntry.COLUMN_LOCATION_NAME +
ASCENDING_SORT_ORDER;
Uri nonFavoriteStopDetailUri = MptContract.StopDetailEntry.buildFavoriteStopsUri(
MptContract.StopDetailEntry.FAVORITE_FLAG);
return new CursorLoader(getActivity(),
nonFavoriteStopDetailUri,
STOP_DETAILS_COLUMNS,
null,
null,
sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mFavoriteStopDetailAdapter.swapCursor(data);
mCursorRowCnt = data.getCount();
if (mCursorRowCnt == 0) {
mListView.setVisibility(View.GONE);
mEmptyView.setVisibility(View.VISIBLE);
setEmptyViewText(TAG);
} else {
clearEmptyViewText();
mListView.setVisibility(View.VISIBLE);
mEmptyView.setVisibility(View.GONE);
}
}
public void reloadLoader() {
getLoaderManager().restartLoader(loaderId, null, this);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mFavoriteStopDetailAdapter.swapCursor(null);
}
public void setIsInSettingsActivityFlag() {
mIsInSettingsActivityFlag = true;
}
/**
* Passes selected stop details to the parent activity.
*
* @param adapterView
* @param position
*/
private void handleRowSelected(AdapterView<?> adapterView, int position) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
if (mIsInSettingsActivityFlag) {
mListener.updateWidgetStopDetails(
cursor.getString(COL_STOP_DETAILS_STOP_ID),
cursor.getString(COL_STOP_DETAILS_LOCATION_NAME));
}
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FavoriteStopsFragment.OnFavoriteStopsFragmentInteractionListener) {
mListener = (FavoriteStopsFragment.OnFavoriteStopsFragmentInteractionListener) context;
Log.v(TAG, "onAttach - : mListener" + mListener);
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
if (!isVisible || !mIsShowOptionsMenu) {
menu.findItem(R.id.action_train_stops_nearby).setVisible(false);
menu.findItem(R.id.action_stops_nearby).setVisible(false);
menu.findItem(R.id.action_disruptions).setVisible(false);
menu.findItem(R.id.action_about).setVisible(false);
menu.findItem(R.id.action_reload_database).setVisible(false);
} else {
menu.findItem(R.id.action_train_stops_nearby).setVisible(true);
menu.findItem(R.id.action_stops_nearby).setVisible(true);
menu.findItem(R.id.action_disruptions).setVisible(true);
menu.findItem(R.id.action_about).setVisible(true);
menu.findItem(R.id.action_reload_database).setVisible(true);
}
super.onPrepareOptionsMenu(menu);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_favorite_stops, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_train_stops_nearby) {
mListener.startStopsNearbySearch(true);
return true;
} else if (id == R.id.action_stops_nearby) {
mListener.startStopsNearbySearch(false);
return true;
} else if (id == R.id.action_disruptions) {
mListener.getDisruptionsDetails();
return true;
} else if (id == R.id.action_reload_database) {
mListener.reloadDatabase();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFavoriteStopsFragmentInteractionListener {
void startNextDeparturesSearch(StopDetails stopDetails);
void showStopOnMap(String stopName, LatLngDetails latLonDetails);
void startStopsNearbySearch(boolean trainsOnly);
void getDisruptionsDetails();
void updateStopDetailRow(int id, String favoriteColumnValue);
void reloadDatabase();
void updateWidgetStopDetails(String stopId, String locationName);
}
}
| true |
5f2255bb90f5135d89f87166ba09cb9dfd3930f2 | Java | wapio/SAMPLE_CONVERT_PROJECT | /SAMPLE_CONVERT_PROJECT/src/main/java/wapio/convert/FileTypeConverter.java | UTF-8 | 4,136 | 2.78125 | 3 | [] | no_license | package wapio.convert;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class FileTypeConverter {
public static String convertJsonToXml(String filepath) {
System.out.println("INFO JSON->XML変換処理を開始します。");
String stringJson = getStringFileData(filepath);
if (stringJson == null | stringJson.equals("")) { System.out.println("ERROR JSON→XML変換処理を終了します。"); return null; }
Map<String, Object> mapJson = null;
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
try {
Object objectJson = scriptEngine.eval(String.format("(%s)", stringJson));
mapJson = convertObjectJsonToMap(objectJson);
} catch (ScriptException e) {
System.out.println("ERROR スクリプトの実行で異常終了しました。処理を終了します。");
e.printStackTrace();
}
outputMapJsonToXmlFile(mapJson, filepath);
return mapJson.toString();
}
private static void outputMapJsonToXmlFile(Map<String, Object> mapJson, String filepath) {
String outputFilePath = filepath.replaceAll("\\.json$", ".xml");
System.out.println("INFO JSON->XMLファイルを出力します。");
System.out.println("INFO ファイル出力先 -> " + outputFilePath);
try (XMLEncoder xmlEncorder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(outputFilePath)))) {
xmlEncorder.writeObject(mapJson);
} catch (Exception e) {
System.out.println("ERROR 出力用XMLファイルができませんでした。処理を終了します。");
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private static Map<String, Object> convertObjectJsonToMap(Object objectJson) {
Map<String, Object> mapJson = new LinkedHashMap<String, Object>();
try {
Object[] keysOfJson = ((java.util.Set<Object>)objectJson.getClass().getMethod("keySet").invoke(objectJson)).toArray();
if (keysOfJson == null | keysOfJson.length <= 0) { System.out.println("ERROR Jsonデータのプロパティ名配列の取得に失敗しました。処理を終了します。"); return null; }
Method methodToGetValueOfJson = objectJson.getClass().getMethod("get", Class.forName("java.lang.Object"));
for (Object key : keysOfJson) {
Object value = methodToGetValueOfJson.invoke(objectJson, key);
Class<?> javaScriptClass = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror");
if (javaScriptClass.isInstance(value)) {
mapJson.put(key.toString(), convertObjectJsonToMap(value));
} else {
mapJson.put(key.toString(), methodToGetValueOfJson.invoke(objectJson, key));
}
}
} catch (ClassNotFoundException e) {
System.out.println("ERROR JavaScriptのクラスが見つかりませんでした。処理を終了します。");
e.printStackTrace();
} catch (NoSuchMethodException e) {
System.out.println("ERROR メソッドが見つかりませんでした。処理を終了します。");
e.printStackTrace();
} catch (Exception e) {
System.out.println("ERROR 処理の異常終了を検知しました。エラー内容を確認してください。");
e.printStackTrace();
}
return mapJson;
}
private static String getStringFileData(String filepath) {
File f = new File(filepath);
if (!f.exists() | !f.isFile()) { System.out.println("ERROR 有効なファイルパスが指定されていません。"); return null; }
String stringJson = null;
try (FileInputStream input = new FileInputStream(f)) {
byte[] buf = new byte[new Long(f.length()).intValue()];
input.read(buf);
if (buf.length <= 0) { System.out.println("ERROR JSONファイルデータの取得ができませんでした。"); return null; }
stringJson = new String(buf, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return stringJson;
}
} | true |
56ef8db283dffbaae931f36801caf9a1bcb69b26 | Java | anatasic/MovieRecommender | /MovieRecommender/src/rs/fon/is/movies/util/URIGenerator.java | UTF-8 | 445 | 2.515625 | 3 | [
"MIT"
] | permissive | package rs.fon.is.movies.util;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;
import rs.fon.is.movies.domain.Thing;
public class URIGenerator {
public static <T extends Thing> URI generateURI(T resource) throws URISyntaxException{
String uri = Constants.NS + resource.getClass().getSimpleName()+ "/" + UUID.randomUUID();
// System.out.println(uri);
return new URI(uri);
}
}
| true |
4ed1f91a163a2abf383c0e60515b707cbd9bd4ec | Java | nhutam123/C0221G1-le-nhu-tam | /module4/case_study/src/main/java/com/example/case_study/dto/EmployeeDto.java | UTF-8 | 2,535 | 2.328125 | 2 | [] | no_license | package com.example.case_study.dto;
import com.example.case_study.model.entity.Contract;
import com.example.case_study.model.entity.Degree;
import com.example.case_study.model.entity.Division;
import com.example.case_study.model.entity.Position;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.validation.constraints.Pattern;
import java.util.Date;
import java.util.List;
public class EmployeeDto {
private Integer id;
private String name;
@JsonFormat( pattern = "MM/dd/yyyy")
private Date birthday;
private Double salary;
private String phoneNumber;
@Pattern(regexp = "^[a-zA-Z0-9]{1,9}@[0-9a-zA-Z]{1,9}.[0-9a-zA-Z]{1,9}")
private String email;
private String address;
private Position position;
private Division division;
private Degree degree;
List<Contract> contractList;
public EmployeeDto() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public Division getDivision() {
return division;
}
public void setDivision(Division division) {
this.division = division;
}
public Degree getDegree() {
return degree;
}
public void setDegree(Degree degree) {
this.degree = degree;
}
public List<Contract> getContractList() {
return contractList;
}
public void setContractList(List<Contract> contractList) {
this.contractList = contractList;
}
}
| true |
f38bf0163ee45cfd4a6d32058f8b9b06b5766131 | Java | heavensay/treasure | /treasure-common/src/test/java/com/helix/common/security/MessageDigestUtilTest.java | UTF-8 | 2,132 | 2.9375 | 3 | [] | no_license | package com.helix.common.security;
import com.helix.common.codec.HexUtil;
import org.junit.Test;
import java.security.MessageDigest;
import java.security.Signature;
import java.util.Base64;
/**
* @author lijianyu
* @date 2019/3/13 19:39
*/
public class MessageDigestUtilTest {
private static String message = "abcd";
@Test
public void sha256() throws Exception{
MessageDigest sha256 = MessageDigest.getInstance("sha-256");
sha256.update(message.getBytes("utf-8"));
String hexStr = HexUtil.encodeHexStr(sha256.digest());
String hexStr2 = new String(sha256.digest());
System.out.println(hexStr);
System.out.println(hexStr2);
}
@Test
public void sha256with() throws Exception{
Signature signature = Signature.getInstance("SHA256WithRSA");
signature.update(message.getBytes("utf-8"));
signature.sign();
}
@Test
public void md5() throws Exception{
MessageDigest md5 = MessageDigest.getInstance("md5");
md5.update(message.getBytes("utf-8"));
byte[] byteMd5 = md5.digest();
String hexStr = HexUtil.encodeHexStr(byteMd5);
String str = new String(byteMd5);
String base64 = Base64.getEncoder().encodeToString(byteMd5);
System.out.println(hexStr);
System.out.println(str);
System.out.println(base64);
}
/**
* 测试update和digest中传入参数区别;
* md5.update(byte1),md5.digest(byte2) == md5.digest(byte1+byte2)
* @throws Exception
*/
@Test
public void md5ForUpdateAndDigest() throws Exception{
MessageDigest md5 = MessageDigest.getInstance("md5");
md5.reset();
md5.update("123".getBytes("utf-8"));
System.out.println(HexUtil.encodeHexStr(md5.digest("abc".getBytes("utf-8"))));
md5.reset();
System.out.println(HexUtil.encodeHexStr(md5.digest("123abc".getBytes("utf-8"))));
}
@Test
public void md5Encrypt(){
System.out.println(MessageDigestUtil.md5HexStr("abc"));
System.out.println(MessageDigestUtil.md5Base64("abc"));
}
}
| true |
01783f52b8523b436012700de1d8999ba94145a0 | Java | soufianem370/android | /app/src/main/java/com/app/demopfe/ListActivity.java | UTF-8 | 1,403 | 2.0625 | 2 | [] | no_license | package com.app.demopfe;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import static com.app.demopfe.Utils.getVilles;
public class ListActivity extends AppCompatActivity implements VilleViewHolder.ClickItem {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar=findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.title));
toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
VilleAdapter villeAdapter = new VilleAdapter(this);
villeAdapter.setList(getVilles(this));
recyclerView.setAdapter(villeAdapter);
}
@Override
public void onClickItem(int position) {
Intent eventIntent=new Intent(this, DetailCityActivity.class);
eventIntent.putExtra("VILLE",position);
startActivity(eventIntent);
}
}
| true |
bd5508941d2f2af18c9e8f035c2b7617bb7bdfb5 | Java | dengjiaping/hujia-android | /hujia-android/app/src/main/java/com/ihujia/hujia/person/adapter/IntegralPageAdapter.java | UTF-8 | 729 | 2.125 | 2 | [] | no_license | package com.ihujia.hujia.person.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import com.ihujia.hujia.person.controller.IntegralFragment;
import java.util.List;
/**
* Created by zhaoweiwei on 2016/12/22.
*/
public class IntegralPageAdapter extends FragmentPagerAdapter {
List<IntegralFragment> fragments;
public IntegralPageAdapter(FragmentManager fm, List<IntegralFragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
| true |
15d159048eecf3034f346a1a185fe2bbd5f8b039 | Java | NikKosse/MizzMaps | /app/src/main/java/com/example/derek/teamb/ListenerForMap.java | UTF-8 | 1,544 | 2.53125 | 3 | [] | no_license | package com.example.derek.teamb;
/**
* Created by Derek on 10/4/2015.
*/
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
public class ListenerForMap implements TextWatcher{
public static final String TAG = "Listener.java";
Context context;
public ListenerForMap(Context context){
this.context = context;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence userInput, int start, int before, int count) {
try{
// if you want to see in the logcat what the user types
Log.e(TAG, "User input: " + userInput);
Map map = ((Map) context);
// update the adapater
map.myAdapter.notifyDataSetChanged();
// get suggestions from the database
GetObject[] myObjs = map.databaseH.read(userInput.toString());
// update the adapter
map.myAdapter = new CustomMapArrayAdapter(map, R.layout.list_view_row, myObjs);
map.myAutoComplete.setAdapter(map.myAdapter);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} | true |
b640c02bf45f796c553a44a99d100a2077783d50 | Java | pierrot-lc/bataille_navale | /bataille_navale/contenu/etats/Mer.java | UTF-8 | 250 | 2.25 | 2 | [] | no_license | package bataille_navale.contenu.etats;
public class Mer extends Contenu {
String name = "Mer";
public Mer() {
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
| true |
0e48b8ee0a71d3063d01079dd034270be0bb6560 | Java | yarikwest/Warszaty_I_Java | /src/Gra_w_zgadywanie_liczb_2/Main.java | UTF-8 | 1,070 | 3.75 | 4 | [] | no_license | package Gra_w_zgadywanie_liczb_2;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int min = 0, max = 1000, count = 1, answer;
Scanner scanner = new Scanner(System.in);
System.out.println("Pomyśl liczbę od 0 do 1000, a ja ją zgadnę w max.10 próbach");
do {
int guess = ((max - min) / 2) + min;
System.out.println("Zgaduję: " + guess);
answer = getAnswer(scanner);
if (answer == 1)
max = guess;
else if (answer == 2)
min = guess;
count++;
if (count > 10) {
System.out.println("nie oszukuj!");
break;
}
} while (answer != 3);
System.out.println("Wygrałem!");
scanner.close();
}
private static int getAnswer(Scanner scanner) {
int answer;
System.out.println("Wybierz:\t1.Za dużo\t2.Za mało\t3.Zgadłeś");
answer = scanner.nextInt();
return answer;
}
}
| true |
1e9bbb50e29a7e6f48cd1bfcf3557283a70b5a56 | Java | mrcwojcik/hibernate_kurs_dabrowski | /src/main/java/pl/mrcwojcik/hibernate/lessons/relations/App06OneToManyBidirectional.java | UTF-8 | 1,015 | 2.640625 | 3 | [] | no_license | package pl.mrcwojcik.hibernate.lessons.relations;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pl.mrcwojcik.hibernate.App;
import pl.mrcwojcik.hibernate.entity.Review;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;
public class App06OneToManyBidirectional {
private static Logger logger = LogManager.getLogger(App.class);
private static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("unit");
public static void main(String[] args) {
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
List<Review> reviews = em.createQuery("SELECT r FROM Review r").getResultList();
for (Review r: reviews){
logger.info(r);
logger.info(r.getProduct());
}
em.getTransaction().commit();
em.close();
}
}
| true |
eacd9b895ec4182fef84369fd5d10d1bc78365dd | Java | bartekduda/mag | /src/operations/CargoReadWrite.java | UTF-8 | 2,051 | 3.046875 | 3 | [] | no_license | package operations;
import model.Cargo;
import utility.Database;
import java.io.*;
import java.time.LocalDate;
public class CargoReadWrite {
private static String filename = "cargo.csv";
private static String spliter = ",";
public static void writeCargoToFile(){
try(PrintWriter outS = new PrintWriter(new BufferedWriter(new FileWriter(filename)))){
for(Cargo cargo : Database.lisOfCargo){
outS.write(cargo.getID() + spliter + cargo.getCategory() + spliter + cargo.getDescription()
+ spliter + cargo.getMassOfPackage() + spliter + cargo.getNumberOfPackages()
+ spliter + cargo.getAssignedWarehouse() + spliter + cargo.getArrivalDate());
outS.println();
}
}catch (IOException e){
System.out.println(e.getMessage());
}
}
public static void readCargoFromFile(){
try(BufferedReader inS = new BufferedReader(new FileReader(filename))){
int id;
String category;
String description;
double massOfPackage;
int numberOfPackages;
int assignedWarehouse;
LocalDate arrivalDate;
String line;
String[] lineArray;
while ((line = inS.readLine()) != null){
lineArray = line.split(spliter);
id = Integer.parseInt(lineArray[0]);
category = lineArray[1];
description = lineArray[2];
massOfPackage = Double.parseDouble(lineArray[3]);
numberOfPackages = Integer.parseInt(lineArray[4]);
assignedWarehouse = Integer.parseInt(lineArray[5]);
arrivalDate = LocalDate.parse(lineArray[6]);
Database.lisOfCargo.add(new Cargo(id,category,description,massOfPackage,
numberOfPackages,assignedWarehouse,arrivalDate));
}
}catch (IOException e){
System.out.println(e.getMessage());
}
}
}
| true |
8c77ad55b6cb20f76caaaa5d07f3409e46a01fec | Java | adrianryt/DarwinProjektPO | /src/objects/Genotype.java | UTF-8 | 2,099 | 2.9375 | 3 | [] | no_license | package objects;
import map.MapDirection;
import java.util.Random;
public class Genotype {
private int[] GeneArr = {0,0,0,0,0,0,0,0};
private Random generator = new Random();
private int genesNum;
public int[] getGeneArr() {
return GeneArr;
}
public Genotype(int nGenes){
genesNum = nGenes;
for(int i=0; i < genesNum; i++){
GeneArr[generator.nextInt(8)]++;
}
validation();
}
private void validation(){
for(int i=0; i<8; i++){
while(GeneArr[i] == 0){
int x = generator.nextInt(8);
if(GeneArr[x] > 1) {
GeneArr[x]--;
GeneArr[i]++;
}
}
}
}
public MapDirection getNextMove(){
int n = generator.nextInt(genesNum) + 1;
int GenIdx = 0;
while(true){
if(n - this.GeneArr[GenIdx] > 0){
n-=this.GeneArr[GenIdx];
GenIdx++;
}
else{
return MapDirection.values()[GenIdx];
}
}
}
private int getIGenFromGenotype(Genotype gen, int i){
int n = i;
int GenIdx =0;
while(n > 0){
if(n - GeneArr[GenIdx] > 0){
n-=GeneArr[GenIdx];
GenIdx++;
}
else{
return GenIdx;
}
}
return GenIdx;
}
public Genotype getGenotypeForChild(Genotype genB){
Genotype result = new Genotype(this.genesNum);
result.GeneArr = new int[]{0,0,0,0,0,0,0,0};
int point1 = generator.nextInt(this.genesNum / 2)+1;
int point2 = generator.nextInt(this.genesNum / 2)+1 + genesNum/2;
for(int i = 0; i < this.genesNum; i++){
if(i > point1 && i < point2){
result.GeneArr[getIGenFromGenotype(genB, i)]++;
}
else{
result.GeneArr[getIGenFromGenotype(this, i)]++;
}
}
result.validation();
return result;
}
}
| true |
1e821a251d6d89eb156bd2fcd604f779f548a38f | Java | samufacanha2/MyTwitter | /MyTwitter/src/br/ufc/dc/poo/MyTwitter/Twitter/Exceptions/SIException.java | ISO-8859-1 | 300 | 2.484375 | 2 | [] | no_license | package br.ufc.dc.poo.MyTwitter.Twitter.Exceptions;
public class SIException extends Exception {
private static final long serialVersionUID = 1L;
public SIException() {
super("Voce no pode seguir a si mesmo! ");
}
public String getMessage() {
return super.getMessage();
}
}
| true |
e78ca4cf1e02157ef13d999fb1cc3e1921344357 | Java | Army1990/Army_LDJ | /multiDemo/src/main/java/com/ichoice/egan/eganview/Utils/Bimp.java | UTF-8 | 2,359 | 2.109375 | 2 | [] | no_license | package com.ichoice.egan.eganview.Utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import com.maychoo.meifou.R;
import org.xutils.image.ImageOptions;
import org.xutils.x;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 刘大军 on 2015/12/10.
*/
public class Bimp {
public static int max = 0;
public static boolean act_bool = true;
public static List<Bitmap> bmp = new ArrayList<Bitmap>();
//图片sd地址 上传服务器时把图片调用下面方法压缩后 保存到临时文件夹 图片压缩后小于100KB,失真度不明显
public static List<String> drr = new ArrayList<String>();
public static Bitmap revitionImageSize(String path) throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(
new File(path)));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
in.close();
int i = 0;
Bitmap bitmap = null;
while (true) {
if ((options.outWidth >> i <= 1000)
&& (options.outHeight >> i <= 1000)) {
in = new BufferedInputStream(
new FileInputStream(new File(path)));
options.inSampleSize = (int) Math.pow(2.0D, i);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(in, null, options);
break;
}
i += 1;
}
return bitmap;
}
// 下载图片
private static void downAndSetImage(ImageView v, String imagePath) {
ImageOptions.Builder builder = new ImageOptions.Builder();
builder.setLoadingDrawableId(R.mipmap.mflogo_gray);
builder.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
builder.setFailureDrawableId(R.mipmap.mflogo_gray);
x.image().bind(v, imagePath, builder.build());
}
// 下载图片设置为圆角图片
private static void downAndSetCircleImage(ImageView v, String imagePath) {
ImageOptions.Builder builder = new ImageOptions.Builder();
builder.setCircular(true);
builder.setLoadingDrawableId(R.mipmap.mflogo_gray);
builder.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
builder.setFailureDrawableId(R.mipmap.mflogo_gray);
x.image().bind(v, imagePath, builder.build());
}
}
| true |
a2b7b29dcd805583a126ebc3be5f657b754f5fa6 | Java | dngronglong/carloan | /src/main/java/org/project/loan/beans/CustomerBean.java | UTF-8 | 17,721 | 2.171875 | 2 | [] | no_license | package org.project.loan.beans;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* 客户基本信息实体类
* @author 李山
*
*/
@Entity
@Table(name="t_customer")
public class CustomerBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name="customer_id")
@GenericGenerator(name="hibernate.strategy", strategy="identity")
@GeneratedValue(generator="hibernate.strategy")
private int customerId;//客户信息的id
@Column(name="customer_lendTime")
private Date customer_lendTime;//客户希望申请最长还款期限
@Column(name="customer_application",length=100)
private String customerApplication;//客户的车贷申请表
@Column(name="customer_child",length=100)
private String customerChild;//客户有无子女
@Column(name="customer_chum",length=100)
private String customerChum;//客户有无共同的居住者
@Column(name="customer_comAdderss",length=100)
private String customerComAdderss;//客户的工作单位地址
@Column(name="customer_commissioner",length=100)
private String customerCommissioner;//客户的车贷专员
@Column(name="customer_comNun",length=11)
private int customerComNun;//客户的单位电话
@Column(name="customer_company",length=100)
private String customerCompany;//客户的单位名称
@Column(name="customer_date")
private Date customerDate;//客户申请的日期
@Column(name="customer_demand",length=100)
private String customerDemand;//客户的借款详细用途
@Column(name="customer_department",length=100)
private String customerDepartment;//客户在单位的所在部门
@Column(name="customer_duty",length=100)
private String customerDuty;//客户在单位的职务
@Column(name="customer_education",length=100)
private String customerEducation;//客户的最高学历
@Column(name="customer_enclosure",length=100)
private String customerEnclosure;//客户申请资料的其他附件
@Column(name="customer_house",length=100)
private String customerHouse;//客户的房产状态
@Column(name="customer_idcard",length=100)
private String customerIdcard;//客户的身份证(原件)
@Column(name="customer_lendLimit",length=11)
private int customerIendLimit;//客户的希望申请借款额度
@Column(name="customer_income",length=11)
private int customerIncome;//客户的月收入
@Column(name="customer_joinCom")
private Date customerJoinCom;//客户进入该单位时间
@Column(name="customer_know",length=100)
private String customerKnow;//客户如何得知惠普
@Column(name="customer_marry",length=100)
private String customerMarry;//客户的婚姻状况
@Column(name="customer_newAddress",length=100)
private String customerNewAddress;//客户的现住址
@Column(name="customer_payLimit",length=11)
private int customerPayLimit;//客户可承受月还款额度
@Column(name="customer_phone",length=11)
private int customerPhone;//客户的手机号码
@Column(name="customer_postcode",length=11)
private int customerPostcode;//客户的居住地的邮政编码
@Column(name="customer_quality",length=100)
private String customerQuality;//客户所在单位的单位性质
@Column(name="customer_saleman",length=100)
private String customerSaleman;//客户的业务员姓名
@Column(name="customer_scale",length=11)
private int customerScale;//客户所在单位的公司规模
@Column(name="customer_sort",length=100)
private String customerSort;//客户所在单位的行业类别
@Column(name="customer_tel",length=11)
private int customerTel;//客户电话号码
@Column(name="customer_type",length=100)
private String customerType;//客户类型
@OneToMany(fetch=FetchType.LAZY)
@Cascade(value= {CascadeType.PERSIST})
@JoinColumn(name="fk_customer_id")
private Set<ContactsBean> customerContactsList;//该客户有哪些联系人
@OneToOne(fetch=FetchType.LAZY)
@Cascade(value= {CascadeType.ALL})
@JoinColumn(name="fk_idcard_id")
private IdCardBean customerIdcardBean;//客户的身份证
public CustomerBean(){
}
/**
* 得到客户的id
* @return the customerId
*/
public int getCustomerId() {
return customerId;
}
/**
* 设置客户的id
* @param customerId the customerId to set
*/
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
/**
* 得到客户的希望申请最长还款期限
* @return the customer_lendTime
*/
public Date getCustomer_lendTime() {
return customer_lendTime;
}
/**
* 设置客户的希望申请最长还款期限
* @param customer_lendTime the customer_lendTime to set
*/
public void setCustomer_lendTime(Date customer_lendTime) {
this.customer_lendTime = customer_lendTime;
}
/**
* 得到客户的车贷申请表
* @return the customerApplication
*/
public String getCustomerApplication() {
return customerApplication;
}
/**
* 设置客户的车贷申请表
* @param customerApplication the customerApplication to set
*/
public void setCustomerApplication(String customerApplication) {
this.customerApplication = customerApplication;
}
/**
* 得到客户的有无子女的情况
* @return the customerChild
*/
public String getCustomerChild() {
return customerChild;
}
/**
* 设置客户的有无子女的情况
* @param customerChild the customerChild to set
*/
public void setCustomerChild(String customerChild) {
this.customerChild = customerChild;
}
/**
* 得到客户的有误共同的居住者情况
* @return the customerChum
*/
public String getCustomerChum() {
return customerChum;
}
/**
* 设置客户的有误共同的居住者情况
* @param customerChum the customerChum to set
*/
public void setCustomerChum(String customerChum) {
this.customerChum = customerChum;
}
/**
* 得到客户的单位的地址
* @return the customerComAdderss
*/
public String getCustomerComAdderss() {
return customerComAdderss;
}
/**
* 设置客户的单位的地址
* @param customerComAdderss the customerComAdderss to set
*/
public void setCustomerComAdderss(String customerComAdderss) {
this.customerComAdderss = customerComAdderss;
}
/**
* 得到客户的车贷专员
* @return the customerCommissioner
*/
public String getCustomerCommissioner() {
return customerCommissioner;
}
/**
* 设置客户的车贷专员
* @param customerCommissioner the customerCommissioner to set
*/
public void setCustomerCommissioner(String customerCommissioner) {
this.customerCommissioner = customerCommissioner;
}
/**
* 得到客户的单位电话
* @return the customerComNun
*/
public int getCustomerComNun() {
return customerComNun;
}
/**
* 设置客户的单位电话
* @param customerComNun the customerComNun to set
*/
public void setCustomerComNun(int customerComNun) {
this.customerComNun = customerComNun;
}
/**
* 得到客户的单位的全名
* @return the customerCompany
*/
public String getCustomerCompany() {
return customerCompany;
}
/**
* 设置客户的单位的全名
* @param customerCompany the customerCompany to set
*/
public void setCustomerCompany(String customerCompany) {
this.customerCompany = customerCompany;
}
/**
* 得到客户的申请日期
* @return the customerDate
*/
public Date getCustomerDate() {
return customerDate;
}
/**
* 设置客户的申请日期
* @param customerDate the customerDate to set
*/
public void setCustomerDate(Date customerDate) {
this.customerDate = customerDate;
}
/**
* 得到客户的借款用途
* @return the customerDemand
*/
public String getCustomerDemand() {
return customerDemand;
}
/**
* 设置客户的借款用途
* @param customerDemand the customerDemand to set
*/
public void setCustomerDemand(String customerDemand) {
this.customerDemand = customerDemand;
}
/**
* 得到客户在单位所在的部门
* @return the customerDepartment
*/
public String getCustomerDepartment() {
return customerDepartment;
}
/**
* 设置客户在单位所在的部门
* @param customerDepartment the customerDepartment to set
*/
public void setCustomerDepartment(String customerDepartment) {
this.customerDepartment = customerDepartment;
}
/**
* 得到客户在单位的职位
* @return the customerDuty
*/
public String getCustomerDuty() {
return customerDuty;
}
/**
* 设置客户在单位的职位
* @param customerDuty the customerDuty to set
*/
public void setCustomerDuty(String customerDuty) {
this.customerDuty = customerDuty;
}
/**
* 得到客户的最高学历
* @return the customerEducation
*/
public String getCustomerEducation() {
return customerEducation;
}
/**
* 设置客户的最高学历
* @param customerEducation the customerEducation to set
*/
public void setCustomerEducation(String customerEducation) {
this.customerEducation = customerEducation;
}
/**
* 得到客户的申请资料的其他附件
* @return the customerEnclosure
*/
public String getCustomerEnclosure() {
return customerEnclosure;
}
/**
* 设置客户的申请资料的其他附件
* @param customerEnclosure the customerEnclosure to set
*/
public void setCustomerEnclosure(String customerEnclosure) {
this.customerEnclosure = customerEnclosure;
}
/**
* 得到客户的房产状态
* @return the customerHouse
*/
public String getCustomerHouse() {
return customerHouse;
}
/**
* 设置客户的房产状态
* @param customerHouse the customerHouse to set
*/
public void setCustomerHouse(String customerHouse) {
this.customerHouse = customerHouse;
}
/**
* 得到客户的身份证(原件)
* @return the customerIdcard
*/
public String getCustomerIdcard() {
return customerIdcard;
}
/**
* 设置客户的身份证(原件)
* @param customerIdcard the customerIdcard to set
*/
public void setCustomerIdcard(String customerIdcard) {
this.customerIdcard = customerIdcard;
}
/**
* 得到
* @return the customerIendLimit
*/
public int getCustomerIendLimit() {
return customerIendLimit;
}
/**
* 设置客户所希望借款的额度
* @param customerIendLimit the customerIendLimit to set
*/
public void setCustomerIendLimit(int customerIendLimit) {
this.customerIendLimit = customerIendLimit;
}
/**
* 得到客户的月收入
* @return the customerIncome
*/
public int getCustomerIncome() {
return customerIncome;
}
/**
* 设置客户的月收入
* @param customerIncome the customerIncome to set
*/
public void setCustomerIncome(int customerIncome) {
this.customerIncome = customerIncome;
}
/**
* 得到客户进入单位的时间
* @return the customerJoinCom
*/
public Date getCustomerJoinCom() {
return customerJoinCom;
}
/**
* 设置客户进入单位的时间
* @param customerJoinCom the customerJoinCom to set
*/
public void setCustomerJoinCom(Date customerJoinCom) {
this.customerJoinCom = customerJoinCom;
}
/**
* 得到客户是如何知道惠普的
* @return the customerKnow
*/
public String getCustomerKnow() {
return customerKnow;
}
/**
* 设置客户是如何知道惠普的
* @param customerKnow the customerKnow to set
*/
public void setCustomerKnow(String customerKnow) {
this.customerKnow = customerKnow;
}
/**
* 得到客户是否结婚的情况
* @return the customerMarry
*/
public String getCustomerMarry() {
return customerMarry;
}
/**
* 设置客户是否结婚的情况
* @param customerMarry the customerMarry to set
*/
public void setCustomerMarry(String customerMarry) {
this.customerMarry = customerMarry;
}
/**
* 得到客户的现居住地的地址
* @return the customerNewAddress
*/
public String getCustomerNewAddress() {
return customerNewAddress;
}
/**
* 设置客户的现居住地的地址
* @param customerNewAddress the customerNewAddress to set
*/
public void setCustomerNewAddress(String customerNewAddress) {
this.customerNewAddress = customerNewAddress;
}
/**
* 得到客户可承受的还款额度
* @return the customerPayLimit
*/
public int getCustomerPayLimit() {
return customerPayLimit;
}
/**
* 设置客户可承受的还款额度
* @param customerPayLimit the customerPayLimit to set
*/
public void setCustomerPayLimit(int customerPayLimit) {
this.customerPayLimit = customerPayLimit;
}
/**
* 得到客户的手机号码
* @return the customerPhone
*/
public int getCustomerPhone() {
return customerPhone;
}
/**
* 设置客户的手机号码
* @param customerPhone the customerPhone to set
*/
public void setCustomerPhone(int customerPhone) {
this.customerPhone = customerPhone;
}
/**
* 得到客户的居住地的邮政编码
* @return the customerPostcode
*/
public int getCustomerPostcode() {
return customerPostcode;
}
/**
* 设置客户的居住地的邮政编码
* @param customerPostcode the customerPostcode to set
*/
public void setCustomerPostcode(int customerPostcode) {
this.customerPostcode = customerPostcode;
}
/**
* 得到客户所在单位的类型
* @return the customerQuality
*/
public String getCustomerQuality() {
return customerQuality;
}
/**
* 设置客户所在单位的类型
* @param customerQuality the customerQuality to set
*/
public void setCustomerQuality(String customerQuality) {
this.customerQuality = customerQuality;
}
/**
* 得到客户的业务员姓名
* @return the customerSaleman
*/
public String getCustomerSaleman() {
return customerSaleman;
}
/**
* 设置客户的业务员姓名
* @param customerSaleman the customerSaleman to set
*/
public void setCustomerSaleman(String customerSaleman) {
this.customerSaleman = customerSaleman;
}
/**
* 得到客户所在单位的规模
* @return the customerScale
*/
public int getCustomerScale() {
return customerScale;
}
/**
* 设置客户所在单位的规模
* @param customerScale the customerScale to set
*/
public void setCustomerScale(int customerScale) {
this.customerScale = customerScale;
}
/**
* 得到客户所在 行业的类别
* @return the customerSort
*/
public String getCustomerSort() {
return customerSort;
}
/**
* 设置客户所在 行业的类别
* @param customerSort the customerSort to set
*/
public void setCustomerSort(String customerSort) {
this.customerSort = customerSort;
}
/**
* 得到客户的电话号码
* @return the customerTel
*/
public int getCustomerTel() {
return customerTel;
}
/**
* 设置客户的电话号码
* @param customerTel the customerTel to set
*/
public void setCustomerTel(int customerTel) {
this.customerTel = customerTel;
}
/**
* 得到客户的类别
* @return the customerType
*/
public String getCustomerType() {
return customerType;
}
/**
* 设置客户的类别
* @param customerType the customerType to set
*/
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
/**
* 得到客户的身份证
* @return the customerIdcardBean
*/
public IdCardBean getCustomerIdcardBean() {
return customerIdcardBean;
}
/**
* 设置客户的身份证
* @param customerIdcardBean the customerIdcardBean to set
*/
public void setCustomerIdcardBean(IdCardBean customerIdcardBean) {
this.customerIdcardBean = customerIdcardBean;
}
/**
* 得到客户联系人的集合
* @return the customerContactsList
*/
public Set<ContactsBean> getCustomerContactsList() {
return customerContactsList;
}
/**
* 设置客户联系人
* @param customerContactsList the customerContactsList to set
*/
public void setCustomerContactsList(Set<ContactsBean> customerContactsList) {
this.customerContactsList = customerContactsList;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "CustomerBean [customerId=" + customerId + ", customer_lendTime=" + customer_lendTime
+ ", customerApplication=" + customerApplication + ", customerChild=" + customerChild
+ ", customerChum=" + customerChum + ", customerComAdderss=" + customerComAdderss
+ ", customerCommissioner=" + customerCommissioner + ", customerComNun=" + customerComNun
+ ", customerCompany=" + customerCompany + ", customerDate=" + customerDate + ", customerDemand="
+ customerDemand + ", customerDepartment=" + customerDepartment + ", customerDuty=" + customerDuty
+ ", customerEducation=" + customerEducation + ", customerEnclosure=" + customerEnclosure
+ ", customerHouse=" + customerHouse + ", customerIdcard=" + customerIdcard + ", customerIendLimit="
+ customerIendLimit + ", customerIncome=" + customerIncome + ", customerJoinCom=" + customerJoinCom
+ ", customerKnow=" + customerKnow + ", customerMarry=" + customerMarry + ", customerNewAddress="
+ customerNewAddress + ", customerPayLimit=" + customerPayLimit + ", customerPhone=" + customerPhone
+ ", customerPostcode=" + customerPostcode + ", customerQuality=" + customerQuality
+ ", customerSaleman=" + customerSaleman + ", customerScale=" + customerScale + ", customerSort="
+ customerSort + ", customerTel=" + customerTel + ", customerType=" + customerType
+ ", customerContactsList=" + customerContactsList + ", customerIdcardBean=" + customerIdcardBean + "]";
}
} | true |
50173cd7777f0770c2f3a7384c826f1b78a46168 | Java | Lith0102/springBoot2.0 | /src/main/java/com/core/AllowAnonymous.java | UTF-8 | 175 | 1.890625 | 2 | [] | no_license | package com.core;
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AllowAnonymous {
}
| true |
51a9d5fc83c54d58bf983adff056518c96d5b63a | Java | apache/cloudstack | /engine/schema/src/main/java/com/cloud/vm/dao/NicIpAliasDaoImpl.java | UTF-8 | 7,155 | 1.867188 | 2 | [
"GPL-2.0-only",
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown"
] | permissive | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.vm.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.vm.NicIpAlias;
@Component
public class NicIpAliasDaoImpl extends GenericDaoBase<NicIpAliasVO, Long> implements NicIpAliasDao {
private final SearchBuilder<NicIpAliasVO> AllFieldsSearch;
private final GenericSearchBuilder<NicIpAliasVO, String> IpSearch;
protected NicIpAliasDaoImpl() {
super();
AllFieldsSearch = createSearchBuilder();
AllFieldsSearch.and("instanceId", AllFieldsSearch.entity().getVmId(), Op.EQ);
AllFieldsSearch.and("network", AllFieldsSearch.entity().getNetworkId(), Op.EQ);
AllFieldsSearch.and("address", AllFieldsSearch.entity().getIp4Address(), Op.EQ);
AllFieldsSearch.and("nicId", AllFieldsSearch.entity().getNicId(), Op.EQ);
AllFieldsSearch.and("gateway", AllFieldsSearch.entity().getGateway(), Op.EQ);
AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ);
AllFieldsSearch.done();
IpSearch = createSearchBuilder(String.class);
IpSearch.select(null, Func.DISTINCT, IpSearch.entity().getIp4Address());
IpSearch.and("network", IpSearch.entity().getNetworkId(), Op.EQ);
IpSearch.and("address", IpSearch.entity().getIp4Address(), Op.NNULL);
IpSearch.done();
}
@Override
public List<NicIpAliasVO> listByVmId(long instanceId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("instanceId", instanceId);
return listBy(sc);
}
@Override
public List<NicIpAliasVO> listByNicId(long nicId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("nicId", nicId);
return listBy(sc);
}
@Override
public List<String> listAliasIpAddressInNetwork(long networkId) {
SearchCriteria<String> sc = IpSearch.create();
sc.setParameters("network", networkId);
return customSearch(sc, null);
}
@Override
public List<NicIpAliasVO> listByNetworkId(long networkId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("network", networkId);
return listBy(sc);
}
@Override
public List<NicIpAliasVO> listByNetworkIdAndState(long networkId, NicIpAlias.State state) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("network", networkId);
sc.setParameters("state", state);
return listBy(sc);
}
@Override
public List<NicIpAliasVO> listByNicIdAndVmid(long nicId, long vmId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("nicId", nicId);
sc.setParameters("instanceId", vmId);
return listBy(sc);
}
@Override
public List<NicIpAliasVO> getAliasIpForVm(long vmId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("instanceId", vmId);
sc.setParameters("state", NicIpAlias.State.active);
return listBy(sc);
}
@Override
public List<String> getAliasIpAddressesForNic(long nicId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("nicId", nicId);
List<NicIpAliasVO> results = search(sc, null);
List<String> ips = new ArrayList<String>(results.size());
for (NicIpAliasVO result : results) {
ips.add(result.getIp4Address());
ips.add(result.getIp6Address());
}
return ips;
}
@Override
public NicIpAliasVO findByInstanceIdAndNetworkId(long networkId, long instanceId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("network", networkId);
sc.setParameters("instanceId", instanceId);
sc.setParameters("state", NicIpAlias.State.active);
return findOneBy(sc);
}
@Override
public NicIpAliasVO findByIp4AddressAndNetworkId(String ip4Address, long networkId) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public NicIpAliasVO findByGatewayAndNetworkIdAndState(String gateway, long networkId, NicIpAlias.State state) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("gateway", gateway);
sc.setParameters("network", networkId);
sc.setParameters("state", state);
return findOneBy(sc);
}
@Override
public NicIpAliasVO findByIp4AddressAndVmId(String ip4Address, long vmId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("address", ip4Address);
sc.setParameters("instanceId", vmId);
return findOneBy(sc);
}
@Override
public NicIpAliasVO findByIp4AddressAndNicId(String ip4Address, long nicId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("address", ip4Address);
sc.setParameters("nicId", nicId);
return findOneBy(sc);
}
@Override
public NicIpAliasVO findByIp4AddressAndNetworkIdAndInstanceId(long networkId, Long vmId, String vmIp) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("network", networkId);
sc.setParameters("instanceId", vmId);
sc.setParameters("address", vmIp);
return findOneBy(sc);
}
@Override
public Integer countAliasIps(long id) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("instanceId", id);
List<NicIpAliasVO> list = listBy(sc);
return list.size();
}
@Override
public int moveIpAliases(long fromNicId, long toNicId) {
SearchCriteria<NicIpAliasVO> sc = AllFieldsSearch.create();
sc.setParameters("nicId", fromNicId);
NicIpAliasVO update = createForUpdate();
update.setNicId(toNicId);
return update(update, sc);
}
}
| true |
2b036c912b2aa05869f55f2aebb256e172868c9a | Java | weihuanhuan/MiscellaneousTest | /feature/src/main/java/basic/args/ValueDeliveryTest.java | UTF-8 | 1,007 | 3.609375 | 4 | [] | no_license | package basic.args;
import java.util.ArrayList;
import java.util.List;
/**
* Created by JasonFitch on 6/21/2019.
*/
public class ValueDeliveryTest {
public static void main(String[] args) {
List<String> list = null;
test(list);
System.out.println(list.size());
}
//JF 注意part1和part2是相等的,
// java 是基于值copy传递的,这里复制了新的引用list,只是这个引用和先前的引用指向同一个地址,
// 随后修改了,新的引用,函数结束,这里可以看见旧的引用并没有进行任何修改所以是空指针异常。
//part 1
private static void test(List<String> list) {
list = new ArrayList<>();
list.add("asd");
}
// 因此part1相当于是下面的形式,list定义了一个本地变量,全程使用的是本地变量而已。
//part 2
private static void test() {
List<String> list = new ArrayList<>();
list.add("asd");
}
}
| true |
58f5ad139063ed89fd233f6402adb6899936ce80 | Java | NisalSP9/Flagship-ERP | /src/java/com/flagship/erp/service/impl/OPsServiceImpl.java | UTF-8 | 4,524 | 1.859375 | 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.flagship.erp.service.impl;
import com.flagship.erp.dao.POsDAO;
import com.flagship.erp.dao.impl.OPsDAOImpl;
import com.flagship.erp.model.OPSModel;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.flagship.erp.service.POsService;
/**
*
* @author aDMIN
*/
public class OPsServiceImpl implements POsService {
public boolean addOPs(OPSModel model, Connection connection) throws SQLException, ClassNotFoundException {
OPsDAOImpl dAOImpl = new OPsDAOImpl();
return dAOImpl.addOPs(model, connection);
}
public ResultSet viewAllPOs(Connection connection) throws SQLException, ClassNotFoundException {
OPsDAOImpl dAOImpl = new OPsDAOImpl();
return dAOImpl.viewAllPOs(connection);
}
public boolean deleteOPs(Connection connection, String id) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.deleteOPs(connection, id);
}
public boolean QTYapp(Connection connection, String id, String date) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.QTYapp(connection, id, date);
}
public ResultSet modiAppedQTY(Connection connection) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.modiAppedQTY(connection);
}
public boolean cancelAppQTY(Connection connection, String id) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.cancelAppQTY(connection, id);
}
public ResultSet pendingPurApp(Connection connection) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.pendingPurApp(connection);
}
public boolean purchaseApp(Connection connection, String id, String supName, double unitPrice, String date,String sup_id) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.purchaseApp(connection, id, supName, unitPrice, date,sup_id);
}
public ResultSet modiPurcApp(Connection connection) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.modiPurcApp(connection);
}
public boolean cancelPurcApp(Connection connection, String id) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.cancelPurcApp(connection, id);
}
public ResultSet readyToPrint(Connection connection,String name,String off) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.readyToPrint(connection,name,off);
}
public boolean rejectQTYAPP(Connection connection, String id, String note) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.rejectQTYAPP(connection, id, note);
}
public ResultSet pendingQTYApp(Connection connection) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.pendingQTYApp(connection);
}
public ResultSet rejectedPOs(Connection connection) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.rejectedPOs(connection);
}
public ResultSet priviouseOrders(Connection connection, String id, String phase, String element, String item) throws SQLException, ClassNotFoundException {
POsDAO pOsDAO = new OPsDAOImpl();
return pOsDAO.priviouseOrders(connection, id, phase, element, item);
}
public boolean updatePOS(Connection connection, OPSModel model) throws SQLException, ClassNotFoundException {
POsDAO dAO = new OPsDAOImpl();
return dAO.updatePOS(connection, model);
}
public ResultSet getSuppliersInPOS(Connection connection) throws SQLException, ClassNotFoundException {
POsDAO dAO = new OPsDAOImpl();
return dAO.getSuppliersInPOS(connection);
}
}
| true |
431abae05b43de47e88af8557683bf9a0099b4aa | Java | marcos-nvs/financiers | /financiers/src/main/java/br/com/ln/entity/LnPerfilacessoPK.java | UTF-8 | 2,001 | 2.265625 | 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 br.com.ln.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
*
* @author Marcos Naves
*/
@Embeddable
public class LnPerfilacessoPK implements Serializable {
@Basic(optional = false)
@Column(name = "per_in_codigo")
private int perInCodigo;
@Basic(optional = false)
@Column(name = "mod_in_codigo")
private int modInCodigo;
public LnPerfilacessoPK() {
}
public LnPerfilacessoPK(int perInCodigo, int modInCodigo) {
this.perInCodigo = perInCodigo;
this.modInCodigo = modInCodigo;
}
public int getPerInCodigo() {
return perInCodigo;
}
public void setPerInCodigo(int perInCodigo) {
this.perInCodigo = perInCodigo;
}
public int getModInCodigo() {
return modInCodigo;
}
public void setModInCodigo(int modInCodigo) {
this.modInCodigo = modInCodigo;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) perInCodigo;
hash += (int) modInCodigo;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof LnPerfilacessoPK)) {
return false;
}
LnPerfilacessoPK other = (LnPerfilacessoPK) object;
if (this.perInCodigo != other.perInCodigo) {
return false;
}
if (this.modInCodigo != other.modInCodigo) {
return false;
}
return true;
}
@Override
public String toString() {
return "br.com.hibernate.entities.LnPerfilacessoPK[ perInCodigo=" + perInCodigo + ", modInCodigo=" + modInCodigo + " ]";
}
}
| true |
2d52cc54b59c6bdff32ec60f7f3c0851a76d8265 | Java | dgut07219/news | /src/main/java/com/xkx/newssystem/filter/AuthorityFilter.java | UTF-8 | 1,815 | 2.21875 | 2 | [] | no_license | package com.xkx.newssystem.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xkx.newssystem.authority.domian.Authority;
import com.xkx.newssystem.authority.tools.AuthorityTool;
import com.xkx.newssystem.authority.tools.Message;
@WebFilter(filterName = "AuthorityFilter", urlPatterns = { "/UserServlet", "/NewsServlet", "/CommonServlet","/jsps/admin/*",
"/jsps/user/*", "/jsps/newsAuthor/*", "/jsps/common/*" })
public class AuthorityFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
req.setCharacterEncoding("utf-8");
res.setCharacterEncoding("utf-8");
String key = AuthorityTool.getKey(req);
System.out.println("filter=" + key);
Authority authority = AuthorityTool.authorityMap.get(key);
if (authority == null) {// 无权限
Message message = new Message();
message.setMessage("权限不够!");
message.setRedirectTime(1000);
request.setAttribute("message", message);
request.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
return;
} else
chain.doFilter(request, response);// 有权限,可以继续访问
}
public void destroy() {
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
| true |
4ba45a3b0077e09894834b76e892a75a8421836d | Java | askor2005/blagosfera | /Blagosfera/core/src/main/java/ru/radom/kabinet/dto/ErrorResponseDto.java | UTF-8 | 532 | 1.953125 | 2 | [] | no_license | package ru.radom.kabinet.dto;
import lombok.Getter;
import java.util.Map;
/**
*
* Created by vgusev on 25.03.2016.
*/
@Getter
public class ErrorResponseDto implements CommonResponseDto {
private String result = "error";
private String message;
private Map<String, String> errors;
public ErrorResponseDto(String message) {
this.message = message;
}
public ErrorResponseDto(String message, Map<String, String> errors) {
this.message = message;
this.errors = errors;
}
}
| true |
0489737fa38019517c2c633a0315354cfdc6bead | Java | ShreevaraPunacha/DinOrd | /app/src/main/java/com/example/andoid/dinord/Juice.java | UTF-8 | 7,751 | 2.3125 | 2 | [] | no_license | package com.example.andoid.dinord;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class Juice extends AppCompatActivity {
String Name = "";
private Spinner coldItems;
private LinearLayout juiceItems;
private LinearLayout milkShakes;
private Spinner juiceSpinner;
private Spinner milkShakeSpinner;
private TextView summaryTextView;
int quantity = 0;
int FinalPrice = 0;
String SelectedCold = "";
String Message = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juice);
Bundle bundle = getIntent().getExtras();
Name = bundle.getString("nameOfTheUser");
displayName();
summaryTextView = (TextView) this.findViewById(R.id.summary);
summaryTextView.setVisibility(TextView.GONE);
juiceItems = (LinearLayout) this.findViewById(R.id.juice_linear_layout);
milkShakes = (LinearLayout) this.findViewById(R.id.milkShake_linear_layout);
coldItems = (Spinner) findViewById(R.id.cold_items_spinner);
//spinner.setOnItemSelectedListener(AdapterView.OnItemSelectedListener);
List<String> items = new ArrayList<String>();
items.add("Juice Items");
items.add("Milkshakes");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
coldItems.setAdapter(adapter);
if (coldItems.getSelectedItem().toString().equals("Juice Items")) {
milkShakes.setVisibility(LinearLayout.GONE);
juiceItems.setVisibility(LinearLayout.VISIBLE);
} else {
milkShakes.setVisibility(LinearLayout.VISIBLE);
juiceItems.setVisibility(LinearLayout.GONE);
}
coldItems.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// here we change layout visibility again
if (coldItems.getSelectedItem().toString().equals("Juice Items")) {
milkShakes.setVisibility(LinearLayout.GONE);
juiceItems.setVisibility(LinearLayout.VISIBLE);
juiceItemsSpinner();
} else {
milkShakes.setVisibility(LinearLayout.VISIBLE);
juiceItems.setVisibility(LinearLayout.GONE);
milkShakesSpinner();
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void juiceItemsSpinner() {
SelectedCold = "Juice";
priceCalculation(quantity);
juiceSpinner = (Spinner) findViewById(R.id.juices_spinner);
List<String> items = new ArrayList<String>();
items.add("Orange");
items.add("Mango");
items.add("Chikku");
items.add("Apple");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
juiceSpinner.setAdapter(adapter);
}
private void milkShakesSpinner() {
SelectedCold = "MilkShake";
priceCalculation(quantity);
milkShakeSpinner = (Spinner) findViewById(R.id.milkShake_spinner);
List<String> items = new ArrayList<String>();
items.add("Chikku");
items.add("Badam");
items.add("Strawberry");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
milkShakeSpinner.setAdapter(adapter);
}
private void displayName() {
String displayMessage = "Hello!! " + Name;
TextView nameMessage = (TextView) findViewById(R.id.name_display);
nameMessage.setText(displayMessage);
}
public void increment(View view) {
if (quantity == 25) {
Toast.makeText(this, " You cannot have more than 25 cups of coffees", Toast.LENGTH_SHORT).show();
return;
}
quantity = quantity + 1;
display(quantity);
priceCalculation(quantity);
}
public void decrement(View view) {
if (quantity == 1) {
Toast.makeText(this, " You cannot have less than 1 cup of coffee", Toast.LENGTH_SHORT).show();
return;
}
quantity = quantity - 1;
display(quantity);
priceCalculation(quantity);
}
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(String.valueOf(number));
}
private void priceCalculation(int quantity) {
int pricePerItem = 0;
if(SelectedCold.equals("Juice")){
pricePerItem = 10;
}else if (SelectedCold.equals("MilkShake")){
pricePerItem = 8;
}
int price = quantity * pricePerItem;
FinalPrice = price;
displayPrice(price);
}
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
public void submitOrder(View view) {
if(quantity == 0){
Toast.makeText(getApplicationContext()," You cannot order Zero Items!!", Toast.LENGTH_SHORT).show();
}else {
SQLiteDatabase OrderDataBase;
OrderDataBase = openOrCreateDatabase("UsersAndOrders", MODE_PRIVATE, null);
OrderDataBase.execSQL("CREATE TABLE IF NOT EXISTS user(UserName VARCHAR,Item VARCHAR, Quantity VARCHAR , Price INTEGER);");
String DataSave = "";
Message += "Name : " + Name;
if (SelectedCold.equals("Juice")) {
DataSave = String.valueOf(juiceSpinner.getSelectedItem()) + " Juice";
Message += "\nDetails: Order for " + quantity + " glasses of" + String.valueOf(juiceSpinner.getSelectedItem()) + " Juice";
} else if (SelectedCold.equals("MilkShake")) {
DataSave = String.valueOf(milkShakeSpinner.getSelectedItem()) + " MilkShake";
Message += "\nDetails: Order for " + quantity + " glasses of " + String.valueOf(milkShakeSpinner.getSelectedItem()) + " MilkShake";
}
OrderDataBase.execSQL("INSERT INTO orders VALUES('" + Name + "','" + DataSave + "','" + quantity + "' , '"+FinalPrice+"' );");
Message += "\nBill amount: $ " + FinalPrice;
Message += "\nThank You ";
displayMessage(Message);
}
}
private void displayMessage(String message) {
summaryTextView.setVisibility(TextView.VISIBLE);
TextView priceTextView = (TextView) findViewById(R.id.message_text_view);
priceTextView.setText(message);
}
public void addMore(View view){
Intent intent = new Intent(Juice.this, AddMore.class);
intent.putExtra("nameOfTheUser", Name);
startActivity(intent);
}
}
| true |
71f3a6ad448f0746480db02702d467b7b7d89926 | Java | JiaYunSong/Java-Art | /JAVA-阚/Unit 07/text_file/in_out/Format_File_IO.java | GB18030 | 895 | 3.203125 | 3 | [] | no_license | package in_out;
import java.io.*;
import java.util.Scanner;
import javax.swing.*;
public class Format_File_IO {
public static void main(String[] args) {
try {
File f=new File(".\\in_using\\in_out");
JFileChooser fc=new JFileChooser(f);
fc.showOpenDialog(null);
f=fc.getSelectedFile();
String fi=f.toString();
PrintWriter pw=new PrintWriter(fi);
int x=10; double y=15.2; String str="abcd";
pw.print(x+" ");
pw.print(y+" ");
pw.println(str);
pw.format("%d %f %s", x,y,str);
pw.close();
System.out.println(fi+"дɹ");
Scanner sc=new Scanner(new File(fi));
while(sc.hasNext()) {
x=sc.nextInt();
y=sc.nextDouble();
str=sc.next();
System.out.println(x+" "+y+" "+str);
}
sc.close();
System.out.println(fi+"ȡɹ");
}
catch(IOException e){
System.out.println("Ҳд");
}
}
}
| true |
83ba0f96138b6636638f5eec91a75a77ccccefc8 | Java | COMBASE/Api-Progz | /ImportFoodXML/src/foodxml/Item_price.java | UTF-8 | 1,069 | 2.140625 | 2 | [] | no_license | package foodxml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.FIELD)
public class Item_price
{
@XmlValue
private float value;
@XmlAttribute(name="quantity_scale")
private String quantity_scale;
@XmlAttribute(name="unit_factor")
private String unit_factor;
@XmlAttribute(name="discount")
private String discount;
public String getQuantity_scale()
{
return quantity_scale;
}
public void setQuantity_scale(String quantity_scale)
{
this.quantity_scale = quantity_scale;
}
public String getUnit_factor()
{
return unit_factor;
}
public void setUnit_factor(String unit_factor)
{
this.unit_factor = unit_factor;
}
public String getDiscount()
{
return discount;
}
public void setDiscount(String discount)
{
this.discount = discount;
}
public float getValue()
{
return value;
}
public void setValue(float value)
{
this.value = value;
}
}
| true |
30b40cde7234316a97951aa6fc49b09734db5d43 | Java | MykhailoMike/programming_patterns | /src/main/java/com/mkaloshyn/creational/abstract_factory_02/rockBand/RockSinger.java | UTF-8 | 309 | 2.953125 | 3 | [] | no_license | package main.java.com.mkaloshyn.creational.abstract_factory_02.rockBand;
import main.java.com.mkaloshyn.creational.abstract_factory_02.Soloist;
public class RockSinger implements Soloist {
@Override
public void sing() {
System.out.println("The soloist of the rock band sings rock");
}
}
| true |
c2dc46c24c4a7eb02a5defb741890eef5901bcb6 | Java | xiuFranklin/cocos2d-js-ajax-protobuf-nodejs-springmvc | /src/main/java/com/why/game/web/interceptor/ControllerInterceptor.java | UTF-8 | 3,554 | 2.625 | 3 | [] | no_license | package com.why.game.web.interceptor;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class ControllerInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
/**
* 在业务处理器处理请求之前被调用
* 如果返回false
* 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
*
* 如果返回true
* 执行下一个拦截器,直到所有的拦截器都执行完毕
* 再执行被拦截的Controller
* 然后进入拦截器链,
* 从最后一个拦截器往回执行所有的postHandle()
* 接着再从最后一个拦截器往回执行所有的afterCompletion()
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String queryStr = request.getQueryString();
logger.info(handler.getClass().getSimpleName()+", "+request.getRequestURI()+", "+paramMap(request)+(queryStr == null ? "" : ", "+queryStr));
//返回json格式,其实mvc.xml的mappingJacksonHttpMessageConverter会自动处理了
//response.setContentType("application/json;charset=UTF-8");
//跨域许可,支持HTTP方法等信息
response.setHeader("access-control-allow-origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "1000");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Range, Content-Disposition, Content-Description");
return true;
}
@SuppressWarnings("unchecked")
private Map<String, String> headerMap(HttpServletRequest request){
Enumeration<String> names = request.getHeaderNames();
Map<String, String> headerMap = new HashMap<String, String>();
while(names.hasMoreElements()){
String name = names.nextElement();
headerMap.put(name, request.getHeader(name));
}
//logger.info("header : "+headerMap.toString());
return headerMap;
}
@SuppressWarnings("unchecked")
private Map<String, String> paramMap(HttpServletRequest request){
Map<String, String> paramMap = new HashMap<String, String>();
Map<String, String[]> map = request.getParameterMap();
for(Object key:map.keySet()){
paramMap.put(key.toString(), Arrays.toString(map.get(key)));
}
return paramMap;
}
//在业务处理器处理请求执行完成后,生成视图之前执行的动作
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
/**
* 在DispatcherServlet完全处理完请求后被调用
*
* 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
| true |
5c9ddd6f5878128d1e81584ad0de770c8de6582c | Java | JJAGUIRRESC/Asistentedemedicacion | /app/src/main/java/com/medicacion/juanjose/asistentedemedicacion/sync/Sincronizacion.java | UTF-8 | 10,271 | 2.140625 | 2 | [] | no_license | package com.medicacion.juanjose.asistentedemedicacion.sync;
import android.content.ContentResolver;
import android.content.Context;
import android.util.Log;
import com.medicacion.juanjose.asistentedemedicacion.constantes.G;
import com.medicacion.juanjose.asistentedemedicacion.pojos.Bitacora;
import com.medicacion.juanjose.asistentedemedicacion.pojos.BitacoraUsuario;
import com.medicacion.juanjose.asistentedemedicacion.pojos.Medicamento;
import com.medicacion.juanjose.asistentedemedicacion.pojos.Usuario;
import com.medicacion.juanjose.asistentedemedicacion.proveedor.BitacoraProveedor;
import com.medicacion.juanjose.asistentedemedicacion.proveedor.BitacoraProveedorUsuario;
import com.medicacion.juanjose.asistentedemedicacion.proveedor.MedicamentoProveedor;
import com.medicacion.juanjose.asistentedemedicacion.proveedor.UsuarioProveedor;
import com.medicacion.juanjose.asistentedemedicacion.volley.MedicamentoVolley;
import com.medicacion.juanjose.asistentedemedicacion.volley.UsuarioVolley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by Juanjo on 06/12/2017.
*/
public class Sincronizacion {
private static final String LOGTAG = "Juanjo - Sincronizacion";
private static ContentResolver resolvedor;
private static Context contexto;
private static boolean esperandoRespuestaDeServidor = false;
public Sincronizacion(Context contexto){
this.resolvedor = contexto.getContentResolver();
this.contexto = contexto;
recibirActualizacionesDelServidor(); //La primera vez se cargan los datos siempre
recibirActualizacionesDelServidorUsuario();
}
public synchronized static boolean isEsperandoRespuestaDeServidor() {
return esperandoRespuestaDeServidor;
}
public synchronized static void setEsperandoRespuestaDeServidor(boolean esperandoRespuestaDeServidor) {
Sincronizacion.esperandoRespuestaDeServidor = esperandoRespuestaDeServidor;
}
public synchronized boolean sincronizar(){
Log.i("sincronizacion","SINCRONIZAR");
if(isEsperandoRespuestaDeServidor()){
return true;
}
if(G.VERSION_ADMINISTRADOR){
enviarActualizacionesAlServidor();
enviarActualizacionesAlServidorUsuario();
recibirActualizacionesDelServidor();
recibirActualizacionesDelServidorUsuario();
} else {
recibirActualizacionesDelServidor();
}
return true;
}
private static void enviarActualizacionesAlServidor(){
ArrayList<Bitacora> registrosBitacora = BitacoraProveedor.readAllRecord(resolvedor);
for(Bitacora bitacora : registrosBitacora){
switch(bitacora.getOperacion()){
case G.OPERACION_INSERTAR:
Medicamento medicamento = null;
try {
medicamento = MedicamentoProveedor.readRecord(resolvedor, bitacora.getID_Medicamento());
MedicamentoVolley.addMedicamento(medicamento, true, bitacora.getID());
} catch (Exception e) {
e.printStackTrace();
}
break;
case G.OPERACION_MODIFICAR:
try {
medicamento = MedicamentoProveedor.readRecord(resolvedor, bitacora.getID_Medicamento());
MedicamentoVolley.updateMedicamento(medicamento, true, bitacora.getID());
} catch (Exception e) {
e.printStackTrace();
}
break;
case G.OPERACION_BORRAR:
MedicamentoVolley.delMedicamento(bitacora.getID_Medicamento(), true, bitacora.getID());
break;
}
Log.i("sincronizacion", "acabo de enviar");
}
}
public static void enviarActualizacionesAlServidorUsuario() {
ArrayList<BitacoraUsuario> registrosBitacoraProveedor = BitacoraProveedorUsuario.readAllRecord(resolvedor);
for (BitacoraUsuario bitacoraUsuario : registrosBitacoraProveedor) {
switch (bitacoraUsuario.getOperacion()) {
case G.OPERACION_INSERTAR:
Usuario usuario = null;
try {
usuario = UsuarioProveedor.readRecord(resolvedor, bitacoraUsuario.getID_Usuario());
UsuarioVolley.addUsuario(usuario, true, bitacoraUsuario.getID());
} catch (Exception e) {
e.printStackTrace();
}
break;
case G.OPERACION_MODIFICAR:
try {
usuario = UsuarioProveedor.readRecord(resolvedor, bitacoraUsuario.getID_Usuario());
UsuarioVolley.updateUsuario(usuario, true, bitacoraUsuario.getID());
} catch (Exception e) {
e.printStackTrace();
}
break;
case G.OPERACION_BORRAR:
UsuarioVolley.delUsuario(bitacoraUsuario.getID_Usuario(), true, bitacoraUsuario.getID());
break;
}
Log.i("sincronizacion", "acabo de enviar");
}
}
// Medicamentos
private static void recibirActualizacionesDelServidor(){
MedicamentoVolley.getAllMedicamento();
}
// Usuarios
public static void recibirActualizacionesDelServidorUsuario(){
UsuarioVolley.getAllUsuario();
}
// Medicamentos
public static void realizarActualizacionesDelServidorUnaVezRecibidas(JSONArray jsonArray){
Log.i("sincronizacion", "recibirActualizacionesDelServidor");
try {
ArrayList<Integer> identificadoresDeRegistrosActualizados = new ArrayList<Integer>();
ArrayList<Medicamento> registrosNuevos = new ArrayList<>();
ArrayList<Medicamento> registrosViejos = MedicamentoProveedor.readAllRecord(resolvedor);
ArrayList<Integer> identificadoresDeRegistrosViejos = new ArrayList<Integer>();
for(Medicamento i : registrosViejos) identificadoresDeRegistrosViejos.add(i.getID());
JSONObject obj = null;
for (int i = 0; i < jsonArray.length(); i++ ){
obj = jsonArray.getJSONObject(i);
registrosNuevos.add(new Medicamento(obj.getInt("PK_ID"), obj.getString("nombre"), obj.getString("hora")));
}
for(Medicamento medicamento: registrosNuevos) {
try {
if(identificadoresDeRegistrosViejos.contains(medicamento.getID())) {
MedicamentoProveedor.updateRecord(resolvedor, medicamento, null);
} else {
MedicamentoProveedor.insertRecord(resolvedor, medicamento, null);
}
identificadoresDeRegistrosActualizados.add(medicamento.getID());
} catch (Exception e){
Log.i("sincronizacion",
"Probablemente el registro ya existía en la BD."+"" +
" Esto se podría controlar mejor con una Bitácora.");
}
}
for(Medicamento medicamento: registrosViejos){
if(!identificadoresDeRegistrosActualizados.contains(medicamento.getID())){
try {
MedicamentoProveedor.deleteRecord(resolvedor, medicamento.getID());
}catch(Exception e){
Log.i("sincronizacion", "Error al borrar el registro con id:" + medicamento.getID());
}
}
}
//MedicamentoVolley.getAllMedicamento(); //Los baja y los guarda en SQLite
} catch (Exception e) {
e.printStackTrace();
}
}
// Usuarios
public static void realizarActualizacionesDelServidorUnaVezRecibidasUsuario(JSONArray jsonArray){
Log.i("sincronizacion", "recibirActualizacionesDelServidor");
try {
ArrayList<Integer> identificadoresDeRegistrosActualizados = new ArrayList<Integer>();
ArrayList<Usuario> registrosNuevos = new ArrayList<>();
ArrayList<Usuario> registrosViejos = UsuarioProveedor.readAllRecord(resolvedor);
ArrayList<Integer> identificadoresDeRegistrosViejos = new ArrayList<Integer>();
for(Usuario i : registrosViejos) identificadoresDeRegistrosViejos.add(i.getID());
JSONObject obj = null;
for (int i = 0; i < jsonArray.length(); i++ ){
obj = jsonArray.getJSONObject(i);
registrosNuevos.add(new Usuario(obj.getInt("PK_ID"), obj.getString("nombre"), obj.getString("password")));
}
for(Usuario usuario: registrosNuevos) {
try {
if(identificadoresDeRegistrosViejos.contains(usuario.getID())) {
UsuarioProveedor.updateRecord(resolvedor, usuario, null);
} else {
UsuarioProveedor.insertRecord(resolvedor, usuario, null);
}
identificadoresDeRegistrosActualizados.add(usuario.getID());
} catch (Exception e){
Log.i("sincronizacion",
"Probablemente el registro ya existía en la BD."+"" +
" Esto se podría controlar mejor con una Bitácora.");
}
}
for(Usuario usuario: registrosViejos){
if(!identificadoresDeRegistrosActualizados.contains(usuario.getID())){
try {
UsuarioProveedor.deleteRecord(resolvedor, usuario.getID());
}catch(Exception e){
Log.i("sincronizacion", "Error al borrar el registro con id:" + usuario.getID());
}
}
}
//UsuarioVolley.getAllUsuario(); //Los baja y los guarda en SQLite
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
855a065738dcd3abe3fa2dfc7defb431d81f9a4c | Java | kanghonghai/springsecurityoauth2 | /net5ijy-oauth2-common/src/main/java/org/net5ijy/oauth2/configuration/CustomUserAuthenticationConverter.java | UTF-8 | 2,075 | 2.453125 | 2 | [] | no_license | package org.net5ijy.oauth2.configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.net5ijy.oauth2.details.CustomUserDetail;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
/**
* Implementation of UserAuthenticationConverter. Converts to and from an Authentication using name,
* authorities and resource urls.
*
* @author XGF
* @date 2019/9/19 20:50
*/
@Slf4j
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
CustomUserDetail principal = (CustomUserDetail) authentication.getPrincipal();
Map<String, Object> response = new HashMap<>(16);
response.putAll(super.convertUserAuthentication(authentication));
response.put("urls", principal.getUrls());
log.info("CustomUserAuthenticationConverter.convertUserAuthentication, response: {}", response);
return response;
}
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
Authentication authentication = super.extractAuthentication(map);
CustomUserDetail userDetail =
new CustomUserDetail(
authentication.getPrincipal().toString(),
"",
authentication.getAuthorities());
Object urls = map.get("urls");
if (urls instanceof ArrayList) {
userDetail.setUrls(new HashSet<String>() {
{
for (Object url : (ArrayList) urls) {
add(url.toString());
}
}
});
}
Authentication auth =
new UsernamePasswordAuthenticationToken(userDetail, "N/A", authentication.getAuthorities());
log.info("CustomUserAuthenticationConverter.extractAuthentication, authentication: {}", auth);
return auth;
}
}
| true |
1653d795ba3afe5ed0ca04f1dfee165bd200a063 | Java | subenoeva/mmp_mobile_app | /app/src/main/java/mmp/mymoneyplatform_mobile_app/pojo/CardViewData.java | UTF-8 | 7,484 | 3.015625 | 3 | [] | no_license | package mmp.mymoneyplatform_mobile_app.pojo;
import android.content.Context;
import android.graphics.drawable.Drawable;
import mmp.mymoneyplatform_mobile_app.R;
/**
* Created by K on 12/04/2016.
* This class holds all the properties related to an individual CardView in the CardView list
* It has references for every single element of the card that is not common, like the title,
* subtitle, the color of the title, the background color, the amount of money displayed and it has
* a reference to an instance of HealthPanelData, which represents the little board on the bottom
* of the card, displaying the actual health on that item (see CardViewData for more information).
*/
public class CardViewData {
private String title, subtitle;
private int titleColor, backgroundColor;
private double money;
private HealthPanelData healthPanel;
public CardViewData(String title, String subtitle, int titleColor, int backgroundColor,
double money, HealthPanelData healthPanel) {
this.title = title;
this.subtitle = subtitle;
this.titleColor = titleColor;
this.backgroundColor = backgroundColor;
this.money = money;
this.healthPanel = healthPanel;
}
//region Getters and Setters
public int getBackgroundColor() {
return backgroundColor;
}
@SuppressWarnings("unused")
public void setBackgroundColor(int backgroundColor) {
this.backgroundColor = backgroundColor;
}
public HealthPanelData getHealthPanel() {
return healthPanel;
}
public double getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
public String getSubtitle() {
return subtitle;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getTitleColor() {
return titleColor;
}
//endregion
@Override
public String toString() {
return "CardViewData{" +
"backgroundColor='" + backgroundColor + '\'' +
", healthPanel=" + healthPanel +
", money=" + money +
", subtitle='" + subtitle + '\'' +
", title='" + title + '\'' +
", titleColor='" + titleColor + '\'' +
'}';
}
/**
* Created by K on 12/04/2016.
* This class holds all the properties related to a HealthPanel that is always contained in a
* CardViewData instance. We store everything that is not common for two different HealthPanel
* instances.
* We also provide a reference to the Context of the activity holding this object, so we can
* access the resources in our XML tables (such as strings.xml and colors.xml)
* Makes sense that this class is inside of CardViewData.java and static to it since a CardView
* always has a HealthPanel inside of it
*/
@SuppressWarnings({"JavaDoc", "deprecation"})
public static class HealthPanelData {
/**
* We need the context of the Application in order to get the color of the health status
* from our resources XML files (colors.xml)
*/
private Context c;
private String title, status;
private Drawable progressBar;
private int healthProgress, statusColor, backgroundColor;
public HealthPanelData(Context c, String title, int healthProgress, int backgroundColor) {
this.c = c;
this.title = title;
this.healthProgress = healthProgress;
assignStatus(this.healthProgress);
this.backgroundColor = backgroundColor;
}
/**
* This method assigns a status to the HealthPanel, and depending on that status it changes
* the text of the @title and both the color of the @title and progress bar (the background
* doesn't change thought)
* Throws an IllegalArgumentException if the value of @healthProgress isn't between 0 and
* 100.
*
* @param healthProgress
*/
private void assignStatus(double healthProgress) {
//Depending on the healthProgress value we assign tha value for the Status and Color
if (healthProgress >= 0 && healthProgress <= 25) {
// Less or equal to 25%
status = c.getString(R.string.cv_hp_state_poor);
statusColor = c.getResources().getColor(R.color.colorStatePoor);
progressBar = c.getResources().getDrawable(R.drawable.progress_bar_poor);
} else if (healthProgress > 25 && healthProgress <= 50) {
// more than 25% and less or equal to 50%
status = c.getString(R.string.cv_hp_state_medium);
statusColor = c.getResources().getColor(R.color.colorStateMedium);
progressBar = c.getResources().getDrawable(R.drawable.progress_bar_medium);
} else if (healthProgress > 50 && healthProgress <= 75) {
// more than 50% and less or equal to 75%
status = c.getString(R.string.cv_hp_state_good);
statusColor = c.getResources().getColor(R.color.colorStateGood);
progressBar = c.getResources().getDrawable(R.drawable.progress_bar_good);
} else if (healthProgress > 75 && healthProgress <= 100) {
// more than 75% and less or equal to 100%
status = c.getString(R.string.cv_hp_state_excellent);
statusColor = c.getResources().getColor(R.color.colorStateExcelent);
progressBar = c.getResources().getDrawable(R.drawable.progress_bar_excelent);
} else {
throw new IllegalArgumentException("The value of the healthProgress must " +
"be between 0 and 100");
}
}
//region Getters and Setters
/**
* @return the String value of the title ("Poor", "Medium", etc...)
*/
public String getTitle() {
return title;
}
public Drawable getProgressBar() {
return progressBar;
}
/**
* @return the text that will be displayed on the status title
*/
public String getStatus() {
return status;
}
/**
* @return the percentage value of the progress bar at any moment
*/
public int getHealthProgress() {
return healthProgress;
}
/**
* @return the color of both title and progress bar
*/
public int getStatusColor() {
return statusColor;
}
/**
* @return the background color of the health panel
*/
public int getBackgroundColor() {
return backgroundColor;
}
/**
* Sets a new value for the progress bar and then reassigns the colors.
* Throws an IllegalArgumentException if the value of @healthProgress isn't between 0 and
* 100.
*
* @param healthProgress
*/
public void setHealthProgress(int healthProgress) {
this.healthProgress = healthProgress;
//Update the status to match the new progress value
assignStatus(this.healthProgress);
}
//endregion
}
} | true |
619d86fc9d2ff205cc82d1adf0a7b6d1e1797faa | Java | nmly68it/DesignPatterns | /DesignPattern/src/dylan/coder/designpattern/observer/Subscriber.java | UTF-8 | 303 | 3.125 | 3 | [] | no_license | package dylan.coder.designpattern.observer;
public class Subscriber implements Observer{
private String username;
public Subscriber(String username) {
this.username = username;
}
@Override
public void displayNotification(String msg) {
System.out.println(username + " - " + msg);
}
}
| true |
be2e16831a7a880567803db038755af3267a8b99 | Java | okay456okay/7d-mall-microservice | /mall-admin/src/main/java/com/dunshan/mall/dao/SmsCouponDao.java | UTF-8 | 342 | 1.828125 | 2 | [
"Apache-2.0"
] | permissive | package com.dunshan.mall.dao;
import com.dunshan.mall.dto.SmsCouponParam;
import org.apache.ibatis.annotations.Param;
/**
* 自定义优惠券管理Dao
* Created by dunshan on 2018/8/29.
*/
public interface SmsCouponDao {
/**
* 获取优惠券详情包括绑定关系
*/
SmsCouponParam getItem(@Param("id") Long id);
}
| true |
7c030d89d71e4ea8f4c18deee89eaa41ef247651 | Java | micaellopes/android-final-apre | /app/src/main/java/com/example/andrey/academiaand/AcademiaController.java | UTF-8 | 619 | 2.515625 | 3 | [] | no_license | package com.example.andrey.academiaand;
import com.example.andrey.academiaand.model.Academia;
/**
* Created by Andrey on 12/06/2017.
*/
public class AcademiaController {
private static AcademiaController instace;
private Academia academia;
private AcademiaController(){}
public static AcademiaController getInstace(){
if( instace == null){
instace = new AcademiaController();
}
return instace;
}
public Academia getAcademia() {
return academia;
}
public void setAcademia(Academia academia) {
this.academia = academia;
}
}
| true |
eabe31314a39fecd545a27550a4c4f1fdd03ebc6 | Java | daisy-fhb/daisycores | /bangsen/src/main/java/com/daisy/bangsen/util/InitUtil.java | UTF-8 | 1,183 | 1.867188 | 2 | [] | no_license | package com.daisy.bangsen.util;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;
@Component
public class InitUtil implements ApplicationContextAware, ServletContextAware,
InitializingBean, ApplicationListener<ContextRefreshedEvent> {
@Override
public void afterPropertiesSet() {}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
}
@Override
public void setServletContext(ServletContext servletContext) { }
}
| true |
42adbb8509a792e1f4e43cfea48e0a8cd78ea16e | Java | blackdargn/AndroidUtil | /src/com/android/util/fragment/MyFragmentPagerAdpater.java | UTF-8 | 1,934 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | package com.android.util.fragment;
import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdpater extends FragmentPagerAdapter {
private ArrayList<Fragment> mFragments;
public MyFragmentPagerAdpater(FragmentManager fm, int size, OnTabListener listener) {
super(fm);
mFragments = new ArrayList<Fragment>(size);
for(int i =0; i<size; i++) {
addFragment(listener.newFragment(i));
}
}
public MyFragmentPagerAdpater(FragmentManager fm) {
super(fm);
mFragments = new ArrayList<Fragment>();
}
public void addFragment(Fragment item) {
if(item instanceof BaseFragment) {
((BaseFragment)item).isHostTab = false;
}
mFragments.add(item);
notifyDataSetChanged();
}
public void updateFragment(int oldId, int newId) {
if(newId >= 0 && newId < mFragments.size()) {
Fragment item = getItem(newId);
if(item instanceof BaseFragment) {
BaseFragment fragment = (BaseFragment)item;
if(fragment.isVisible()) {
fragment._onResume();
}else {
fragment.checkDelayResume();
}
}
}
if(oldId >= 0 && oldId < mFragments.size()) {
Fragment item = getItem(oldId);
if(item instanceof BaseFragment) {
BaseFragment fragment = (BaseFragment)item;
fragment.onPause();
}
}
}
@Override
public Fragment getItem(int index) {
if(index < 0 || index >= mFragments.size()) return null;
return mFragments.get(index);
}
@Override
public int getCount() {
return mFragments.size();
}
} | true |
0afef06a2c2314fc9c7a4b17e67854be2724df6e | Java | mikyone/wireshark-pdml | /src/test/java/com/tshark/automation/pdml/config/ConfigLoaderTest.java | UTF-8 | 1,194 | 2.203125 | 2 | [] | no_license | package com.tshark.automation.pdml.config;
import org.apache.commons.io.IOUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.net.URLEncoder;
/**
* Created by onicolas on 01/09/2015.
*/
public class ConfigLoaderTest{
@Test
public void testGetConfiguration() throws JAXBException, IOException {
URLEncoder.encode("%20", "UTF-8");
String xmlConfig = IOUtils.toString(ConfigLoaderTest.class.getClassLoader().getResourceAsStream("FakeConfiguration.xml"));
Configuration configuration = ConfigLoader.getConfiguration(xmlConfig);
Assert.assertNotNull(configuration);
Assert.assertEquals(3, configuration.getOutputs().size());
Assert.assertEquals("protocol", configuration.getOutputs().get(2).getType());
Assert.assertEquals("json", configuration.getOutputs().get(2).getName());
Assert.assertEquals("defaultProtocol", configuration.getOutputs().get(2).getConvertor());
Assert.assertEquals(1, configuration.getFilters().size());
Assert.assertEquals("POST", configuration.getFilters().get(0).getValue());
}
}
| true |
a842453377ccc9e51b486c4d1797348a63df7f2f | Java | ZuzannaWeichel/VendingMachine | /m1-capstone/src/main/java/com/techelevator/Dispenser.java | UTF-8 | 1,404 | 3.25 | 3 | [] | no_license | package com.techelevator;
import java.util.ArrayList;
public class Dispenser {
private double currentMoneyProvided = 0;
private ArrayList<VendingItem> itemsPurchased = new ArrayList<>();
public void purchase(VendingItem item) {
itemsPurchased.add(item);
currentMoneyProvided = ((currentMoneyProvided * 100) - (item.getPrice() * 100)) /100;
}
public String returnChange() {
int [] coins = new int [] {25,10,5};
int change = (int) Math.ceil(currentMoneyProvided * 100);
currentMoneyProvided = 0;
String toReturn = "";
for ( int i = 0; i < coins.length ; i++) {
double factor = change * 1.0 /coins[i];
int numberOfCoins = (int)factor;
if(numberOfCoins > 0 ) {
toReturn += numberOfCoins+" "+ switchToCoins(coins[i]) +" ";
change = ((change * 100) - (numberOfCoins * coins[i] * 100)) / 100;
}
}
return toReturn;
}
private String switchToCoins(int coin) {
String coins = "";
switch (coin) {
case 25 : coins = "quarter(s)";
break;
case 10 : coins = "dime(s)";
break;
case 5 : coins = "nickel(s)";
break;
default : coins = "";
}
return coins;
}
public void addCash(int cash) {
currentMoneyProvided += cash;
}
public double getCurrentMoneyProvided() {
return currentMoneyProvided;
}
public ArrayList<VendingItem> getList() {
return itemsPurchased;
}
public void clearList() {
itemsPurchased.clear();
}
}
| true |
11048536710db0b0bcf02e6be275b5c2828de481 | Java | 1onely-lucas/LunarClient | /src/main/java/com/moonsworth/lunar/bridge/minecraft/util/Vector3d.java | UTF-8 | 3,148 | 2.734375 | 3 | [] | no_license | package com.moonsworth.lunar.bridge.minecraft.util;
public class Vector3d {
public double lIlIlIlIlIIlIIlIIllIIIIIl;
public double IlllIIIIIIlllIlIIlllIlIIl;
public double lIllIlIIIlIIIIIIIlllIlIll;
public static Vector3d lIlIlIlIlIIlIIlIIllIIIIIl(Vector3d vector3d, Vector3d vector3d2, Vector3d vector3d3) {
if (vector3d3 == null) {
vector3d3 = new Vector3d();
}
vector3d3.lIlIlIlIlIIlIIlIIllIIIIIl = vector3d.lIlIlIlIlIIlIIlIIllIIIIIl - vector3d2.lIlIlIlIlIIlIIlIIllIIIIIl;
vector3d3.IlllIIIIIIlllIlIIlllIlIIl = vector3d.IlllIIIIIIlllIlIIlllIlIIl - vector3d2.IlllIIIIIIlllIlIIlllIlIIl;
vector3d3.lIllIlIIIlIIIIIIIlllIlIll = vector3d.lIllIlIIIlIIIIIIIlllIlIll - vector3d2.lIllIlIIIlIIIIIIIlllIlIll;
return vector3d3;
}
public double lIlIlIlIlIIlIIlIIllIIIIIl() {
return this.lIlIlIlIlIIlIIlIIllIIIIIl;
}
public double IlllIIIIIIlllIlIIlllIlIIl() {
return this.IlllIIIIIIlllIlIIlllIlIIl;
}
public double lIllIlIIIlIIIIIIIlllIlIll() {
return this.lIllIlIIIlIIIIIIIlllIlIll;
}
public void lIlIlIlIlIIlIIlIIllIIIIIl(double d) {
this.lIlIlIlIlIIlIIlIIllIIIIIl = d;
}
public void IlllIIIIIIlllIlIIlllIlIIl(double d) {
this.IlllIIIIIIlllIlIIlllIlIIl = d;
}
public void lIllIlIIIlIIIIIIIlllIlIll(double d) {
this.lIllIlIIIlIIIIIIIlllIlIll = d;
}
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Vector3d)) {
return false;
}
Vector3d vector3d = (Vector3d)object;
if (!vector3d.lIlIlIlIlIIlIIlIIllIIIIIl(this)) {
return false;
}
if (Double.compare(this.lIlIlIlIlIIlIIlIIllIIIIIl(), vector3d.lIlIlIlIlIIlIIlIIllIIIIIl()) != 0) {
return false;
}
if (Double.compare(this.IlllIIIIIIlllIlIIlllIlIIl(), vector3d.IlllIIIIIIlllIlIIlllIlIIl()) != 0) {
return false;
}
return Double.compare(this.lIllIlIIIlIIIIIIIlllIlIll(), vector3d.lIllIlIIIlIIIIIIIlllIlIll()) == 0;
}
public boolean lIlIlIlIlIIlIIlIIllIIIIIl(Object object) {
return object instanceof Vector3d;
}
public int hashCode() {
int n = 59;
int n2 = 1;
long l = Double.doubleToLongBits(this.lIlIlIlIlIIlIIlIIllIIIIIl());
n2 = n2 * 59 + (int)(l >>> 32 ^ l);
long l2 = Double.doubleToLongBits(this.IlllIIIIIIlllIlIIlllIlIIl());
n2 = n2 * 59 + (int)(l2 >>> 32 ^ l2);
long l3 = Double.doubleToLongBits(this.lIllIlIIIlIIIIIIIlllIlIll());
n2 = n2 * 59 + (int)(l3 >>> 32 ^ l3);
return n2;
}
public String toString() {
return "Vector3d(x=" + this.lIlIlIlIlIIlIIlIIllIIIIIl() + ", y=" + this.IlllIIIIIIlllIlIIlllIlIIl() + ", z=" + this.lIllIlIIIlIIIIIIIlllIlIll() + ")";
}
public Vector3d() {
}
public Vector3d(double d, double d2, double d3) {
this.lIlIlIlIlIIlIIlIIllIIIIIl = d;
this.IlllIIIIIIlllIlIIlllIlIIl = d2;
this.lIllIlIIIlIIIIIIIlllIlIll = d3;
}
} | true |
8a60e3255516928758621bd06885e85ed56fad84 | Java | adrbin42/MathOperands2 | /src/com/lionssharewebdev/Main.java | UTF-8 | 1,359 | 3.5625 | 4 | [] | no_license | package com.lionssharewebdev;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Please enter a number.");
Scanner scanner1 = new Scanner(System.in);
String input1 = scanner1.nextLine();
System.out.println("The first number is " + input1);
System.out.println("Please enter a second number.");
Scanner scanner2 = new Scanner(System.in);
String input2 = scanner2.nextLine();
System.out.println("The second number is " + input2);
double operand1 = Double.parseDouble(input1);
double operand2 = Double.parseDouble(input2);
double sum = operand1 + operand2;
double diff = operand1 - operand2;
double div = operand1 / operand2;
double multiply = operand1 * operand2;
double remainder = operand1 % operand2;
showResults(sum,diff,div,multiply,remainder);
}
public static void showResults (double sum, double diff, double div, double multiply, double remainder){
System.out.println("The sum of both numbers is: " + sum);
System.out.println("The difference of both numbers is: " + diff);
System.out.println("The result of multiplying both numbers is : " + multiply);
System.out.println("Both numbers divided are : " + div);
System.out.println("The remainder of both operands " + remainder);
}
}
| true |
a9b9fbd76a2f4d81b118c6ab93a6a0b3a115a739 | Java | sarvanparth/Lab-3 | /ZoneTime.java | UTF-8 | 732 | 3.34375 | 3 | [] | no_license | import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Scanner;
public class ZoneTime {
public String zoneId;
public void dateAndTime(String str) {
LocalDateTime ldt = LocalDateTime.now();
ZoneId Id = ZoneId.of(str);
System.out.println("TimeZone : " + Id);
//LocalDateTime + ZoneId = ZonedDateTime
ZonedDateTime ZonedDateTime = ldt.atZone(Id);
System.out.println("Date and Time of Given Zone : " + ZonedDateTime);
}
public static void main(String[] args){
ZoneTime obj = new ZoneTime();
Scanner s = new Scanner(System.in);
System.out.println("Enter Zone Id: ");
String str = s.nextLine();
obj.dateAndTime(str);
s.close();
}
}
| true |
f95f4f02c7a03fc51166c4da3132576ede9f095c | Java | shake822/idea | /base_java/src/main/java/CalendarTest.java | UTF-8 | 1,641 | 2.421875 | 2 | [] | no_license | import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/******************************************************************************
* Copyright (C) 2015 ShenZhen ComTop Information Technology Co.,Ltd
* All Rights Reserved.
* �����Ϊ���ڿ����տ������ơ�δ������˾��ʽ����ͬ�⣬�����κθ��ˡ����岻��ʹ�á�
* ���ơ��Ļ������.
******************************************************************************/
/**
* FIXME ��ע����Ϣ
*
* @author zhaoqunqi
* @since 1.0
* @createDate 2015-03-17
*/
public class CalendarTest {
/**
*
* FIXME ����ע����Ϣ
*
* @param args
* SD
*/
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// cal.setTime(new Date(2015, 3, 1));
cal.add(Calendar.DATE, -1);
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.MILLISECOND,0);
cal.set(Calendar.SECOND,0);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(cal.getTime()));
Date date = new Date(60000*60*8+4000);
System.out.println(date.getTimezoneOffset());
System.out.println(date.getHours());
SimpleDateFormat aFormat = new SimpleDateFormat(":mm:ss");
System.out.println(aFormat.format(date));
int hours = date.getHours()-8;
if(hours<0){
hours = hours+24;
}
// int i=0;
System.out.println(hours+aFormat.format(date));
}
}
| true |
53f7f715f0f9fb335ebeb4e805faea4ecde18064 | Java | london2103/Faktura | /src/main/java/com/my/order/OrderStateUnableToComplete.java | UTF-8 | 1,026 | 2.34375 | 2 | [] | no_license | package com.my.order;
import com.my.executor.InvalidStateException;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
/**
* Created by marcin on 15.01.16.
*/
@Entity
@DiscriminatorValue("UN")
public class OrderStateUnableToComplete extends OrderState {
public OrderStateUnableToComplete() {
orderStateType = OrderStateType.UNABLE_TO_COMPLETE;
}
@Override
public void cancel() throws InvalidStateException {
getOrderComponent().setState(new OrderStateCancelled());
}
@Override
public void send() throws InvalidStateException {
throw new InvalidStateException();
}
@Override
public void pay() throws InvalidStateException {
throw new InvalidStateException();
}
@Override
public void complete() throws InvalidStateException {
throw new InvalidStateException();
}
@Override
public void unableToComplete() throws InvalidStateException {
throw new InvalidStateException();
}
}
| true |
cc698505bd855b433afcd451d7c3a2daec66f06d | Java | MrHup/Attendance | /app/src/main/java/com/babygirl/attendance/objects/Course.java | UTF-8 | 1,561 | 2.328125 | 2 | [] | no_license | package com.babygirl.attendance.objects;
import android.content.Intent;
import java.io.Serializable;
public class Course implements Serializable {
private String DQRC;
private String course_name;
private String instructor_name;
//private String desc;
private String target_year;
public String getDQRC() {
return DQRC;
}
public void setDQRC(String DQRC) {
this.DQRC = DQRC;
}
public String getCourse_name() {
return course_name;
}
public void setCourse_name(String course_name) {
this.course_name = course_name;
}
public String getInstructor_name() {
return instructor_name;
}
public void setInstructor_name(String instructor_name) {
this.instructor_name = instructor_name;
}
public String getTarget_year() {
return target_year;
}
public void setTarget_year(String target_year) {
this.target_year = target_year;
}
@Override
public String toString() {
return "Course{" +
"DQRC='" + DQRC + '\'' +
", course_name='" + course_name + '\'' +
", instructor_name='" + instructor_name + '\'' +
", target_year='" + target_year + '\'' +
'}';
}
public Course(String DQRC, String course_name, String instructor_name, String target_year)
{
this.DQRC = DQRC;
this.course_name = course_name;
this.instructor_name = instructor_name;
this.target_year = target_year;
}
}
| true |
5112190cbc425faf83436ece209ae3bf3cf1bd4a | Java | Faye413/Where-Is-My-Money-Android-App | /WhereIsMyMoney/src/com/whereismymoney/activity/Login.java | UTF-8 | 4,648 | 2.640625 | 3 | [] | no_license | package com.whereismymoney.activity;
import com.whereismymoney.R;
import com.whereismymoney.model.CredentialManager;
import com.whereismymoney.service.IntegrityCheck;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
/**
* This class handles the login page.
*/
public class Login extends Activity implements View.OnClickListener {
/**
* This is a private PasswordManager used for checking passwords.
*/
private CredentialManager passwordManager;
/**
* A button the user uses to login.
*/
private Button login;
/**
* A button the user uses to register.
*/
private Button register;
/**
* A button the user presses when he has forgotten his password.
*/
private Button forgotPassword;
private EditText username;
private EditText password;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Turn off the window's title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
passwordManager = new CredentialManager();
login = (Button) findViewById(R.id.button_login_login);
register = (Button) findViewById(R.id.button_login_register);
forgotPassword = (Button) findViewById(R.id.button_forgot_password);
login.setOnClickListener(this);
register.setOnClickListener(this);
forgotPassword.setOnClickListener(this);
username = (EditText) findViewById(R.id.edit_text_login_username);
password = (EditText) findViewById(R.id.edit_text_login_password);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_login_login:
onLoginClicked();
break;
case R.id.button_login_register:
Intent goToRegister = new Intent(
"android.intent.action.REGISTER");
startActivity(goToRegister);
break;
case R.id.button_forgot_password:
Intent goToForgotPassword = new Intent(
"android.intent.action.FORGOTPASSWORD");
startActivity(goToForgotPassword);
break;
}
}
private void onLoginClicked() {
String failAlert = "Registration Failed";
String failReason = null;
// checking to see if the password is at least 7 characters and
// the username is at least one character
if (IntegrityCheck.checkPasswordLength(password.getText()
.toString(), 7)
&& IntegrityCheck.isInputValid(username.getText()
.toString())) {
// checks with the server to see if the login info is valid
if (passwordManager.login(username.getText().toString(),
password.getText().toString())) {
Intent goToAccountList = new Intent(
"android.intent.action.ACCOUNTINFO");
startActivity(goToAccountList);
} else {
// the server returned false for the login method with
// those parameters
failReason = "Incorrect User Name or Password";
}
} else {
// alerting the user that the password is <7 characters
if (!IntegrityCheck.checkPasswordLength(password.getText()
.toString(), 7)) {
failReason = "Your password must be at least 7 characters";
} else {
// alerting the user that they didn't enter a username
failReason = "You need to enter a username!";
}
AlertDialog loginFailAlert = new AlertDialog.Builder(
Login.this).create();
loginFailAlert.setTitle(failAlert);
loginFailAlert.setMessage(failReason);
loginFailAlert.show();
}
}
} | true |
3d780fc73147d78a8f2885902d291a1777774871 | Java | fj8542758/redtorch | /rt-node-master/src/main/java/xyz/redtorch/node/master/po/OperatorPo.java | UTF-8 | 4,692 | 1.960938 | 2 | [
"MIT"
] | permissive | package xyz.redtorch.node.master.po;
import java.util.HashSet;
import java.util.Set;
public class OperatorPo {
private String operatorId;
private boolean associatedToUser = false;
private String username;
private String description;
private boolean canReadAllAccounts = true;
private Set<String> acceptReadSpecialAccountIdSet = new HashSet<>();
private Set<String> denyReadSpecialAccountIdSet = new HashSet<>();
private boolean canTradeAllAccounts = false;
private Set<String> acceptTradeSpecialAccountIdSet = new HashSet<>();
private Set<String> denyTradeSpecialAccountIdSet = new HashSet<>();
private boolean canTradeAllContracts = false;
private Set<String> acceptTradeSpecialUnifiedSymbolSet = new HashSet<>();
private Set<String> denyTradeSpecialUnifiedSymbolSet = new HashSet<>();
private boolean canSubscribeAllContracts = true;
private Set<String> acceptSubscribeSpecialUnifiedSymbolSet = new HashSet<>();
private Set<String> denySubscribeSpecialUnifiedSymbolSet = new HashSet<>();
public String getOperatorId() {
return operatorId;
}
public void setOperatorId(String operatorId) {
this.operatorId = operatorId;
}
public boolean isAssociatedToUser() {
return associatedToUser;
}
public void setAssociatedToUser(boolean associatedToUser) {
this.associatedToUser = associatedToUser;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isCanReadAllAccounts() {
return canReadAllAccounts;
}
public void setCanReadAllAccounts(boolean canReadAllAccounts) {
this.canReadAllAccounts = canReadAllAccounts;
}
public Set<String> getAcceptReadSpecialAccountIdSet() {
return acceptReadSpecialAccountIdSet;
}
public void setAcceptReadSpecialAccountIdSet(Set<String> acceptReadSpecialAccountIdSet) {
this.acceptReadSpecialAccountIdSet = acceptReadSpecialAccountIdSet;
}
public Set<String> getDenyReadSpecialAccountIdSet() {
return denyReadSpecialAccountIdSet;
}
public void setDenyReadSpecialAccountIdSet(Set<String> denyReadSpecialAccountIdSet) {
this.denyReadSpecialAccountIdSet = denyReadSpecialAccountIdSet;
}
public boolean isCanTradeAllAccounts() {
return canTradeAllAccounts;
}
public void setCanTradeAllAccounts(boolean canTradeAllAccounts) {
this.canTradeAllAccounts = canTradeAllAccounts;
}
public Set<String> getAcceptTradeSpecialAccountIdSet() {
return acceptTradeSpecialAccountIdSet;
}
public void setAcceptTradeSpecialAccountIdSet(Set<String> acceptTradeSpecialAccountIdSet) {
this.acceptTradeSpecialAccountIdSet = acceptTradeSpecialAccountIdSet;
}
public Set<String> getDenyTradeSpecialAccountIdSet() {
return denyTradeSpecialAccountIdSet;
}
public void setDenyTradeSpecialAccountIdSet(Set<String> denyTradeSpecialAccountIdSet) {
this.denyTradeSpecialAccountIdSet = denyTradeSpecialAccountIdSet;
}
public boolean isCanTradeAllContracts() {
return canTradeAllContracts;
}
public void setCanTradeAllContracts(boolean canTradeAllContracts) {
this.canTradeAllContracts = canTradeAllContracts;
}
public Set<String> getAcceptTradeSpecialUnifiedSymbolSet() {
return acceptTradeSpecialUnifiedSymbolSet;
}
public void setAcceptTradeSpecialUnifiedSymbolSet(Set<String> acceptTradeSpecialUnifiedSymbolSet) {
this.acceptTradeSpecialUnifiedSymbolSet = acceptTradeSpecialUnifiedSymbolSet;
}
public Set<String> getDenyTradeSpecialUnifiedSymbolSet() {
return denyTradeSpecialUnifiedSymbolSet;
}
public void setDenyTradeSpecialUnifiedSymbolSet(Set<String> denyTradeSpecialUnifiedSymbolSet) {
this.denyTradeSpecialUnifiedSymbolSet = denyTradeSpecialUnifiedSymbolSet;
}
public boolean isCanSubscribeAllContracts() {
return canSubscribeAllContracts;
}
public void setCanSubscribeAllContracts(boolean canSubscribeAllContracts) {
this.canSubscribeAllContracts = canSubscribeAllContracts;
}
public Set<String> getAcceptSubscribeSpecialUnifiedSymbolSet() {
return acceptSubscribeSpecialUnifiedSymbolSet;
}
public void setAcceptSubscribeSpecialUnifiedSymbolSet(Set<String> acceptSubscribeSpecialUnifiedSymbolSet) {
this.acceptSubscribeSpecialUnifiedSymbolSet = acceptSubscribeSpecialUnifiedSymbolSet;
}
public Set<String> getDenySubscribeSpecialUnifiedSymbolSet() {
return denySubscribeSpecialUnifiedSymbolSet;
}
public void setDenySubscribeSpecialUnifiedSymbolSet(Set<String> denySubscribeSpecialUnifiedSymbolSet) {
this.denySubscribeSpecialUnifiedSymbolSet = denySubscribeSpecialUnifiedSymbolSet;
}
}
| true |
9437f04f18a93acf9987b4652de34403328b916f | Java | reesealanj/alien-attack-game | /src/AlienAttackBoard.java | UTF-8 | 728 | 2.859375 | 3 | [] | no_license | import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class AlienAttackBoard extends JPanel {
private static final long serialVersionUID = 1L;
protected static int boardSize = 750;
protected static int gridSize = 30;
protected static int numGrids = 25;
public AlienAttackBoard() {
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setBackground(Color.DARK_GRAY);
setLayout(null);
setSize(boardSize, boardSize);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(boardSize, boardSize);
}
@Override
public Dimension getMaximumSize() {
return new Dimension(boardSize, boardSize);
}
}
| true |