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 |
---|---|---|---|---|---|---|---|---|---|---|---|
f5c09e435d962fca6883fbc15faeeb95be5a3c6a
|
Java
|
SergAnya/Project
|
/src/main/java/com/bykov/project/conference/dao/DaoFactory.java
|
UTF-8
| 623 | 2.09375 | 2 |
[] |
no_license
|
package com.bykov.project.conference.dao;
public abstract class DaoFactory {
private static volatile DaoFactory daoFactory;
public abstract DaoUser getUserDao();
public abstract DaoReport getReportDao();
public abstract DaoSpeaker getSpeakerDao();
public abstract DaoConference getConferenceDao();
static public DaoFactory getInstance() {
if (daoFactory == null) {
synchronized (DaoFactory.class) {
if (daoFactory == null) {
daoFactory = new JdbcDaoFactory();
}
}
}
return daoFactory;
}
}
| true |
13d02544ba82dabf10b1201a4d729bf8aee66a80
|
Java
|
piabc/MZS-Getter
|
/src/Main.java
|
UTF-8
| 243 | 1.898438 | 2 |
[] |
no_license
|
import core.Process;
public class Main {
public static void main(String[] args) {
String src = Process.getSource("https://mp3.zing.vn/bai-hat/Da-Lo-Yeu-Em-Nhieu-JustaTee/ZW8W6UEF.html");
System.out.println(src);
}
}
| true |
1ad98fd0daa5fc39845a318248b4ad29f2ed8945
|
Java
|
zhang-zi-ang/mytest
|
/JavaBasicTest/src/Demo_14_Red/NormalMode.java
|
UTF-8
| 667 | 2.90625 | 3 |
[] |
no_license
|
package Demo_14_Red;
import Red.OpenMode;
import java.util.ArrayList;
/**
* @program: mygit
* @author: zhang-zi-ang
* @create: 2020-03-28 14:59
* @description: ${description}
*/
public class NormalMode implements OpenMode {
@Override
public ArrayList<Integer> divide(final int totalMoney, final int totalCount) {
ArrayList<Integer> list = new ArrayList<>();
int avg = totalMoney / totalCount; //平均数
int mod = totalMoney % totalCount; //余数,模除,零头
//注意,最后一个先留着
for (int i = 0; i < totalCount - 1; i++) {
list.add(avg);
}
//最后一个红包放零头
list.add(avg + mod);
return list;
}
}
| true |
c99b63d1d9cff8fd88aaddc9c00cea205713b9f8
|
Java
|
UnicornoftheSea99/CSC212P7
|
/src/main/java/edu/smith/cs/csc212/p7/SelectSort.java
|
UTF-8
| 1,220 | 3.75 | 4 |
[] |
no_license
|
//CSC212 P7
//Emily Rhyu
package edu.smith.cs.csc212.p7;
import java.util.List;
//Sources:
//Data Structures and Algorithms in Java, 2nd ed.by Drozdek
//https://www.geeksforgeeks.org/selection-sort/
//https://www.youtube.com/watch?v=AgFR0kO05RM
/**
*
* Select Sort is a simply sort that is O(n^2).
* @author emilyrhyu
*
* Sorting method brings minimum value to front of list until sorted.
*/
public class SelectSort {
/**
* Swap items in a list!
*
* @param items the list.
* @param i swap the item at this index with the one at least.
* @param least swap the item at this index with the one at i.
*/
public static void swap(List<Integer> items, int i, int least) {
int tmp = items.get(least);
items.set(least, items.get(i));
items.set(i, tmp);
}
/**
* Select Sort Finds the Minimum Value and Brings it to the Front.
*
* @param input - the list to be sorted.
* @param N- size of list
*/
public static void selectSort(List<Integer> input) {
int N = input.size();
for (int i = 0; i < N - 1; i++) {
int least = i;
for (int j = i + 1; j < N; j++) {
if (input.get(least) > input.get(j)) {
swap(input, least, j);
}
}
swap(input, i, least);
}
}
}
| true |
0b4556a707c3a525cadd475f8b1b5f2e3f4c14a3
|
Java
|
patricklaux/xcache
|
/xcache-common/src/main/java/com/igeeksky/xcache/util/BeanUtils.java
|
UTF-8
| 2,579 | 2.53125 | 3 |
[] |
no_license
|
/*
* Copyright 2017 Patrick.lau All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.igeeksky.xcache.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Bean工具类
*
* @author Patrick.Lau
* @since 0.0.1 2017-03-02
*/
public abstract class BeanUtils {
private BeanUtils() {
}
public static Object getBeanProperty(Object bean, String fieldName) throws ReflectiveOperationException {
Objects.requireNonNull(bean, "bean must not be null");
Field field = bean.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(bean);
}
@SuppressWarnings("unchecked")
public static <T> List<T> getBeansProperty(Object[] list, String fieldName, Class<T> type) throws ReflectiveOperationException {
Objects.requireNonNull(list, "beanList must not be null");
if (list.length > 0) {
List<T> ids = new ArrayList<T>();
for (Object o : list) {
ids.add((T) getBeanProperty(o, fieldName));
}
return ids;
}
return null;
}
public static <T> T instantiateClass(Class<T> clazz, Object... params) throws ReflectiveOperationException {
if (clazz.isInterface()) {
throw new InstantiationException(clazz.getName() + " is an interface");
}
Class<?>[] parameterTypes = new Class<?>[params.length];
for (int i = 0; i < params.length; i++) {
Object obj = params[i];
if (null != obj) {
parameterTypes[i] = params[i].getClass();
}
}
try {
Constructor<T> constructor = clazz.getConstructor(parameterTypes);
return constructor.newInstance(params);
} catch (NoSuchMethodException e) {
Constructor<T> constructor = clazz.getDeclaredConstructor();
return constructor.newInstance();
}
}
}
| true |
9f921ab4363356ec55c30c556e735e72e35544f2
|
Java
|
lee-seul/KNU_computer
|
/Java/ch07/src/mathtest/MathTest.java
|
UTF-8
| 331 | 3.546875 | 4 |
[] |
no_license
|
package mathtest;
class Math {
int add(int x, int y){
return x + y;
}
}
public class MathTest {
public static void main(String[] args) {
int sum;
Math obj = new Math();
sum = obj.add(2, 3);
System.out.println("2와 3d의 합은 " +sum);
sum = obj.add(7, 8);
System.out.println("7와 8의 합은 " + sum);
}
}
| true |
92911329b52e22d44fffb530cbaf8f208ec7fc38
|
Java
|
OmerHikly/BigProject
|
/Alphatest/app/src/main/java/com/example/alpha_test/Team.java
|
UTF-8
| 8,547 | 2.40625 | 2 |
[] |
no_license
|
package com.example.alpha_test;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import org.parceler.Parcels;
import java.util.ArrayList;
import java.util.List;
import static com.example.alpha_test.FirebaseHelper.refSchool;
public class Team extends AppCompatActivity {
Teacher teacher;//עצם מסוג מורה
String school,phone,cls;//מאפיינים של מורה (כיתה, בית ספר וטלפון)
String GroupName;//יכיל את שם הקבוצה שנבחרה במסך הקודם
ArrayList<String> Students = new ArrayList<>();// יכיל את התלמידים ששייכים לקבוצה
ArrayList<String> ExistPhones = new ArrayList<>();//רשימת התלמידים שנבחרו להיווסף לקבוצה
Toolbar toolbar;
ListView lv;
Button btn;
Student student;
GroupAdapter adapter;//מתאם אישי שעוצב עבור הlistview
DatabaseReference refGroup;// רפרנס אל מיקום הקבוצה ב -database
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team);
lv=findViewById(R.id.StudentsLv);
btn=findViewById(R.id.AddMembers);
toolbar=findViewById(R.id.tb);
Intent gi=getIntent();//רכיב שמעביר את הערכים שהועברו מהמסך הקודם
GroupName=gi.getStringExtra("name");//הצבת שם הקבוצה מהמסך הקודם
toolbar.setTitle(GroupName);
setSupportActionBar(toolbar);
Parcelable parcelable=getIntent().getParcelableExtra("teacher");//קבלת עצם המורה מהאקטיביטים הקודמים
teacher= Parcels.unwrap(parcelable);//קישורו אל העצם מסוג מורה שהגדרנו עבור המסך הזה
school=teacher.getSchool();;//השמת ערכים בתכונות של המורה
phone=teacher.getPhone();
cls=teacher.getCls();
refGroup=refSchool.child(school).child("Teacher").child(phone).child("zgroups").child(GroupName);//הגדרת הרפרנס
SetList();// פעולה ששמה בListview את הרשימה של התלמידים ששייכים לקבוצה
}
private void SetList() {
refSchool.child(school).child("Teacher").child(phone).child("zgroups").child(GroupName).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Students.clear();
ExistPhones.clear();
if (dataSnapshot.getValue() != null) {
String team = dataSnapshot.getValue().toString();
String Splitted[] = team.split(" ");
for (int i = 0; i < Splitted.length; i++) {
String StudentD = Splitted[i];
char last=StudentD.charAt(StudentD.length()-1);
if(last==','){
StudentD=StudentD.substring(0,StudentD.length()-1);
}
ExistPhones.add(StudentD);
}
showData();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void showData() {
Students.clear();
for(String p:ExistPhones) {
refSchool.child(school).child("Student").child(p).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dsp) {
student = new Student();
student = dsp.getValue(Student.class);
String id = student.getId();
String name = student.getName();
String secondname = student.getSecondName();
String uphone = student.getPhone();
String x = "תלמיד: " + name + " " + secondname + " " + id + " " + uphone;
Students.add(x);
Adapt(Students);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
private void Adapt(ArrayList<String> arrayList) {// פעולת הקישור בין המתאם שעוצב עבור המסך הזה אל הרשימה הנגללת (listview)
adapter = new GroupAdapter(this, R.layout.user_list_unconfirmed, arrayList);
lv.setAdapter(adapter);
}
public class GroupAdapter extends ArrayAdapter {//ה-class עבור המתאם המעוצב שיצרתי
private int layout;
public GroupAdapter(@NonNull Context context, int resource, @NonNull List objects) {
super(context, 0, objects);
layout = resource;
}
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder mainViewholder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.approve=convertView.findViewById(R.id.approve);
viewHolder.details = convertView.findViewById(R.id.detail);
viewHolder.remove = convertView.findViewById(R.id.remove);
convertView.setTag(viewHolder);
}
mainViewholder =(ViewHolder) convertView.getTag();
final String str = Students.get(position);
final String[] Splitted = str.split(" ");
String text = Splitted[0] + " " + Splitted[1] + " " + Splitted[2] + Splitted[3];
mainViewholder.details.setText(text);
mainViewholder.approve.setVisibility(View.GONE);
mainViewholder.remove.setText("הסר");
mainViewholder.remove.setOnClickListener(new View.OnClickListener() {
@Override//פעולה זו מאםשרת למורה להסיר תלמיד מהקבוצה בגלל שכנראה התלמיד עבר כיתה
public void onClick(View v) {
Students.remove(position);
ExistPhones.remove(position);
Adapt(Students);
if (Students.isEmpty()) {
refGroup.removeValue();
} else {
String GroupData = ExistPhones.toString();
GroupData=GroupData.substring(1,GroupData.length()-1); //שורה זו מסירה את ה'[' וה-']' שמופיעם כאשר עושים toString() ל-Arraylist -
refGroup.setValue(GroupData);
}
}
});
return convertView;//בשורה הזו הפעולה מחזירה את התצוגה החדשה שהגדרנו
}
}
public class ViewHolder {//רכיבי התצוגה שיועדו לlistview
TextView details;
Button remove,approve;
}
public void AddStudents(View view) {//פעולת מעבר בין המסכים שמעבירה את המורה בלחיצת כפתור אל המסך שבו הוא יכול להוסיף תלמידים נוספים לקבוצה
Intent i=new Intent(this,AddStudentsToGroup.class);
Parcelable parcelable= Parcels.wrap(teacher);
i.putExtra("teacher", parcelable);
i.putExtra("name",GroupName);
i.putExtra("Stu",Students);
i.putExtra("Ex",ExistPhones);
startActivity(i);
}
}
| true |
dfe38214613cf8322e69fa5b0717f9bef3090b8f
|
Java
|
terexwizard/accountapp
|
/src/java/com/scc/pay/business/PROCESSBRINGFORWARD.java
|
UTF-8
| 17,373 | 1.976563 | 2 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.scc.pay.business;
import com.scc.f1.business.BusinessImpl;
import com.scc.f1.util.BeanUtil;
import com.scc.f1.util.Utils;
import com.scc.pay.db.Bringforward;
import com.scc.pay.db.BringforwardPK;
import com.scc.pay.db.TbBank;
import com.scc.pay.util.CenterUtils;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import javax.persistence.Query;
/**
*
* @author xtra
* @version 1.00.00
* 12/06/2555 12:50:20
*/
public class PROCESSBRINGFORWARD extends BusinessImpl {
private int bfdate = 0;
@Override
protected Object doProcess(Object inobj) {
HashMap<String,String> vhm = (HashMap<String,String>)inobj;
String vuser = vhm.get("vuser");
String vbfdate = vhm.get("vbfdate");
logger.debug(">>processBringforward date:" + vhm.get("vbfdate"));
//if(countBringforward(vbfdate)){
bfdate = Integer.parseInt(vbfdate);
if(!Utils.NVL(vbfdate).equals("")){
//มีการแก้ไขวันที่
if(!Utils.NVL(vbfdate).equals(Utils.formatDateToStringToDBEn(Utils.getcurDateTime()))){
//ลบแล้วคำนวณใหม่
String sql = "delete FROM Bringforward r "
+ "where r.bringforwardPK.bfdate >= :bfdate ";
//+ "where r.bringforwardPK.bfdate > :bfdate ";
Query query = em.createQuery(sql);
query.setParameter("bfdate",vbfdate);
query.executeUpdate();
}
}
checkLastBringforward();
processBringforward(vuser);
//}
return inobj;
}
private boolean countBringforward(String dailydate){
String previousDay = CenterUtils.previousDayEn(dailydate,1);
Long count = checkLastDataBringforward(previousDay);
if(count == 0){
return true;
}else{
return false;
}
}
private void checkLastBringforward(){
logger.debug(">>processBringforward :"+bfdate);
Long count = checkLastDataBringforward(Integer.toString(bfdate));
if(count == 0){
//bfdate--;
bfdate = Integer.parseInt(CenterUtils.previousDayEn(Integer.toString(bfdate), 1));
checkLastBringforward();
}else{
logger.debug(">>processBringforward finish:"+bfdate);
}
}
private void processBringforward(String vuser){
if(isDateValid(Utils.NVL(bfdate))){
// if(bfdate < (Integer.parseInt(Utils.getcurDateDB(false))-2)){ //ไม่ทำวันที่ ปัจจุบัน -2
// bfdate = Integer.parseInt(CenterUtils.nextDayEn(Integer.toString(bfdate),1));
//
// processBringforward(vuser);
// }
logger.debug(">>processBringforward loop:"+bfdate+" // "+Utils.getcurDateDB(false));
if(bfdate == (Integer.parseInt(Utils.getcurDateDB(false)))){
processBringforwardUpdate(vuser,bfdate);
}else{
transactionCommit();
transactionBegin();
processBringforwardInsert(vuser,bfdate);
logger.debug(">>processBringforward loop else :"+bfdate+" // "+Utils.getcurDateDB(false));
//if(bfdate < (Integer.parseInt(Utils.getcurDateDB(false))-2)){ //ไม่ทำวันที่ ปัจจุบัน -2
if(bfdate < (Integer.parseInt(Utils.getcurDateDB(false))-1)){ //ทำถึงวันที่ ปัจจุบัน -1
bfdate = Integer.parseInt(CenterUtils.nextDayEn(Integer.toString(bfdate),1));
processBringforward(vuser);
}
}
}
}
private Long checkLastDataBringforward(String bfdate){
String sql = "select count(r.bringforwardPK.bfdate) FROM Bringforward r "
+ "where r.bringforwardPK.bfdate = :bfdate ";
Query query = em.createQuery(sql);
query.setParameter("bfdate",bfdate);
Long count = (Long)query.getSingleResult();
logger.debug(">>processBringforward "+bfdate +" // "+count);
return count;
}
private void processBringforwardInsert(String vuser,int processdate){
String sql = "select r FROM Bringforward r "
+ "where r.bringforwardPK.bfdate = :bfdate ";
Query query = em.createQuery(sql);
query.setParameter("bfdate",Integer.toString(processdate));
List<Bringforward> l = query.getResultList();
logger.debug(">>processBringforwardInsert "+processdate+" , size:"+l.size());
for(Bringforward dbold : l){
em.detach(dbold);
//String nextbfdate = Integer.toString(processdate +1);
String nextbfdate = CenterUtils.nextDayEn(Integer.toString(processdate),1);
Bringforward db = new Bringforward(new BringforwardPK());
BeanUtil.copyProperties(db, dbold);
db.setBringforwardPK(dbold.getBringforwardPK());
logger.debug(">>processBringforwardInsert "+processdate+" "+nextbfdate+
" ,getBankid:"+db.getBringforwardPK().getBankid()+
" ,getBfdate:"+db.getBringforwardPK().getBfdate());
db.getBringforwardPK().setBfdate(nextbfdate);
db.setReceived(countDailyReceived(nextbfdate,db.getBringforwardPK().getBankid()));
db.setPaid(countDailyPaid(nextbfdate,db.getBringforwardPK().getBankid()));
db.setBpchqrcv(countChequeClearDailyReceived(nextbfdate,db.getBringforwardPK().getBankid(),true));
db.setBpchqpaid(countChequeClearDailyPaid(nextbfdate,db.getBringforwardPK().getBankid(),true));
db.setBtchqrcv(countChequeClearDailyReceived(nextbfdate,db.getBringforwardPK().getBankid(),false));
db.setBtchqpaid(countChequeClearDailyPaid(nextbfdate,db.getBringforwardPK().getBankid(),false));
if(db.getBringforwardPK().getBankid() == 3){
logger.debug(">>processBringforwardInsert terex "+nextbfdate+" // "+db.getActualmoney());
logger.debug(">>processBringforwardInsert terex "+nextbfdate+" // getActualmoney:"+db.getActualmoney()+
" // getReceived:"+db.getReceived()+" // db.getBpchqrcv:"+db.getBpchqrcv()+
" // getBtchqpaid:"+db.getBtchqpaid()+" // getPaid:"+db.getPaid()
+" // getBpchqpaid:"+db.getBpchqpaid()+" // getBtchqrcv:"+db.getBtchqrcv());
}
//Double actualmoney = (db.getActualmoney()+db.getReceived()) - db.getPaid();
Double actualmoney = (db.getActualmoney()+db.getReceived()+db.getBpchqrcv()+db.getBtchqpaid()) - db.getPaid()-db.getBpchqpaid()-db.getBtchqrcv();
db.setActualmoney(actualmoney);
db.setUpdlcnt(1);
db.setUpdtime( Utils.getcurDateTime() );
db.setUpduser(vuser);
//==========================
//persist(db);
Bringforward dbvn = em.find(Bringforward.class, db.getBringforwardPK());
if(dbvn == null){
persist(db);
}else{
BeanUtil.copyProperties(dbvn, db);
merge(dbvn);
}
transactionCommit();
transactionBegin();
}
}
private void processBringforwardUpdate(String vuser,int processdate){
logger.debug(">>processBringforwardUpdate "+processdate);
String sql = "select r FROM Bringforward r "
+ "where r.bringforwardPK.bfdate = :bfdate ";
Query query = em.createQuery(sql);
query.setParameter("bfdate",Integer.toString(processdate));
List<Bringforward> l = query.getResultList();
for(Bringforward db : l){
em.detach(db);
String sqlpre = "select r FROM Bringforward r "
+ "where r.bringforwardPK.bfdate = :bfdate and r.bringforwardPK.bankid = :bankid";
Query querypre = em.createQuery(sqlpre);
String previousDay = CenterUtils.previousDayEn(Integer.toString(processdate), 1);
querypre.setParameter("bfdate",previousDay);
querypre.setParameter("bankid",new BigDecimal(db.getBringforwardPK().getBankid()));
List<Bringforward> lpre = querypre.getResultList();
Bringforward bringforward = new Bringforward();
for(Bringforward dbpre : lpre){
BeanUtil.copyProperties(bringforward, dbpre);
}
//=================================
//String nextbfdate = Integer.toString(processdate +1);
String nextbfdate = Integer.toString(processdate);
db.getBringforwardPK().setBfdate(nextbfdate);
db.setReceived(countDailyReceived(nextbfdate,db.getBringforwardPK().getBankid()));
db.setPaid(countDailyPaid(nextbfdate,db.getBringforwardPK().getBankid()));
db.setBpchqrcv(countChequeClearDailyReceived(nextbfdate,db.getBringforwardPK().getBankid(),true));
db.setBpchqpaid(countChequeClearDailyPaid(nextbfdate,db.getBringforwardPK().getBankid(),true));
db.setBtchqrcv(countChequeClearDailyReceived(nextbfdate,db.getBringforwardPK().getBankid(),false));
db.setBtchqpaid(countChequeClearDailyPaid(nextbfdate,db.getBringforwardPK().getBankid(),false));
//Double actualmoney = (db.getActualmoney()+db.getReceived()) - db.getPaid();
//Double actualmoney = (db.getActualmoney()+db.getReceived()+db.getBpchqrcv()+db.getBtchqpaid()) - db.getPaid()-db.getBpchqpaid()-db.getBtchqrcv();
logger.debug(" getActualmoney:"+bringforward.getActualmoney()+
" getReceived:"+db.getReceived()+" getBpchqrcv:"+db.getBpchqrcv()+
" getBtchqpaid:"+db.getBtchqpaid()+" -getPaid:"+db.getPaid()+
" -getBpchqpaid:"+db.getBpchqpaid()+" -getBtchqrcv:"+db.getBtchqrcv());
Double actualmoney = (bringforward.getActualmoney()+db.getReceived()+db.getBpchqrcv()+db.getBtchqpaid()) - db.getPaid()-db.getBpchqpaid()-db.getBtchqrcv();
db.setActualmoney(actualmoney);
db.setUpdlcnt(1);
db.setUpdtime( Utils.getcurDateTime() );
db.setUpduser(vuser);
//==========================
//persist(db);
Bringforward dbvn = em.find(Bringforward.class, db.getBringforwardPK());
if(dbvn == null){
persist(db);
}else{
BeanUtil.copyProperties(dbvn, db);
merge(dbvn);
}
}
}
private Double countDailyReceived(String dailydate,int payby){
String sql = "select ";
//if(payby == 2){
if(checkmonetaryusd(payby)){
sql += "sum(r.amount) FROM Daily r ";
}else{
sql += "sum(r.receivedamount) FROM Daily r ";
}
sql += "where r.dailydate = :dailydate and r.payby = :payby ";
//+ "and r.cheque = :cheque";
Query query = em.createQuery(sql);
query.setParameter("dailydate",dailydate);
query.setParameter("payby",new BigDecimal(payby).doubleValue());
//query.setParameter("cheque","false");
Double sum = (Double)query.getSingleResult();
logger.debug(">>countDailyReceived "+sum);
if(sum == null){
return new Double("0");
}else{
return sum;
}
}
private Double countDailyPaid(String dailydate,int payby){
String sql = "select ";
//if(payby == 2){
if(checkmonetaryusd(payby)){
sql += "sum(r.amount2) FROM Daily r ";
}else{
sql += "sum(r.paidamount) FROM Daily r ";
}
sql += "where r.dailydate = :dailydate and r.payby = :payby ";
//+ "and r.cheque = :cheque";
Query query = em.createQuery(sql);
query.setParameter("dailydate",dailydate);
query.setParameter("payby",new BigDecimal(payby).doubleValue());
//query.setParameter("cheque","false");
Double sum = (Double)query.getSingleResult();
logger.debug(">>countDailyPaid "+sum);
if(sum == null){
return new Double("0");
}else{
return sum;
}
}
private Double countChequeClearDailyReceived(String dailydate,int payby,boolean vclear){
String sql = "select ";
//if(payby == 2){
if(checkmonetaryusd(payby)){
sql += "sum(r.amount) FROM Daily r ";
}else{
sql += "sum(r.receivedamount) FROM Daily r ";
}
if(vclear){
sql += "where r.chequedate = :chequedate and r.payby = :payby ";
sql += "and r.chequedate is not null "; //cheque clear
}else{
sql += "where r.dailydate = :dailydate and r.payby = :payby ";
sql += "and r.chequedate is null "; //cheque not clear
}
sql += "and r.cheque = :cheque ";
Query query = em.createQuery(sql);
if(vclear){
query.setParameter("chequedate",dailydate);
}else{
query.setParameter("dailydate",dailydate);
}
query.setParameter("payby",new BigDecimal(payby).doubleValue());
query.setParameter("cheque","true");
Double sum = (Double)query.getSingleResult();
logger.debug(">>countChequeClearDailyReceived "+sum);
if(sum == null){
return new Double("0");
}else{
return sum;
}
}
private Double countChequeClearDailyPaid(String dailydate,int payby,boolean vclear){
String sql = "select ";
//if(payby == 2){
if(checkmonetaryusd(payby)){
sql += "sum(r.amount2) FROM Daily r ";
}else{
sql += "sum(r.paidamount) FROM Daily r ";
}
if(vclear){
sql += "where r.chequedate = :chequedate and r.payby = :payby ";
sql += "and r.chequedate is not null "; //cheque clear
}else{
sql += "where r.dailydate = :dailydate and r.payby = :payby ";
sql += "and r.chequedate is null "; //cheque not clear
}
sql += "and r.cheque = :cheque ";
Query query = em.createQuery(sql);
if(vclear){
query.setParameter("chequedate",dailydate);
}else{
query.setParameter("dailydate",dailydate);
}
query.setParameter("payby",new BigDecimal(payby).doubleValue());
query.setParameter("cheque","true");
Double sum = (Double)query.getSingleResult();
logger.debug(">>countChequeClearDailyPaid "+sum);
if(sum == null){
return new Double("0");
}else{
return sum;
}
}
private boolean checkmonetaryusd(int payby){
TbBank db = em.find(TbBank.class, payby);
if(db != null){
if(db.getMonetaryusd().equals("true")){
return true;
}
return false;
}
return false;
}
public static boolean isDateValid(String date)
{
try {
DateFormat df = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
df.setLenient(false);
df.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
}
| true |
6b4e79854611e077e29173bfc9863f6b1fe6a2ac
|
Java
|
JoseLuisMartins/PokerServer-LPOO
|
/poker-server/src/Gui/GameUI.java
|
UTF-8
| 11,252 | 2.5625 | 3 |
[] |
no_license
|
package Gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.TexturePaint;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.Timer;
import Logic.Game;
import Logic.Table;
import common.Card;
import common.PlayerInterface;
public class GameUI extends JPanel implements UiInterface{
private static final long serialVersionUID = 1L;
private BufferedImage cardsImage;
private BufferedImage background;
private BufferedImage table;
private BufferedImage wood;
private BufferedImage money;
private BufferedImage play;
private BufferedImage waiting;
private BufferedImage dealerImage;
private BufferedImage smalBlindImage;
private BufferedImage bigBlindImage;
private BufferedImage dealerAvatar;
static Game game;
private ArrayList<Integer> xValues ;
private ArrayList<Integer> yValues ;
private ArrayList<Integer> posCards; // dx1 - dy1 - dx2 - dy2
private ArrayList<Integer> positionXOfMoney;
private ArrayList<Integer> positionYOfMoney;
private int diameter;
private int cellWidth;
private int cellHeight;
private int x;
private int y;
private Boolean animating = false;
private int potPosX;
private int potPosY;
private Boolean left = false;
private Boolean up = false;
private Timer timer;
private int animationAmount;
private boolean drawPlayerCards = false;
private int screenHeight;
private int screenWidth;
private int state=0;
public GameUI(Game g) {
try {
cardsImage = ImageIO.read(new File("cards.jpg"));
background = ImageIO.read(new File("background.jpg"));
table = ImageIO.read(new File("table.jpg"));
wood = ImageIO.read(new File("wood.jpg"));
money = ImageIO.read(new File("money.png"));
play = ImageIO.read(new File("play.jpg"));
waiting = ImageIO.read(new File("waiting.jpg"));
dealerImage = ImageIO.read(new File("dealer.png"));
smalBlindImage = ImageIO.read(new File("smallblind.png"));
bigBlindImage = ImageIO.read(new File("bigblind.png"));
dealerAvatar = ImageIO.read(new File("dealeravatar.png"));
} catch (IOException e) {
e.printStackTrace();
}
game = g;
game.setUi((UiInterface)this);
xValues = new ArrayList<Integer>(Arrays.asList(1057, 1020, 800, 440, 240, 205));
yValues = new ArrayList<Integer>(Arrays.asList(150, 410, 515, 510, 405, 150));
positionXOfMoney = new ArrayList<Integer>(Arrays.asList(967, 965, 800, 490, 370, 330));
positionYOfMoney = new ArrayList<Integer>(Arrays.asList(200, 385, 450, 435, 385, 215));
cellWidth = cardsImage.getWidth()/13;
cellHeight = cardsImage.getHeight()/5;
initializePosCards();
screenHeight = 768;
screenWidth = 1366;
potPosX = screenWidth/2 ;
potPosY = screenHeight/2 - 50 ;
diameter = 100;
}
public void drawText(Graphics g, String text, int x, int y, int size){
Font f = g.getFont();
g.setFont(new Font( "Serif", Font.BOLD, size));
g.setColor(Color.WHITE);
g.drawString(text, x, y);
g.setFont(f);
}
public void initializePosCards(){
posCards = new ArrayList<Integer>();
for (int i = 0 ; i< xValues.size(); i++) {
for(int j = 0; j < 2; j++){
int dx2 = xValues.get(i) - j * cellWidth;
int dx1 = dx2 - cellWidth;
int dy1 = yValues.get(i) ;
int dy2 = yValues.get(i) + cellHeight;
posCards.add(dx1);
posCards.add(dy1);
posCards.add(dx2);
posCards.add(dy2);
}
}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
ArrayList<PlayerInterface> players = game.getPlayers();
switch (state) {
case 0:
g.drawImage(play, 0, 0, null);
drawText(g, "Poker", 0, 100, 100);
break;
case 1:
g.drawImage(waiting, 0, 0, null);
drawText(g, "Waiting for players ...", 400, screenHeight/2 - 50, 60);
for(int i = 0; i < players.size(); i++){
if(players.get(i).getInGame()){
drawPlayer(g,players.get(i),i,Color.GREEN);
}
else{
drawPlayer(g,players.get(i),i,Color.RED);
}
}
break;
case 2:
if(!animating){
g.drawImage(background, 0, 0, null);
g.drawImage(dealerAvatar, screenWidth/2 + 90, 5, screenHeight/2 + 250, 90, 0, 0, dealerAvatar.getWidth(), dealerAvatar.getHeight(), null);
}
drawBackgroundImages((Graphics2D)g);
int dy1 = screenHeight/5;
int dy2 = dy1 + 125;
Card[] cards = Table.getInstance().getTableContent();
for(int i = 0; i < cards.length; i++ ){
int dx1 = i* cellWidth + i * 20 + screenWidth/3;
int dx2 = dx1 + cellWidth ;
ArrayList<Integer> pos = cards[i].postionOnImage(cellWidth, cellHeight);
g.drawImage(cardsImage, dx1,dy1,dx2,dy2, pos.get(0), pos.get(1), pos.get(2),pos.get(3) , null);
}
drawMoneyPlayers(g);
if(animating){
g.setColor(Color.WHITE);
g.drawImage(money, x, y, x + 40, y + 40, 0, 0, money.getWidth(), money.getHeight(), null);
g.drawString("" + animationAmount, x, y);
}else{
if(!drawPlayerCards ){
for(int i = 0; i < players.size(); i++){
if(i == game.getcurrentPlayerInd()){
drawPlayer(g,players.get(i),i,Color.GREEN);
}
else if(players.get(i).getInGame()){
drawPlayer(g,players.get(i),i,Color.RED);
}else
drawPlayer(g,players.get(i),i,Color.DARK_GRAY);
}
}else{
showPlayerCards(g,game.getPlayers());
String rank="";
StringBuilder s=new StringBuilder();
for(int i = 0; i < players.size(); i++){
if(players.get(i).getWin()){
rank=players.get(i).getHandRank().toString();
drawPlayer(g,players.get(i),i,Color.BLUE);
s.append(players.get(i).getName());
s.append(" ");
}else
drawPlayer(g,players.get(i),i,Color.BLACK);
}
int size = 18;
drawText(g, rank, screenWidth/2 - (rank.length()/2) * size/2, screenHeight/2 + 10 ,size);
drawText(g, s.toString(), screenWidth/2 - (rank.length()/2) * size/2, screenHeight/2 + 40 ,size);
}
}
int pot=game.getPot();
g.drawImage(money, potPosX, potPosY, potPosX + 40, potPosY + 40, 0, 0, money.getWidth(), money.getHeight(), null);
g.setColor(Color.WHITE);
g.drawString("" + pot, potPosX, potPosY);
break;
}
}
public void drawMoneyPlayers(Graphics g){
for(int i = 0; i < game.getPlayers().size(); i++){
g.setColor(Color.WHITE);
g.drawImage(money, positionXOfMoney.get(i), positionYOfMoney.get(i), positionXOfMoney.get(i) + 40, positionYOfMoney.get(i) + 40, 0, 0, money.getWidth(), money.getHeight(), null);
}
}
public void drawPlayer(Graphics g,PlayerInterface player, int id, Color c){
g.setColor(c);
g.fillOval(xValues.get(id), yValues.get(id), diameter, diameter);
g.setColor(Color.WHITE);
g.drawString(player.getName(), xValues.get(id) + 20, yValues.get(id) + 30);
g.drawString("Money: " + player.getMoney(), xValues.get(id) + 20, yValues.get(id) + 46);
g.drawString("Bet: " + player.getCurrentBet(), xValues.get(id) + 20, yValues.get(id) + 62);
int dealer = game.getDealerInd();
int numPlayers = game.getPlayers().size();
if(dealer==id)
g.drawImage(dealerImage, xValues.get(id)+20, yValues.get(id)+72, xValues.get(id)+20 + 30, yValues.get(id)+72 + 30, 0, 0, dealerImage.getWidth(), dealerImage.getHeight(), null);
else if(((dealer + 1)%numPlayers) == id)
g.drawImage(smalBlindImage, xValues.get(id)+55, yValues.get(id)+72, xValues.get(id)+55 + 30, yValues.get(id)+72 + 30, 0, 0, smalBlindImage.getWidth(), smalBlindImage.getHeight(), null);
if(((dealer + 2)%numPlayers) == id)
g.drawImage(bigBlindImage, xValues.get(id)+55, yValues.get(id)+72, xValues.get(id)+55 + 30, yValues.get(id)+72 + 30, 0, 0, bigBlindImage.getWidth(), bigBlindImage.getHeight(), null);
}
public void drawAllPlayersInRed(Graphics g, ArrayList<PlayerInterface> players){
for(int i = 0; i < players.size(); i++){
drawPlayer(g, players.get(i), i, Color.RED);
}
repaint();
}
private void showPlayerCards(Graphics g, ArrayList<PlayerInterface> players){
for(int i = 0; i < players.size(); i++){
ArrayList<Card> hand = players.get(i).getHand();
for(int j = 0; j < hand.size(); j++){
ArrayList<Integer> position = hand.get(j).postionOnImage(cellWidth, cellHeight);
g.drawImage(cardsImage, posCards.get(0 + i*8 + j* 4),posCards.get(1 + i*8 + j* 4),posCards.get(2 + i*8 + j* 4),posCards.get(3 +i*8 + j* 4), position.get(0), position.get(1), position.get(2),position.get(3), null);
}
}
}
@Override
public void updateUI() {
repaint();
}
@Override
public void playAnimation(int id, int val) {
if(val == 0)
return;
animating = true;
x = positionXOfMoney.get(id);
y = positionYOfMoney.get(id);
int division = 20;
int velY =(potPosY - y)/division;
int velX = (potPosX - x)/division;
animationAmount = val;
if(velY > 0)
up = true;
else
up = false;
if(id < 3)
left = false;
else
left = true;
int time=5;
timer = new Timer(time ,new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//atualiza as variaveis
if( ((left == false) && potPosX > x ) || ((left == true) && potPosX < x)){
timer.stop();
animating = false;
repaint();
return;
}
if(((up == false) && potPosY > y ) || ((up == true) && potPosY < y)){
timer.stop();
animating = false;
repaint();
return;
}
x += velX;
y += velY;
repaint();
}
});
timer.start();
try {
Thread.sleep(time*division);
} catch (Exception e) {
}
repaint();
}
public void drawBackgroundImages(Graphics2D g2d){
int xOvalPosition = screenWidth/5;
int yOvalPosition = screenHeight/10 ;
Shape oval = new Ellipse2D.Float(xOvalPosition, yOvalPosition , (xOvalPosition * 3), (yOvalPosition * 6));
Rectangle2D tr = new Rectangle2D.Double(0, 0, wood.getWidth(), wood.getHeight());
TexturePaint tp = new TexturePaint(wood, tr);
g2d.setPaint(tp);
g2d.fill(oval);
Shape oval2 = new Ellipse2D.Float(xOvalPosition + 25, yOvalPosition + 25, (xOvalPosition * 3) - 50, (yOvalPosition * 6) - 50);
Rectangle2D rec = new Rectangle2D.Double(0, 0, table.getWidth(), table.getHeight());
TexturePaint t = new TexturePaint(table, rec);
g2d.setPaint(t);
g2d.fill(oval2);
}
@Override
public void drawPlayerCards(boolean flag) {
drawPlayerCards = flag;
}
public void drawRectangle(Graphics g, int x, int y){
int margem = 5;
g.drawRect(x - margem, y - margem, x + cellWidth + margem, y + cellHeight + margem);
}
@Override
public void gameState(int state) {
this.state = state;
repaint();
}
}
| true |
6d649f77d7668a73c951e231424973356d837829
|
Java
|
Alfred-Huang/Nailsalon-backend
|
/src/main/java/com/nailsalon/nailsalonbackend/mapper/appointment/AppointmentMapper.java
|
UTF-8
| 371 | 1.898438 | 2 |
[] |
no_license
|
package com.nailsalon.nailsalonbackend.mapper.appointment;
import com.nailsalon.nailsalonbackend.pojo.Appointment;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface AppointmentMapper {
void addAppointment(Appointment appointment);
void deleteAppointment(String appointmentId);
}
| true |
cb850f835cf2ee9dddb7ae44ca9265cdc53d14e0
|
Java
|
doooyeon/LKC
|
/LCK/src/contents/Contents.java
|
UHC
| 1,889 | 2.625 | 3 |
[] |
no_license
|
package contents;
import java.io.Serializable;
import java.util.Calendar;
import server_manager.LinKlipboard;
// Ʈ
public abstract class Contents implements Serializable {
private static final long serialVersionUID = 4131370422438049456L;
private static int serialNum = LinKlipboard.NULL;
protected String date;
protected String sharer;
protected int type;
public Contents() {
}
public Contents(String sharer) {
this();
this.sharer = sharer;
}
public void setSharer(String sharer) {
this.sharer = sharer;
}
public static void setSerialNum(int serialNum) {
Contents.serialNum = serialNum;
}
public void setDate() {
this.date = now();
}
public int getSerialNum() {
return serialNum;
}
public String getSharer() {
return sharer;
}
public String getDate() {
return date;
}
public int getType() {
return type;
}
/** @return YYYY-MM-DD HH:MM:SS ð */
public static String now() {
Calendar cal = Calendar.getInstance();
String year = Integer.toString(cal.get(Calendar.YEAR));
String month = Integer.toString(cal.get(Calendar.MONTH)+1);
String date = Integer.toString(cal.get(Calendar.DATE));
String hour = Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
if(Integer.parseInt(hour) < 10) {
hour = "0" + hour;
}
if(Integer.parseInt(hour) > 12) {
hour = " " + Integer.toString(Integer.parseInt(hour)-12);
}
else {
hour = " " + hour;
}
String minute = Integer.toString(cal.get(Calendar.MINUTE));
if(Integer.parseInt(minute) < 10) {
minute = "0" + minute;
}
String sec = Integer.toString(cal.get(Calendar.SECOND));
if(Integer.parseInt(sec) < 10) {
sec = "0" + sec;
}
return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + sec;
}
}
| true |
232b468b836f9812b07283e4a277175b2480d558
|
Java
|
emreozdem/University
|
/Fourth Semester/PhishingURLdetection/src/Main.java
|
UTF-8
| 2,625 | 3.28125 | 3 |
[] |
no_license
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws FileNotFoundException
{
int N_GRAM_NUMBER = 3;
int FEATURE_SIZE = 5000;
File legitimateTrain = new File("../legitimate-train.txt");
Scanner legitimateTrainInput = new Scanner(legitimateTrain);
File phishingTrain = new File("../phishing-train.txt");
Scanner phishingTrainInput = new Scanner(phishingTrain);
File legitimateTest = new File("../legitimate-test.txt");
Scanner legitimateTestInput = new Scanner(legitimateTest);
File phishingTest = new File("../phishing-test.txt");
Scanner phishingTestInput = new Scanner(phishingTest);
// All data in TST. We are giving scanners as argument. So constructor method can construct.
TST theTST = new TST(legitimateTrainInput,phishingTrainInput,legitimateTestInput,phishingTestInput,N_GRAM_NUMBER);
// Finding and printing most important phishing n-grams.
int minimumOccurrenceOfPhishing = theTST.root.printMostImportantPhishing(FEATURE_SIZE); // minimum frequency
String lastMostImportantPhishing = theTST.root.temp; // last n-gram with minimum frequency
System.out.println(FEATURE_SIZE+" strong phishing n-grams have been saved to the file\"strong_phishing_features.txt\"");
// Finding and printing most important legitimate n-grams.
int minimumOccurrenceOfLegitimate = theTST.root.printMostImportantLegitimate(FEATURE_SIZE); // minimum frequency
String lastMostImportantLegitimate = theTST.root.temp; // last n-gram with minimum frequency
System.out.println(FEATURE_SIZE+" strong legitimate n-grams have been saved to the file\"strong_legitimate_features.txt\"");
// Finding and printing weights of all n-grams.
int numberOfWords = theTST.root.printAllFeatureWeights(); // amount of all n-grams
System.out.println(numberOfWords+" n-grams + weights have been saved to the file \"all_feature_weights.txt\"");
// Firstly looks frequency. If frequency less than minimum, removes. else looks for alphabetic order respect to last n-gram.
int removedWords = theTST.root.removeInsignificantOnes(minimumOccurrenceOfLegitimate,minimumOccurrenceOfPhishing,lastMostImportantLegitimate,lastMostImportantPhishing,true,true);
System.out.println(removedWords+" insignificant n-grams have been removed from the TST");
// Calculates weights of n-grams and sums up weights. Determines legitimate or phishing.
theTST.testIt(new Scanner(legitimateTest), new Scanner(phishingTest),N_GRAM_NUMBER);
}
}
| true |
67f157a8310f9a45486950630da6b9f196cca379
|
Java
|
sureshkona/TessaractOcr
|
/src/main/java/com/example/ocr/tessaractdemo/TessaractDemoApplication.java
|
UTF-8
| 336 | 1.5625 | 2 |
[] |
no_license
|
package com.example.ocr.tessaractdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TessaractDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TessaractDemoApplication.class, args);
}
}
| true |
cb9f75e94d3a86072cc773654ab15a22f936470f
|
Java
|
vismayauday/JavaPrograms
|
/bprime.java
|
UTF-8
| 323 | 2.671875 | 3 |
[] |
no_license
|
import java.util.*;
class bprime
{
public static void main(String args[])
{
int n,m,i,j,k,l;
Scanner in=new Scanner(System.in);
n=in.nextInt();
m=in.nextInt();
for(i=n;i<=m;i++)
{
if(i==1 || i==2)
continue;
}
}
}
| true |
a1be8d262c55157bea00e1280b3c884173bc8431
|
Java
|
NationalSecurityAgency/datawave
|
/warehouse/core/src/test/java/datawave/util/cli/AccumuloArgsTest.java
|
UTF-8
| 2,267 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
package datawave.util.cli;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
public class AccumuloArgsTest {
@Test
public void testNewBuilder() {
// @formatter:off
AccumuloArgs args = AccumuloArgs.newBuilder()
.withDefaultTable("defaultTableName")
.build();
String[] argv = {
"-u", "Bob",
"--password", "zekret",
"-i", "instance",
"-z", "localhost:2181",
"-t", "testTable"
};
JCommander.newBuilder()
.addObject(args)
.build()
.parse(argv);
// @formatter:on
assertThat(args.user(), is("Bob"));
assertThat(args.password(), is("zekret"));
assertThat(args.instance(), is("instance"));
assertThat(args.zookeepers(), is("localhost:2181"));
assertThat(args.table(), is("testTable"));
}
@Test
public void testNewBuilder_WithExtraOpts() {
// @formatter:off
AccumuloArgs args = AccumuloArgs.newBuilder()
.withDefaultTable("defaultTableName")
.build();
TestArg other = new TestArg();
String[] argv = {
"--user", "Steve",
"--password", "zekret",
"--instance", "instance",
"--zookeepers", "localhost:2181",
"--table", "testTable",
"--color", "magenta"
};
JCommander.newBuilder()
.addObject(args)
.addObject(other)
.build()
.parse(argv);
// @formatter:on
assertThat(args.user(), is("Steve"));
assertThat(args.password(), is("zekret"));
assertThat(args.instance(), is("instance"));
assertThat(args.zookeepers(), is("localhost:2181"));
assertThat(args.table(), is("testTable"));
// make sure extra args are available
assertThat(other.color, is("magenta"));
}
private static class TestArg {
@Parameter(names = {"-c", "--color"})
String color;
}
}
| true |
fd11ae4c43411a8f91eae6084b71ef3e5f9c11f4
|
Java
|
JimSP/gate
|
/gate-dto/src/main/java/com/github/jimsp/gate/dto/exception/UserNotRemovedException.java
|
UTF-8
| 182 | 1.65625 | 2 |
[] |
no_license
|
package com.github.jimsp.gate.dto.exception;
public class UserNotRemovedException extends RuntimeException{
private static final long serialVersionUID = -5378164242882842882L;
}
| true |
750b7f379f220cb52ee6576a38298ffcfe2d8f88
|
Java
|
archanadubey/test-github
|
/eclipse-TEST/Testemo/src/StringReverse.java
|
UTF-8
| 428 | 3.109375 | 3 |
[] |
no_license
|
public class StringReverse {
public static void main(String[] args) {
String s ="Archana";
System.out.println("Given String are:-"+s);
StringBuilder str2=new StringBuilder();
//str2.append(s);
System.out.println(str2);
str2=str2.reverse();
System.out.println("Reversed String are: "+str2);
// ========================================================
}
}
| true |
408a0945f4dda3c877d9ba94af61ff28f3da59c5
|
Java
|
chenqian19911214/winguoapp_4.5
|
/app/src/main/java/com/winguo/adapter/SpacesItemDecoration.java
|
UTF-8
| 1,768 | 2.421875 | 2 |
[] |
no_license
|
package com.winguo.adapter;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.aispeech.client.IFacadeListener;
/**
* 为条目(上下左右设置间距)设置分隔线
* 使用必须RecyclerView 所在的布局背景不能为白色
* Created by admin on 2017/4/12.
*/
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space=space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
int orientation = linearLayoutManager.getOrientation();
if (orientation == LinearLayoutManager.HORIZONTAL) {
outRect.right=space;
outRect.bottom=space;
outRect.top = space;
if(parent.getChildAdapterPosition(view)==0){
outRect.left=space;
}
} else if (orientation == LinearLayoutManager.VERTICAL) {
outRect.bottom=space;
if(parent.getChildAdapterPosition(view)==0){
outRect.top = space;
}
}
} else {
outRect.left=space;
outRect.right=space;
outRect.bottom=space;
if(parent.getChildAdapterPosition(view)==0){
outRect.top=space;
}
}
}
}
| true |
f833c577ed38e6fc3f7d9cfedddf4fb485255a2c
|
Java
|
maoyanting/java-learning
|
/src/main/java/com/sandao/javalearning/algorithm/offer/Solution17.java
|
UTF-8
| 1,388 | 4.09375 | 4 |
[] |
no_license
|
package com.sandao.javalearning.algorithm.offer;
/**
* 输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。
* 比如输入 3,则打印出 1、2、3 一直到最大的 3 位数即 999。
* @author maoyanting
* @version V1.0
* @date 2020/09/12
*/
public class Solution17 {
public static void main(String[] args) {
print1ToMaxOfNDigits(2);
}
public static void print1ToMaxOfNDigits(int n) {
if (n <= 0)
return;
//构造大小为n数组
char[] number = new char[n];
print1ToMaxOfNDigits(number, 0);
}
private static void print1ToMaxOfNDigits(char[] number, int digit) {
if (digit == number.length) {
//这个数组已经被填满了
printNumber(number);
return;
}
for (int i = 0; i < 10; i++) {
number[digit] = (char) (i + '0');
//递归填写下一个位置的数字
print1ToMaxOfNDigits(number, digit + 1);
}
}
/**
* 打印数组
* @param number
*/
private static void printNumber(char[] number) {
int index = 0;
while (index < number.length && number[index] == '0') {
index++;
}
while (index < number.length) {
System.out.print(number[index++]);
}
System.out.println();
}
}
| true |
138dd71613009aeb2ce9c4dce28757e95dd8eede
|
Java
|
lmj521/lufax-jijin
|
/src/test/java/com/lufax/jijin/fundation/service/RegisterServiceTest.java
|
UTF-8
| 2,487 | 1.992188 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.lufax.jijin.fundation.service;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import com.google.common.collect.Maps;
import com.lufax.jijin.base.utils.JsonHelper;
import com.lufax.jijin.fundation.dto.JijinRegisteRecordDTO;
@TransactionConfiguration(defaultRollback = false)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/applicationContext.xml", "file:src/main/resources/dataSource.xml"})
public class RegisterServiceTest extends AbstractTransactionalJUnit4SpringContextTests{
@Autowired
private AccountService service;
@Test@Ignore
public void testSaveRegisterAccountSuccess() {
JijinRegisteRecordDTO request = new JijinRegisteRecordDTO();
request.setAppNo("registerservice_test");
request.setContractNo("contract_no");
request.setCustNo("customer");
request.setErrorCode("0");
request.setErrorMsg("success");
request.setInstId("inst_test");
request.setPayNo("paf");
request.setChannel("PAF");
request.setStatus(JijinRegisteRecordDTO.RegisteStatus.SUCCESS);
request.setUserId(1112);
assertTrue(service.saveRegisterAccount(request));
}
@Test@Ignore
public void testSaveRegisterAccountFail(){
JijinRegisteRecordDTO request = new JijinRegisteRecordDTO();
request.setAppNo("registerservice_test");
request.setContractNo("contract_no");
request.setCustNo("customer");
request.setErrorCode("0");
request.setErrorMsg("success");
request.setInstId("inst_test");
request.setPayNo("paf");
request.setChannel("PAF");
request.setStatus(JijinRegisteRecordDTO.RegisteStatus.FAIL);
request.setUserId(1112);
assertTrue(service.saveRegisterAccount(request));
}
@Test@Ignore
public void testmq(){
Map<String, String> paras = Maps.newHashMap();
paras.put("fundCode", "111111");
paras.put("increaseDate", "20150615");
paras.put("dayIncrease", "0.0014");
paras.put("monthIncrease", null);
paras.put("sixMonthIncrease", null);
paras.put("thisYearIncrease", null);
paras.put("threeMonthIncrease", null);
paras.put("totalIncrease", null);
paras.put("yearIncrease", null);
System.out.println(JsonHelper.toJson(paras));
}
}
| true |
4553457237625ba2f9252253d0c40e21e46e0309
|
Java
|
yyuvly/teamProject
|
/teamProjectFinal/src/main/java/domain/GoodsVO.java
|
UTF-8
| 1,335 | 1.921875 | 2 |
[] |
no_license
|
package domain;
import java.util.List;
import org.apache.ibatis.type.Alias;
import org.springframework.web.multipart.MultipartFile;
@Alias("goodsVO")
public class GoodsVO {
private int num;
private String item;
private String img;
private int price;
private int count;
private String descript;
private String[] desarr;
private List<MultipartFile> descriptFile;
public GoodsVO() {}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<MultipartFile> getDescriptFile() {
return descriptFile;
}
public void setDescriptFile(List<MultipartFile> descriptFile) {
this.descriptFile = descriptFile;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescript() {
return descript;
}
public void setDescript(String descript) {
this.descript = descript;
}
public String[] getDesarr() {
return desarr;
}
public void setDesarr(String[] desarr) {
this.desarr = desarr;
}
}
| true |
3f9e3c62012488456700f391c53892e2780c5006
|
Java
|
ajaychebbi/todo-apps
|
/java/bluemix-todo-app/src/main/java/net/bluemix/todo/model/CloudantRow.java
|
UTF-8
| 1,819 | 2.484375 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright IBM Corp. 2014
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bluemix.todo.model;
/**
* Represents an individual row of results returned when getting documents from the Cloudant DB.
*/
public class CloudantRow {
private String id;
private int key;
private CloudantToDo doc;
private ToDo value;
/**
* Gets the value.
* @return The value.
*/
public ToDo getValue() {
return value;
}
/**
* Sets the value.
* @param value The value to set.
*/
public void setValue(ToDo value) {
this.value = value;
}
/**
* Gets the key.
* @return The key.
*/
public int getKey() {
return key;
}
/**
* Sets the key.
* @param key The key to set.
*/
public void setKey(int key) {
this.key = key;
}
/**
* Gets the ID.
* @return The ID.
*/
public String getId() {
return id;
}
/**
* Sets the ID.
* @param id The ID to set.
*/
public void setId(String id) {
this.id = id;
}
/**
* Gets the ToDo document for the row.
* @return The ToDo.
*/
public CloudantToDo getDoc() {
return doc;
}
/**
* Sets the ToDo document for the row.
* @param doc The ToDo document to set.
*/
public void setDoc(CloudantToDo doc) {
this.doc = doc;
}
}
| true |
c6a3eb366c859cfe040c92ecc6e07624ba47ec4b
|
Java
|
cbuschka/podman-maven-plugin
|
/src/main/java/nl/lexemmens/podman/image/ImageConfiguration.java
|
UTF-8
| 3,235 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package nl.lexemmens.podman.image;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Holds the configuration for the container images that are being built. Values of this class will be set via
* the Maven pom, except for the image hash.
*/
public class ImageConfiguration {
/**
* The name of the image without the target registry. May contain the repository. Must be all lowercase and no special characters
*/
@Parameter(required = true)
protected String name;
@Parameter
protected BuildImageConfiguration build;
/**
* Set after the image is built.
*/
private String imageHash;
/**
* <p>
* Constructor
* </p>
*/
public ImageConfiguration() {
// Empty - will be injected
}
/**
* <p>
* Returns an Optional that may or may not hold the image hash
* </p>
*
* @return An {@link Optional} that may hold the image hash
*/
public final Optional<String> getImageHash() {
return Optional.ofNullable(imageHash);
}
/**
* <p>
* Sets the image hash to a specific value
* </p>
*
* @param imageHash The image hash to set. This should be a SHA256 hash.
*/
public final void setImageHash(String imageHash) {
this.imageHash = imageHash;
}
/**
* <p>
* Returns the build configuration
* </p>
*
* @return the configuration used for building the image
*/
public BuildImageConfiguration getBuild() {
return build;
}
/**
* <p>
* Returns a list of image names formatted as the image name [colon] tag.
* </p>
* <p>
* Note that registry information is not prepended to this image name
* </p>
*
* @return A list of image names
*/
public List<String> getImageNames() {
List<String> imageNames = new ArrayList<>();
for (String tag : build.getAllTags()) {
imageNames.add(String.format("%s:%s", name, tag));
}
return imageNames;
}
/**
* <p>
* Returns the name of the image without the tag and registry
* </p>
*
* @return The name of the image
*/
public String getImageName() {
return name;
}
/**
* Initializes this configuration and fills any null values with default values.
*
* @param mavenProject The MavenProject to derive some of the values from
* @param log The log for logging any errors that occur during validation
* @throws MojoExecutionException In case validation fails.
*/
public void initAndValidate(MavenProject mavenProject, Log log) throws MojoExecutionException {
if (name == null) {
String msg = "Image name must not be null, must be alphanumeric and may contain slashes, such as: valid/image/name";
log.error(msg);
throw new MojoExecutionException(msg);
}
build.validate(mavenProject, log);
}
}
| true |
5503158aa83804947fb5a9ddaa3fe132c50b642e
|
Java
|
shaolin-example-com-my-shopify-com/KidWatcher
|
/AppLock/com/android/gallery3d/ui/AlbumLabelMaker.java
|
UTF-8
| 6,598 | 1.882813 | 2 |
[] |
no_license
|
package com.android.gallery3d.ui;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.PorterDuff.Mode;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import com.android.gallery3d.C0488R;
import com.android.gallery3d.data.BitmapPool;
import com.android.gallery3d.ui.AlbumSetSlotRenderer.LabelSpec;
import com.android.gallery3d.util.ThreadPool.Job;
import com.android.gallery3d.util.ThreadPool.JobContext;
public class AlbumLabelMaker {
private static final int BORDER_SIZE = 0;
private BitmapPool mBitmapPool;
private final LazyLoadedBitmap mCameraIcon = new LazyLoadedBitmap(C0488R.drawable.transparent);
private final Context mContext;
private final TextPaint mCountPaint;
private int mLabelWidth;
private final LazyLoadedBitmap mLocalSetIcon = new LazyLoadedBitmap(C0488R.drawable.transparent);
private final LazyLoadedBitmap mMtpIcon = new LazyLoadedBitmap(C0488R.drawable.transparent);
private final LazyLoadedBitmap mPicasaIcon = new LazyLoadedBitmap(C0488R.drawable.transparent);
private final LabelSpec mSpec;
private final TextPaint mTitlePaint;
private class AlbumLabelJob implements Job<Bitmap> {
private final String mCount;
private final int mSourceType;
private final String mTitle;
public AlbumLabelJob(String str, String str2, int i) {
this.mTitle = str;
this.mCount = str2;
this.mSourceType = i;
}
public Bitmap run(JobContext jobContext) {
int access$300;
Bitmap bitmap;
LabelSpec access$100 = AlbumLabelMaker.this.mSpec;
String str = this.mTitle;
String str2 = this.mCount;
Bitmap access$200 = AlbumLabelMaker.this.getOverlayAlbumIcon(this.mSourceType);
synchronized (this) {
access$300 = AlbumLabelMaker.this.mLabelWidth;
bitmap = AlbumLabelMaker.this.mBitmapPool.getBitmap();
}
Bitmap createBitmap = bitmap == null ? Bitmap.createBitmap(access$300 + 0, access$100.labelBackgroundHeight + 0, Config.ARGB_8888) : bitmap;
Canvas canvas = new Canvas(createBitmap);
canvas.clipRect(0, 0, createBitmap.getWidth() + 0, createBitmap.getHeight() + 0);
canvas.drawColor(AlbumLabelMaker.this.mSpec.backgroundColor, Mode.SRC);
canvas.translate(0.0f, 0.0f);
if (jobContext.isCancelled()) {
return null;
}
int i = access$100.leftMargin + access$100.iconSize;
AlbumLabelMaker.drawText(canvas, i, (access$100.labelBackgroundHeight - access$100.titleFontSize) / 2, str, ((access$300 - access$100.leftMargin) - i) - access$100.titleRightMargin, AlbumLabelMaker.this.mTitlePaint);
if (jobContext.isCancelled()) {
return null;
}
i = access$300 - access$100.titleRightMargin;
AlbumLabelMaker.drawText(canvas, i, (access$100.labelBackgroundHeight - access$100.countFontSize) / 2, str2, access$300 - i, AlbumLabelMaker.this.mCountPaint);
if (access$200 == null) {
return createBitmap;
}
if (jobContext.isCancelled()) {
return null;
}
float width = ((float) access$100.iconSize) / ((float) access$200.getWidth());
canvas.translate((float) access$100.leftMargin, ((float) (access$100.labelBackgroundHeight - Math.round(((float) access$200.getHeight()) * width))) / 2.0f);
canvas.scale(width, width);
canvas.drawBitmap(access$200, 0.0f, 0.0f, null);
return createBitmap;
}
}
private class LazyLoadedBitmap {
private Bitmap mBitmap;
private int mResId;
public LazyLoadedBitmap(int i) {
this.mResId = i;
}
public synchronized Bitmap get() {
if (this.mBitmap == null) {
Options options = new Options();
options.inPreferredConfig = Config.ARGB_8888;
this.mBitmap = BitmapFactory.decodeResource(AlbumLabelMaker.this.mContext.getResources(), this.mResId, options);
}
return this.mBitmap;
}
}
public AlbumLabelMaker(Context context, LabelSpec labelSpec) {
this.mContext = context;
this.mSpec = labelSpec;
this.mTitlePaint = getTextPaint(labelSpec.titleFontSize, labelSpec.titleColor, false);
this.mCountPaint = getTextPaint(labelSpec.countFontSize, labelSpec.countColor, false);
}
static void drawText(Canvas canvas, int i, int i2, String str, int i3, TextPaint textPaint) {
synchronized (textPaint) {
canvas.drawText(TextUtils.ellipsize(str, textPaint, (float) i3, TruncateAt.END).toString(), (float) i, (float) (i2 - textPaint.getFontMetricsInt().ascent), textPaint);
}
}
public static int getBorderSize() {
return 0;
}
private Bitmap getOverlayAlbumIcon(int i) {
switch (i) {
case 1:
return this.mLocalSetIcon.get();
case 2:
return this.mPicasaIcon.get();
case 3:
return this.mMtpIcon.get();
case 4:
return this.mCameraIcon.get();
default:
return null;
}
}
private static TextPaint getTextPaint(int i, int i2, boolean z) {
TextPaint textPaint = new TextPaint();
textPaint.setTextSize((float) i);
textPaint.setAntiAlias(true);
textPaint.setColor(i2);
if (z) {
textPaint.setTypeface(Typeface.defaultFromStyle(1));
}
return textPaint;
}
public void clearRecycledLabels() {
if (this.mBitmapPool != null) {
this.mBitmapPool.clear();
}
}
public void recycleLabel(Bitmap bitmap) {
this.mBitmapPool.recycle(bitmap);
}
public Job<Bitmap> requestLabel(String str, String str2, int i) {
return new AlbumLabelJob(str, str2, i);
}
public synchronized void setLabelWidth(int i) {
if (this.mLabelWidth != i) {
this.mLabelWidth = i;
this.mBitmapPool = new BitmapPool(i + 0, 0 + this.mSpec.labelBackgroundHeight, 16);
}
}
}
| true |
4c1cb8b59fcb4523e815e55bb8def2374ef6639e
|
Java
|
spwahaha/Coding-Problems
|
/Coding Problems/src/leetcode/Swap_Nodes_in_Pairs.java
|
UTF-8
| 695 | 3.5 | 4 |
[] |
no_license
|
package leetcode;
public class Swap_Nodes_in_Pairs {
public static ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode newHead = head.next;
head.next = swapPairs(newHead.next);
newHead.next = head;
return newHead;
}
public static void main(String[] args){
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
node1.next = node2;
node2.next = node3;
node3.next = node4;
System.out.println(node1);
System.out.println(swapPairs(node1));
}
}
| true |
1da57c3f5f8b08acea42fb805d1ed06e5ac63c69
|
Java
|
gabrielrbl/restapi-java
|
/src/main/java/armazempb/desafio/repository/PedidoRepository.java
|
UTF-8
| 216 | 1.5625 | 2 |
[] |
no_license
|
package armazempb.desafio.repository;
import org.springframework.data.repository.CrudRepository;
import armazempb.desafio.model.Pedido;
public interface PedidoRepository extends CrudRepository<Pedido, Integer> {
}
| true |
690edd20d839160642d9c49da2574f2d73dd3c1e
|
Java
|
aeisses/Android-FACCookBook
|
/app/src/main/java/github/com/foodactioncommitteecookbook/purchase/PurchaseActivity.java
|
UTF-8
| 472 | 2.015625 | 2 |
[] |
no_license
|
package github.com.foodactioncommitteecookbook.purchase;
import android.os.Bundle;
import github.com.foodactioncommitteecookbook.BaseActivity;
import github.com.foodactioncommitteecookbook.R;
/**
* Shows recipes available for purchase.
*/
public class PurchaseActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase);
}
}
| true |
958147d87b6eb0241997b7f8691d5a67ac996ef5
|
Java
|
Hugo-Gao/InterestBlog
|
/src/main/java/com/gaoyunfan/controller/UserHelper.java
|
UTF-8
| 928 | 2.328125 | 2 |
[] |
no_license
|
package com.gaoyunfan.controller;
import com.gaoyunfan.dto.ResultMsg;
import com.gaoyunfan.model.User;
import org.apache.commons.lang3.StringUtils;
/**
* @author yunfan.gyf
**/
public class UserHelper {
public static ResultMsg validate(User account) {
if (StringUtils.isBlank(account.getEmail())) {
return ResultMsg.errorMsg("Email有误");
}
if (StringUtils.isBlank(account.getPassword())) {
return ResultMsg.errorMsg("密码有误");
}
if (StringUtils.isBlank(account.getBlogName())) {
return ResultMsg.errorMsg("博客名称有误");
}
if (StringUtils.isBlank(account.getAboutme())) {
return ResultMsg.errorMsg("个人详情有误");
}
if (account.getAvatarFile().isEmpty()) {
return ResultMsg.errorMsg("头像不能为空");
}
return ResultMsg.successMsg("");
}
}
| true |
cbf6099ad55af84df781a00b3a1e3182b0384762
|
Java
|
jinujohn990/spring-security-with-jwt
|
/springsecurity-jwt/src/main/java/com/jinu/jwt/controller/MainController.java
|
UTF-8
| 1,332 | 2.21875 | 2 |
[] |
no_license
|
package com.jinu.jwt.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jinu.jwt.dto.request.GenerateJwtTokenRequest;
import com.jinu.jwt.serviceimpl.JwtUtil;
@Controller
public class MainController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
JwtUtil jwtUtil;
@GetMapping("/hello")
@ResponseBody
public String hello() {
return "You are authenticated...";
}
@PostMapping("/authenticate")
public String generateJwtToken(@RequestBody GenerateJwtTokenRequest request) throws Exception {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
}catch (Exception e) {
throw new Exception("inavalid username/password");
}
return jwtUtil.generateToken(request.getUsername());
}
}
| true |
d775f45675256de47c7aa3cd2d195d05efa311e0
|
Java
|
Regeneration-Team-2/RegenerationInsuranceProject
|
/src/utilities/ReadFromConsole.java
|
UTF-8
| 1,908 | 3.453125 | 3 |
[
"MIT"
] |
permissive
|
package utilities;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class ReadFromConsole {
private String userInput;
private int userInt;
public static double readDoubleFromConsole() {
Scanner scanner = new Scanner(System.in);
try {
return Double.parseDouble(scanner.next());
} catch (NumberFormatException e) {
System.out.println("###################################################");
System.out.println("Bad input format.Please insert an acceptable input");
System.out.println("###################################################\n");
return -1;
}
}
public static int readIntFromConsole() {
Scanner scanner = new Scanner(System.in);
try {
return Integer.parseInt(scanner.next());
} catch (NumberFormatException e) {
System.out.println("###################################################");
System.out.println("Bad input format.Please insert an acceptable input");
System.out.println("###################################################\n");
return -1;
}
}
public static String readStringFromConsole() {
Scanner scanner = new Scanner(System.in);
try {
return scanner.nextLine();
} catch (NullPointerException e) {
return "Something went wrong.Incorrect type of input\n";
}
}
//another way
/* public static LocalDate currentDate() {
LocalDate currentDate = LocalDate.now();
return currentDate;
}
public static LocalDate plusDate() {
String day = readStringFromConsole();
int days = Integer.parseInt(day);
LocalDate requestedDate = LocalDate.now().plusDays(days);
return requestedDate;
}*/
}
| true |
52c39cdc00dcdeae360fb91c1a7c41e5dd6f9fb9
|
Java
|
MCWarcraft/HonorPoints
|
/src/bourg/austin/HonorPoints/CurrencyConnector.java
|
UTF-8
| 815 | 2.671875 | 3 |
[] |
no_license
|
package bourg.austin.HonorPoints;
import org.bukkit.OfflinePlayer;
public class CurrencyConnector
{
public CurrencyConnector()
{
}
public int getPlayerCurrency(OfflinePlayer player)
{
return DatabaseOperations.getCurrency(player);
}
public boolean canAfford(OfflinePlayer player, int cost)
{
return DatabaseOperations.getCurrency(player) >= cost;
}
public boolean giveCurrency(OfflinePlayer player, int amount)
{
if (amount < 0)
return false;
DatabaseOperations.setCurrency(player, DatabaseOperations.getCurrency(player) + amount);
return true;
}
public boolean deductCurrency(OfflinePlayer player, int amount)
{
if (!canAfford(player, amount))
return false;
DatabaseOperations.setCurrency(player, DatabaseOperations.getCurrency(player) - amount);
return true;
}
}
| true |
62b9aa0a1fd2cedefb78b6497bf560683f042bf7
|
Java
|
Steven-Adriaensen/IS4APE
|
/src/is4ape/pm/ImportanceSamplingModel.java
|
UTF-8
| 4,090 | 2.984375 | 3 |
[] |
no_license
|
package is4ape.pm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* This class implements all importance sampling estimators.
* Its implementation is fully generic w.r.t. the type (i.e. representation) of designs and executions.
*
* @author Steven Adriaensen
*
* @param <DesignType> The type of the design
* @param <ExecutionType> The type of the execution
*/
public class ImportanceSamplingModel<DesignType,ExecutionType> implements PerformanceModel<DesignType,ExecutionType>{
final BiFunction<DesignType,ExecutionType,Double> pr; //The function describing the relationship between design and execution space
final Function<ExecutionType,Double> p; //The notion of 'desirability of an execution' used
List<ExecutionType> execs; //E': list of executions generated
List<Double> qs; //Q'(e) for all e in E' (to avoid re-computing these)
Map<DesignType,Integer> Theta_used; //\Theta': the mixture of configurations used to generate E'
//used to compute variability p
double sum_p;
double sum_p2;
/**
* Creates an instance of the IS estimator.
* @param f: The notion of 'desirability of an execution' to be used
* @param pr The function to be used to compute the likelihood of generating an execution using a given design
*/
public ImportanceSamplingModel(Function<ExecutionType,Double> p,BiFunction<DesignType,ExecutionType,Double> pr){
this.p = p;
this.pr = pr;
execs = new ArrayList<ExecutionType>();
Theta_used = new HashMap<DesignType,Integer>();
qs = new ArrayList<Double>();
sum_p = 0;
sum_p2 = 0;
}
public void update(DesignType theta, ExecutionType exec){
double p_exec = p.apply(exec);
//update for standard deviation
sum_p += p_exec;
sum_p2 += p_exec*p_exec;
//update g-values:
//for existing executions O(E')
for(int i = 0; i < execs.size(); i++){
qs.set(i,qs.get(i)+pr.apply(theta, execs.get(i)));
}
execs.add(exec);
if(Theta_used.containsKey(theta)){
Theta_used.put(theta,Theta_used.get(theta) + 1);
}else{
Theta_used.put(theta,1);
}
//for new execution O(Pi')
double qNew = 0;
Set<DesignType> keyset = Theta_used.keySet();
for(DesignType used_pi : keyset){
qNew += Theta_used.get(used_pi)*pr.apply(used_pi,exec);
}
qs.add(qNew);
}
private double STD(){
return Math.sqrt(sum_p2/execs.size() - (sum_p*sum_p)/(execs.size()*execs.size()));
}
public double o(DesignType theta) {
double mean = 0;
//compute IS estimate
double norm = 0;
//loop over all prior executions, adding weighted observations
for(int i = 0; i < execs.size(); i++){
ExecutionType exec = execs.get(i);
double w = pr.apply(theta,exec)/qs.get(i);
norm += w;
mean += w*p.apply(exec);
}
//normalise
return norm == 0? mean : mean/norm;
}
@Override
public double unc(DesignType theta){
//if n = 0
double n = n(theta);
if(n == 0){
return Double.POSITIVE_INFINITY;
}else{
return STD()/Math.sqrt(n);
}
}
public double n(DesignType theta) {
double n = 0;
double norm = 0; //sum of weights
double norm2 = 0; //sum of squared weights
//loop over all prior executions
for(int i = 0; i < execs.size(); i++){
double w = pr.apply(theta,execs.get(i))/qs.get(i);
norm += w;
norm2 += w*w;
}
if(norm == 0){
//no relevant executions
n = 0;
}else{
double neff = (norm*norm)/norm2;
n = neff*Math.min(norm, 1.0/norm);
}
return n;
}
public double sim(DesignType theta1, DesignType theta2) {
double n1 = n(theta1);
if(n1 == 0){
return 0;
}
double n2 = n(theta2);
if(n2 == 0){
return 0;
}
double sc = 0;
double norm1 = 0;
double norm2 = 0;
for(int i = 0; i < qs.size(); i++){
ExecutionType exec = execs.get(i);
double G = qs.get(i);
double w1 = pr.apply(theta1,exec)/G;
double w2 = pr.apply(theta2,exec)/G;
norm1 += w1;
norm2 += w2;
sc += Math.min(w1,w2);
}
//normalise
sc = sc/Math.max(norm1, norm2);
return sc;
}
}
| true |
12a2effa2638e490cc4cc72c26b8f7d6b0ea22f5
|
Java
|
wmHappy/SuperSibuUpload
|
/src/com/wangmin/utils/HttpUtils.java
|
UTF-8
| 1,662 | 2.34375 | 2 |
[] |
no_license
|
package com.wangmin.utils;
import java.awt.Component;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.imageio.ImageIO;
import com.wangmin.utils.DialogUtils.DialogType;
public class HttpUtils {
public static BufferedImage loadImage(String urls){
HttpURLConnection urlConnection = null;
BufferedInputStream bufferedInputStream = null;
try{
URL url = new URL(urls);
urlConnection = (HttpURLConnection) url.openConnection();
bufferedInputStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedImage bufferedImage = ImageIO.read(bufferedInputStream);
return bufferedImage;
}catch(Exception e){
e.printStackTrace();
return ResourceUtils.loadBufferedImageLocation("loading.jpg");
}finally{
IOutils.closeResource(bufferedInputStream);
if(urlConnection!=null){
urlConnection.disconnect();
}
}
}
/**
* 测试提交,添加注释
* /
public static String getJson(Component component,String urls,String encode){
HttpURLConnection urlConnection = null;
try{
URL url = new URL(urls);
urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),encode));
return IOutils.getString(bufferedReader,true);
}catch(Exception e){
e.printStackTrace();
DialogUtils.showMessageDialog(component, urls+"»ñÈ¡Êý¾Ýʧ°Ü "+e.getMessage(), DialogType.NORMAL);
return null;
}
}
}
| true |
f5bb4074545ea8db6132853891fdef3d8275d065
|
Java
|
Datilus/TareaSyncrona
|
/app/src/main/java/com/example/tareasyncrona/services/db/TaxDatabaseServiceImpl.java
|
UTF-8
| 1,534 | 2.46875 | 2 |
[] |
no_license
|
package com.example.tareasyncrona.services.db;
import com.annimon.stream.Stream;
import com.example.tareasyncrona.data.api.ResponseDataWithCode;
import com.example.tareasyncrona.data.api.Tax;
import com.example.tareasyncrona.data.db.TaxEntity;
import com.example.tareasyncrona.domain.services.interfaces.TaxService;
import java.util.ArrayList;
import java.util.List;
import io.realm.Realm;
public class TaxDatabaseServiceImpl implements TaxService {
private static TaxDatabaseServiceImpl instance;
private TaxDatabaseServiceImpl() {
}
public static TaxDatabaseServiceImpl getInstance() {
if (instance == null)
instance = new TaxDatabaseServiceImpl();
return instance;
}
@Override
public ResponseDataWithCode<ArrayList<Tax>> fetch() {
return null;
}
@Override
public void addList(ArrayList<Tax> taxes) {
List<TaxEntity> taxEntities = Stream.of(taxes)
.map(tax -> new TaxEntity(tax))
.toList();
try (Realm realm = Realm.getDefaultInstance()) {
realm.executeTransaction(innerRealm -> innerRealm.copyToRealmOrUpdate(taxEntities));
}
}
@Override
public void addObject(Tax tax) {
TaxEntity taxEntity = Stream.of(tax)
.map(item -> new TaxEntity(item))
.single();
try (Realm realm = Realm.getDefaultInstance()) {
realm.executeTransaction(innerRealm -> innerRealm.copyToRealmOrUpdate(taxEntity));
}
}
}
| true |
1af561408f59e7b24db72b2a99d0d5d9039e7209
|
Java
|
kaiyilian/bm-project
|
/arya-salary/src/main/java/com/bumu/arya/salary/controller/CustomerAccountController.java
|
UTF-8
| 4,969 | 2.125 | 2 |
[] |
no_license
|
package com.bumu.arya.salary.controller;
import com.bumu.arya.response.HttpResponse;
import com.bumu.arya.salary.command.*;
import com.bumu.arya.salary.result.*;
import com.bumu.arya.salary.service.CustomerAccountService;
import com.bumu.arya.salary.service.CustomerService;
import com.bumu.arya.salary.service.SalaryFileService;
import com.bumu.common.SessionInfo;
import com.bumu.common.result.FileUploadFileResult;
import com.bumu.common.result.Pager;
import com.bumu.common.result.PagerResult;
import com.bumu.common.service.FileUploadService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* 客户管理
* @Author: Gujianchao
* @Description:
* @Date: 2017/6/30
*/
@Controller
@Api(tags = {"客户台账管理account"})
@RequestMapping(value = "/salary/customer/account")
public class CustomerAccountController {
@Autowired
private CustomerService customerService;
@Autowired
private FileUploadService fileUploadService;
@Autowired
private CustomerAccountService customerAccountService;
@Autowired
private SalaryFileService salaryFileService;
@ApiOperation(value = "台账列表")
@ApiResponse(code = 200, message = "成功", response = HttpResponse.class)
@RequestMapping(value = "/page", method = RequestMethod.GET)
@ResponseBody
public HttpResponse<PagerResult<CustomerAccountResult>> accountPage(
@ApiParam("客户ID") @RequestParam(value = "customerId") String customerId,
@ApiParam("查询条件-时间(年-月)") @RequestParam(value = "yearMonth") String yearMonth,
@ApiParam("当前页") @RequestParam(value = "page", defaultValue = "1") Integer page,
@ApiParam("一页数量") @RequestParam(value = "page_size", defaultValue = "10") Integer pageSize) throws Exception{
return new HttpResponse<>(customerAccountService.pageAccount(customerId, yearMonth, page, pageSize));
}
@ApiOperation(value = "导出台账")
@ApiResponse(code = 200, message = "成功", response = HttpResponse.class)
@RequestMapping(value = "/export", method = RequestMethod.POST)
@ResponseBody
public HttpResponse<FileUploadFileResult> accountExport(
@ApiParam @Valid @RequestBody CustomerAccountExportCommand customerAccountExportCommand) throws Exception{
return new HttpResponse(salaryFileService.exportAccount(customerAccountExportCommand.getCustomerId(), customerAccountExportCommand.getYearMonth()));
}
@ApiOperation(value = "更新台账信息")
@ApiResponse(code = 200, message = "成功", response = HttpResponse.class)
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ResponseBody
public HttpResponse<Void> updateAccount(
@ApiParam @Valid @RequestBody CustomerAccountUpdateCommand customerAccountUpdateCommand,
BindingResult bindingResult,
SessionInfo sessionInfo) {
customerAccountService.updateAccount(customerAccountUpdateCommand);
return new HttpResponse<>();
}
@ApiOperation(value = "台账汇总")
@ApiResponse(code = 200, message = "成功", response = HttpResponse.class)
@RequestMapping(value = "/total", method = RequestMethod.GET)
@ResponseBody
public HttpResponse<CustomerAccountTotalResult> accountTotal(
@ApiParam("开始时间") @RequestParam(value = "startTime") Long startTime,
@ApiParam("结束时间") @RequestParam(value = "endTime") Long endTime,
@ApiParam("当前页") @RequestParam(value = "page", defaultValue = "1") Integer page,
@ApiParam("一页数量") @RequestParam(value = "page_size", defaultValue = "10") Integer pageSize) {
//customerAccountService.updateAccount(startTime, endTime);
return new HttpResponse<>(customerAccountService.customerAccountTotalList(startTime, endTime, page, pageSize));
}
@ApiOperation(value = "导出台账汇总")
@ApiResponse(code = 200, message = "成功", response = HttpResponse.class)
@RequestMapping(value = "/total/export", method = RequestMethod.POST)
@ResponseBody
public HttpResponse<FileUploadFileResult> accountTotalExport(
@ApiParam @Valid @RequestBody CustomerAccountTotalCommand customerAccountTotalCommand,
BindingResult bindingResult) throws Exception{
CustomerAccountTotalResult customerAccountTotalResult = customerAccountService.customerAccountTotalList(customerAccountTotalCommand.getStartTime(), customerAccountTotalCommand.getEndTime(), null, null);
FileUploadFileResult fileUploadFileResult = salaryFileService.exportCustomerAccountTotal(customerAccountTotalResult);
return new HttpResponse<>(fileUploadFileResult);
}
}
| true |
d56fd58982d1ab04dab05595f2382712951825fc
|
Java
|
alee/tdar
|
/src/main/java/org/tdar/core/bean/entity/TdarUser.java
|
UTF-8
| 7,384 | 1.960938 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.tdar.core.bean.entity;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.hibernate.annotations.Check;
import org.hibernate.annotations.Type;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Norms;
import org.hibernate.search.annotations.Store;
import org.hibernate.validator.constraints.Length;
import org.tdar.core.bean.FieldLength;
import org.tdar.core.bean.Obfuscatable;
import org.tdar.core.bean.resource.BookmarkedResource;
import org.tdar.search.index.analyzer.NonTokenizingLowercaseKeywordAnalyzer;
import org.tdar.search.index.analyzer.TdarCaseSensitiveStandardAnalyzer;
@Entity
@Indexed
@Table(name = "tdar_user")
@XmlRootElement(name = "user")
@Check(constraints = "username <> ''")
public class TdarUser extends Person {
private static final long serialVersionUID = 6232922939044373880L;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "person")
private Set<BookmarkedResource> bookmarkedResources = new LinkedHashSet<>();
@Column(unique = true, nullable = true)
@Length(min = 1, max = FieldLength.FIELD_LENGTH_255)
private String username;
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE, CascadeType.DETACH }, optional = true)
/* who to contact when owner is no longer 'reachable' */
private Institution proxyInstitution;
@Lob
@Type(type = "org.hibernate.type.StringClobType")
@Column(name = "proxy_note")
private String proxyNote;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_login")
private Date lastLogin;
@Enumerated(EnumType.STRING)
@Column(name = "affiliation", length = FieldLength.FIELD_LENGTH_255)
@Field(norms = Norms.NO, store = Store.YES)
@Analyzer(impl = TdarCaseSensitiveStandardAnalyzer.class)
private UserAffiliation affiliation;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "penultimate_login")
private Date penultimateLogin;
@Column(name = "total_login")
private Long totalLogins = 0L;
// can this user contribute resources?
@Column(name = "contributor", nullable = false, columnDefinition = "boolean default FALSE")
private Boolean contributor = Boolean.FALSE;
@Column(name = "contributor_reason", length = FieldLength.FIELD_LENGTH_512)
@Length(max = FieldLength.FIELD_LENGTH_512)
private String contributorReason;
// version of the latest TOS that the user has accepted
@Column(name = "tos_version", nullable = false, columnDefinition = "int default 0")
private Integer tosVersion = 0;
// version of the latest Creator Agreement that the user has accepted
@Column(name = "contributor_agreement_version", nullable = false, columnDefinition = "int default 0")
private Integer contributorAgreementVersion = 0;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "dismissed_notifications_date", nullable = true)
private Date dismissedNotificationsDate;
public TdarUser() {
}
public TdarUser(String firstName, String lastName, String email) {
super(firstName, lastName, email);
}
public Boolean getContributor() {
return contributor;
}
public Boolean isContributor() {
return contributor;
}
public void setContributor(Boolean contributor) {
this.contributor = contributor;
}
@XmlTransient
public String getContributorReason() {
return contributorReason;
}
public void setContributorReason(String contributorReason) {
this.contributorReason = contributorReason;
}
public Long getTotalLogins() {
if (totalLogins == null) {
return 0L;
}
return totalLogins;
}
public void setTotalLogins(Long totalLogins) {
this.totalLogins = totalLogins;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.penultimateLogin = getLastLogin();
this.lastLogin = lastLogin;
}
public void incrementLoginCount() {
totalLogins = getTotalLogins() + 1;
}
public Date getPenultimateLogin() {
return penultimateLogin;
}
public void setPenultimateLogin(Date penultimateLogin) {
this.penultimateLogin = penultimateLogin;
}
@Override
public Set<Obfuscatable> obfuscate() {
Set<Obfuscatable> results = new HashSet<>();
setObfuscated(true);
results.addAll(super.obfuscate());
setObfuscatedObjectDifferent(true);
setContributor(false);
setObfuscated(true);
setLastLogin(null);
setPenultimateLogin(null);
setTotalLogins(null);
return results;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Field
@Analyzer(impl = NonTokenizingLowercaseKeywordAnalyzer.class)
public boolean isRegistered() {
return true;
}
@Override
public boolean isDedupable() {
return false;
}
@XmlTransient
public Set<BookmarkedResource> getBookmarkedResources() {
return bookmarkedResources;
}
public void setBookmarkedResources(Set<BookmarkedResource> bookmarkedResources) {
this.bookmarkedResources = bookmarkedResources;
}
public Institution getProxyInstitution() {
return proxyInstitution;
}
public void setProxyInstitution(Institution proxyInstitution) {
this.proxyInstitution = proxyInstitution;
}
public String getProxyNote() {
return proxyNote;
}
public void setProxyNote(String proxyNote) {
this.proxyNote = proxyNote;
}
public Integer getContributorAgreementVersion() {
return contributorAgreementVersion;
}
public void setContributorAgreementVersion(Integer contributorAgreementVersion) {
this.contributorAgreementVersion = contributorAgreementVersion;
}
public Integer getTosVersion() {
return tosVersion;
}
public void setTosVersion(Integer tosVersion) {
this.tosVersion = tosVersion;
}
public UserAffiliation getAffiliation() {
return affiliation;
}
public void setAffiliation(UserAffiliation affiliation) {
this.affiliation = affiliation;
}
public Date getDismissedNotificationsDate() {
return dismissedNotificationsDate;
}
public void updateDismissedNotificationsDate() {
setDismissedNotificationsDate(new Date());
}
public void setDismissedNotificationsDate(Date dismissedNotificationsDate) {
this.dismissedNotificationsDate = dismissedNotificationsDate;
}
}
| true |
bc2d867c0f64f1b07ece955f5ee0fc6882fe6c72
|
Java
|
AlexBrosso/SistemaZOO
|
/SistemaZOO/Zoologico/src/zoo/comando/comida/ConsultarComida.java
|
UTF-8
| 437 | 2.359375 | 2 |
[] |
no_license
|
package zoo.comando.comida;
import java.io.IOException;
import java.util.Scanner;
import zoo.cadastro.Comida;
import zoo.comando.Comando;
import zoo.dao.ComidaDAO;
public class ConsultarComida implements Comando{
public void execute(Scanner entrada) throws IOException{
ComidaDAO com = new ComidaDAO();
for (Comida comida : com.getComidas()) { //retorna os alimentos cadastrados no banco
System.out.println(comida);
}
}
}
| true |
4a924bc6b7da7fb0883ef53b45278a8de2a41557
|
Java
|
vhviveiros/LPS
|
/src/dao/ClientDao.java
|
UTF-8
| 1,356 | 2.578125 | 3 |
[] |
no_license
|
package dao;
import model.Client;
import controller.ControllerSingleton;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ClientDao extends UserDao<Client> {
/**
* @param args 0=cpf, 1=rg
* @return
* @throws SQLException
*/
@Override
public Client getItem(String[] args) throws SQLException {
return executeStmt(conn -> {
PreparedStatement ps = conn.prepareStatement(
"SELECT * FROM tbl_user WHERE cpf=? && identity=?");
ps.setString(1, args[0]);
ps.setString(2, args[1]);
ResultSet rs = ps.executeQuery();
if (rs.next())
return new Client(
rs.getInt("id"),
rs.getString("name"),
rs.getBoolean("gender"),
new java.util.Date(rs.getDate("birthdate").getTime()),
rs.getLong("cpf"),
rs.getLong("identity"),
ControllerSingleton.ADDRESS_CONTROLLER.getItem(args),
ControllerSingleton.CREDENTIALS_CONTROLLER.getItem(args)
);
throw new SQLException();
});
}
@Override
protected boolean isClient() {
return true;
}
}
| true |
13ea52308dcf40053603c6c69468a0579c265fda
|
Java
|
zhangjunyong8888888/lenovoRepository
|
/src/main/java/com/lenovo/repository/data/dao/ErrorListDao.java
|
UTF-8
| 291 | 1.585938 | 2 |
[] |
no_license
|
package com.lenovo.repository.data.dao;
import com.lenovo.repository.data.pojo.ErrorList;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ErrorListDao extends JpaRepository<ErrorList,String> {
}
| true |
73e0657f9a0931ebb5e7530f37a7f621dcfab2ad
|
Java
|
gov466/Java
|
/Demo_automation/src/test/java/demo.java
|
UTF-8
| 5,472 | 2.046875 | 2 |
[
"MIT"
] |
permissive
|
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class demo {
public static WebDriver driver;
@Test
public void browser() {
String currentDir= System.getProperty("user.dir");
System.out.println("Launching browser");
//System.out.println(currentDir);
String msedgepath=currentDir+"//msedgedriver.exe";
//String Driverpath = "C:\\Users\\Govin\\Resolve6\\chromedriver_win32\\chromedriver.exe";
System.setProperty("webdriver.edge.driver", msedgepath); // set ie driver and location
driver = new EdgeDriver(); // driver object
driver.manage().window().maximize();
driver.get("http://demo.automationtesting.in/");
}
@Test
public void register() {
driver.findElement(By.xpath("//*[@id='email']")).sendKeys("[email protected]");
driver.findElement(By.xpath("//*[@id='enterimg']")).click();
driver.findElement(By.xpath("//*[@id=\"basicBootstrapForm\"]/div[1]/div[2]/input")).sendKeys("Raj");
driver.findElement(By.xpath("//*[@id='basicBootstrapForm']/div[1]/div[1]/input")).sendKeys("Govind");
driver.findElement(By.xpath("//*[@id ='basicBootstrapForm']/div[2]/div[1]/textarea")).sendKeys("200 Abc Ave,Toronto, M5G9G6");
driver.findElement(By.xpath("//*[@type='email']")).sendKeys("[email protected]");
driver.findElement(By.xpath("//*[@type='tel']")).sendKeys("6476470000");
WebElement radio_1= driver.findElement(By.xpath("//*[@id=\"basicBootstrapForm\"]/div[5]/div/label[1]/input"));
radio_1.click();
WebElement checkbox_1=driver.findElement(By.xpath("//*[@id=\"basicBootstrapForm\"]/div[6]/div/div[1]/input"));
checkbox_1.click();
WebElement checkbox_2=driver.findElement(By.xpath("//*[@id=\"basicBootstrapForm\"]/div[6]/div/div[2]/input"));
checkbox_2.click();
WebElement checkbox_3=driver.findElement(By.xpath("//*[@id=\"basicBootstrapForm\"]/div[6]/div/div[3]/input"));
checkbox_3.click();
//
// driver.findElement(By.xpath("//*[@id='basicBootstrapForm']/div[7]/div[1]/multi-select/div[2]/ul")).click();
Actions action = new Actions(driver);
// WebElement language= driver.findElement(By.xpath("//*[@id=\"msdd\"]"));
// action.click(language).build().perform();
//driver.manage().timeouts().implicitlyWait(3,TimeUnit.SECONDS);
// WebElement language = driver.findElement(By.xpath("//*[@id=\"basicBootstrapForm\"]/div[7]/div/multi-select/div[2]/ul"));
// Select sel_language = new Select(language);
// List<WebElement> options = sel_language.getOptions();
//
// for (WebElement option : options) {
// System.out.println(option.getText());
// if (option.getText().equals("English")) {
// option.click();
//
// }
// }
WebElement skills= driver.findElement(By.xpath("//*[@id=\"Skills\"]"));
Select sel_skills = new Select(skills);
sel_skills.selectByValue("HTML");
WebElement countries= driver.findElement(By.xpath("//*[@id=\"countries\"]"));
Select Sel_country = new Select(countries);
Sel_country.selectByValue("India");
// WebElement country= driver.findElement(By.xpath("//*[@id=\"select2-country-results\"]"));
//Select Sel2_country = new Select(country);
//Sel2_country.selectByValue("India");
//driver.findElement(By.xpath("//*[@class='select2-selection__arrow']")).click();
WebElement Country_1= driver.findElement(By.xpath("//*[@class='select2-selection select2-selection--single']"));
action.click(Country_1).build().perform();
driver.findElement(By.xpath("//*[@class='select2-search__field']")).sendKeys("India");
WebElement select2Country= driver.findElement(By.xpath("//*[@id=\"select2-country-results\"]/li"));
action.click(select2Country).build().perform();
WebElement year= driver.findElement(By.xpath("//*[@id='yearbox']"));
Select Sel_year = new Select(year);
Sel_year.selectByValue("1994");
WebElement month= driver.findElement(By.xpath("//*[@id=\"basicBootstrapForm\"]/div[11]/div[2]/select"));
Select Sel_month = new Select(month);
Sel_month.selectByValue("January");
WebElement date= driver.findElement(By.xpath("//*[@id='daybox']"));
Select Sel_date = new Select(date);
Sel_date.selectByValue("17");
driver.findElement(By.xpath("//*[@id='firstpassword']")).sendKeys("Govind@123");
driver.findElement(By.xpath("//*[@id='secondpassword']")).sendKeys("Govind@123");
driver.findElement(By.xpath("//*[@id=\"submitbtn\"]")).click();
//move to switch
action.moveToElement(driver.findElement(By.xpath("//*[@id=\"header\"]/nav/div/div[2]/ul/li[4]"))).build().perform();
driver.findElement(By.xpath("//*[@id=\"header\"]/nav/div/div[2]/ul/li[4]/ul/li[1]/a")).click();
driver.findElement(By.xpath("//*[@id=dismiss-button")).click();
String currentwindow = driver.getWindowHandle();
driver.findElement(By.xpath("//*[@class='btn btn-danger']")).click();
driver.switchTo().window(currentwindow);
//Select Sel_country2 = new Select(Country_1);
//Sel_country2.selectByVisibleText("India");
//System.out.println("entered the word");
//driver.close();
}
}
| true |
099c1666bdfaab5db556a1fb942f57e0bce81cbc
|
Java
|
zhengxingtao/jaagro-platform-crm
|
/crm-biz/src/main/java/com/jaagro/crm/biz/mapper/NewsMapper.java
|
UTF-8
| 707 | 1.679688 | 2 |
[] |
no_license
|
package com.jaagro.crm.biz.mapper;
import com.jaagro.crm.biz.entity.News;
import java.util.List;
public interface NewsMapper {
/**
*
* @mbggenerated 2018-11-16
*/
int deleteByPrimaryKey(Integer id);
/**
*
* @mbggenerated 2018-11-16
*/
int insert(News record);
/**
*
* @mbggenerated 2018-11-16
*/
int insertSelective(News record);
/**
*
* @mbggenerated 2018-11-16
*/
News selectByPrimaryKey(Integer id);
/**
*
* @mbggenerated 2018-11-16
*/
int updateByPrimaryKeySelective(News record);
/**
*
* @mbggenerated 2018-11-16
*/
int updateByPrimaryKey(News record);
}
| true |
424f30a0565e5297458724ccc134fb721db99ab2
|
Java
|
TokarAndrii/carServiceStation
|
/src/main/java/filter/SessionFilterClient.java
|
UTF-8
| 2,201 | 2.25 | 2 |
[] |
no_license
|
package filter;
import model.Admin;
import model.Client;
import model.Worker;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import service.ClientServImpl;
import service.WorkServImpl;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SessionFilterClient implements Filter {
private static final Logger LOGGER = Logger.getLogger(SessionFilterClient.class);
private ClientServImpl clientServ;
private WorkServImpl workServ;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
ApplicationContext applicationContext =
(ApplicationContext) filterConfig.getServletContext().getAttribute("spring-context");
clientServ = applicationContext.getBean(ClientServImpl.class);
workServ = applicationContext.getBean(WorkServImpl.class);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("accessToken") && cookie.equals("acessToken")) {
String value = cookie.getValue();
if (clientServ.getClient(value) != null) {
Client client = clientServ.getClient(value);
request.setAttribute("accessToken", value);
}
if (workServ.getWorker(value) != null) {
Worker worker = workServ.getWorker(value);
request.setAttribute("accessToken", value);
} else {
LOGGER.info("Authentification failled");
}
}
}
filterChain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
| true |
01c14eee3f2956bd259f4b1ac5a93cdfccfa4b42
|
Java
|
cobbanro/DemolitionDerby
|
/src/main/java/Car.java
|
UTF-8
| 525 | 3.171875 | 3 |
[] |
no_license
|
import Behaviours.IDriveable;
public abstract class Car implements IDriveable {
private String model;
private int fuelLevel;
public Car(String model, int fuelLevel){
this.model = model;
this.fuelLevel = fuelLevel;
}
public String drive() {
return "vroomy vroomy vroomy";
}
public void reFuel() {
this.fuelLevel = 100;
}
public String getModel(){
return this.model;
}
public int getFuelLevel(){
return this.fuelLevel;
}
}
| true |
a8b757dac570a4484e5f2bce3aa19a4ca7a6467e
|
Java
|
Coldstream-Louis/Clearwater-data-visualization
|
/Back End/src/main/java/neo4jentities/Node.java
|
UTF-8
| 883 | 2.21875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package neo4jentities;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Property;
import org.neo4j.ogm.annotation.Relationship;
import java.util.Set;
@NodeEntity
public class Node {
//@GraphId
//private Long id;
private String Name;
/*@Relationship()
private Set<Relationship> relationships;
public Set<Relationship> getRelationships() {
return relationships;
}
public void setRelationships(Set<Relationship> relationships) {
this.relationships = relationships;
}*/
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
/*public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}*/
}
| true |
12fff5ffc3bffcbf225d34f43d0f7105f63125eb
|
Java
|
nisheeth84/prjs_sample
|
/aio-service/src/main/java/com/viettel/coms/dto/WorkItemDTO.java
|
UTF-8
| 8,325 | 1.703125 | 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.viettel.coms.dto;
import com.viettel.coms.bo.WorkItemBO;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author thuannht
*/
@XmlRootElement(name = "WORK_ITEMBO")
@JsonIgnoreProperties(ignoreUnknown = true)
public class WorkItemDTO extends ComsBaseFWDTO<WorkItemBO> {
private java.lang.Long workItemId;
private java.lang.Long constructionId;
private java.lang.Long catWorkItemTypeId;
private java.lang.String code;
private java.lang.String name;
private java.lang.String isInternal;
private java.lang.Long constructorId;
private java.lang.Long supervisorId;
private java.util.Date startingDate;
private java.util.Date completeDate;
private java.lang.String status;
private java.lang.Double quantity;
private java.lang.Double approveQuantity;
private java.lang.String approveState;
private java.util.Date approveDate;
private java.lang.Long approveUserId;
private java.lang.String approveDescription;
private java.util.Date createdDate;
private java.lang.Long createdUserId;
private java.lang.Long createdGroupId;
private java.util.Date updatedDate;
private java.lang.Long updatedUserId;
private java.lang.Long updatedGroupId;
private java.lang.Long performerId;
private java.lang.Long catWorkItemGroupId;
// hoanm1_20181015_start
private String partnerName;
public String getPartnerName() {
return partnerName;
}
public void setPartnerName(String partnerName) {
this.partnerName = partnerName;
}
// hoanm1_20181015_end
@Override
public WorkItemBO toModel() {
WorkItemBO workItemBO = new WorkItemBO();
workItemBO.setWorkItemId(this.workItemId);
workItemBO.setConstructionId(this.constructionId);
workItemBO.setCatWorkItemTypeId(this.catWorkItemTypeId);
workItemBO.setCode(this.code);
workItemBO.setName(this.name);
workItemBO.setIsInternal(this.isInternal);
workItemBO.setConstructorId(this.constructorId);
workItemBO.setSupervisorId(this.supervisorId);
workItemBO.setStartingDate(this.startingDate);
workItemBO.setCompleteDate(this.completeDate);
workItemBO.setStatus(this.status);
workItemBO.setQuantity(this.quantity);
workItemBO.setApproveQuantity(this.approveQuantity);
workItemBO.setApproveState(this.approveState);
workItemBO.setApproveDate(this.approveDate);
workItemBO.setApproveUserId(this.approveUserId);
workItemBO.setApproveDescription(this.approveDescription);
workItemBO.setCreatedDate(this.createdDate);
workItemBO.setCreatedUserId(this.createdUserId);
workItemBO.setCreatedGroupId(this.createdGroupId);
workItemBO.setUpdatedDate(this.updatedDate);
workItemBO.setUpdatedUserId(this.updatedUserId);
workItemBO.setUpdatedGroupId(this.updatedGroupId);
workItemBO.setPerformerId(this.performerId);
workItemBO.setCatWorkItemGroupId(catWorkItemGroupId);
return workItemBO;
}
public java.lang.Long getPerformerId() {
return performerId;
}
public void setPerformerId(java.lang.Long performerId) {
this.performerId = performerId;
}
public java.lang.Long getWorkItemId() {
return workItemId;
}
public void setWorkItemId(java.lang.Long workItemId) {
this.workItemId = workItemId;
}
public java.lang.Long getConstructionId() {
return constructionId;
}
public void setConstructionId(java.lang.Long constructionId) {
this.constructionId = constructionId;
}
public java.lang.Long getCatWorkItemTypeId() {
return catWorkItemTypeId;
}
public void setCatWorkItemTypeId(java.lang.Long catWorkItemTypeId) {
this.catWorkItemTypeId = catWorkItemTypeId;
}
public java.lang.String getCode() {
return code;
}
public void setCode(java.lang.String code) {
this.code = code;
}
public java.lang.String getName() {
return name;
}
public void setName(java.lang.String name) {
this.name = name;
}
public java.lang.String getIsInternal() {
return isInternal;
}
public void setIsInternal(java.lang.String isInternal) {
this.isInternal = isInternal;
}
public java.lang.Long getConstructorId() {
return constructorId;
}
public void setConstructorId(java.lang.Long constructorId) {
this.constructorId = constructorId;
}
public java.lang.Long getSupervisorId() {
return supervisorId;
}
public void setSupervisorId(java.lang.Long supervisorId) {
this.supervisorId = supervisorId;
}
public java.util.Date getStartingDate() {
return startingDate;
}
public void setStartingDate(java.util.Date startingDate) {
this.startingDate = startingDate;
}
public java.util.Date getCompleteDate() {
return completeDate;
}
public void setCompleteDate(java.util.Date completeDate) {
this.completeDate = completeDate;
}
public java.lang.String getStatus() {
return status;
}
public void setStatus(java.lang.String status) {
this.status = status;
}
public java.lang.Double getQuantity() {
return quantity;
}
public void setQuantity(java.lang.Double quantity) {
this.quantity = quantity;
}
public java.lang.Double getApproveQuantity() {
return approveQuantity;
}
public void setApproveQuantity(java.lang.Double approveQuantity) {
this.approveQuantity = approveQuantity;
}
public java.lang.String getApproveState() {
return approveState;
}
public void setApproveState(java.lang.String approveState) {
this.approveState = approveState;
}
public java.util.Date getApproveDate() {
return approveDate;
}
public void setApproveDate(java.util.Date approveDate) {
this.approveDate = approveDate;
}
public java.lang.Long getApproveUserId() {
return approveUserId;
}
public void setApproveUserId(java.lang.Long approveUserId) {
this.approveUserId = approveUserId;
}
public java.lang.String getApproveDescription() {
return approveDescription;
}
public void setApproveDescription(java.lang.String approveDescription) {
this.approveDescription = approveDescription;
}
public java.util.Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(java.util.Date createdDate) {
this.createdDate = createdDate;
}
public java.lang.Long getCreatedUserId() {
return createdUserId;
}
public void setCreatedUserId(java.lang.Long createdUserId) {
this.createdUserId = createdUserId;
}
public java.lang.Long getCreatedGroupId() {
return createdGroupId;
}
public void setCreatedGroupId(java.lang.Long createdGroupId) {
this.createdGroupId = createdGroupId;
}
public java.util.Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(java.util.Date updatedDate) {
this.updatedDate = updatedDate;
}
public java.lang.Long getUpdatedUserId() {
return updatedUserId;
}
public void setUpdatedUserId(java.lang.Long updatedUserId) {
this.updatedUserId = updatedUserId;
}
public java.lang.Long getUpdatedGroupId() {
return updatedGroupId;
}
public void setUpdatedGroupId(java.lang.Long updatedGroupId) {
this.updatedGroupId = updatedGroupId;
}
public java.lang.Long getCatWorkItemGroupId() {
return catWorkItemGroupId;
}
public void setCatWorkItemGroupId(java.lang.Long catWorkItemGroupId) {
this.catWorkItemGroupId = catWorkItemGroupId;
}
@Override
public Long getFWModelId() {
return workItemId;
}
@Override
public String catchName() {
return getWorkItemId().toString();
}
}
| true |
7d003ec782f4c26150fdbb95e778ecaa65d33c5d
|
Java
|
sky24987/springCloud-Summary
|
/cloud-eureka-server2/src/main/java/com/zheng/SpringBootApplicationEureka2.java
|
UTF-8
| 493 | 1.65625 | 2 |
[] |
no_license
|
package com.zheng;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* SpringCloud启动类
*
* @author 郑国超
* @Version 1.0
* @Data 2018/7/2 8:53
*/
@EnableEurekaServer
@org.springframework.boot.autoconfigure.SpringBootApplication
public class SpringBootApplicationEureka2 {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplicationEureka2.class,args);
}
}
| true |
a4b824c00b53231faeda2b454171eff56298688b
|
Java
|
ptkjw1997/BaekJoon
|
/11057-오르막 수.java
|
UTF-8
| 1,174 | 2.921875 | 3 |
[] |
no_license
|
package baekjoon;/*
* import java.io.*
* import java.utils.*
*
* Scanner sc = new Scanner(System.in)
* BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
*
* sc.nextLine()
* br.readLine()
*
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
LinkedList<Integer> queue = new LinkedList<Integer>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int num = Integer.parseInt(br.readLine());
int[][] DP = new int[1001][10];
for(int i = 0; i < 10; i++) {
DP[0][i] = 0;
DP[1][i] = 1;
}
for(int i = 2; i < num+1; i++) {
int sum = 0;
for(int j = 0; j < 10; j++) {
sum += DP[i-1][j];
DP[i][j] = sum % 10007;
}
}
int result = 0;
for(int i = 0; i < 10; i++) {
result = (result + DP[num][i]) % 10007;
}
System.out.println(result);
}
}
| true |
91168242136670fcf8488f7908669ad83eaebcdb
|
Java
|
Davidhua1996/capture
|
/capture/src/com/david/util/SystemContext.java
|
UTF-8
| 278 | 1.921875 | 2 |
[] |
no_license
|
package com.david.util;
public class SystemContext {
private static String COOKIE_NAME = "ASP.NET_SessionId";
public static String getCookie_name() {
return COOKIE_NAME;
}
public static void setCookie_name(String cookie_name) {
COOKIE_NAME=cookie_name;
}
}
| true |
c30182644228dfb18daa9535adab98869cd8b85a
|
Java
|
MostafaAttia777/coivd_25
|
/app/src/main/java/com/MostafaCovied/Mostafacovied/Login/LoginScreen.java
|
UTF-8
| 3,544 | 1.96875 | 2 |
[] |
no_license
|
package com.MostafaCovied.Mostafacovied.Login;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.MostafaCovied.Mostafacovied.Activity.Home_Screen;
import com.MostafaCovied.Mostafacovied.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginScreen extends AppCompatActivity {
TextView textView_create_Account;
TextInputLayout textInputLayout_email;
TextInputLayout textInputLayout_password;
TextView textView_btn_login;
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
textView_create_Account = findViewById(R.id.createAccuont);
textInputLayout_email = findViewById(R.id.my_textbox_Email);
textInputLayout_password = findViewById(R.id.my_textbox_password);
textView_btn_login = findViewById(R.id.btn_login);
// final String ministry_of_Health = firebaseAuth.getCurrentUser().getEmail();
textView_create_Account.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
create_Account();
}
});
textView_btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = textInputLayout_email.getEditText().getText().toString();
String password = textInputLayout_password.getEditText().getText().toString();
if (TextUtils.isEmpty(email) && TextUtils.isEmpty(password)) {
textInputLayout_password.setError("Enter your password");
textInputLayout_email.setError("Enter your Email");
} else if (TextUtils.isEmpty(email)) {
textInputLayout_email.setError("Enter your Email");
} else if (TextUtils.isEmpty(password)) {
textInputLayout_password.setError("Enter your password");
}
else if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
Login_Op();
}
}
;
});
}
private void Login_Op() {
String email = textInputLayout_email.getEditText().getText().toString();
String password = textInputLayout_password.getEditText().getText().toString();
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(LoginScreen.this, "Welcome", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Home_Screen.class));
finish();
}
}
});
}
private void create_Account() {
startActivity(new Intent(getApplicationContext(), CreateAccount.class));
}
}
| true |
ffa1d9b1530fbca31711b3cfa4acfd4c9912cf37
|
Java
|
moutainhigh/autofund
|
/src/main/java/com/xwguan/autofund/util/BijectionMap.java
|
UTF-8
| 4,909 | 3.375 | 3 |
[] |
no_license
|
package com.xwguan.autofund.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* A bijection map. The key and value satisfy a one to one correspondence, thus we can get unique value by key and
* unique key by value. The values of key or value are <b>NOT ALLOWED</b> to be null. The method {@code int hashCode()}
* and {@code boolean equals(Object obj)} <b>MUST</b> be overrided in the class of the key and value, or unpredictable
* mapping errors may occur in this class.
*
* @author XWGuan
* @version 1.0.0
* @date 2017-12-02
*/
public class BijectionMap<K, V> {
private Map<K, V> k2vMap;
private Map<V, K> v2kMap;
public BijectionMap() {
this.k2vMap = new HashMap<>();
this.v2kMap = new HashMap<>();
}
public BijectionMap(int initialCapacity) {
this.k2vMap = new HashMap<>(initialCapacity);
this.v2kMap = new HashMap<>(initialCapacity);
}
public Set<K> keySet() {
return k2vMap.keySet();
}
public Set<V> valueSet() {
return v2kMap.keySet();
}
public boolean containsKey(K key) {
return key != null && k2vMap.containsKey(key);
}
public boolean containsValue(V value) {
return value != null && v2kMap.containsKey(value);
}
public boolean containsBijection(K key, V value) {
// logically, containsX(x) && getY(x).equals(y) and containsY(y) && getX(y).equals(x) are equivalent
return containsKey(key) && getValue(key).equals(value);
// TODO
}
/**
* Put the bijection of key and value into this map. If the mapping of key or value has already existed, nothing
* will be put in, and false is to be returned.
*
* @param key
* @param value
* @return true if successfully put, false if key or value has already existed
*/
public boolean put(K key, V value) {
if (key == null || value == null) {
throw new NullPointerException("null is not an accepted value in " + this.getClass().getName());
}
if (containsKey(key) || containsValue(value)) {
return false;
}
try {
k2vMap.put(key, value);
v2kMap.put(value, key);
return true;
} catch (Exception e) {
// roll back to avoid inconformity of the two map
k2vMap.remove(key);
v2kMap.remove(value);
throw e;
}
}
/**
* Remeve bijection if the bijection exists
*
* @param key
* @param value
* @return the previous value associated with key, or null if there was no mapping for key
*/
public V remove(K key, V value) {
if (!containsBijection(key, value)) {
return null;
}
try {
k2vMap.remove(key);
v2kMap.remove(value);
return value;
} catch (Exception e) {
k2vMap.put(key, value);
v2kMap.put(value, key);
throw e;
}
}
/**
* Remove bijection if key exist
*
* @param key
* @return the previous value associated with key, or null if there was no mapping for key
*/
public V remove(K key) {
if (containsKey(key)) {
return remove(key, getValue(key));
} else {
return null;
}
}
/**
* Get value associated with key
*
* @param key the key whose associated value is to be returned
* @return the value to which the specified key is mapped, or null if this map contains no mapping for the key
*/
public V getValue(K key) {
return k2vMap.get(key);
}
/**
* Get key associated with value
*
* @param value the value whose associated key is to be returned
* @return the key to which the specified value is mapped, or null if this map contains no mapping for the value
*/
public K getKey(V value) {
return v2kMap.get(value);
}
/**
* Get a new HashMap with the same key and associated value of this object
*
* @return a new HashMap with the same key and associated value of this object
*/
public Map<K, V> getHashMap() {
return new HashMap<K, V>(k2vMap);
}
/**
* Get a new HashMap whose key is the value and value is the associated key of this object
*
* @return a new HashMap whose key is the value and value is the associated key of this object
*/
public Map<V, K> getReversedHashMap() {
return new HashMap<V, K>(v2kMap);
}
public int size() {
return k2vMap.size();
}
public boolean isEmpty() {
return k2vMap.isEmpty();
}
public void clear() {
k2vMap.clear();
v2kMap.clear();
}
@Override
public String toString() {
return "BijectionMap " + k2vMap.toString();
}
}
| true |
c8dd685738ce53f84b08f5a8813b35e3daff7b36
|
Java
|
Dalahro/ProjetDouble
|
/src/champelecpckg/Electron.java
|
UTF-8
| 237 | 2.015625 | 2 |
[
"MIT"
] |
permissive
|
package champelecpckg;
import basepckg.Particule;
public class Electron extends Particule {
public Electron(double posx, double posy, double vx, double vy) {
super(posx, posy, vx, vy);
this.attributs.put("masse", 9.1e-31);
}
}
| true |
c7faa0a07c4b04a68e90fae477a52b9fe62449a8
|
Java
|
Eltorus/Java11_16_Zhuk
|
/Task2_Zhuk/src/by/tc/eq/bean/requestimpl/RentEquipmentRequest.java
|
UTF-8
| 434 | 2.140625 | 2 |
[] |
no_license
|
package by.tc.eq.bean.requestimpl;
import by.tc.eq.bean.Request;
import by.tc.eq.bean.entity.Good;
import by.tc.eq.bean.entity.User;
public class RentEquipmentRequest extends Request {
private Good good;
private User user;
public Good getGood() {
return good;
}
public void setGood(Good good) {
this.good = good;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| true |
7d478da59d3c241fc7beac81e6cdccafd2ce9cf9
|
Java
|
caiyaguang/Oceanus
|
/core/src/main/java/script/Runtime.java
|
UTF-8
| 668 | 1.960938 | 2 |
[] |
no_license
|
package script;
import chat.errors.CoreException;
import script.core.runtime.AbstractRuntimeContext;
import script.core.runtime.classloader.ClassHolder;
import script.core.runtime.classloader.DefaultClassLoader;
import script.core.runtime.handler.AbstractClassAnnotationHandler;
import script.core.runtime.handler.annotation.clazz.ClassAnnotationHandler;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public abstract class Runtime {
protected AbstractRuntimeContext runtimeContext;
public abstract void start() throws CoreException;
public abstract void close();
public String path(Class<?> c){return null;}
}
| true |
cc8d84f48e183927c3a334d4cb30636ff1162d7d
|
Java
|
DvlFaster/Reservations
|
/src/reservation_entities/UserBean.java
|
UTF-8
| 2,246 | 2.3125 | 2 |
[] |
no_license
|
package reservation_entities;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class UserBean {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", precision = 0)
private int id;
@Column(name = "first_name", unique = true, length = 50, nullable = false)
private String first_name;
@Column(name = "last_name", unique = true, length = 50, nullable = false)
private String last_name;
@Column(name = "email", unique = true, length = 50, nullable = false)
private String email;
@Column(name = "pass", unique = true, length = 64, nullable = false)
private String pass;
@Column(name = "city", unique = true, length = 50, nullable = false)
private String city;
@Column(name = "telefon_number", precision = 0)
private int telefon_number;
//private List<UserType> user_type;
//public List<UserType> getComments() {
// return user_type;
//}
//public void setComments(List<UserType> user_type) {
// this.user_type = user_type;
//}
public UserBean() {
super();
}
public UserBean(String email, String pass) {
super();
this.email = email;
this.pass = pass;
}
public String getFirst_name(){
return first_name;
}
public void setFirst_name(String first_name){
this.first_name = first_name;
}
public String getLast_name(){
return last_name;
}
public void setLast_name(String last_name){
this.last_name = last_name;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getPass(){
return pass;
}
public void setPass(String pass){
this.pass = pass;
}
public String getCity(){
return city;
}
public void setCity(String city){
this.city = city;
}
public int getTelefon_number(){
return telefon_number;
}
public void setTelefon_number(int telefon_number){
this.telefon_number = telefon_number;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| true |
ecd926d3f55908f6a455ac20aba670ca32c50d23
|
Java
|
menyouping/jLang
|
/src/com/jay/parser/element/Precedence.java
|
UTF-8
| 209 | 2.265625 | 2 |
[] |
no_license
|
package com.jay.parser.element;
public class Precedence {
int value;
boolean leftAssoc; // left associative
public Precedence(int v, boolean a) {
value = v;
leftAssoc = a;
}
}
| true |
e42b59f574893be495221b9ca2b6098cb2ab64f3
|
Java
|
CL-window/SocketLearn
|
/AndroidClient/app/src/main/java/com/slack/androidclient/screen/Callback.java
|
UTF-8
| 309 | 1.796875 | 2 |
[] |
no_license
|
package com.slack.androidclient.screen;
import android.graphics.Bitmap;
/**
* Created by slack on 2020/6/4 下午5:13.
*/
public interface Callback {
default void callback(Bitmap bitmap) {
//
}
default void onStart() {
//
}
default void onStop() {
//
}
}
| true |
e579841610c3ae17627dd3081abbb9333697c56c
|
Java
|
hanaskuliah/AirGestRecTrain
|
/app/src/main/java/com/group1/ml/airgestrectrain/MainActivity.java
|
UTF-8
| 1,448 | 2.125 | 2 |
[] |
no_license
|
package com.group1.ml.airgestrectrain;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
UserAddFragment dialogFragment;
FragmentManager fm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fm = getSupportFragmentManager();
dialogFragment = new UserAddFragment();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
showDialog();
}
});
}
protected void showDialog() {
dialogFragment.show(fm, "lalala");
}
}
| true |
2f59798ef923af5464a19e8f8b15d6869a8891d0
|
Java
|
djandrewd/online-6-6-1
|
/src/ua/goit/online6/third_example/LazySingletonA.java
|
UTF-8
| 762 | 3.359375 | 3 |
[] |
no_license
|
package ua.goit.online6.third_example;
/**
* Example to lazy initialized singleton..
*
* @author andreymi
*/
public class LazySingletonA {
// now when static variable initialized it will initialized with null value.
private static LazySingletonA instance;
// when we first time will call method getInstance then instance variable will create.
// this algorythm is called lazy initialization (opposite is eager).
public static LazySingletonA getInstance() {
if (instance == null) {
instance = new LazySingletonA(10);
}
return instance;
}
private int value;
public LazySingletonA(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
| true |
28987c0066df16fbdcfb3d1b929a52b5eca115f2
|
Java
|
thiendoan2212/Microservices
|
/Project/Order-Service/src/main/java/com/microservices/orderservice/controller/OrderController.java
|
UTF-8
| 2,134 | 2.28125 | 2 |
[] |
no_license
|
package com.microservices.orderservice.controller;
import com.microservices.orderservice.model.OrderDTO;
import com.microservices.orderservice.service.OrderServiceImpl;
import com.microservices.orderservice.util.ApiResponseBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
OrderServiceImpl orderService;
@GetMapping
public Map<String, ?> findAllOrder() {
return ApiResponseBuilder.buildContainsData("List Order", orderService.findAllOrder());
}
@GetMapping("/username/{username}")
public Map<String, ?> findOrderByUsername(@PathVariable String username) {
return ApiResponseBuilder.buildContainsData("Order of username " + username, orderService.findOrderByUsername(username));
}
@GetMapping("/active/{active}")
public Map<String, ?> findOrderByActive(@PathVariable boolean active) {
return ApiResponseBuilder.buildContainsData("List Order " + active, orderService.findOrderByActive(active));
}
@PostMapping
public Map<String, ?> insertOrder(@RequestBody OrderDTO orderDTO) {
OrderDTO savedOrderDTO = orderService.insertOrder(orderDTO);
return ApiResponseBuilder.buildContainsData(String.format("Inserted Order id " + savedOrderDTO.getId()), savedOrderDTO);
}
@PutMapping("/{id}")
public Map<String, ?> updateOrder(@PathVariable Long id, @RequestBody OrderDTO orderDTO) {
OrderDTO savedOrderDTO = orderService.updateOrder(id, orderDTO);
return ApiResponseBuilder.buildContainsData(String.format("Update Order id " + id), savedOrderDTO);
}
@DeleteMapping("/{id}")
public Map<String, ?> deleteOrder(@PathVariable Long id) {
boolean success = orderService.deleteOrder(id);
if (success)
return ApiResponseBuilder.buildSuccess(String.format("Delete Order id " + id + " success"));
else return ApiResponseBuilder.buildSuccess(String.format("Delete Order id " + id + " fail"));
}
}
| true |
0a24c4871dbfc0e9882dff71998b4f61de3f5fbe
|
Java
|
mskalbania/ReactClientListProject
|
/src/main/java/com/clientlist/controller/ClientRestController.java
|
UTF-8
| 1,152 | 2.3125 | 2 |
[] |
no_license
|
package com.clientlist.controller;
import com.clientlist.pojo.Client;
import com.clientlist.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/api")
@CrossOrigin
public class ClientRestController {
private ClientService clientService;
@Autowired
public ClientRestController(ClientService clientService) {
this.clientService = clientService;
}
@GetMapping(value = "/all")
public ResponseEntity<?> getAllClients() {
return clientService.getAll();
}
@GetMapping(value = "/all/{request}")
public ResponseEntity<?> getClientsByRequest(@PathVariable("request") String request) {
if (request.matches("[0-9]*$")) {
return clientService.getAllByYear(Integer.parseInt(request));
} else return clientService.getAllByNameRegex(request);
}
@PostMapping(value = "/add")
public ResponseEntity<?> addClient(@RequestBody Client client) {
return clientService.addClient(client);
}
}
| true |
8113bf32aff2d7190d622f28d3e6e6d60811dcf8
|
Java
|
Giovanni007/GamesList
|
/res_ps/src/main/java/com/gio/ps/res_ps/models/Games.java
|
UTF-8
| 1,714 | 2.265625 | 2 |
[] |
no_license
|
package com.gio.ps.res_ps.models;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
public class Games {
@Id
private ObjectId _id;
private String name;
private String platform;
private String genre;
private String publisher;
private String boxart;
private String releaseDate;
public int players;
// Constructors
public Games() {}
public Games(ObjectId _id, String name, String platform, String genre, String publisher, String boxart,String releaseDate, int players) {
this._id = _id;
this.name = name;
this.platform = platform;
this.genre = genre;
this.publisher = publisher;
this.boxart = boxart;
this.releaseDate = releaseDate;
this.players = players;
}
public String get_id() {
return _id.toHexString();
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getBoxart() {
return boxart;
}
public void setBoxart(String boxart) {
this.boxart = boxart;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public int getPlayers() {
return players;
}
public void setPlayers(int players) {
this.players = players;
}
}
| true |
0350383e9b0333f230a08a1c17fc072148cf3e09
|
Java
|
xueqiao-codes/xueqiao-quotation
|
/quotation_account_dao/java/src/main/java/xueqiao/quotation/account/api/HandleQuotationAccount.java
|
UTF-8
| 3,776 | 2.15625 | 2 |
[] |
no_license
|
package xueqiao.quotation.account.api;
import com.antiy.error_code.ErrorCodeOuter;
import org.soldier.platform.db_helper.DBQueryHelper;
import org.soldier.platform.db_helper.DBTransactionHelper;
import org.soldier.platform.page.IndexedPageOption;
import org.soldier.platform.svr_platform.comm.ErrorInfo;
import xueqiao.quotation.account.config.ConfigurationProperty;
import xueqiao.quotation.account.storage.QuotationAccountTable;
import xueqiao.quotation.account.thriftapi.QuotationAccount;
import xueqiao.quotation.account.thriftapi.QuotationAccountPage;
import xueqiao.quotation.account.thriftapi.ReqQuotationAccountOption;
import java.sql.Connection;
public class HandleQuotationAccount {
public QuotationAccountPage queryQuotationAccount(ReqQuotationAccountOption option, IndexedPageOption pageOption) throws ErrorInfo {
return new DBQueryHelper<QuotationAccountPage>(ConfigurationProperty.instance().getDataSource(null)) {
@Override
protected QuotationAccountPage onQuery(Connection connection) throws Exception {
return new QuotationAccountTable(connection).query(option, pageOption);
}
}.query();
}
public long addQuotationAccount(QuotationAccount account) throws ErrorInfo {
return new DBTransactionHelper<Long>(ConfigurationProperty.instance().getDataSource(null)) {
QuotationAccountTable table;
long accountId;
@Override
public void onPrepareData() throws ErrorInfo, Exception {
table = new QuotationAccountTable(getConnection());
}
@Override
public void onUpdate() throws ErrorInfo, Exception {
QuotationAccount item = table.queryForUpdate(account.getAccountName(), account.getBrokerId(), account.getPlatform(), false);
if (item != null) {
throw new ErrorInfo(ErrorCodeOuter.PARAM_ERROR.getErrorCode(), "Record exists.");
}
accountId = table.add(account);
}
@Override
public Long getResult() {
return accountId;
}
}.execute().getResult();
}
public void updateQuotationAccount(QuotationAccount account) throws ErrorInfo {
new DBTransactionHelper<Void>(ConfigurationProperty.instance().getDataSource(null)) {
QuotationAccountTable table;
@Override
public void onPrepareData() throws ErrorInfo, Exception {
table = new QuotationAccountTable(getConnection());
}
@Override
public void onUpdate() throws ErrorInfo, Exception {
QuotationAccount item = table.queryForUpdate(account.getAccountId(), false);
if (item == null) {
throw new ErrorInfo(ErrorCodeOuter.PARAM_ERROR.getErrorCode(), "Record not found.");
}
table.update(account);
}
@Override
public Void getResult() {
return null;
}
}.execute();
}
public void delete(long accountId) throws ErrorInfo {
new DBTransactionHelper<Void>(ConfigurationProperty.instance().getDataSource(null)) {
QuotationAccountTable table;
@Override
public void onPrepareData() throws ErrorInfo, Exception {
table = new QuotationAccountTable(getConnection());
}
@Override
public void onUpdate() throws ErrorInfo, Exception {
table.delete(accountId);
}
@Override
public Void getResult() {
return null;
}
}.execute();
}
}
| true |
664f262e0e8e6ea278e2539c9e33acc8f436edec
|
Java
|
riotjy/mobjy4j
|
/src/main/java/dev/riotjy/mobjy/export/codegen/java/JavaSerializeStaticCodeGenerator.java
|
UTF-8
| 3,460 | 2.171875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*******************************************************************************
* Copyright 2020 riotjy and listed authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Authors:
* Alex Savulov
*******************************************************************************/
package dev.riotjy.mobjy.export.codegen.java;
import dev.riotjy.mobjy.export.codegen.CodeGenerator;
public class JavaSerializeStaticCodeGenerator extends CodeGenerator {
public JavaSerializeStaticCodeGenerator() {
}
@Override
public String generate() {
return
" private static String serClass(String className, String fields) {\n" +
" String code = \"{\\\"cnid\\\":\" + qtd(className) + \"\";\n" +
" if (null != fields && !fields.isEmpty()) {\n" +
" code += \",\" + fields;\n" +
" }\n" +
" code += \"}\";\n" +
" return code;\n" +
" }\n" +
"\n" +
" private static String serArr(ArrayList<?> arr) {\n" +
" String json = \"[\";\n" +
" Iterator<?> it = arr.iterator();\n" +
" \n" +
" while (it.hasNext()) {\n" +
" Object val = it.next();\n" +
" if (it.hasNext()) {\n" +
" json += lin(serValue(val)); \n" +
" } else {\n" +
" json += serValue(val); \n" +
" }\n" +
" }\n" +
" \n" +
" json += \"]\";\n" +
" return json;\n" +
" }\n" +
"\n" +
" private static String serMap(HashMap<String, ?> hm) {\n" +
" String json = \"{\";\n" +
"\n" +
" Iterator<String> it = hm.keySet().iterator();\n" +
" \n" +
" while (it.hasNext()) {\n" +
" String key = it.next();\n" +
" Object val = hm.get(key);\n" +
" if (it.hasNext()) {\n" +
" json += lin(con(qtd(key), serValue(val))); \n" +
" } else {\n" +
" json += con(qtd(key), serValue(val)); \n" +
" }\n" +
" }\n" +
" \n" +
" json += \"}\";\n" +
" return json;\n" +
" }\n" +
" \n" +
" private static String qtd(String in) {\n" +
" return \"\\\"\" + in + \"\\\"\";\n" +
" }\n" +
" private static String con(String first, String second) {\n" +
" return first + \":\" + second;\n" +
" }\n" +
" private static String lin(String in) {\n" +
" return in + \",\";\n" +
" }\n" +
" private static String crl(String in) {\n" +
" return \"{\" + in + \"}\";\n" +
" }\n" +
" \n" +
" public static String serialize(Object value) {\n" +
" return serValue(value);\n" +
" }\n";
}
}
| true |
00e971ee355a75328b305eec6f7ed4714a971806
|
Java
|
shsh88/test_weka
|
/TestWeka/src/main/java/test/fnc/classification/FNCFeatureEngineering.java
|
UTF-8
| 13,124 | 2.15625 | 2 |
[] |
no_license
|
package test.fnc.classification;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import com.opencsv.CSVReader;
import opennlp.tools.tokenize.Tokenizer;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.InvalidFormatException;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instances;
import weka.core.converters.ArffSaver;
public class FNCFeatureEngineering {
private static TreeSet<String> stopSet;
private static HashMap<Integer, String> idBodyMap;
private static List<List<String>> stances;
static String[] refutingWords = { "fake", "fraud", "hoax", "false", "deny", "denies", "not", "despite", "nope",
"doubt", "doubts", "bogus", "debunk", "pranks", "retract" };
private static Instances instances;
public static void setData() throws IOException {
File bodiesFile = new File("resources/train_bodies.csv");
idBodyMap = getBodiesMap(bodiesFile);
readStances();
}
private static void readStances() throws FileNotFoundException, IOException {
CSVReader stancesReader = new CSVReader(new FileReader("resources/train_stances.csv"));
String[] stancesline;
stances = new ArrayList<>();
stancesReader.readNext();
while ((stancesline = stancesReader.readNext()) != null) {
List<String> record = new ArrayList<>();
record.add(stancesline[0]);
record.add(stancesline[1]);
record.add(stancesline[2]);
stances.add(record);
}
}
private static Instances getWekaInstances() {
ArrayList<Attribute> attributes = new ArrayList<>();
attributes.add(new Attribute("word_overlap"));
for (String refute : refutingWords) {
attributes.add(new Attribute("refute_" + refute));
}
for (String polar : refutingWords) {
attributes.add(new Attribute("polar_" + polar));
}
int[] cgramSizes = { 2, 8, 4, 16 };
for (int size : cgramSizes) {
attributes.add(new Attribute("cgram_hits_" + size));
attributes.add(new Attribute("cgram_early_hits_" + size));
attributes.add(new Attribute("cgram_first_hits_" + size));
}
int[] ngramSizes = { 2, 3, 4, 5, 6 };
for (int size : ngramSizes) {
attributes.add(new Attribute("ngram_hits_" + size));
attributes.add(new Attribute("ngram_early_hits_" + size));
attributes.add(new Attribute("ngram_first_hits_" + size));
}
attributes.add(new Attribute("bin_co_occ_count"));
attributes.add(new Attribute("bin_co_occ_early"));
attributes.add(new Attribute("bin_co_occ_stop_count"));
attributes.add(new Attribute("bin_co_occ_stop_early"));
String stancesClasses[] = new String[] { "unrelated", "related" };
List<String> stanceValues = Arrays.asList(stancesClasses);
attributes.add(new Attribute("class", stanceValues));
instances = new Instances("fnc", attributes, 1000);
for (int i = 0; i < 0; i++) {
List<Double> features = new ArrayList<>();
String headline = stances.get(i).get(0);
String body = idBodyMap.get(stances.get(i).get(1));
features.add(getWordOverlapFeature(headline, body));
features.addAll(getRefutingFeature(headline, body));
features.addAll(getPolarityFeatures(headline, body));
features.addAll(countGrams(headline, body));
features.addAll(binaryCoOccurenceFeatures(headline, body));
features.addAll(binaryCoOccurenceStopFeatures(headline, body));
features.add((double) stanceValues.indexOf(stances.get(i).get(2)));
double[] a = new double[features.size()];
int j = 0;
for (double feature : features) {
a[j++] = feature;
}
instances.add(new DenseInstance(1.0, a));
}
return instances;
}
private static void saveInstancesToARFFFile(String filepath) throws IOException {
ArffSaver saver = new ArffSaver();
saver.setInstances(instances);
saver.setFile(new java.io.File(filepath));
saver.writeBatch();
}
private static HashMap<Integer, String> getBodiesMap(File bodiesFile) {
HashMap<Integer, String> bodyMap = new HashMap<>(100, 100);
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(bodiesFile));
String[] line;
line = reader.readNext();
while ((line = reader.readNext()) != null) {
bodyMap.put(Integer.valueOf(line[0]), line[1]);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return bodyMap;
}
public static String cleanText(String text) {
text = text.replaceAll("[^\\p{ASCII}]", "");
text = text.replaceAll("\\s+", " ");
text = text.replaceAll("\\p{Cntrl}", "");
text = text.replaceAll("[^\\p{Print}]", "");
text = text.replaceAll("\\p{C}", "");
return text;
}
public List<String> tokinize(String sourceText, String modelPath) throws InvalidFormatException, IOException {
InputStream modelIn = null;
modelIn = new FileInputStream(modelPath);
TokenizerModel model = new TokenizerModel(modelIn);
Tokenizer tokenizer = new TokenizerME(model);
String tokens[] = tokenizer.tokenize(sourceText);
return Arrays.asList(tokens);
}
public static List<String> lemmatize(String text) {
return new Lemmatizer().lemmatize(text);
}
public static void initializeStopwords(String stopFile) throws Exception {
stopSet = new TreeSet<>();
Scanner s = new Scanner(new FileReader(stopFile));
while (s.hasNext())
stopSet.add(s.next());
s.close();
}
public static boolean isStopword(String word) {
if (word.length() < 2)
return true;
if (word.charAt(0) >= '0' && word.charAt(0) <= '9')
return true; // remove numbers, "23rd", etc
if (stopSet.contains(word))
return true;
else
return false;
}
public static List<String> removeStopWords(List<String> wordsList) {
List<String> wordsNoStop = new ArrayList<>();
for (String word : wordsList) {
if (word.isEmpty())
continue;
if (isStopword(word))
continue; // remove stopwords
wordsNoStop.add(word);
}
return wordsNoStop;
}
// This method calculate the feature for one record
public static double getWordOverlapFeature(String headLine, String body) {
String cleanHeadline = cleanText(headLine);
String cleanBody = cleanText(body);
List<String> headLineLem = lemmatize(cleanHeadline);
List<String> bodyLem = lemmatize(cleanBody);
Set<String> intersectinSet = new HashSet<>(headLineLem);
Set<String> bodySet = new HashSet<>(bodyLem);
Set<String> UnionSet = new HashSet<>(headLineLem);
intersectinSet.retainAll(bodySet);
UnionSet.addAll(bodySet);
return intersectinSet.size() / UnionSet.size();
}
public static List<Double> getRefutingFeature(String headLine, String body) {
String cleanHeadline = cleanText(headLine);
List<String> headLineLem = lemmatize(cleanHeadline);
List<Double> f = new ArrayList<>();
for (String refutingWord : refutingWords) {
if (headLineLem.contains(refutingWord))
f.add(1.0); // TODO maychange this to add integers
else
f.add(0.0);
}
return f;
}
public static List<Double> getPolarityFeatures(String headLine, String body) {
List<String> refutingWordsList = Arrays.asList(refutingWords);
String cleanHeadline = cleanText(headLine);
String cleanBody = cleanText(body);
List<String> headLineLem = lemmatize(cleanHeadline);
List<String> bodyLem = lemmatize(cleanBody);
List<Double> f = new ArrayList<>();
int h = 0;
for (String word : headLineLem) {
if (refutingWordsList.contains(word))
h++;
}
f.add((double) (h % 2));
int b = 0;
for (String word : bodyLem) {
if (refutingWordsList.contains(word))
b++;
}
f.add((double) (b % 2));
return f;
}
public static List<String> getNGrams(String text, int n) {
List<String> ret = new ArrayList<String>();
String[] input = text.split(" ");
for (int i = 0; i <= input.length - n; i++) {
String ngram = "";
for (int j = i; j < i + n; j++)
ngram += input[j] + " ";
ngram.trim();
ret.add(ngram);
}
return ret;
}
public static List<String> getCharGrams(String text, int n) {
List<String> ret = new ArrayList<String>();
for (int i = 0; i <= text.length() - n; i++) {
String ngram = "";
for (int j = i; j < i + n; j++)
ngram += text.charAt(j);
ngram.trim();
ret.add(ngram);
}
return ret;
}
/**
* vector specifying the sum of how often character sequences of length
* 2,4,8,16 in the headline appear in the entire body, the first 100
* characters and the first 255 characters of the body.
*
* @param headLine
* @param body
*/
public static List<Double> getCharGramsFeatures(String headLine, String body, int size) {
List<String> h = removeStopWords(Arrays.asList(headLine.split(" ")));
// get the string back
StringBuilder sb = new StringBuilder();
for (String s : h) {
sb.append(s);
sb.append(" ");
}
headLine = sb.toString().trim();
List<String> grams = getCharGrams(headLine, size);
int gramHits = 0;
int gramEarlyHits = 0;
int gramFirstHits = 0;
for (String gram : grams) {
if (body.contains(gram)) {
gramHits++;
}
if (body.substring(0, 255).contains(gram)) {
gramEarlyHits++;
}
if (body.substring(0, 100).contains(gram)) {
gramFirstHits++;
}
}
List<Double> f = new ArrayList<>();
f.add((double) gramHits);
f.add((double) gramEarlyHits);
f.add((double) gramFirstHits);
return f;
}
public static List<Double> getNGramsFeatures(String headLine, String body, int size) {
List<String> grams = getNGrams(headLine, size);
int gramHits = 0;
int gramEarlyHits = 0;
for (String gram : grams) {
if (body.contains(gram)) {
gramHits++;
}
if (body.substring(0, 255).contains(gram)) {
gramEarlyHits++;
}
}
List<Double> f = new ArrayList<>();
f.add((double) gramHits);
f.add((double) gramEarlyHits);
return f;
}
public static List<Double> binaryCoOccurenceFeatures(String headLine, String body) {
int binCount = 0;
int binCountEarly = 0;
String[] cleanHeadLine = cleanText(headLine).split(" ");
String cleanBody = cleanText(body);
for (String token : cleanHeadLine) {
if (cleanBody.contains(token)) // TODO traverse, won't we find this?
// --> verse
binCount++;
if (cleanBody.substring(0, 255).contains(token))
binCountEarly++;
}
List<Double> f = new ArrayList<>();
f.add((double) binCount);
f.add((double) binCountEarly);
return f;
}
public static List<Double> binaryCoOccurenceStopFeatures(String headLine, String body) {
int binCount = 0;
int binCountEarly = 0;
String[] cleanHeadLine = cleanText(headLine).split(" ");
List<String> cleanHead = removeStopWords(Arrays.asList(cleanHeadLine));
String cleanBody = cleanText(body);
for (String token : cleanHead) {
if (cleanBody.contains(token)) // TODO traverse, won't we find this?
// --> verse
binCount++;
if (cleanBody.substring(0, 255).contains(token))
binCountEarly++;
}
List<Double> f = new ArrayList<>();
f.add((double) binCount);
f.add((double) binCountEarly);
return f;
}
public static List<Double> countGrams(String headLine, String body) {
String cleanHeadline = cleanText(headLine);
String cleanBody = cleanText(body);
List<Double> f = new ArrayList<>();
f.addAll(getCharGramsFeatures(cleanHeadline, cleanBody, 2));
f.addAll(getCharGramsFeatures(cleanHeadline, cleanBody, 8));
f.addAll(getCharGramsFeatures(cleanHeadline, cleanBody, 4));
f.addAll(getCharGramsFeatures(cleanHeadline, cleanBody, 16));
f.addAll(getNGramsFeatures(cleanHeadline, cleanBody, 2));
f.addAll(getNGramsFeatures(cleanHeadline, cleanBody, 3));
f.addAll(getNGramsFeatures(cleanHeadline, cleanBody, 4));
f.addAll(getNGramsFeatures(cleanHeadline, cleanBody, 5));
f.addAll(getNGramsFeatures(cleanHeadline, cleanBody, 6));
return f;
}
public static void FNCFeaturesToARFF(String filePath) {
// get the data also first
}
public static void main(String[] args) throws Exception {
initializeStopwords("resources/stopwords.txt");
// String text = new FNCFeatureEngineering().cleanText("Our Retina
// MacBook Air rumour article brings"
// + " together everything we know or can plausibly predict about "
// + "Apple's next MacBook Air laptop: a laptop that we're pretty sure
// will come with a "
// + "Retina display. We're also interested in rumours that Apple will
// be launching its next "
// + "MacBook Air in a new size: one based on a 12in screen.");
/*
* String text = new FNCFeatureEngineering()
* .cleanText("\"Let's get this vis-a-vis\", he said, \"these boys' marks are really that well?\""
* );
*
* System.out.println(text);
*
* System.out.println(getNGrams(text, 3));
* System.out.println(getCharGrams(text, 3));
*/
// System.out.println(new FNCFeatureEngineering().lemmatize(text));
// System.out.println(removeStopWords(new
// FNCFeatureEngineering().lemmatize(text)));
}
}
| true |
5d4d5e194feb46feace99913074fe27e23698479
|
Java
|
schierlm/OberonEmulator
|
/WebsocketServer/src/main/java/websocketserver/Main.java
|
UTF-8
| 4,477 | 2.484375 | 2 |
[
"ISC"
] |
permissive
|
package websocketserver;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
public class Main {
public static void main(String[] args) throws Exception {
boolean headless = false;
if (args.length > 0 && args[0].equals("--headless")) {
args = Arrays.copyOfRange(args, 1, args.length);
headless = true;
}
Server server = HeadlessMain.init(args);
if (!headless && !GraphicsEnvironment.isHeadless() && SystemTray.isSupported()) {
ByteArrayOutputStream logBuffer = new ByteArrayOutputStream();
System.setErr(LogRedirectorStream.wrap(System.err, logBuffer));
System.setOut(LogRedirectorStream.wrap(System.out, logBuffer));
showTrayIcon(server, logBuffer);
}
HeadlessMain.run(server);
}
private static void showTrayIcon(Server server, ByteArrayOutputStream logBuffer) throws AWTException {
int port = ((ServerConnector) server.getConnectors()[0]).getPort();
Image image = Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/icon.png"));
SystemTray tray = SystemTray.getSystemTray();
TextArea text = new TextArea(25, 100);
ActionListener listener = (e -> {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
try {
Desktop.getDesktop().browse(new URI("http://localhost:" + port + "/"));
} catch (IOException | URISyntaxException ex) {
ex.printStackTrace();
}
}
});
PopupMenu popup = new PopupMenu();
MenuItem defaultItem = new MenuItem("Open in browser");
defaultItem.setFont(new Font(Font.DIALOG, Font.BOLD, 12));
defaultItem.addActionListener(listener);
popup.add(defaultItem);
MenuItem showLogItem = new MenuItem("Show logs");
showLogItem.addActionListener(e -> {
synchronized (logBuffer) {
text.setText(text.getText() + new String(logBuffer.toByteArray()));
logBuffer.reset();
}
text.setFont(new Font("Monospaced", Font.PLAIN, 12));
Frame statusWindow = new Frame("Logs - OberonEmulator WebsocketServer");
statusWindow.add(text, BorderLayout.CENTER);
statusWindow.pack();
statusWindow.setLocationRelativeTo(null);
statusWindow.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
statusWindow.dispose();
}
});
statusWindow.setVisible(true);
});
popup.add(showLogItem);
popup.addSeparator();
MenuItem exitItem = new MenuItem("Exit");
popup.add(exitItem);
TrayIcon trayIcon = new TrayIcon(image, "Running on port " + port, popup);
exitItem.addActionListener(e -> {
try {
server.stop();
server.join();
} catch (Exception ex) {
ex.printStackTrace();
}
tray.remove(trayIcon);
});
trayIcon.addActionListener(listener);
tray.add(trayIcon);
}
public static final class LogRedirectorStream extends OutputStream {
private final OutputStream out;
private final OutputStream orig;
private LogRedirectorStream(ByteArrayOutputStream logBuffer, PrintStream orig) {
this.out = logBuffer;
this.orig = orig;
}
private static PrintStream wrap(PrintStream orig, ByteArrayOutputStream logBuffer) {
return new PrintStream(new LogRedirectorStream(logBuffer, orig), true);
}
@Override
public synchronized void write(int b) throws IOException {
out.write(b);
orig.write(b);
}
@Override
public synchronized void write(byte[] b) throws IOException {
out.write(b);
orig.write(b);
}
@Override
public synchronized void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
orig.write(b, off, len);
}
@Override
public synchronized void flush() throws IOException {
out.flush();
orig.flush();
}
@Override
public synchronized void close() throws IOException {
try {
out.close();
} finally {
orig.close();
}
}
}
}
| true |
0ea33af189c9146069f045771fbab26ba98bbf39
|
Java
|
dstozek/mind-notes
|
/MindNotes/src/mindnotes/client/presentation/UndoableAction.java
|
UTF-8
| 1,069 | 3.140625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package mindnotes.client.presentation;
/**
* Undoable Action is an editor action that can be undone. Create a new instance
* of a class implementing UndoableAction for each action taken by the user.
* These actions are then put on the undo stack.
*
* Some actions might, under certain conditions, not change the stade of the
* edited document (e.g. pasting when the clipboard is empty). If the doAction()
* method returns true, it means the document state has changed.
*
* @author dominik
*
*/
public interface UndoableAction {
/**
* Perform all operations associated with this action.
*
* @return true if the edited document's state was changed as a result of
* this action
*/
public boolean doAction();
/**
* Undo the action. Must be called after a call to doAction(); it can be
* assumed that the document state is the same as AFTER the call to
* doAction(); undoAction() must revert the document state to the same state
* as before the doAction(); call.
*/
public void undoAction();
}
| true |
351a38ee92326c236ed0251de11d9a01ead37d63
|
Java
|
harshad0889/Brandstore
|
/app/src/main/java/com/example/brandstore/Add_sale.java
|
UTF-8
| 15,947 | 1.90625 | 2 |
[] |
no_license
|
package com.example.brandstore;
import android.Manifest;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class Add_sale extends AppCompatActivity {
DatabaseHelper db;
EditText sale_title,sale_desc,s_start,s_end;
TextView prodlist,product_items;
private int tdate,tmonth,tyear,fdate,fmonth,fyear;
Button add_sale,cancel,addimage,chooseprod,choose_sitems;
final int REQUEST_CODE_GALLERY = 999;
SharedPreferences sp;
ListView lv_category,lv_sitems;
ImageView iv;
private int mdate,mmonth,myear;
String[] listitems;
boolean[] checkeditems;
String[] day = {"pants","shirts"};
String sl_start,sl_end;
final Calendar myCalendar = Calendar.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sale);
db = new DatabaseHelper(this);
sale_title = (EditText) findViewById(R.id.sale_title);
sale_desc = (EditText) findViewById(R.id.sale_desc);
add_sale = findViewById(R.id.add_sale);
cancel= findViewById(R.id.p_cancel);
addimage = findViewById(R.id.addimage);
prodlist= findViewById(R.id.prod_list);
chooseprod = findViewById(R.id.choose_prod);
iv = findViewById(R.id.iv);
lv_category = findViewById(R.id.lvcat);
lv_sitems = findViewById(R.id.lv_sitems);
s_start = findViewById(R.id.start_date);
s_end = findViewById(R.id.end_date);
//sample of single items
//textview
product_items = findViewById(R.id.product_items);
//button
choose_sitems = findViewById(R.id.choose_sitems);
final boolean []selected_item;
final ArrayList<Integer> itemslist = new ArrayList<>();
final String date6 = new SimpleDateFormat("dd MMMM YYYY", Locale.getDefault()).format(new Date());
// listitems= getResources().getStringArray(R.array.)
//new date picker test method
//date picker dialogue
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayofmonth) {
myCalendar.set(Calendar.YEAR,year);
myCalendar.set(Calendar.MONTH,month);
myCalendar.set(Calendar.DAY_OF_MONTH,dayofmonth);
String Myformat = "dd MMMM YYYY";
SimpleDateFormat sdf = new SimpleDateFormat(Myformat, Locale.US);
s_start.setText(sdf.format(myCalendar.getTime()));
}
};
//date picker dialogue
final DatePickerDialog.OnDateSetListener date2 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet( final DatePicker datePicker, int year, int month, int dayofmonth) {
myCalendar.set(Calendar.YEAR,year);
myCalendar.set(Calendar.MONTH,month);
myCalendar.set(Calendar.DAY_OF_MONTH,dayofmonth);
String Myformat = "dd MMMM YYYY";
SimpleDateFormat sdf = new SimpleDateFormat(Myformat, Locale.US);
s_end.setText(sdf.format(myCalendar.getTime()));
}
};
//date picker
s_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// date2.onDateSet();
new DatePickerDialog(Add_sale.this,date,myCalendar.get(Calendar.YEAR),myCalendar.get(Calendar.MONTH),myCalendar.get(Calendar.DAY_OF_MONTH)).show();
//DatePickerDialog datePickerDialog = new DatePickerDialog(Add_sale.this,date,myCalendar.get(Calendar.YEAR),myCalendar.get(Calendar.MONTH),myCalendar.get(Calendar.DAY_OF_MONTH)).show();
//datePickerDialog.getDatePicker().setMinDate(Long.parseLong(date6));
//return datePickerDialog;
// String Myformat = "dd MMMM YYYY";
// SimpleDateFormat sdf = new SimpleDateFormat(Myformat, Locale.US);
// s_start.setText(sdf.format(myCalendar.getTime()));
}
});
/*s_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Calendar cal = Calendar.getInstance();
fdate = cal.get(Calendar.DATE);
fmonth = cal.get(Calendar.MONTH);
fyear = cal.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(Add_sale.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int date) {
//String fdate = date+"-"+month+"-"+year;
String Myformat = "dd MMMM YYYY";
SimpleDateFormat sdf = new SimpleDateFormat(Myformat, Locale.US);
s_start.setText(sdf.format(myCalendar.getTime()));
}
},fyear,fmonth,fdate);
datePickerDialog.getDatePicker().setMinDate(cal.getTimeInMillis());
datePickerDialog.show();
}
});*/
s_end.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new DatePickerDialog(Add_sale.this,date2,myCalendar.get(Calendar.YEAR),myCalendar.get(Calendar.MONTH),myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
/*s_end.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//String sales_sdate= s_start.getText().toString();
final Calendar cal = Calendar.getInstance();
fdate = cal.get(Calendar.DATE);
fmonth = cal.get(Calendar.MONTH);
fyear = cal.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(Add_sale.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int date) {
//String fdate = date+"-"+month+"-"+year;
String Myformat = "dd MMMM YYYY";
SimpleDateFormat sdf = new SimpleDateFormat(Myformat, Locale.US);
s_end.setText(sdf.format(myCalendar.getTime()));
}
},fyear,fmonth,fdate);
datePickerDialog.show();
}
});*/
List<String> names = new ArrayList<>();
Cursor cursor = db.getData("SELECT cat_name FROM cate_table ");
if(cursor != null){
while(cursor.moveToNext()){
names.add(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_ctname)));
}
}
lv_category = new ListView(this);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,names);
lv_category.setAdapter(adapter);
AlertDialog.Builder builder = new AlertDialog.Builder(Add_sale.this);
builder.setCancelable(true);
builder.setView(lv_category);
final AlertDialog dialog = builder.create();
//tried many times had no result to display the list of items in array to choose them in a mult select drop down list
// listitems = names.toArray();
// names= Arrays.asList(String );
//checkeditems= new boolean[day.length];
//listitems= getResources().getStringArray();
chooseprod.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.show();
lv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
prodlist.setText(adapter.getItem(i));
dialog.dismiss();
}
});
}
});
/////////////////////////////////////////////////////////////////
//list for single items
List<String> s_names = new ArrayList<>();
//selected_item = new boolean[s_names.length];
String[] itemsarray = {"pansts","shirts"};
Cursor cursorx = db.getData("SELECT pname from product_table");
if(cursorx != null){
while(cursorx.moveToNext()){
s_names.add(cursorx.getString(cursorx.getColumnIndex(DatabaseHelper.COL_pname)));
}
}
lv_sitems = new ListView(this);
final ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,s_names);
lv_sitems.setAdapter(adapter1);
lv_sitems.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv_sitems.setItemChecked(2,true);
//lv_sitems.setOnItemClickListener(this);
final AlertDialog.Builder builder1 = new AlertDialog.Builder(Add_sale.this);
// String[] itemsarray2 =new String[]{};
//selected_item = new boolean[itemsarray2.length];
builder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(Add_sale.this, " selected ", Toast.LENGTH_LONG).show();
builder1.setCancelable(true);
}
});
builder1.setCancelable(false);
builder1.setTitle("select items");
builder1.setView(lv_sitems);
final AlertDialog dialog1 = builder1.create();
// button click
choose_sitems.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog1.show();
lv_sitems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// product_items.setText(adapter1.getItem(i));
// dialog1.dismiss();
String selected="";
int choice = lv_sitems.getCount();
SparseBooleanArray sparseBooleanArray = lv_sitems.getCheckedItemPositions();
for (int is = 0;is < choice; is++){
if (sparseBooleanArray.get(is)){
selected += lv_sitems.getItemAtPosition(is).toString()+",";
}
}
prodlist.setText(selected);
}
});
}
});
addimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions
(Add_sale.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
intent.setType("image/*");
startActivityForResult(intent,1);
}
});
//*******************ADD SALE BUTTON CLICK****************
add_sale.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String stitle = sale_title.getText().toString();
String sdesc= sale_desc.getText().toString();
String s_product= prodlist.getText().toString();
String sale_sdate= s_start.getText().toString();
String sale_edate= s_end.getText().toString();
if (sale_title.length() == 0) {
sale_title.requestFocus();
sale_title.setError("please enter sale name");
} else if (sale_desc.length() == 0) {
sale_desc.requestFocus();
sale_desc.setError("please enter sale desc ");
}else if (sale_desc.length() > 2) {
sale_desc.requestFocus();
sale_desc.setError("please enter valid offer ");
}
else if (s_start.length() == 0) {
s_start.requestFocus();
s_start.setError("please enter sale date ");
}
else if (s_end.length() == 0) {
s_end.requestFocus();
s_end.setError("please enter sale date ");
}
else {
byte[] newentryimg = imageViewToByte(iv);
add_sale(stitle, sdesc,sale_sdate,sale_edate, newentryimg);
Toast.makeText(Add_sale.this, "sale added succesfully ", Toast.LENGTH_LONG).show();
Intent r = new Intent(Add_sale.this, Home.class);
startActivity(r);
finish();
}
}
private void add_sale(String stitle, String sdesc,String sale_sdate, String sale_edate, byte[] newentryimg) {
boolean insertsaledata = db.insert_sale_data(stitle, sdesc,sale_sdate,sale_edate, newentryimg);
}
private byte[] imageViewToByte (ImageView iv){
Bitmap bitmap = ((BitmapDrawable) iv.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri imageuri = data.getData();
try {
InputStream is = getContentResolver().openInputStream(imageuri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
iv.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent in = new Intent(getApplicationContext(), product_view.class);
startActivity(in);
finish();
}
}
| true |
a4f385b731dabae6dcd390a344ec3dfedb061252
|
Java
|
wangpengcheng123/wang
|
/src/main/java/m01/d27/wangpengcheng/TestDemo.java
|
UTF-8
| 1,072 | 2.890625 | 3 |
[] |
no_license
|
/**
* Project Name:shopping
* File Name:TestDemo.java
* Package Name:com.frame
* Date:2018年1月27日下午1:33:59
* Copyright (c) 2018, bluemobi All Rights Reserved.
*/
package m01.d27.wangpengcheng;
import javax.swing.JFrame;
/**
* 5。画板需要放在窗体中,所以要创建一个窗体,在窗体中引入画板的对象,将对象放在该窗体中----4<br/>
* Description: <br/>
* Date: 2018年1月27日 下午1:33:59 <br/>
*
* @author pengchengwang
* @version
* @see
*/
public class TestDemo extends JFrame {
public TestDemo() {
MyPanel myPanel = new MyPanel();
this.addKeyListener(myPanel);// 里面的实参的类型是keyListener类型
this.add(myPanel);
Thread thread = new Thread(myPanel);
thread.start();
this.setBounds(200, 200, 1000, 1000);
this.setTitle("坦克大战");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
TestDemo testDemo = new TestDemo();
}
}
| true |
04c24cd0e824e7c7ebf13ab2d1e5a2e346ecf3f7
|
Java
|
ClausPolanka/e2etrace
|
/src/java/org/e2etrace/trace/ITraceStep.java
|
UTF-8
| 3,838 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package org.e2etrace.trace;
/*
* Copyright 2006 Gunther Popp
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Every monitored step in a service call is represented by a trace step.
* <p>
*
* A trace step at minimum consists of a unique id, that identifies the
* monitored step within the trace session and the duration (in ms) of the
* executed step. An example for such an id is the fully qualified class name
* plus the name of the executed method.
* <p>
*
* Additionally, most trace steps have a parent and one to several children.
* <p>
*
* @author Gunther Popp
*
*/
public interface ITraceStep {
/**
* Return the id of the trace step.
* <p>
*
* @return trace step id
*/
ITraceStepId getId();
/**
* Enter the trace step and start time measuring.<p>
*
* This method should only be called once for a trace step. All subsequent calls
* will be ignored.
*/
void enter();
/**
* Leave the trace step and calculate the elapsed time since
* <code>enter</code> has been called.
*
* The elapsed time is returned by <code>getDuration()</code>.
* <p>
*
* Leaving a step implies that all children are left, too.
* <p>
*
* This method should only be called once for a trace step. All subsequent calls
* will be ignored.
*/
void leave();
/**
* Checks, if the current trace step is active.
* <p>
*
* A step is active between the calls to <code>enter</code> and
* <code>leave</code>.
*
* @return true: The trace step is active.
*/
boolean isActive();
/**
* Returns the isolated duration of this TraceStep.
* <p>
*
* The duration is the time elapsed between the calls to <code>enter</code>
* and <code>leave</code> minus the durations of all children.
* <p>
*
* @return duration of this TraceStep in ms (-1: no valid duration exists for
* this trace step)
*/
long getIsolatedDuration();
/**
* Returns the duration of this TraceStep and all children.
* <p>
*
* This value reflects the overall execution time of a trace step between the
* calls to <code>enter</code> and <code>leave</code> inclusive the
* durations of all children.
* <p>
*
* @return accumulated duration in ms
*/
long getDuration();
/**
* Adds a new child to this trace step.
* <p>
*
* The implementation must make sure that the child receives a references to this
* trace step. This reference must be returned by <code>getParent()</code>.<p>
*
* @param child trace step to add as child
*/
void addChild(ITraceStep child);
/**
* Returns the list of children for this trace steps.
*
* @return Array containing the children
*/
ITraceStep[] getChildren();
/**
* Returns the parent of a TraceStep, if any exists.
* <p>
*
* @return Parent trace step
*/
ITraceStep getParent();
/**
* Set the parent of a TraceStep.
* <p>
*
* This method is invoked when a new child is added using <code>addChild()</code>. It should
* never be called manually.<p>
* <p>
*
* @param parent new parent of the child.
*/
void setParent(ITraceStep parent);
}
| true |
e735a19b1047c002f90783a74777293bc49b68cc
|
Java
|
RichichiDomotics/poder-judicial
|
/nsjp-dto/src/main/java/mx/gob/segob/nsjp/dto/medida/MedidaDTO.java
|
ISO-8859-1
| 8,559 | 2.421875 | 2 |
[] |
no_license
|
/**
* Nombre del Programa : MedidaDTO.java
* Autor : GustavoBP
* Compania : Ultrasist
* Proyecto : NSJP Fecha: 05/08/2011
* Marca de cambio : N/A
* Descripcion General : Describir el objetivo de la clase de manera breve
* Programa Dependiente :N/A
* Programa Subsecuente :N/A
* Cond. de ejecucion :N/A
* Dias de ejecucion :N/A Horario: N/A
* MODIFICACIONES
*------------------------------------------------------------------------------
* Autor :N/A
* Compania :N/A
* Proyecto :N/A Fecha: N/A
* Modificacion :N/A
*------------------------------------------------------------------------------
*/
package mx.gob.segob.nsjp.dto.medida;
import java.util.Date;
import java.util.List;
import mx.gob.segob.nsjp.dto.catalogo.ValorDTO;
import mx.gob.segob.nsjp.dto.documento.DocumentoDTO;
import mx.gob.segob.nsjp.dto.domicilio.DomicilioDTO;
import mx.gob.segob.nsjp.dto.funcionario.FuncionarioDTO;
import mx.gob.segob.nsjp.dto.involucrado.InvolucradoDTO;
/**
* Clase para la transferencia de datos entre la vista y el negocio, del objeto Medida.
*
* @version 1.0
* @author GustavoBP
*
*/
public class MedidaDTO extends DocumentoDTO {
private Date fechaInicio;
private Date fechaFin;
private String descripcionMedida;
//Relaciones
private InvolucradoDTO involucrado;
private FuncionarioDTO funcionario;
private ValorDTO valorPeriodicidad;
private ValorDTO valorTipoMedida;
private DomicilioDTO domicilio;
private CompromisoPeriodicoDTO compromisoPeriodico;
private List<IncidenciaDTO> incidencias;
private String seguimiento;
private ValorDTO estatus;
private String fechaInicioStr;
private String fechaFinStr;
/**
* Numero de la Causa en PJ. Campo usando en SSP.
*/
private String numeroCausa;
/**
* Numero de la carpeta de ejecucin en PJ. Campo usando en SSP.
*/
private String numeroCarpetaEjecucion;
/**
* Nombre del juez de PJ. Campo usando en SSP.
*/
private String juezOrdena;
/**
* Nombre de caso en PJ. Campo usando en SSP.
*/
private String numeroCaso;
/**
* Mtodo de acceso al campo fechaInicio.
* @return El valor del campo fechaInicio
*/
public Date getFechaInicio() {
return fechaInicio;
}
/**
* Asigna el valor al campo fechaInicio.
* @param fechaInicio el valor fechaInicio a asignar
*/
public void setFechaInicio(Date fechaInicio) {
this.fechaInicio = fechaInicio;
}
/**
* Mtodo de acceso al campo fechaFin.
* @return El valor del campo fechaFin
*/
public Date getFechaFin() {
return fechaFin;
}
/**
* Asigna el valor al campo fechaFin.
* @param fechaFin el valor fechaFin a asignar
*/
public void setFechaFin(Date fechaFin) {
this.fechaFin = fechaFin;
}
/**
* Mtodo de acceso al campo descripcionMedida.
* @return El valor del campo descripcionMedida
*/
public String getDescripcionMedida() {
return descripcionMedida;
}
/**
* Asigna el valor al campo descripcionMedida.
* @param descripcionMedida el valor descripcionMedida a asignar
*/
public void setDescripcionMedida(String descripcionMedida) {
this.descripcionMedida = descripcionMedida;
}
/**
* Mtodo de acceso al campo involucrado.
* @return El valor del campo involucrado
*/
public InvolucradoDTO getInvolucrado() {
return involucrado;
}
/**
* Asigna el valor al campo involucrado.
* @param involucrado el valor involucrado a asignar
*/
public void setInvolucrado(InvolucradoDTO involucrado) {
this.involucrado = involucrado;
}
/**
* Mtodo de acceso al campo funcionario.
* @return El valor del campo funcionario
*/
public FuncionarioDTO getFuncionario() {
return funcionario;
}
/**
* Asigna el valor al campo funcionario.
* @param funcionario el valor funcionario a asignar
*/
public void setFuncionario(FuncionarioDTO funcionario) {
this.funcionario = funcionario;
}
/**
* Mtodo de acceso al campo valorPeriodicidad.
* @return El valor del campo valorPeriodicidad
*/
public ValorDTO getValorPeriodicidad() {
return valorPeriodicidad;
}
/**
* Asigna el valor al campo valorPeriodicidad.
* @param valorPeriodicidad el valor valorPeriodicidad a asignar
*/
public void setValorPeriodicidad(ValorDTO valorPeriodicidad) {
this.valorPeriodicidad = valorPeriodicidad;
}
/**
* Mtodo de acceso al campo valorTipoMedida.
* @return El valor del campo valorTipoMedida
*/
public ValorDTO getValorTipoMedida() {
return valorTipoMedida;
}
/**
* Asigna el valor al campo valorTipoMedida.
* @param valorTipoMedida el valor valorTipoMedida a asignar
*/
public void setValorTipoMedida(ValorDTO valorTipoMedida) {
this.valorTipoMedida = valorTipoMedida;
}
/**
* Mtodo de acceso al campo domicilio.
* @return El valor del campo domicilio
*/
public DomicilioDTO getDomicilio() {
return domicilio;
}
/**
* Asigna el valor al campo domicilio.
* @param domicilio el valor domicilio a asignar
*/
public void setDomicilio(DomicilioDTO domicilio) {
this.domicilio = domicilio;
}
/**
* Mtodo de acceso al campo compromisoPeriodico.
* @return El valor del campo compromisoPeriodico
*/
public CompromisoPeriodicoDTO getCompromisoPeriodico() {
return compromisoPeriodico;
}
/**
* Asigna el valor al campo compromisoPeriodico.
* @param compromisoPeriodico el valor compromisoPeriodico a asignar
*/
public void setCompromisoPeriodico(CompromisoPeriodicoDTO compromisoPeriodico) {
this.compromisoPeriodico = compromisoPeriodico;
}
/**
* Mtodo de acceso al campo incidencias.
* @return El valor del campo incidencias
*/
public List<IncidenciaDTO> getIncidencias() {
return incidencias;
}
/**
* Asigna el valor al campo incidencias.
* @param incidencias el valor incidencias a asignar
*/
public void setIncidencias(List<IncidenciaDTO> incidencias) {
this.incidencias = incidencias;
}
/**
* Mtodo de acceso al campo seguimiento.
* @return El valor del campo seguimiento
*/
public String getSeguimiento() {
return seguimiento;
}
/**
* Asigna el valor al campo seguimiento.
* @param seguimiento el valor seguimiento a asignar
*/
public void setSeguimiento(String seguimiento) {
this.seguimiento = seguimiento;
}
public void setEstatus(ValorDTO estatus) {
this.estatus = estatus;
}
public ValorDTO getEstatus() {
return estatus;
}
/**
* Mtodo de acceso al campo numeroCausa.
* @return El valor del campo numeroCausa
*/
public String getNumeroCausa() {
return numeroCausa;
}
/**
* Asigna el valor al campo numeroCausa.
* @param numeroCausa el valor numeroCausa a asignar
*/
public void setNumeroCausa(String numeroCausa) {
this.numeroCausa = numeroCausa;
}
/**
* Mtodo de acceso al campo numeroCarpetaEjecucion.
* @return El valor del campo numeroCarpetaEjecucion
*/
public String getNumeroCarpetaEjecucion() {
return numeroCarpetaEjecucion;
}
/**
* Asigna el valor al campo numeroCarpetaEjecucion.
* @param numeroCarpetaEjecucion el valor numeroCarpetaEjecucion a asignar
*/
public void setNumeroCarpetaEjecucion(String numeroCarpetaEjecucion) {
this.numeroCarpetaEjecucion = numeroCarpetaEjecucion;
}
/**
* Mtodo de acceso al campo juezOrdena.
* @return El valor del campo juezOrdena
*/
public String getJuezOrdena() {
return juezOrdena;
}
/**
* Asigna el valor al campo juezOrdena.
* @param juezOrdena el valor juezOrdena a asignar
*/
public void setJuezOrdena(String juezOrdena) {
this.juezOrdena = juezOrdena;
}
public void setNumeroCaso(String numeroCaso) {
this.numeroCaso = numeroCaso;
}
public String getNumeroCaso() {
return numeroCaso;
}
/**
* @return the fechaInicioStr
*/
public String getFechaInicioStr() {
return fechaInicioStr;
}
/**
* @param fechaInicioStr the fechaInicioStr to set
*/
public void setFechaInicioStr(String fechaInicioStr) {
this.fechaInicioStr = fechaInicioStr;
}
/**
* @return the fechaFinStr
*/
public String getFechaFinStr() {
return fechaFinStr;
}
/**
* @param fechaFinStr the fechaFinStr to set
*/
public void setFechaFinStr(String fechaFinStr) {
this.fechaFinStr = fechaFinStr;
}
}
| true |
9cf2ba9eb23209d41098856b848061d02d984f6b
|
Java
|
mccreery/tilesheet
|
/src/main/java/tilesheet/GuiFrame.java
|
UTF-8
| 7,816 | 2.328125 | 2 |
[
"MIT"
] |
permissive
|
package tilesheet;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBufferShort;
import java.awt.image.DataBufferUShort;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import tilesheet.ConversionContext.Majority;
public class GuiFrame extends JFrame {
private static final long serialVersionUID = 1L;
private final TilesheetViewer viewer;
private final RightPanel rightPanel;
private ConversionContext context;
private BufferedImage image;
private File file;
public GuiFrame() {
viewer = new TilesheetViewer();
viewer.setPreferredSize(new Dimension(500, 500));
add(viewer, BorderLayout.CENTER);
rightPanel = new RightPanel();
rightPanel.setPreferredSize(new Dimension(300, 0));
add(rightPanel, BorderLayout.LINE_END);
JButton loadButton = new JButton(new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser(file);
chooser.setFileFilter(new FileNameExtensionFilter("Image files", "jpg", "png", "gif", "bmp"));
if(chooser.showOpenDialog(GuiFrame.this) == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage image = ImageIO.read(chooser.getSelectedFile());
setImage(chooser.getSelectedFile(), image);
} catch(IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(GuiFrame.this, String.format("Could not open image.%n%s", ex.getMessage()), "Open failed", JOptionPane.ERROR_MESSAGE);
}
}
}
});
loadButton.setText("Load");
add(loadButton, BorderLayout.PAGE_START);
JButton saveButton = new JButton(new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser(file);
chooser.setFileFilter(new FileNameExtensionFilter("PNG image files", "png"));
chooser.addChoosableFileFilter(new FileNameExtensionFilter("C source code", "c"));
chooser.addChoosableFileFilter(new FileNameExtensionFilter("AVR assembly source code", "asm"));
chooser.setAcceptAllFileFilterUsed(false);
if(chooser.showSaveDialog(GuiFrame.this) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String ext;
FileNameExtensionFilter filter = (FileNameExtensionFilter)chooser.getFileFilter();
if(!filter.accept(file)) {
ext = filter.getExtensions()[0];
file = new File(file.getAbsolutePath() + '.' + ext);
} else {
ext = getExtension(file);
}
String cleanName = GuiFrame.this.file.getName().replaceAll("[^a-zA-Z]", "");
BufferedImage stitched = TilesheetConverter.stitch(context, image);
try {
if(ext.equals("png")) {
ImageIO.write(stitched, "png", file);
} else {
byte[] data = getRawBytes(stitched.getRaster().getDataBuffer(), ByteOrder.BIG_ENDIAN);
if(ext.equals("c")) {
File headerFile = new File(FileUtil.filePathNoExt(file.getPath()) + ".h");
int numChars = new ImageTileList(image, context).size();
int bpp = stitched.getColorModel().getPixelSize();
try(PrintWriter sourceWriter = new PrintWriter(file);
PrintWriter headerWriter = new PrintWriter(headerFile)) {
sourceWriter.write(HexUtil.getCSource(headerFile, data));
headerWriter.write(HexUtil.getCHeader(headerFile, numChars, bpp, context.tileSize.x, context.tileSize.y, context.targetMemoryOrder == Majority.COLUMN));
}
} else if(ext.equals("asm")) {
try(PrintWriter writer = new PrintWriter(file)) {
writer.write(HexUtil.getAvrDb(cleanName, data, 8));
}
}
}
} catch(IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(GuiFrame.this, String.format("Could not save image.%n%s", ex.getMessage()), "Save failed", JOptionPane.ERROR_MESSAGE);
}
}
}
});
saveButton.setText("Save");
add(saveButton, BorderLayout.PAGE_END);
setTitle("Tilesheet Converter");
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
/**
* Gets the file extension from a file, if any, without the dot.
* If a file has no extension this returns an empty string.
*/
private static String getExtension(File file) {
String name = file.getName();
int i = name.lastIndexOf('.');
return name.substring(i == -1 ? name.length() : i+1);
}
public void setImage(File file, BufferedImage image) {
this.file = file;
this.image = image;
viewer.setImage(image);
}
public void setContext(ConversionContext context) {
this.context = context;
viewer.setContext(context);
rightPanel.setContext(context);
}
public static byte[] getRawBytes(DataBuffer buffer, ByteOrder order) {
if(buffer instanceof DataBufferByte) {
return ((DataBufferByte)buffer).getData();
} else if(buffer instanceof DataBufferUShort) {
return shortsToBytes(((DataBufferUShort)buffer).getData(), order);
} else if(buffer instanceof DataBufferShort) {
return shortsToBytes(((DataBufferUShort)buffer).getData(), order);
} else if(buffer instanceof DataBufferInt) {
return intsToBytes(((DataBufferInt)buffer).getData(), order);
} else {
throw new IllegalArgumentException("Invalid data buffer type " + buffer.getClass());
}
}
private static byte[] shortsToBytes(short[] shorts, ByteOrder order) {
byte[] bytes = new byte[shorts.length * 2];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
byteBuffer.order(order);
byteBuffer.asShortBuffer().put(shorts);
byteBuffer.flip();
return bytes;
}
private static byte[] intsToBytes(int[] ints, ByteOrder order) {
byte[] bytes = new byte[ints.length * 4];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
byteBuffer.order(order);
byteBuffer.asIntBuffer().put(ints);
byteBuffer.flip();
return bytes;
}
}
| true |
602dcd71cacfa8972d60cafbdbf75199b84f543a
|
Java
|
alokmi/uniprot-rest-api
|
/common-rest/src/main/java/org/uniprot/api/common/repository/solrstream/AbstractTupleStreamTemplate.java
|
UTF-8
| 2,469 | 2.25 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.uniprot.api.common.repository.solrstream;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.solr.client.solrj.io.SolrClientCache;
import org.apache.solr.client.solrj.io.stream.StreamContext;
import org.apache.solr.client.solrj.io.stream.TupleStream;
import org.apache.solr.client.solrj.io.stream.expr.DefaultStreamFactory;
import org.apache.solr.client.solrj.io.stream.expr.StreamFactory;
/**
* This class is responsible for providing {@link StreamFactory} and {@link StreamContext} for the
* creation of {@link TupleStream} instance.
*
* <p>Created 25/07/2020
*
* @author sahmad
*/
@Slf4j
public abstract class AbstractTupleStreamTemplate {
private StreamFactory streamFactory;
private StreamContext streamContext;
protected StreamFactory getStreamFactory(String zkHost, String collection) {
if (Objects.isNull(this.streamFactory)) {
initTupleStreamFactory(zkHost, collection);
} else {
log.info("DefaultStreamFactory already created for collection {}", collection);
}
return this.streamFactory;
}
protected StreamContext getStreamContext(String collection, HttpClient httpClient) {
if (Objects.isNull(this.streamContext)) {
initStreamContext(collection, httpClient);
} else {
log.info("StreamContext already created for collection {}", collection);
}
return this.streamContext;
}
private void initTupleStreamFactory(String zookeeperHost, String collection) {
this.streamFactory =
new DefaultStreamFactory().withCollectionZkHost(collection, zookeeperHost);
log.info("Created new DefaultStreamFactory for {} and {}", zookeeperHost, collection);
}
/**
* For tweaking, see: https://www.mail-archive.com/[email protected]/msg131338.html
*/
private void initStreamContext(String collection, HttpClient httpClient) {
StreamContext context = new StreamContext();
// this should be the same for each collection, so that
// they share client caches
context.workerID = collection.hashCode();
context.numWorkers = 1;
SolrClientCache solrClientCache = new SolrClientCache(httpClient);
context.setSolrClientCache(solrClientCache);
this.streamContext = context;
log.info("Created new StreamContext for {} ", collection);
}
}
| true |
a0dc10f2b808b293f9ac91ac15fdda771e4db155
|
Java
|
MrZhangCF/eclipse_workspace
|
/RestTest/src/main/java/service/ClassService.java
|
UTF-8
| 248 | 2.015625 | 2 |
[] |
no_license
|
package service;
import java.util.List;
import model.ClassTaken;
import model.Student;
public interface ClassService {
public List<ClassTaken> getClassByStudentId();
public Student getStudentById(int id);
public void removeStudent(int id);
}
| true |
0bdadbfcf93934c1998a7963aaa8b0a234772347
|
Java
|
fuwenchao/javalearning
|
/src/main/java/me/wenchao/javabasic/basic/BB.java
|
UTF-8
| 853 | 3.5 | 4 |
[] |
no_license
|
package me.wenchao.javabasic.basic;
/**
* @Author wenchaofu
* @DATE 16:31 2018/7/6
* @DESC
*/
class AA {
public int i = 12;
public AA(){}
// public AA(int i ){
// this.i = i;
//
// }
public void print(){
System.out.println("this is AA");
}
public final void finalPrint(){
System.out.println("this is final AA");
}
}
public class BB extends AA {
public int i = -6;
// public BB(int i){
// super(i);
// }
public BB(){}
public void print(){
System.out.println("this is BB");
}
/*
public final void finalPrint(){
System.out.println("this is final BB");
}*/
public static void main(String[] args) {
AA xx = new BB();
System.out.println(xx.i);
xx.print();
// print();
xx.finalPrint();
}
}
| true |
06442478c145ecd71ae56b8b15ff56165e7c1038
|
Java
|
markhughes/TempleRun
|
/src/de/jan/TempleRun.java
|
UTF-8
| 4,277 | 2.25 | 2 |
[] |
no_license
|
package de.jan;
import java.io.File;
import java.io.IOException;
import net.milkbowl.vault.Vault;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import de.jan.commands.PlayerCommands;
import de.jan.listeners.PlayerListener;
import de.jan.loader.ConfigLoader;
import de.jan.manager.ArenaManager;
import de.jan.manager.GhostManager;
import de.jan.manager.MagnetManager;
import de.jan.manager.PlayerManager;
import de.jan.manager.Util;
import de.jan.manager.WalkCheckerManager;
import de.jan.trplayer.TRPlayer;
public class TempleRun extends JavaPlugin {
static {
new File("plugins/TempleRun").mkdirs();
}
// Initialisierung
public static TempleRun instance;
public static GhostManager ghostManager;
public static ArenaManager arenaManager;
public static PlayerManager playerManager;
public static WalkCheckerManager walkManager;
public static MagnetManager magnetManager;
// Vault
public Economy economy = null;
// Datbase
public static FileConfiguration database;
@Override
public void onEnable() {
loadConfig();
// Initialisierung
instance = this;
try {
ConfigLoader loader = new ConfigLoader("plugins/TempleRun/", "database.yml", "/resources/database.yml");
if (database == null)
database = loader.getConfig();
debug("Config successful created / loaded.");
} catch (Exception e) {
debug("An Error occurred while creating / loading database.yml");
}
ghostManager = new GhostManager(instance);
arenaManager = new ArenaManager(database);
arenaManager.loadArenas();
playerManager = new PlayerManager();
new Util();
// Commands + Listener
getCommand("templerun").setExecutor(new PlayerCommands());
getServer().getPluginManager().registerEvents(new PlayerListener(), this);
walkManager = new WalkCheckerManager();
magnetManager = new MagnetManager();
// Start Metrics
startMetrics();
checkUpdates();
if (getVault() == null) {
debug("Vault Plugin not found.");
} else {
debug("Hocked into Vault.");
}
debug("Plugin completly loaded.");
}
@Override
public void onDisable() {
for (TRPlayer tr : PlayerManager.players) {
tr.restoreInventory();
tr.getPlayer().teleport(tr.getOldlocation());
// Give the player the old speed back
Player player = tr.getPlayer();
player.setWalkSpeed(.2F);
}
PlayerManager.players.clear();
ghostManager.clearGhosts();
debug("Plugin completly disabled.");
}
public static void debug(String msg) {
System.out.println("[TempleRun] " + msg);
}
private void loadConfig() {
if (new File(getDataFolder() + "/config.yml").exists()) {
getConfig().options().copyDefaults(true);
debug("New config.yml created.");
} else {
saveDefaultConfig();
debug("Config loaded.");
}
}
private void startMetrics() {
try {
Metrics ms = new Metrics(this);
ms.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private void checkUpdates() {
if (getConfig().getBoolean("TempleRun.Updater.checkUpdates", false)) {
Updater updater = new Updater(this, "templerun", this.getFile(), Updater.UpdateType.DEFAULT, true);
if (updater.getResult() == Updater.UpdateResult.UPDATE_AVAILABLE) {
debug("An new Update is available.");
} else {
debug("Everything is up to date.");
}
}
}
public Vault getVault() {
Plugin plugin = getServer().getPluginManager().getPlugin("Vault");
if (plugin == null || !(plugin instanceof Vault)) {
return null;
}
if (!getConfig().getBoolean("TempleRun.Vault.usingVault", false)) {
return null;
}
setupEconomy();
return (Vault) plugin;
}
private boolean setupEconomy() {
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
return (economy != null);
}
}
| true |
3e361337f6ef00c0f8ee743d7500ccae40ca89c2
|
Java
|
valterlobo/json-schema
|
/src/test/java/org/imaginary/json/schema/AppTest.java
|
UTF-8
| 1,749 | 2.734375 | 3 |
[] |
no_license
|
package org.imaginary.json.schema;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.junit.Test;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
@Test
public void shouldAnswerWithTrue()
{
String strJson =
"{ \"rectangle\":{"
+ "\"a\" : -5,"
+ "\"b\" : 5"
+ "} }";
InputStream inputStream = getClass().getResourceAsStream("rectangle-schema.json");
try {
String schemaRaw = IOUtils.toString(inputStream, "UTF-8");
List<String> violations = JsonSchemaValidator.validator(schemaRaw , strJson);
violations.stream().forEach(System.out::println);
assertTrue( true );
}catch (IOException e){
}
}
@Test
public void testValidadorParam()
{
String strJson =
"{ \"rectangle\":{"
+ "\"a\" : 50,"
+ "\"b\" : 5"
+ "} }";
InputStream inputStream = getClass().getResourceAsStream("rectangle-schema.json");
try {
String schemaRaw = IOUtils.toString(inputStream, "UTF-8");
List<String> violations = JsonSchemaValidator.validator(schemaRaw , strJson);
if (violations.size() > 0 ){
assertTrue( false );
}else {
JSONObject jsonOBJ = new JSONObject(strJson);
System.out.println(jsonOBJ.getJSONObject("rectangle").getNumber("a"));
assertTrue( true );
}
}catch (IOException e){
assertTrue( false );
}
}
}
| true |
03469afc833109952af485a09c72ad72798296ac
|
Java
|
boosky-microservices/bookshelf-service
|
/src/main/java/booksy/bookshelfservice/configuration/SecurityConfiguration.java
|
UTF-8
| 3,110 | 2.171875 | 2 |
[] |
no_license
|
package booksy.bookshelfservice.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jwt.*;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
import java.util.Collections;
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
String issuerUri;
@Value("${AUDIENCE}")
private String audience;
@Bean
JwtDecoder jwtDecoder() {
NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
JwtDecoders.fromOidcIssuerLocation(issuerUri);
OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
jwtDecoder.setJwtValidator(withAudience);
return jwtDecoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests(authorizeRequests ->
authorizeRequests
.anyRequest()
.authenticated()
)
.oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer
.jwt(jwt -> jwt.decoder(JwtDecoders.fromIssuerLocation(issuerUri))
)
);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method", "Access-Control-Request-Headers","Origin","Cache-Control", "Content-Type", "Authorization"));
configuration.setAllowedOriginPatterns(Arrays.asList("*"));
configuration.setAllowedMethods(Collections.singletonList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
| true |
b8791aa5d4cbba0e7409b6bad58f6a3167695066
|
Java
|
wg1977/YourCaiWang
|
/app/src/main/java/com/my3w/farm/activity/user/UserAddressActivity.java
|
UTF-8
| 6,808 | 1.804688 | 2 |
[] |
no_license
|
package com.my3w.farm.activity.user;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.my3w.farm.R;
import com.my3w.farm.activity.baseActivity;
import com.my3w.farm.activity.login.LoginActivity;
import com.my3w.farm.activity.user.adapter.addressAdapter;
import com.my3w.farm.activity.user.entity.AddressEntity;
import com.my3w.farm.comment.image.ImageMagent;
import com.westars.framework.cache.DataCache;
import com.westars.framework.reaizepage.net.http.HttpRequest;
import com.westars.framework.view.image.RoundImageView;
import com.westars.framework.view.list.ListExtView;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class UserAddressActivity extends baseActivity {
private TextView title_name;
private TextView title_username;
private LinearLayout title_icon_box;
private RoundImageView title_icon;
private ArrayList<AddressEntity> list = new ArrayList<AddressEntity>();
private addressAdapter addressadapter;
private ListExtView listview;
private LinearLayout back_button;
private LinearLayout noit_button;
private LinearLayout user_btton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_address);
initView();
initData();
initEvent();
}
private void initView() {
title_name = (TextView) findViewById(R.id.title_name);
title_name.setText("地址管理");
title_username = (TextView) findViewById(R.id.title_username);
String user_nickString = DataCache.get(UserAddressActivity.this).getAsString("user_nick");
if (user_nickString != null && !user_nickString.equals(""))
title_username.setText(user_nickString);
else
title_username.setText("");
title_icon_box = (LinearLayout) findViewById(R.id.title_icon_box);
title_icon = (RoundImageView) findViewById(R.id.title_icon);
String user_picString = DataCache.get(UserAddressActivity.this).getAsString("user_pic");
if (user_picString != null && !user_picString.equals(""))
ImageMagent.getInstance().displayImage(user_picString, title_icon);
listview = (ListExtView) findViewById(R.id.listview);
listview.setShowHeaderView(false);
listview.setShowFooterView(false);
addressadapter = new addressAdapter(this, list);
listview.setAdapter(addressadapter);
back_button = (LinearLayout) findViewById(R.id.back_button);
noit_button = (LinearLayout) findViewById(R.id.noit_button);
user_btton = (LinearLayout) findViewById(R.id.user_btton);
}
private void initData() {
HttpRequest http = new HttpRequest(this, handler);
http.execute(getResources().getString(R.string.config_host_url) + "user.php?action=addresslist&token="
+ DataCache.get(this).getAsString("token"));
}
private void initEvent() {
// 返回
back_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(UserAddressActivity.this, UserCenterActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.anim_activity_close_left, R.anim.anim_activity_close_right);
}
});
// 个人中心
title_icon_box.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(UserAddressActivity.this, UserCenterActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.anim_activity_open_left, R.anim.anim_activity_open_right);
}
});
// 消息
noit_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
// 个人中心
user_btton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(UserAddressActivity.this, UserCenterActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.anim_activity_open_left, R.anim.anim_activity_open_right);
}
});
}
// 获取区域handler
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 200) {
String json = (String) msg.obj;
if (json != null) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(json);
int result = jsonObject.optInt("errCode");
JSONArray jsonArray = jsonObject.optJSONArray("errMsg");
if (result == 0) {
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject addressObject = jsonArray.getJSONObject(i);
AddressEntity data = new AddressEntity();
data.setId(addressObject.optInt("id"));
data.setAddress(addressObject.optString("address"));
data.setCity(addressObject.optString("city"));
data.setCode(addressObject.optString("code"));
data.setUserName(addressObject.optString("uname"));
data.setPhone(addressObject.optString("phone"));
data.setProvince(addressObject.optString("province"));
data.setCounty(addressObject.optString("county"));
data.setUserchecked(addressObject.optInt("userchecked"));
list.add(data);
}
if (addressadapter != null)
addressadapter.notifyDataSetChanged();
}
} else if (result == 1) {
Toast.makeText(UserAddressActivity.this, "登录超时或已经被别人登录,请重新登录", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(UserAddressActivity.this, LoginActivity.class);
startActivity(intent);
sendBroadcast(new Intent("finish"));
overridePendingTransition(R.anim.anim_activity_open_left, R.anim.anim_activity_open_right);
}
} catch (JSONException e) {
Toast.makeText(UserAddressActivity.this, "数据出现异常,请重试", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(UserAddressActivity.this, "网络出现了点问题,请查看网络连接是否正常后再重试", Toast.LENGTH_SHORT).show();
}
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent(UserAddressActivity.this, UserCenterActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.anim_activity_close_left, R.anim.anim_activity_close_right);
}
return super.onKeyDown(keyCode, event);
}
}
| true |
c4851d12e538337277c62e6553f982670b4c179c
|
Java
|
DanglingPointer/GeoQuiz9000
|
/app/src/main/java/no/ntnu/tdt4240/geoquiz9000/adapters/ScoreAdapter.java
|
UTF-8
| 2,852 | 2.328125 | 2 |
[] |
no_license
|
package no.ntnu.tdt4240.geoquiz9000.adapters;
import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import no.ntnu.tdt4240.geoquiz9000.R;
import no.ntnu.tdt4240.geoquiz9000.models.Score;
import no.ntnu.tdt4240.geoquiz9000.ui.UiUtils;
import no.ntnu.tdt4240.geoquiz9000.utils.GeoUtils;
import no.ntnu.tdt4240.geoquiz9000.utils.GeoUtils.Units;
public class ScoreAdapter extends ArrayAdapter<Score> {
private static final int LAYOUT_ID = R.layout.item_score;
public ScoreAdapter(Context context, List<Score> scores) {
super(context, LAYOUT_ID, scores);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
final Score record = getItem(position);
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(LAYOUT_ID, null);
holder = new ViewHolder(convertView, getContext());
convertView.setTag(holder);
}
else {
holder = (ViewHolder)convertView.getTag();
}
if (record != null) {
holder.bind(record);
}
return convertView;
}
private static class ViewHolder {
private final TextView m_playerName;
private final TextView m_distance;
private final TextView m_mapName;
private Context m_context;
public ViewHolder(View rootView, Context context) {
Typeface font = UiUtils.getTextFont(m_context = context);
m_playerName = (TextView)rootView.findViewById(R.id.player_label);
m_playerName.setTypeface(font);
m_distance = (TextView)rootView.findViewById(R.id.total_distance_label);
m_distance.setTypeface(font);
m_mapName = (TextView)rootView.findViewById(R.id.map_pack_label);
m_mapName.setTypeface(font);
}
public void bind(Score data) {
m_playerName.setText(data.getPlayerName());
float distance = data.getTotalDistance();
switch (GeoUtils.getCurrentUnits(m_context)) {
case MILES:
distance = GeoUtils.kmToMiles(distance);
break;
default:
break;
}
String text = m_context.getString(R.string.score_distance_line,
distance, GeoUtils.getCurrentUnits(m_context).toString());
m_distance.setText(text);
m_mapName.setText(data.getMapPackName());
}
}
}
| true |
c138a09d63e43b36d43a786a824f3343aef50cc6
|
Java
|
Kiran-Maharjan/DataAbstraction_abstract
|
/src/com/kingkong/dataabstraction/Program.java
|
UTF-8
| 1,080 | 3.234375 | 3 |
[] |
no_license
|
/*
** *****************[email protected]
*Concept of:----
*override
* Abstraction:
* Concept of override:
*Constructor:
*Inheritence:
*/
package com.kingkong.dataabstraction;
import com.kingkong.dataabstraction.entities.BaseGuitar;
import com.kingkong.dataabstraction.entities.ElectricGuitar;
import com.kingkong.dataabstraction.entities.Guitar;
/**
*
* @author kiran
*/
public class Program {
public static void main(String[] args) {
//..guitar -> parent class, other guitar -> child
/* --uncomment 1
ElectricGuitar g= new ElectricGuitar();
g.play();//calls parent play() */
/*-- solution 1: override parent play()
solution2: make fuction like plays1 or plays2. for new objects like electricguitar ..
g.play_ElectricGuitar();
solution 3: so make abstract play() in parent
*/
//Guitar g=new Guitar() {}; //-> cannot be created. it asks which guiatar?
Guitar g=new ElectricGuitar();
g.play();
}
}
| true |
75f4bdc376f084a01019a9c1d349cbadb6d88f4d
|
Java
|
moystre/myFriends
|
/app/src/main/java/com/easv/myfriends/myfriends/DetailsActivity.java
|
UTF-8
| 9,788 | 2.140625 | 2 |
[] |
no_license
|
package com.easv.myfriends.myfriends;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.easv.myfriends.myfriends.model.Friend;
import com.easv.myfriends.myfriends.service.FriendsService;
import com.easv.myfriends.myfriends.service.MessageService;
import java.util.Date;
public class DetailsActivity extends AppCompatActivity {
// <------------------- DECLARATIONS ------------------->
private static final String TAG = "MapActivity"; //Activity's TAG used for Log
FriendsService friendsService;
MessageService messageService;
Friend selectedFriend;
Integer selectedFriendId;
Boolean isNewFriend;
Location currentLocation;
double currentLocationLongitude;
double currentLocationLatitude;
private ImageView profilePicture;
private EditText nameEditText; // displaying/updating friend's name
private EditText addressEditText; // displaying/updating friend's address
private EditText phoneEditText; // displaying/updating friend's phoneNumber
private EditText emailEditText; // displaying/updating friend's email
private EditText birthdayEditText; // displaying/updating friend's birthday
private EditText websiteEditText; // displaying/updating friend's website
private Button takePictureButton; // Button for taking a picture
private Button setHomeAddressLocationButton; // Button for setting friend's home location
private Button showHomeAddressLocationButton; // Button for showing friend's home location on a map
private Button callButton; // Button for calling
private Button sendSmsButton; // Button for sending an sms
private Button sendEmailButton; // Button for sending an email
private Button setDateButton; // Button for setting friend's birthday
private Button saveProfileButton; // Button for saving/updating profile of a friend
private String name; // value of friend's name
private String address; // value of friend's address
private Location homeAddressLocation; // value of friend's homeAddressLocation
private String phoneNumber; // value of friend's phoneNumber
private String email; // value of friend's email
private String website; // value of friend's website
private Date birthday; // value of friend's birthday
private String picturePath; // value of friend's picturePath
private Friend friend; // Instance of a friend
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
friendsService = new FriendsService(this);
// <------------------- RETREIVING EXTRAS ------------------->
selectedFriendId = getIntent().getIntExtra("friendId", 0);
isNewFriend = getIntent().getBooleanExtra("isNewFriend", false);
//currentLocationLongitude = getIntent().getDoubleExtra("currentLocationLatitude", 0);
//currentLocationLatitude = getIntent().getDoubleExtra("currentLocationLongitude", 0);
// <------------------- CREATE AND POPULATE FRIEND OBJECT ------------------->
if(!isNewFriend) {
selectedFriend = friendsService.get(selectedFriendId);
}
else {
selectedFriend = new Friend();
}
// <------------------- FINDING EditTexts BY findViewById ------------------->
this.profilePicture = findViewById(R.id.friendDetailsPictureEdit);
this.nameEditText = findViewById(R.id.friendDetailsNameEdit);
this.addressEditText = findViewById(R.id.friendDetailsAddressEdit);
this.phoneEditText = findViewById(R.id.friendDetailsPhoneEdit);
this.emailEditText = findViewById(R.id.friendDetailsEmailEdit);
this.birthdayEditText = findViewById(R.id.friendDetailsBirthdayEdit);
this.websiteEditText = findViewById(R.id.friendDetailsWebsiteEdit);
// <------------------- ASSIGNING TextViews values ------------------->
if(selectedFriend.getmPictureString()!=null && selectedFriend.getmPictureString()!="") {
this.profilePicture.setImageBitmap(BitmapFactory.decodeFile(selectedFriend.getmPictureString()));
}
Log.d("XXXXXXXXXXXXXXXXXXXX", selectedFriend.getmPictureString());
this.nameEditText.setText(selectedFriend.getmName());
this.addressEditText.setText(selectedFriend.getmAddress());
this.phoneEditText.setText(selectedFriend.getmPhoneNumber());
this.emailEditText.setText(selectedFriend.getmEmail());
this.birthdayEditText.setText(selectedFriend.getmBirthdayStringDAYMONTH());
this.websiteEditText.setText(Html.fromHtml(selectedFriend.getmWebsite()));
this.websiteEditText.setMovementMethod(LinkMovementMethod.getInstance());
// <------------------- ASSIGNING ImageView picture ------------------->
this.nameEditText.setText(selectedFriend.getmName());
}
// <------------------- onClick METHODS FOR BUTTONS ------------------->
// taking a new picture/updating previous one
public void takePicture(View v) {
Intent i = new Intent(getApplicationContext(), CameraActivity.class);
startActivityForResult(i, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
String resultPath = data.getStringExtra("imagePath");
selectedFriend.setmPicturePath(resultPath);
this.profilePicture.setImageBitmap(BitmapFactory.decodeFile(selectedFriend.getmPictureString()));
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result todo
}
}
}
// setting homeAddressLoccation
public void setHomeAddressLocation(View v){
/* Log.d(TAG, "Home location set to: " + currentLocation);
currentLocation.setLatitude(currentLocationLatitude);
currentLocation.setLongitude(currentLocationLongitude);
selectedFriend.setmLocation(currentLocation);
messageService.message(getApplicationContext(), "New address set");*/
}
// showing homeAddressLocation on a map
public void showHomeAddressLocation(View v){}
// calling a friend's number with built-in application
public void call(View v){
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:"+selectedFriend.getmPhoneNumber()));
startActivity(callIntent);
}
// sending an sms with built-in application
public void sendSms(View v) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", selectedFriend.getmPhoneNumber());
smsIntent.putExtra("sms_body","");
startActivity(smsIntent);
}
// sending an email with default mailbox application
public void sendEmail(View v) {
Uri uri = Uri.parse("mailto:"+selectedFriend.getmEmail());
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, uri);
emailIntent.putExtra(Intent.EXTRA_SUBJECT,"");
startActivity(emailIntent);
}
// setting date of friend's birthday
public void setDate(View v) {}
// saving/updating friend's profile
public void saveProfile(View v) {
if(!isNewFriend) {
selectedFriend.setmName(nameEditText.getText().toString().trim());
selectedFriend.setmAddress(addressEditText.getText().toString().trim());
//todo set location
selectedFriend.setmPhoneNumber(phoneEditText.getText().toString().trim());
selectedFriend.setmEmail(emailEditText.getText().toString().trim());
//todo set birthday
selectedFriend.setmWebsite(websiteEditText.getText().toString().trim());
friendsService.update(selectedFriend);
}
else {
selectedFriend.setmName(nameEditText.getText().toString().trim());
selectedFriend.setmAddress(addressEditText.getText().toString().trim());
//todo set location
selectedFriend.setmPhoneNumber(phoneEditText.getText().toString().trim());
selectedFriend.setmEmail(emailEditText.getText().toString().trim());
//todo set birthday
selectedFriend.setmWebsite(websiteEditText.getText().toString().trim());
// todo defaultpic
friendsService.addFriend(selectedFriend);
}
}
// <------------------- CRUD FUNCTIONALITY FOR Friend's profile ------------------->
// CREATE
// no excluded method for Create since it always takes place by updating previously created one
// READ
// Getting values of a friend's profile from (array) and displaying them
public void readProfile(){} // finding friend by id/number ?
// UPDAtE
// Assigning new values to friend's profile from EditText fields
public void updateProfile(Friend frienToUpdate){}
// DELETE
// Deleting friend's profile with all it's values
public void deleteProfile(Friend friendToDelete){}
}
| true |
0f93f779f82b77b511d4ac7351ed283377354ce2
|
Java
|
xiongzhenhai-zh/produce-project-managerment
|
/src/main/java/com/carejava/duce/ject/web/business/IProduceRecordBusiness.java
|
UTF-8
| 656 | 1.820313 | 2 |
[] |
no_license
|
package com.carejava.duce.ject.web.business;
import com.carejava.duce.ject.web.core.ResultBean;
import com.carejava.duce.ject.web.entity.ProduceRecordEntity;
import com.carejava.duce.ject.web.in.vo.ProduceRecordVO;
import javax.servlet.http.HttpServletRequest;
public interface IProduceRecordBusiness {
ResultBean add(ProduceRecordEntity produceRecordEntity);
ResultBean update(ProduceRecordEntity produceRecordEntity);
ResultBean selectPageList(HttpServletRequest request, ProduceRecordVO produceRecordVO);
ResultBean delete(HttpServletRequest request, ProduceRecordEntity produceRecordEntity);
ResultBean queryById(Long id);
}
| true |
3e8d19e3c27459b31bc37bfe21ad81cf3439186c
|
Java
|
heatork/piggy
|
/Piggy/src/howbuy/android/util/CpUtil.java
|
UTF-8
| 14,300 | 1.71875 | 2 |
[] |
no_license
|
package howbuy.android.util;
import howbuy.android.lib.MyAsyncTask;
import howbuy.android.piggy.UserUtil;
import howbuy.android.piggy.UserUtil.UserBankVeryType;
import howbuy.android.piggy.api.DispatchAccessData;
import howbuy.android.piggy.api.dto.BindCardAuthModeDto;
import howbuy.android.piggy.api.dto.BindCardDto;
import howbuy.android.piggy.api.dto.BindCardUploadParams;
import howbuy.android.piggy.api.dto.BindCardUploadParams.Channels;
import howbuy.android.piggy.api.dto.UpdateDto;
import howbuy.android.piggy.api.dto.UserCardDto;
import howbuy.android.piggy.api.dto.UserCardListDto;
import howbuy.android.piggy.application.ApplicationParams;
import howbuy.android.piggy.dialog.PiggyProgressDialog;
import howbuy.android.piggy.service.ServiceMger.TaskBean;
import howbuy.android.piggy.service.UpdateUserDataService;
import howbuy.android.piggy.ui.BindCardSucceedActivity;
import howbuy.android.piggy.ui.CpNetConnTimeoutActivity;
import howbuy.android.piggy.ui.PrefectActivity;
import howbuy.android.piggy.ui.base.AbstractFragment;
import howbuy.android.piggy.ui.fragment.BindCardFragment;
import howbuy.android.piggy.ui.fragment.BindCardSucceedFragment;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import com.google.myjson.Gson;
import com.hxcr.chinapay.activity.Initialize;
import com.hxcr.chinapay.util.CPGlobaInfo;
import com.hxcr.chinapay.util.Utils;
public class CpUtil {
public static final String Request_Type_Nomal = "11";
public static final String Request_Type_Cp_Success = "12";
public static final String Request_Type_Cp_TimeOut = "13";
private PiggyProgressDialog mpDialog;
private AbstractFragment mContext;
private int mIntoType;
private BindTask mBindTask;
private AuthTask mAuthTask;
private String mBankAcct = null;
public CpUtil(int intoType, AbstractFragment mContext) {
this.mIntoType = intoType;
this.mContext = mContext;
}
/**
* 处理onResume
*/
public void onResumeCp() {
final String cpResCode = Utils.getPayResult();
CPGlobaInfo.init(); // 清空返回结果
if (!TextUtils.isEmpty(cpResCode)) {
String res = handleCpRes(mIntoType, cpResCode);
if (res == null) {
// 超时|成功这时已handleCpRes去获取用户信息
showProgressDialog("正在获取数据");
}
}
}
public void startBindCard(UserCardDto card) {
if (mBindTask != null) {
mBindTask.cancel(true);
}
mBindTask = new BindTask();
// String custNo, String bankAcct, String bankCode, String cnapsNo,
// String provCode, String custBankId
String custNo = UserUtil.getUserNo();
mBankAcct = card.getBankAcct();
String bankCode = card.getBankCode();
String cnapsNo = card.getBankRegionCode();
String provCode = card.getProvCode();
String custBankId = card.getCustBankId();
mBindTask.execute(custNo, mBankAcct, bankCode, cnapsNo, provCode, custBankId);
showProgressDialog("正在绑定银行卡");
}
public void startBankAuth( String bankCode, String custBankId) {
if (mAuthTask != null) {
mAuthTask.cancel(true);
}
mAuthTask = new AuthTask();
String custNo = UserUtil.getUserNo();
//String custNo, String bankCode, String custBankId,
mAuthTask.execute(custNo,bankCode, custBankId);
showProgressDialog("正在验证银行卡");
}
public static String parseCpResult(String cpCode) {
if (!TextUtils.isEmpty(cpCode) && cpCode.length() >= 14) {
return cpCode.trim().substring(10, 14);
}
return null;
}
public static boolean isSuccess(String cpRes) {
if (!TextUtils.isEmpty(cpRes) && cpRes.equals("0000")) {
return true;
}
return false;
}
public static boolean isTimeOut(String cpRes) {
if (!TextUtils.isEmpty(cpRes) && cpRes.equals("9901")) {
return true;
}
return false;
}
public static String otherRes(String cpResult) {
if (!TextUtils.isEmpty(cpResult)) {
// if ("9903".equals(cpResult)) {
// return "报文解析错误";
// } else if ("9902".equals(cpResult)) {
// return "您已取消绑卡";
// } else if ("9904".equals(cpResult)) {
// return "配置文件验证失败";
// } else if ("9905".equals(cpResult)) {
// return "调用参数不正确";
// } else if ("2007".equals(cpResult)) {
// return "通讯超时";
// } else if (cpResult.startsWith("200")) {
// return "通讯异常";
// } else {
// // return "系统异常");
// }
return "绑卡失败!";
}
return "未知异常";
}
public void dissmisProgressDialog() {
if (mpDialog != null && mpDialog.isShowing()) {
mpDialog.dismiss();
}
}
public void showProgressDialog(String text) {
mpDialog = new PiggyProgressDialog(mContext.getActivity());
mpDialog.show();
mpDialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
if (mBindTask != null) {
mBindTask.cancel(true);
}
}
});
}
public String handleCpRes(int pageType, String cpCode) {
String cpRes = parseCpResult(cpCode);
if (isSuccess(cpRes)) {
launchTask(Request_Type_Cp_Success, null);
return null;
} else if (isTimeOut(cpRes)) {
launchTask(Request_Type_Cp_TimeOut, new String[] { mBankAcct });
return null;
}
// 失败
String otherRes = otherRes(cpRes);
Intent ien = new Intent();
ien.putExtra(Cons.Intent_type, pageType);
ien.putExtra(Cons.Intent_id, BindCardSucceedFragment.Type_Res_BindCardFailed);
ien.setClass(mContext.getSherlockActivity(), BindCardSucceedActivity.class);
mContext.startActivity(ien);
return otherRes;
}
public void handleStepRqRes(int intoType, String reqId, UserCardListDto cardListDto, UserCardDto mCardDto) {
try {
UserCardListDto u = cardListDto;
if (u != null && u.getContentCode() == Cons.SHOW_SUCCESS) {
UserUtil.UserBankVeryType bankType = UserUtil.VrfyCardStatus(mCardDto.getBankAcct());
Intent ien = new Intent();
if ((bankType == UserBankVeryType.VrfySuccessBindCard)) {
ien.putExtra(Cons.Intent_type, intoType);
ien.putExtra(Cons.Intent_id, BindCardSucceedFragment.Type_Res_BindCardSuccess);
ien.setClass(mContext.getSherlockActivity(), BindCardSucceedActivity.class);
try {
Activity a = (Activity) mContext.getActivity();
if (a.getComponentName().getClassName().contains("BindCardActivity")) {
a.finish();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (Request_Type_Cp_TimeOut.equals(reqId)) {
ien.putExtra(Cons.Intent_type, intoType);
ien.putExtra(Cons.Intent_bean, mCardDto);
ien.setClass(mContext.getActivity(), CpNetConnTimeoutActivity.class);
} else {//
ien.putExtra(Cons.Intent_type, intoType);
ien.putExtra(Cons.Intent_id, BindCardSucceedFragment.Type_Res_BindCardFailed);
ien.setClass(mContext.getActivity(), BindCardSucceedActivity.class);
}
}
mContext.startActivity(ien);
} else {
// 获取用户银行卡信息失败
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void launchTask(String type, String[] args) {
ApplicationParams.getInstance().getServiceMger().addTask(new TaskBean(UpdateUserDataService.TaskType_UserCard, type, args));
}
private void startCpPluis(BindCardDto result){
Utils.setPackageName(mContext.getSherlockActivity().getPackageName());
Intent t = new Intent(mContext.getSherlockActivity(), Initialize.class);
String info = result.buildOrderInf(Cons.CP_Debug_Flag);
t.putExtra(CPGlobaInfo.XML_TAG, info);
mContext.startActivity(t);
}
/**
* 绑定银行task
*
* @ClassName: BindCardFragment.java
* @Description:
* @author yescpu [email protected]
* @date 2013-10-17下午4:55:59
*/
public class BindTask extends MyAsyncTask<String, Void, BindCardDto> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected BindCardDto doInBackground(String... params) {
// TODO Auto-generated method stub
return DispatchAccessData.getInstance().bindCard(params[0], params[1], params[2], params[3], params[4], params[5], getSupportChalln());// custNo,
}
@Override
protected void onPostExecute(BindCardDto result) {
super.onPostExecute(result);
if (result.getContentCode() == Cons.SHOW_SUCCESS) {// 普通渠道绑卡成功
String channelId = result.getChannelId();
if (channelId!=null &&channelId.equals("1013")) {
startCpPluis(result);
}else {
BindCardAuthModeDto defaultAuth= result.getDefaultAuth();
if (defaultAuth!=null) {
if (defaultAuth.getAuthMode().equals(BindCardAuthModeDto.Auth_WeChat)) {
//返回成功
mContext.showToastShort("绑定成功");
ApplicationParams.getInstance().getServiceMger().addTask(new TaskBean(UpdateUserDataService.TaskType_UserCard, BindCardFragment.BindCardRequsetNormal));
}else if (defaultAuth.getAuthMode().equals(BindCardAuthModeDto.Auth_DaKuang)) {
//返回成功
mContext.showToastShort("绑定成功");
ApplicationParams.getInstance().getServiceMger().addTask(new TaskBean(UpdateUserDataService.TaskType_UserCard, BindCardFragment.BindCardRequsetNormal));
}else if(defaultAuth.getAuthMode().equals(BindCardAuthModeDto.Auth_B2c)){
//调用cp
startCpPluis(result);
}else {
// 调用升级接口
showProgressDialog("请稍后...");
new UpdateTask().execute();
}
}else {
mContext.showToastShort("绑定成功");
ApplicationParams.getInstance().getServiceMger().addTask(new TaskBean(UpdateUserDataService.TaskType_UserCard, BindCardFragment.BindCardRequsetNormal));
}
}
} else if (result.getContentCode() == Cons.SHOW_BindOtherChannl) {
dissmisProgressDialog();
mContext.showToastShort(result.getContentMsg());
} else {
dissmisProgressDialog();
mContext.showToastShort(result.getContentMsg());
}
}
}
public class UpdateTask extends MyAsyncTask<Void, Void, UpdateDto> {
@Override
protected UpdateDto doInBackground(Void... params) {
// TODO Auto-generated method stub
return DispatchAccessData.getInstance().checkUpdate();
}
@Override
protected void onPostExecute(UpdateDto result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (mpDialog != null && mpDialog.isShowing()) {
mpDialog.dismiss();
}
if (mContext.isAdded()) {
if (result.contentCode == Cons.SHOW_SUCCESS) {
UpdateDto arg1 = result;
// arg1.setVersionNeedUpdate("1");
String needUpdate = arg1.getVersionNeedUpdate();
if (!needUpdate.equals("2")) {
String url = arg1.getUpdateUrl();
showUpdateDialog(url);
}
}
// getActivity().finish();
}
}
private void showUpdateDialog(final String url) {
new AlertDialog.Builder(mContext.getActivity()).setMessage("当前版本不支持新增的开户渠道,更新到新版本后即可开户。").setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}).setPositiveButton("升级", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String murl = url;
Intent i = new Intent("android.intent.action.VIEW");
i.setData(Uri.parse(murl));
mContext.startActivity(i);
}
});
}
}
/**
* 银行鉴权task
*
* @ClassName: BindCardFragment.java
* @Description:
* @author yescpu [email protected]
* @date 2013-10-17下午4:55:59
*/
public class AuthTask extends MyAsyncTask<String, Void, BindCardDto> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected BindCardDto doInBackground(String... params) {
return DispatchAccessData.getInstance().bankAuth(params[0], params[1], params[2], getSupportChalln());// custNo,
}
@Override
protected void onPostExecute(BindCardDto result) {
super.onPostExecute(result);
if (result.getContentCode() == Cons.SHOW_SUCCESS) {// 普通渠道绑卡成功
String channelId = result.getChannelId();
if (channelId!=null &&channelId.equals("1013")) {
startCpPluis(result);
}else {
BindCardAuthModeDto defaultAuth= result.getDefaultAuth();
if (defaultAuth!=null) {
if (defaultAuth.getAuthMode().equals(BindCardAuthModeDto.Auth_WeChat)) {
//跳转到微信
Intent it=new Intent(mContext.getActivity(),PrefectActivity.class);
mContext.startActivity(it);
dissmisProgressDialog();
}else if (defaultAuth.getAuthMode().equals(BindCardAuthModeDto.Auth_DaKuang)) {
//返回成功
mContext.showToastShort("绑定成功");
ApplicationParams.getInstance().getServiceMger().addTask(new TaskBean(UpdateUserDataService.TaskType_UserCard, BindCardFragment.BindCardRequsetNormal));
dissmisProgressDialog();
}else if(defaultAuth.getAuthMode().equals(BindCardAuthModeDto.Auth_B2c)){
//调用cp
startCpPluis(result);
}else {
// 调用升级接口
showProgressDialog("请稍后...");
new UpdateTask().execute();
}
}else {
//未知|跳转到微信
Intent it=new Intent(mContext.getActivity(),PrefectActivity.class);
mContext.startActivity(it);
dissmisProgressDialog();
}
}
} else if (result.getContentCode() == Cons.SHOW_BindOtherChannl) {
dissmisProgressDialog();
mContext.showToastShort(result.getContentMsg());
} else {
dissmisProgressDialog();
mContext.showToastShort(result.getContentMsg());
}
}
}
private String getSupportChalln() {
BindCardUploadParams channles = new BindCardUploadParams();
ArrayList<Channels> list = new ArrayList<Channels>();
list.add(new Channels("1013", "1"));
list.add(new Channels("02", "1"));
channles.setChannels(list);
String supportPayChannel = new Gson().toJson(channles);
return supportPayChannel;
}
}
| true |
d95a1e0b202d4347adaee55becbdd4cc25ac9370
|
Java
|
duslabo/android_work
|
/businesshall/src/com/yfcomm/mpos/codec/TimeoutException.java
|
UTF-8
| 442 | 1.960938 | 2 |
[] |
no_license
|
package com.yfcomm.mpos.codec;
import com.yfcomm.mpos.model.syn.ErrorCode;
public class TimeoutException extends MPOSException {
private static final long serialVersionUID = -4836551583610686707L;
public TimeoutException() {
super(ErrorCode.TIMEOUT.getCode(),ErrorCode.TIMEOUT.getDefaultMessage());
}
public TimeoutException(DeviceContext dc) {
super(ErrorCode.TIMEOUT.getCode(), dc.getErrorMessage(ErrorCode.TIMEOUT));
}
}
| true |
a8df6f0d09c14b197300d18f46c3d99ef889ee10
|
Java
|
kavya-96/pavitra
|
/EmployeeManagementSystem/src/com/cg/ems/service/IEmployeeService.java
|
UTF-8
| 224 | 1.84375 | 2 |
[] |
no_license
|
package com.cg.ems.service;
import com.cg.ems.exception.EMSException;
import com.cg.ems.model.Employee;
public interface IEmployeeService {
Employee findEmployee(String EmployeeId) throws EMSException;
}
| true |
047a9210b94f8dc5c6073355e84cadb875474c70
|
Java
|
bellmit/ego-survey
|
/src/main/java/ru/airlabs/ego/survey/dto/UIError.java
|
UTF-8
| 872 | 2.125 | 2 |
[] |
no_license
|
package ru.airlabs.ego.survey.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Базовая модель для передачи ошибок клиента из UI
*
* @author Aleksey Gorbachev
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UIError {
/**
* URL, где произошла ошибка
*/
private String url;
/**
* Номер строки, где произошла ошибка
*/
private Integer lineNumber;
/**
* Номер столбца для строки где произошла ошибка
*/
private Integer colNumber;
/**
* Текст ошибки клиента
*/
private String errorMessage;
/**
* Объект ошибки клиента (Error Object)
*/
private String errorObj;
}
| true |
80c1bf18fc9cd8d81d58949032688241203cf678
|
Java
|
misselvexu/opscloud4
|
/opscloud-datasource-zabbix/src/main/java/com/baiyi/opscloud/zabbix/entry/ZabbixTemplate.java
|
UTF-8
| 544 | 1.765625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.baiyi.opscloud.zabbix.entry;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.io.Serializable;
/**
* @Author <a href="mailto:[email protected]">修远</a>
* @Date 2021/7/1 2:48 下午
* @Since 1.0
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class ZabbixTemplate implements Serializable {
//@JsonProperty("templateid")
private String templateid;
private String name;
// 模板的正式名称。
private String host;
private String description;
}
| true |
f8dc6cb1878bb1abe3c6754b8f1ef64f529e8fed
|
Java
|
yixinsiyu/pg
|
/pg-web/src/main/java/net/engining/pg/web/BaseResponseBean.java
|
UTF-8
| 1,612 | 2.453125 | 2 |
[] |
no_license
|
package net.engining.pg.web;
import java.io.Serializable;
import java.util.Map;
import com.google.common.collect.Maps;
import net.engining.pg.support.core.exception.ErrorCode;
/**
* 具体业务交易的Nested Response Bean的基类
* @author luxue
*
*/
public class BaseResponseBean implements Serializable{
private static final long serialVersionUID = 1L;
/**
* 返回结果码
*/
private String returnCode = ErrorCode.Success.getValue();
/**
* 返回结果描述
*/
private String returnDesc = ErrorCode.Success.getLabel();
/**
* 其他附加信息
*/
private Map<String, Serializable> additionalRepMap;
public BaseResponseBean() {
this.additionalRepMap = Maps.newHashMap();
}
/**
* @return the additionalRepMap
*/
public Map<String, Serializable> getAdditionalRepMap() {
return additionalRepMap;
}
/**
* @param additionalRepMap
* the additionalRepMap to set
*/
public void putAdditionalRepMap(String repKey, Serializable repBean) {
add(repKey, repBean);
}
private void add(String repKey, Serializable repBean) {
this.additionalRepMap.put(repKey, repBean);
}
/**
* @return the returnCode
*/
public String getReturnCode() {
return returnCode;
}
/**
* @param returnCode the returnCode to set
*/
public void setReturnCode(String returnCode) {
this.returnCode = returnCode;
}
/**
* @return the returnDesc
*/
public String getReturnDesc() {
return returnDesc;
}
/**
* @param returnDesc the returnDesc to set
*/
public void setReturnDesc(String returnDesc) {
this.returnDesc = returnDesc;
}
}
| true |
90609f649bff5a104d7707e6935224c5a3673faa
|
Java
|
portablesimula/SimulaCompiler
|
/Simula/src/simula/compiler/SyntaxClass.java
|
UTF-8
| 4,342 | 2.6875 | 3 |
[] |
no_license
|
/*
* (CC) This work is licensed under a Creative Commons
* Attribution 4.0 International License.
*
* You find a copy of the License on the following
* page: https://creativecommons.org/licenses/by/4.0/
*/
package simula.compiler;
import simula.compiler.declaration.Declaration;
import simula.compiler.expression.Expression;
import simula.compiler.statement.Statement;
import simula.compiler.utilities.Global;
import simula.compiler.utilities.Type;
import simula.compiler.utilities.Util;
/**
* The class SyntaxClass.
* <p>
* The Simula Compiler uses Recursive Descent Parsing. Each syntax class is a
* subclass of this class.
* <p>
* A NonTerminal object represents non terminal symbol in the formal syntax.
* <p>
* Parsing descends in a top-down manner, until the final nonterminal has been
* processed. The parsing process depends on a global variable, currentToken,
* which contains the current symbol from the input, and the function nextSymb,
* which updates currentToken when called.
* <p>
* For further description of Recursive Descent Parsing see <a href=
* "https://en.wikipedia.org/wiki/Recursive_descent_parser">Wikipedia</a>.
*
* <pre>
*
* ***********************************************************************
* META-SYNTAX:
*
* MetaSymbol Meaning
*
* = is defined to be
* | alternatively
* [ x ] 0 or 1 instance of x
* { x } 0 or more instances of x
* ( x | y ) grouping: either x or y
* xyz the terminal symbol xyz
* MetaIdentifier a non terminal symbol
* ***********************************************************************
* </pre>
*
* Link to GitHub: <a href=
* "https://github.com/portablesimula/SimulaCompiler/blob/master/Simula/src/simula/compiler/SyntaxClass.java"><b>Source
* File</b></a>.
*
* @author Øystein Myhre Andersen
*/
public abstract sealed class SyntaxClass permits Declaration, Statement, Expression {
/**
* Controls semantic checking.
* <p>
* Set true when doChecking(), put or get is called
*/
private boolean CHECKED = false;
/**
* The type
*/
public Type type = null;
/**
* The source line number
*/
public int lineNumber;
/**
* Create a new SyntaxClass.
*/
protected SyntaxClass() {
lineNumber = Global.sourceLineNumber;
}
/**
* Perform semantic checking.
* <p>
* This must be redefined in every subclass.
*/
public void doChecking() {
if (IS_SEMANTICS_CHECKED())
return;
Global.sourceLineNumber = lineNumber;
String name = this.getClass().getSimpleName();
Util.IERR("*** NOT IMPLEMENTED: " + "" + name + ".doChecking");
}
/**
* Set semantic checked.
* <p>
* Should be called from all doChecking,put,get methods to signal that semantic
* checking is done.
*/
protected void SET_SEMANTICS_CHECKED() {
CHECKED = true;
}
/**
* Returns true if semantic checking is done.
*
* @return true if semantic checking is done
*/
protected boolean IS_SEMANTICS_CHECKED() {
return (CHECKED);
}
/**
* Assert that semantic checking done.
*/
protected void ASSERT_SEMANTICS_CHECKED() {
if (!CHECKED)
Util.error("FATAL error - Semantic checker not called: " + this.getClass().getName() + ", " + this);
if (this instanceof Declaration decl) {
if (decl.externalIdent == null)
Util.error("External Identifier is not set");
}
}
/**
* Output possible declaration code.
*/
public void doDeclarationCoding() {
}
/**
* Output Java code.
*/
public void doJavaCoding() {
Global.sourceLineNumber = lineNumber;
GeneratedJavaClass.code(toJavaCode());
}
/**
* Generate Java code for this Syntax Class.
*
* @return Java code
*/
public String toJavaCode() {
return (toString());
}
/**
* Utility print method.
*
* @param indent number of spaces leading the line
*/
public void print(final int indent) {
Util.println(edIndent(indent) + this);
}
/**
* Utility: Returns a number of blanks.
*
* @param indent the number of blanks requested
* @return a number of blanks.
*/
protected String edIndent(final int indent) {
int i = indent;
String s = "";
while ((i--) > 0)
s = s + " ";
return (s);
}
}
| true |
1a756764f39c7758957789bbf36d7206deeb088c
|
Java
|
saquibhelal/PageObjectModel
|
/IcamTestApplication/src/test/java/com/icam/qa/testcases/CreateNewStudentTest.java
|
UTF-8
| 1,584 | 2.265625 | 2 |
[] |
no_license
|
package com.icam.qa.testcases;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.icam.qa.base.TestBase;
import com.icam.qa.pages.CreateNewStudent;
import com.icam.qa.pages.HomePage;
import com.icam.qa.pages.LoginPage;
import com.icam.qa.util.TestUtil;
public class CreateNewStudentTest extends TestBase {
LoginPage loginPage;
HomePage homePage;
CreateNewStudent createNewStudents;
String sheetName="Student_Creation";
public CreateNewStudentTest(){
super();
}
@BeforeMethod
public void setUp() throws InterruptedException{
initializationBrowser();
createNewStudents=new CreateNewStudent();
loginPage=new LoginPage();
homePage=loginPage.login(Pro.getProperty("username"), Pro.getProperty("password"));
homePage.clickOnNewStudent();
}
@DataProvider
public Object[][] getIcamSheetData(){
Object data[][]=TestUtil.getTestData(sheetName);
return data;
}
@Test(priority=1,dataProvider="getIcamSheetData")
public void createStudent(String ScNo,String fNm,String mdNm,String lNm,
String rlgs,String mthtong,String adrNo,String cellNo,String scNm,String wb,String adrs,String phne,String em,String ach
) throws InterruptedException{
createNewStudents.createNewStudent(ScNo,fNm,mdNm,lNm,rlgs,mthtong,adrNo,cellNo,scNm,wb,adrs,phne,em,ach);
}
@AfterMethod
public void tearDown(){
System.out.println("======Browser is shutting down=====\n");
//driver.quit();
}
}
| true |
b6436e2d5dc3a8b294de8a0ec94129dd286e92c0
|
Java
|
dydo32/javapractice
|
/src/chap10/api/lang/Vehicle.java
|
UHC
| 722 | 3.4375 | 3 |
[] |
no_license
|
package chap10.api.lang;
public class Vehicle extends Owner{
Owner owner;
int price;
public boolean equals(Object obj){
if(obj!=null & obj instanceof Vehicle){
Vehicle v = (Vehicle)obj;
if(this.owner.equals(v.getOwner())){
return true; //ġѴ.
}
}
return false;
}
@Override
public String toString() {
return " : "+ owner+"\n : " +price+"Դϴ."; //owner.toString() صȴ.
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
| true |
085645dbc79c0a2e3e35280b7b1a9fb47c2727ee
|
Java
|
Silentsoul04/learn-java
|
/Time/code/learn-date/src/main/java/lsieun/timezone/DifferentTimeZoneDates.java
|
UTF-8
| 950 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
package lsieun.timezone;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DifferentTimeZoneDates {
public static void main(String[] args) {
TimeZone tz = TimeZone.getTimeZone("EST");
Calendar cal = Calendar.getInstance(tz);
cal.set(Calendar.MONTH, 11); //December
cal.set(Calendar.DATE, 31);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,23);
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);
Date date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("zzz yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
System.out.println(sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Luxembourg"));
System.out.println(sdf.format(date));
}
}
| true |
585013f2bec9a1b0ad4e2e9ed8f757a69d7112e8
|
Java
|
https-priyankadeshmukh-github-com/Equitytrade
|
/newProject/src/BasicProgram/Screenshot.java
|
UTF-8
| 1,110 | 2.375 | 2 |
[] |
no_license
|
package BasicProgram;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Screenshot {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","F:\\Priyanka Jadhav\\Software testing\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com");
driver.manage().window().maximize();
TakesScreenshot ts = (TakesScreenshot)driver;
java.io.File source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("F:\\Priyanka Jadhav\\Software testing\\Selenium\\abc.jpeg"));
}
public static String timestamp(){
String timestamp = new SimpleDateFormat("yyyy_mm_dd__hh__mm__ss").format(new Date());
return timestamp;
}
}
| true |
e81d44d368044c2d90249b2e74d3b5fe4b74b7c6
|
Java
|
luisrains/CEP
|
/src/main/java/py/com/pol/polapp/dao/impl/AlumnoDaoImpl.java
|
UTF-8
| 429 | 1.898438 | 2 |
[] |
no_license
|
package py.com.pol.polapp.dao.impl;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import py.com.pol.polapp.dao.AlumnoDao;
import py.com.pol.polapp.domain.Alumno;
@Repository
@Scope("session")
public class AlumnoDaoImpl extends DaoImpl<Alumno> implements AlumnoDao {
@Override
public String getCamposFiltrables() {
return "cedula||nombre||apellido||carrera";
}
}
| true |
0b9817ce903522969526f41cc2ac8261c87f7d66
|
Java
|
xtawgipl/sealight-parent
|
/data-osram/src/main/java/com/sealight/osram/entity/LightInfosBean.java
|
UTF-8
| 5,380 | 1.765625 | 2 |
[] |
no_license
|
package com.sealight.osram.entity;
public class LightInfosBean {
private Integer id;
private Integer useId;
private Integer typeId;
private Integer technologyId;
private Integer order;
private String bulletList;
private String lampInfo;
private Integer linecardId;
private String linecardName;
private String linksautomotive;
private String osramBestnr;
private String osramEan;
private String osramEce;
private Integer pillarId;
private String pillarImage;
private String pillarName;
private String prio;
private String productImage;
private String productZmp;
private String usp;
public LightInfosBean(){
}
public LightInfosBean(Integer useId, Integer typeId, Integer technologyId, Integer order, String bulletList, String lampInfo, Integer linecardId, String linecardName, String linksautomotive, String osramBestnr, String osramEan, String osramEce, Integer pillarId, String pillarImage, String pillarName, String prio, String productImage, String productZmp, String usp) {
this.useId = useId;
this.typeId = typeId;
this.technologyId = technologyId;
this.order = order;
this.bulletList = bulletList;
this.lampInfo = lampInfo;
this.linecardId = linecardId;
this.linecardName = linecardName;
this.linksautomotive = linksautomotive;
this.osramBestnr = osramBestnr;
this.osramEan = osramEan;
this.osramEce = osramEce;
this.pillarId = pillarId;
this.pillarImage = pillarImage;
this.pillarName = pillarName;
this.prio = prio;
this.productImage = productImage;
this.productZmp = productZmp;
this.usp = usp;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUseId() {
return useId;
}
public void setUseId(Integer useId) {
this.useId = useId;
}
public Integer getTypeId() {
return typeId;
}
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
public Integer getTechnologyId() {
return technologyId;
}
public void setTechnologyId(Integer technologyId) {
this.technologyId = technologyId;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public String getBulletList() {
return bulletList;
}
public void setBulletList(String bulletList) {
this.bulletList = bulletList == null ? null : bulletList.trim();
}
public String getLampInfo() {
return lampInfo;
}
public void setLampInfo(String lampInfo) {
this.lampInfo = lampInfo == null ? null : lampInfo.trim();
}
public Integer getLinecardId() {
return linecardId;
}
public void setLinecardId(Integer linecardId) {
this.linecardId = linecardId;
}
public String getLinecardName() {
return linecardName;
}
public void setLinecardName(String linecardName) {
this.linecardName = linecardName == null ? null : linecardName.trim();
}
public String getLinksautomotive() {
return linksautomotive;
}
public void setLinksautomotive(String linksautomotive) {
this.linksautomotive = linksautomotive == null ? null : linksautomotive.trim();
}
public String getOsramBestnr() {
return osramBestnr;
}
public void setOsramBestnr(String osramBestnr) {
this.osramBestnr = osramBestnr == null ? null : osramBestnr.trim();
}
public String getOsramEan() {
return osramEan;
}
public void setOsramEan(String osramEan) {
this.osramEan = osramEan == null ? null : osramEan.trim();
}
public String getOsramEce() {
return osramEce;
}
public void setOsramEce(String osramEce) {
this.osramEce = osramEce == null ? null : osramEce.trim();
}
public Integer getPillarId() {
return pillarId;
}
public void setPillarId(Integer pillarId) {
this.pillarId = pillarId;
}
public String getPillarImage() {
return pillarImage;
}
public void setPillarImage(String pillarImage) {
this.pillarImage = pillarImage == null ? null : pillarImage.trim();
}
public String getPillarName() {
return pillarName;
}
public void setPillarName(String pillarName) {
this.pillarName = pillarName == null ? null : pillarName.trim();
}
public String getPrio() {
return prio;
}
public void setPrio(String prio) {
this.prio = prio == null ? null : prio.trim();
}
public String getProductImage() {
return productImage;
}
public void setProductImage(String productImage) {
this.productImage = productImage == null ? null : productImage.trim();
}
public String getProductZmp() {
return productZmp;
}
public void setProductZmp(String productZmp) {
this.productZmp = productZmp == null ? null : productZmp.trim();
}
public String getUsp() {
return usp;
}
public void setUsp(String usp) {
this.usp = usp == null ? null : usp.trim();
}
}
| true |
8b642065df6d0a7fd32fa030592c8303a07d9178
|
Java
|
abardevi3/codekata
|
/sumofn.java
|
UTF-8
| 463 | 2.953125 | 3 |
[] |
no_license
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class sumofn {
public static void main(String[] args) throws IOException {
System.out.println("Input any No.");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String data = (String) br.readLine();
int num = Integer.parseInt(data);
int sum = 0;
for (int i = 1; i <= num; i++) {
sum = sum + i;
}
System.out.println("Sum- " + sum);
}
}
| true |
5d8a964365a25bf1f111c6ac8c07290c306b6914
|
Java
|
MaxwellJalves/SOLID
|
/src/main/java/com/estudo/javaoito/JavaOitoLambdas.java
|
UTF-8
| 1,191 | 3.546875 | 4 |
[] |
no_license
|
package com.estudo.javaoito;
import javax.swing.text.html.HTMLDocument;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class JavaOitoLambdas {
public static void main(String[] args){
//criar listar de produtos
List<Produto> produto = new ArrayList<>();
produto.add(new Produto(1010,"LEITE EM PÓ",BigDecimal.valueOf(5.58)));
produto.add(new Produto(2030,"SABONETE LIQUIDO",BigDecimal.valueOf(5.58)));
produto.add(new Produto(9999,"ARROZ INTEGRAL",BigDecimal.valueOf(5.58)));
produto.add(new Produto(8545,"DETERGENTE",BigDecimal.valueOf(5.58)));
produto.add(new Produto(2315,"AMACIANTE",BigDecimal.valueOf(5.58)));
System.out.println(produto);
for(Produto i : produto){
System.out.println(i.getNome());
}
//lambda - Exiba apenas o código e Descrição dos procedimentos
produto.forEach(e -> System.out.println(e.getCodigoInterno() +" || ".concat(e.getNome())));
//Ordenação do menor para o maior
boolean b = produto.contains("LEITE EM PÓ");
System.out.println(b);
}
}
| true |
c2107e8d227dd5335b2bc7e245b48e29820b9361
|
Java
|
desmax/AndroidTest
|
/src/com/example/Screen2.java
|
UTF-8
| 776 | 2.046875 | 2 |
[] |
no_license
|
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/**
* Created with IntelliJ IDEA.
* User: maxim
* Date: 6/17/12
* Time: 3:38 PM
* To change this templateon use File | Settings | File Templates.
*/
public class Screen2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Button button = (Button)findViewById(R.id.button_next_screen2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
}
| true |
b3933f7c2eb4df956aa406eee38c7543e41684f6
|
Java
|
requiredinformation/nightgamesmod
|
/NightgamesMod/nightgames/skills/Charm.java
|
UTF-8
| 2,573 | 2.640625 | 3 |
[] |
no_license
|
package nightgames.skills;
import nightgames.characters.Attribute;
import nightgames.characters.Character;
import nightgames.characters.Emotion;
import nightgames.characters.Trait;
import nightgames.combat.Combat;
import nightgames.combat.Result;
import nightgames.global.Global;
import nightgames.status.Charmed;
import nightgames.status.Stsflag;
public class Charm extends Skill {
public Charm(Character self) {
super("Charm", self, 4);
}
@Override
public boolean usable(Combat c, Character target) {
return getSelf().canRespond() && c.getStance().facing(getSelf(), target) && !target.wary();
}
@Override
public int getMojoCost(Combat c) {
return 30;
}
@Override
public boolean resolve(Combat c, Character target) {
if (target.human() && target.is(Stsflag.blinded)) {
printBlinded(c);
return false;
}
writeOutput(c, Result.normal, target);
double mag = 2 + Global.random(4) + 2 * getSelf().body.getHotness(target);
if (target.has(Trait.imagination)) {
mag += 4;
}
int m = (int) Math.round(mag);
target.tempt(c, getSelf(), m);
double chance = (5 + Math.sqrt(Math.max(0, mag))) / 10.0;
double roll = Global.randomdouble();
if (chance > roll) {
c.write(getSelf(), target.subjectAction("were", "was") + " charmed.");
target.add(c, new Charmed(target));
target.emote(Emotion.horny, 10);
getSelf().emote(Emotion.confident, 20);
}
target.emote(Emotion.horny, 10);
return true;
}
@Override
public boolean requirements(Combat c, Character user, Character target) {
return user.get(Attribute.Cunning) >= 8 && user.get(Attribute.Seduction) > 16;
}
@Override
public Skill copy(Character user) {
return new Charm(user);
}
@Override
public int speed() {
return 9;
}
@Override
public Tactics type(Combat c) {
return Tactics.pleasure;
}
@Override
public String deal(Combat c, int damage, Result modifier, Character target) {
return "You flash a dazzling smile at " + target.getName() + ".";
}
@Override
public String receive(Combat c, int damage, Result modifier, Character target) {
return getSelf().getName() + " flashes a dazzling smile at "+target.subject()+".";
}
@Override
public String describe(Combat c) {
return "Charms your opponent into not hurting you.";
}
}
| true |
6ba80f8b5679962ed73cf0c8785f1018ffb6eefd
|
Java
|
VagnerMachado/CustomJavaLibrary
|
/src/queueLinkedList/Queue.java
|
UTF-8
| 6,462 | 3.59375 | 4 |
[] |
no_license
|
package queueLinkedList;
/**********************************************************************************************************************
* Please refer to the xxxxxxxxx.java file for a description of the project in a larger scope *
* ********************************************************************************************************************
*
*<b>Title:</b> Project x: xxxxxx<br>
*<b>Filename:</b> Queue.java<br>
*<b>Date Written:</b> mm dd yyyy<br>
*<b>Due Date:</b> mm dd yyyy<br>
*<p>
**</p>
*<p><b>Description:</b></p>
*<p>This class implements the abstract methods contained in the QueueADT interface. The class instantiates a new Node
*object every time an item is enqueued, and this way the queue is never full and does not throw that Exception. The methods
*available enable the user to determine if a queue is empty, add or remove an item, see the front or rear item, and the
*size of the queue. The description for each method can be found above each method's signature, in its javadoc.
*</p>
*
*********************************************************************************************************************
* @author VagnerMachado - ID N00820127 - Nassau Community College - Spring 2016 *
*********************************************************************************************************************
*
*/
/**
* Queue Class - implement the methods defined in the QueueADT Class
* @param <T> - a generic data type
*/
public class Queue <T> implements QueueADT<T>
{
/**
* private class Node - defines three constructors for Node objects to assist the Queue class
* @param <E> - a generic data type
*/
private class Node <E>
{
//Node instance data
private E data;
private Node <E> next;
/**
* Node default constructor - sets data and next field as null for the instantiated Node object
*/
public Node()
{
data = null;
next = null;
}
/**
* Node parameterized constructor - Instantiates a Node object with data d.
* @param d - the data for instantiated Node object
*/
public Node(E d)
{
data = d;
next = null;
}
/**
* Node parameterized constructor - isntantiates a Niode object with data d and next n
* @param d - the data for the instantiated Node object
* @param n - the Node next to this Node
*/
public Node (E d, Node<E> n)
{
data = d;
next = n;
}
/**
* setData method - modifier for the data field
* @param d - object to be stored in data field
*/
public void setData(E d) {
data = d;
}
/**
* getNext method - accessor to the next field
* @return next - the Node object next to this Node object
*/
public Node<E> getNext() {
return next;
}
/**
* setNext method - modifier to the nexxt field
* @param n - the Node object next to this Node object
*/
public void setNext(Node<E> n) {
next = n;
}
}
// Queue instance data
private Node<T> front, rear;
public final int CAPACITY =100;
private int size = 0;
/**
* Queue default constructor - instantiates a queue object
*/
@SuppressWarnings("unchecked")
public Queue()
{
// calls the parent class Object constructor
}
/**
* enqueue method - adds an object to the end of the queue
* @param d - object to be added to the end of the queue
*/
public void enqueue(T d)
{
if (rear == null)
rear = front = new Node<T>(d);
else
{
rear.next = new Node<T>(d);
rear = rear.next;
}
size++;
}
//the enqueue method below is for a circular queue implemented by a LinkedList
//if this enqueue method is used, comment out the one above
/*
public void enqueue(T d)
{
if (rear == null)
{
rear = front = new Node<T>(d);
rear.next = front;
}
else
rear.next = new Node<T>(d, front);
size++;
}*/
/**
* dequeue method - removes the object in the front of the queue
* @throws QueueEmptyException - in case the queue is empty
* @return - the item dequeued
*/
public T dequeue() throws QueueEmptyException
{
if (isEmpty())
throw new QueueEmptyException("Empty Queue Exception, there is no entry to dequeue");
T item = front.data;
front = front.next;
if( front == null)
rear = null;
size--;
return item;
}
//the dequeue method below is for a circular queue implemented by a LinkedList
//if this dequeue method is used, comment out the one above
/*
public T dequeue() throws QueueEmptyException
{
if (isEmpty())
throw new QueueEmptyException("Empty Queue Exception, there is no entry to dequeue");
T item = front.data;
if(front == rear)
front = rear = null;
else
{
front = front.next;
rear.next = front;
}
size--;
return item;
}
*/
/**
* front method - shows the data in the front of the queue
* @throws QueueEmptyException - in case the queue is empty
* @return - the item in front of the queue
*/
public T front() throws QueueEmptyException
{
if (isEmpty())
throw new QueueEmptyException ("Empty Queue, there is no item in front of the queue");
T value = front.data;
return value;
}
/**
* isEmpty method - keeps track if the queue is empty or not
* @return true if empty, false otherwise
*/
public boolean isEmpty()
{
return size == 0;
}
/**
* rear method - gives access the the object in the end of the queue
* @return - the object in the rear of the queue
* @throws QueueEmptyException - in case the queue is empty
*/
public T rear() throws QueueEmptyException
{
if(isEmpty())
throw new QueueEmptyException("Empty Queue Exception, there is no itemin the rear of the queue");
T item = rear.data;
return item;
}
/**
* getSize method - gives access to the size of the queue
* @return - the size of the array as an integer
*/
public int getSize() {
return size;
}
/**
* toString method - traverses through the queue and prints a reference to a String containing
* the items currently in the queue
*/
public String toString()
{
String result = "";
Node<T> trav = front;
while(trav != null)
{
result += trav.data + " ";
trav = trav.next;
}
return result;
}
}
| true |