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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6efd49b4d780a1cb4aa89a9ebe2fd3aefeb6fbad
|
Java
|
avleichko/master-service
|
/src/main/java/com/adidas/masterservice/app/AppApplication.java
|
UTF-8
| 1,614
| 1.835938
| 2
|
[] |
no_license
|
package com.adidas.masterservice.app;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.cloud.task.launcher.annotation.EnableTaskLauncher;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@SpringBootApplication
@EnableTaskLauncher
@EnableBinding(Source.class)
@EnableScheduling
@EnableConfigurationProperties
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
// new metric aviliable here http://localhost:8080/actuator/metrics/CUSTOM-TASK-METRIC
@Bean
ApplicationRunner applicationRunner(MeterRegistry meterRegistry) {
return args -> this.executorService.scheduleAtFixedRate(() ->
meterRegistry.timer("CUSTOM-TASK-METRIC")
.record(Duration.ofMillis((long) (Math.random() * 1000))), 500, 500, TimeUnit.MICROSECONDS);
}
}
| true
|
fe4a82b4b54f0c53248091e1f3ae14c895e27569
|
Java
|
amammay/ist242_classwork_homework
|
/ist 242 Eclipse/Labs/src/feb29lab.java
|
UTF-8
| 1,869
| 3.734375
| 4
|
[] |
no_license
|
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* The purpose of this lab is to count letters in a text document and
* store the total number of characters in an output file
*
*
* @author amm7100
*
*/
public class feb29lab {
/**
* Counts letters in a file and returns the number of characters
*
*
* @param args
* @return count
*/
public static int countLetters(String filename){
int count = 0;
Scanner in = null;
try
{
in = new Scanner(new File(filename));
while(in.hasNext())
{
String letter = in.next();
for (int i = 0; i < letter.length(); i++) {
if (Character.isLetter(letter.charAt(i)))
count++;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Input file cannot be opened!");
e.printStackTrace();
}
finally
{
in.close();
}
return count;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
if (args[0] != null && args[1] != null)
{
String inputFile = args[0];
String outputFile = args[1];
int numLetters = countLetters(inputFile);
//Print output
System.out.println("The input file that is being used Currently has the following: ");
System.out.println("Letters : " + numLetters);
PrintWriter out = null;
try
{
out = new PrintWriter(outputFile);
out.println("Letters: " + numLetters);
}
catch (FileNotFoundException e)
{
System.out.println("Output file was not found!");
e.printStackTrace();
}
finally
{
out.close();
}
}
else
{
System.out.println("Input and output files must be supplied ");
}
}
}
| true
|
e1d0d0458d02c479875d76240b3fcc7ec67c428c
|
Java
|
HuntChangGithub/GitHUB
|
/day71_springboot/src/main/java/com/hunt/j1902/service/impl/UserPermissionServiceImpl.java
|
UTF-8
| 1,002
| 2.375
| 2
|
[] |
no_license
|
package com.hunt.j1902.service.impl;
import com.hunt.j1902.mapper.UserPermissionMapper;
import com.hunt.j1902.pojo.UserPermission;
import com.hunt.j1902.service.UserPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by asus on 2019/6/13.
*/
@Service
public class UserPermissionServiceImpl implements UserPermissionService {
@Autowired
private UserPermissionMapper userPermissionMapper;
@Override
public Set<UserPermission> getPermsByName(String uname) {
Set<UserPermission> perms = new HashSet<>();
List<UserPermission> sysPermissionList = userPermissionMapper.getPermsByName(uname);
// 将list集合转为Set集合(提出重复的权限对象,便于权限验证)
for (UserPermission perm: sysPermissionList ) {
perms.add(perm);
}
return perms;
}
}
| true
|
fe13e030be5a4da301d7940f5a7f2126d0de42f2
|
Java
|
ducnguyen111/QuanLyThuVien
|
/QuanLyThuVien/app/src/main/java/com/example/mob_duanmau/ui/FramentPhieuMuon/FragmentQuanLyLoaiSach.java
|
UTF-8
| 4,988
| 2.125
| 2
|
[] |
no_license
|
package com.example.mob_duanmau.ui.FramentPhieuMuon;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.mob_duanmau.Adapter.LoaiSachAdapter;
import com.example.mob_duanmau.Adapter.ThanhVienAdapter;
import com.example.mob_duanmau.DAO.LoaiSachDAO;
import com.example.mob_duanmau.DAO.ThanhVienDAO;
import com.example.mob_duanmau.Model.LoaiSach;
import com.example.mob_duanmau.Model.ThanhVien;
import com.example.mob_duanmau.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class FragmentQuanLyLoaiSach extends Fragment {
ListView mListView;
FloatingActionButton fbloaisach;
ArrayList<LoaiSach> loaiSachArrayList;
Dialog dialog;
EditText ed_maLoai, ed_tenLoai;
Button btn_luu, btn_huy;
LoaiSachDAO loaiSachDAO;
LoaiSach item;
LoaiSachAdapter loaiSachAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_quan_ly_sach,container,false);
mListView = view.findViewById(R.id.lv_loaisach);
fbloaisach = view.findViewById(R.id.flb_loaisach);
loaiSachDAO = new LoaiSachDAO(getActivity());
fbloaisach.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
opendialog(getActivity(),0);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
item = loaiSachArrayList.get(position);
opendialog(getActivity(),1);
return;
}
});
return view;
}
protected void opendialog(final Context context, final int Type){
dialog = new Dialog(context);
dialog.setContentView(R.layout.loaisach_dialog);
ed_maLoai = dialog.findViewById(R.id.ed_maLoai);
ed_tenLoai = dialog.findViewById(R.id.ed_tenLoai);
btn_luu = dialog.findViewById(R.id.btn_luuLoaisach);
btn_huy = dialog.findViewById(R.id.btn_HuyLoaisach);
ed_maLoai.setEnabled(false);
if (Type != 0){
ed_maLoai.setText(String.valueOf(item.maLoai));
ed_tenLoai.setText(item.tenLoai);
}
btn_huy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_luu .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
item = new LoaiSach();
item.tenLoai = ed_tenLoai.getText().toString();
if (Type==0){
if (loaiSachDAO.insert(item)>0){
Toast.makeText(context,"Thêm thành công",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}else
Toast.makeText(context,"Thêm Thất bại",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}else {
item.maLoai = Integer.parseInt(ed_maLoai.getText().toString());
if (loaiSachDAO.update(item)>0){
Toast.makeText(context,"Sửa thành công",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}else
Toast.makeText(context,"Sửa Thất bại",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
capNhatlv();
}
});
dialog.show();
}
void capNhatlv(){
loaiSachArrayList = (ArrayList<LoaiSach>)loaiSachDAO.GetAll();
loaiSachAdapter = new LoaiSachAdapter(getActivity(),this,loaiSachArrayList);
mListView.setAdapter(loaiSachAdapter);
}
public void Xoa(final String Id){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete");
builder.setMessage("Bạn có muốn xóa không");
builder.setCancelable(true);
builder.setPositiveButton("Yes", (dialog1, which) -> {
loaiSachDAO.Delete(Id);
capNhatlv();
dialog1.cancel();
});
builder.setNegativeButton("No", (dialog1, which) -> {dialog1.cancel();});
AlertDialog alertDialog = builder.create();
builder.show();
}
}
| true
|
08b3735ea9c312b650af6463cb61211c2d23eee5
|
Java
|
kilwaz/cen3
|
/src/main/java/clarity/Clarity.java
|
UTF-8
| 286
| 2.015625
| 2
|
[] |
no_license
|
package clarity;
import clarity.load.Load;
import clarity.load.store.expression.Formula;
public class Clarity {
public static Load load() {
return new Load();
}
public static Formula formula(String expression) {
return Formula.create(expression);
}
}
| true
|
a0aa6070a675d0d20317a1eebfd07e80fec0b23d
|
Java
|
Bandana24/SpringProject
|
/src/main/java/com/example/MyfirstSpringBootApplication.java
|
UTF-8
| 806
| 2.140625
| 2
|
[] |
no_license
|
package com.example;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.controller.*;
@SpringBootApplication
//@ComponentScan(basePackages = {"com.example.Controller","com.example.Bean"})
//@ComponentScan(basePackageClasses = BaseController.class)
/*SpringBootApplication annotation already has ComponentScan in it.
But as the controller class is in a different package, specific mention
of ComponentScan is required to map the controller package or the
Controller package class
*/
public class MyfirstSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MyfirstSpringBootApplication.class, args);
}
}
| true
|
dec908760dae7c9a6ea6ebc9cf2f9b9e6c18f4a8
|
Java
|
Petroslav/project1
|
/src/main/java/kekproject/kekproject2/models/Comment.java
|
UTF-8
| 2,329
| 2.40625
| 2
|
[] |
no_license
|
package kekproject.kekproject2.models;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "comments")
public class Comment {
@Id
@Column(name = "comment_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne
@JoinColumn(name = "user_id")
private User author;
@ManyToOne
@JoinColumn(name = "post_id")
private Post parenPost;
@Column(name = "reply_id")
private int replyTo;
@Column(name = "content", columnDefinition = "text", nullable = false, length = 3000)
private String content;
@Column(name = "post_date", nullable = false)
private Date postedOn;
@Column(name = "last_edit")
private Date lastEdit;
@Column(name = "is_edited")
private boolean isEdited;
public Comment(){}
public Comment(User author, Post parenPost, int replyTo, String content, Date postedOn, Date lastEdit, boolean isEdited) {
this.author = author;
this.parenPost = parenPost;
this.replyTo = replyTo;
this.content = content;
this.postedOn = postedOn;
this.lastEdit = lastEdit;
this.isEdited = isEdited;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getAuthor() {
return author;
}
public void setAuthorId(User author) {
this.author = author;
}
public Post getParenPost() {
return parenPost;
}
public void setParenPost(Post parenPost) {
this.parenPost = parenPost;
}
public int getReplyTo() {
return replyTo;
}
public void setReplyTo(int replyTo) {
this.replyTo = replyTo;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getPostedOn() {
return postedOn;
}
public void setPostedOn(Date postedOn) {
this.postedOn = postedOn;
}
public Date getLastEdit() {
return lastEdit;
}
public void setLastEdit(Date lastEdit) {
this.lastEdit = lastEdit;
}
public boolean isEdited() {
return isEdited;
}
public void setEdited(boolean edited) {
isEdited = edited;
}
}
| true
|
3f6b44c20c5952049a73134dcb875864945253bb
|
Java
|
pekka-m/ClimbingApp
|
/ClimbingTrainer/app/src/main/java/me/climbingti/climbingtrainer/practice/detail/PracticeDetailFragment.java
|
UTF-8
| 3,245
| 2.21875
| 2
|
[] |
no_license
|
package me.climbingti.climbingtrainer.practice.detail;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import me.climbingti.climbingtrainer.R;
import me.climbingti.climbingtrainer.common.Injection;
import me.climbingti.climbingtrainer.practice.PracticeOverViewEntity;
/**
* Created by H3173 on 19.11.2015.
*/
public class PracticeDetailFragment extends Fragment implements PracticeDetailContract.View {
private static final String ARG_SECTION_NUMBER = "section number";
private static final String ARG_PRACTICE_ID = "practice_id";
private PracticeDetailContract.Presenter presenter;
TextView textView;
View rootView;
public static PracticeDetailFragment newInstance(int sectionNumber, int id) {
PracticeDetailFragment fragment = new PracticeDetailFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putInt(ARG_PRACTICE_ID, id);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.practice_detail_fragment, container, false);
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
presenter = new PracticeDetailPresenter(Injection.createStatisticsInteractor(getContext()), this);
presenter.loadPracticeDetails(getPracticeIdFromArguments());
}
@Override
public void showPracticeDetails(PracticeOverViewEntity practiceDetails) {
textView = (TextView) this.rootView.findViewById(R.id.practiceDetailsFragment_TextView_date);
textView.setText(practiceDetails.getDate().toString());
textView = (TextView) this.rootView.findViewById(R.id.practiceDetailsFragment_textView_sends_value);
textView.setText(Integer.toString(practiceDetails.getNumberofSends()));
textView = (TextView) this.rootView.findViewById(R.id.practiceDetailsFragment_textView_maxGrade_value);
textView.setText(practiceDetails.getMaxGrade());
textView = (TextView) this.rootView.findViewById(R.id.practiceDetailsFragment_textView_projectingGrades_value);
textView.setText(practiceDetails.getProjectingGrades()[0]);
textView = (TextView) this.rootView.findViewById(R.id.practiceDetailsFragment_textView_totalHangTime_value);
textView.setText(Integer.toString(practiceDetails.getTotalHangtime()));
textView = (TextView) this.rootView.findViewById(R.id.practiceDetailsFragment_textView_campusSteps_value);
textView.setText(Integer.toString(practiceDetails.getCampusSteps()));
textView = (TextView) this.rootView.findViewById(R.id.practiceDetailsFragment_textView_campusDistance_value);
textView.setText(Double.toString(practiceDetails.getCampusDistance()));
}
private int getPracticeIdFromArguments() {
return getArguments().getInt(ARG_PRACTICE_ID, 1);
}
}
| true
|
a4a9ef45c11ecd1b2a0fbc822cf35f4f461b64fc
|
Java
|
Sonnydiao/CSE2
|
/hw06/GetIntegers.java
|
UTF-8
| 1,740
| 4.1875
| 4
|
[] |
no_license
|
/*Ask the user for 5 non-negative integers (if an invalid value is entered, then ask again,
using a loop), and print out the sum of the 5 integers.
Shuotao Diao, shd314@lehigh.edu*/
import java.util.Scanner;//import Scanner class
public class GetIntegers{//define class name
public static void main(String[] args){//main method
Scanner myScanner = new Scanner( System.in );
//declare new Scanner object
System.out.println("Please enter 5 non-negative integers");
//prompt the user to enter 5 non-negative integers
int i = 0;//initialize counter
int sum = 0, input = 0;//declare sum and input variables
String myString;//declare String which is used to store
//invalid inpuy
//while loop which is used to store 5 integers
while ( i < 5 ){
if ( myScanner.hasNextInt() ){
//determine whether the input is integer
input = myScanner.nextInt();
//store the input
if ( input >=0 ){
//determine whether the input is non-negative
sum += input;
i++;
}//end of if
else{
System.out.println("Invalid input, enter again.");
//display invalid input
}
}//end of if
else{
//input is not integer
myString = myScanner.next();//store invalid input
System.out.println("Invalid input, enter again.");
//display invalid input
}
}//end of while
System.out.println("Sum is " + sum);//print out the sum
}//end of main method
}//end of class
| true
|
ef31f4c61475c16ce1a28e9f049c5d06bd143783
|
Java
|
edwardsayer/kogutowicz
|
/renderer/src/main/java/net/anzix/kogutowicz/TileCoord.java
|
UTF-8
| 1,350
| 3.375
| 3
|
[] |
no_license
|
package net.anzix.kogutowicz;
/**
* Tile coorditation betwwen a tile division.
*
* @author elek
*/
public class TileCoord {
private int x;
private int y;
public TileCoord(int x, int y) {
this.x = x;
this.y = y;
}
public TileCoord(TileCoord curr) {
this.x = curr.getX();
this.y = curr.getY();
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TileCoord other = (TileCoord) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 11 * hash + this.x;
return hash;
}
public TileCoord substract(TileCoord tileCoord) {
return new TileCoord(this.x - tileCoord.getX(), this.y - tileCoord.getY());
}
}
| true
|
283b4b338f885d6755b9c689afe0aeaed7d1407b
|
Java
|
pcaronde/secureshares
|
/applet/src/main/java/ro/panzo/secureshares/util/UploadUserInfo.java
|
UTF-8
| 926
| 2.21875
| 2
|
[] |
no_license
|
package ro.panzo.secureshares.util;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
public class UploadUserInfo implements UserInfo, UIKeyboardInteractive
{
private String password;
public UploadUserInfo(String password)
{
this.password = password;
}
public String getPassphrase()
{
return null;
}
public String getPassword()
{
return this.password;
}
public boolean promptPassword(String msg)
{
return true;
}
public boolean promptPassphrase(String msg)
{
return true;
}
public boolean promptYesNo(String msg)
{
return true;
}
public void showMessage(String msg)
{
}
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
return new String[]{password};
}
}
| true
|
d7940d9a21bdfda60a351a6cc1736676a1bfbdd6
|
Java
|
liujianying/GvaAppNew
|
/javatest/src/main/java/com/javatest/JavaTest.java
|
UTF-8
| 1,269
| 2.25
| 2
|
[] |
no_license
|
package com.javatest;
import com.alibaba.fastjson.JSONObject;
import java.util.concurrent.atomic.AtomicInteger;
public class JavaTest {
static AtomicInteger mSerialNumGenerator = new AtomicInteger(0);
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// Schema schema = new Schema(1, "com.jredu.entity");
// //实体类
// Entity employee = schema.addEntity("Employee");
// employee.addIdProperty(); //主键
// employee.addStringProperty("name");
// employee.addDateProperty("hireDate");
// //生成
// new DaoGenerator()
// .generateAll(schema, "/Users/liujianying/GvaApp/javatest/src/main/java/com/ydh/gva/core");
String region_cd_string = ((int)(134567/100))*100 + "";
JSONObject json = new JSONObject();
json.put("A", "a");
if("aa".contains("a")) {
System.out.println("aaaaaav");
}
long ResidueTime = Long.parseLong("-111");
System.out.println(ResidueTime);
}
/**
* 为每个请求生成一个系列号
*
* @return 序列号
*/
public static int generateSerialNumber() {
return mSerialNumGenerator.incrementAndGet();
}
}
| true
|
8ae1900a6c1ed40f2c9e5501dbb8900a52695c08
|
Java
|
LX1993728/backend
|
/app/models/ExpiredMonths.java
|
UTF-8
| 521
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package models;
import java.util.*;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@DiscriminatorValue("months")
@NamedQueries({
@NamedQuery(
name="queryExpiredMonths",
query="SELECT e FROM ExpiredMonths e WHERE e.months = :months"),
})
public class ExpiredMonths extends Expired {
public int months;
public ExpiredMonths() {
}
public ExpiredMonths(int months) {
super();
this.months = months;
}
}
| true
|
5bb6c94b11475a1c267f3d44ec6b53ddffbadd2f
|
Java
|
jingtao0504/learning
|
/test1/src/main/java/ObserverPattern/java/ConcurrentSubject.java
|
UTF-8
| 538
| 2.953125
| 3
|
[] |
no_license
|
package ObserverPattern.java;
import java.util.Observable;
/**
* @ClassName ConcurrentSubject
* @Description TODO
* @Author 景涛(jingtao@cloud-young.com)
* @Date 2018/6/13 17:48
* Version 1.0
**/
public class ConcurrentSubject extends Observable{
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
//通知之前必须先调用setChange方法
this.setChanged();
this.notifyObservers();
}
}
| true
|
3fe7b990862511ebf91fd2588b2e95a875d50856
|
Java
|
BaldrB/bsuirsibd
|
/src/main/java/by/papkoulad/orgteh/models/UserTech.java
|
UTF-8
| 1,413
| 2.296875
| 2
|
[] |
no_license
|
package by.papkoulad.orgteh.models;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class UserTech{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column
private String fio;
@Column
private Integer number;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "usertech", cascade = CascadeType.ALL)
private List<Technics> usertech;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFio() {
return this.fio;
}
public void setFio(String fio) {
this.fio = fio;
}
public Integer getNumber() {
return this.number;
}
public void setNumber(Integer number) {
this.number = number;
}
public List<Technics> getUsertech() {
return this.usertech;
}
public void setUsertech(List<Technics> usertech) {
this.usertech = usertech;
}
public UserTech() {
}
public UserTech(String fio, Integer number) {
this.fio = fio;
this.number = number;
}
}
| true
|
e1011f3a22a7ae300fb807a4a4abd3953bf34b92
|
Java
|
gxlioper/collections
|
/gratewall/ebaic/src_mobile/com/gwssi/ebaic/mobile/impl/ElicLegMobileServiceImpl.java
|
UTF-8
| 543
| 1.71875
| 2
|
[] |
no_license
|
package com.gwssi.ebaic.mobile.impl;
import org.springframework.stereotype.Service;
import com.gwssi.ebaic.mobile.api.ElicLegMobileService;
@Service(value="elicLegMobileServiceImpl")
public class ElicLegMobileServiceImpl implements ElicLegMobileService {
public String getLegMobile(String accountId) {
// TODO Auto-generated method stub
return null;
}
public void saveLegMobile(String accountId, String oldMobile,
String oldMobileValCode, String newMobile, String newMobileValCode) {
// TODO Auto-generated method stub
}
}
| true
|
3c3643f0ac96c857971eac9e7146801e1d1bdbba
|
Java
|
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
|
/ast_results/koelleChristian_trickytripper/app/src/main/java/de/koelle/christian/trickytripper/strategies/SumAmountStrategy.java
|
UTF-8
| 436
| 1.726563
| 2
|
[] |
no_license
|
// isComment
package de.koelle.christian.trickytripper.strategies;
import java.util.List;
import de.koelle.christian.trickytripper.model.Participant;
import de.koelle.christian.trickytripper.model.Payment;
public interface isClassOrIsInterface {
// isComment
// isComment
// isComment
// isComment
// isComment
void isMethod(SumReport isParameter, List<Participant> isParameter, List<Payment> isParameter);
}
| true
|
d966588cab2014eb9c4a8b2a1439c36eea2d0f03
|
Java
|
miliev/hadoop-samples
|
/src/main/java/com/virtualeleven/wordcount/WordCountMain.java
|
UTF-8
| 1,613
| 2.34375
| 2
|
[] |
no_license
|
package com.virtualeleven.wordcount;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class WordCountMain extends Configured implements Tool {
public int run(String[] args) throws Exception {
Configuration conf = new Configuration();
// fs.default.name seems to be deprecated
conf.set("fs.defaultFS", "192.168.120.100:9000");
conf.set("mapred.job.tracker", "192.168.120.100:9001");
conf.set("fs.default.name", "file:///");
Job job = Job.getInstance(conf, "Word Count");
String[] otherArgs = new GenericOptionsParser(conf, args)
.getRemainingArgs();
job.setCombinerClass(WordCountReducer.class);
job.setReducerClass(WordCountReducer.class);
job.setMapperClass(WordCountMapper.class);
job.setJarByClass(WordCountMain.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
return job.waitForCompletion(true) ? 0 : 1;
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new WordCountMain(), args);
System.exit(exitCode);
}
}
| true
|
f37ed46b1b25b2bd0461f4e9f85382a6a8a3a7a2
|
Java
|
devmanager-oxy/oxyapp_apotek
|
/java/com/project/ccs/posmaster/CmdShift.java
|
UTF-8
| 4,436
| 2.234375
| 2
|
[] |
no_license
|
package com.project.ccs.posmaster;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.project.util.*;
import com.project.main.db.*;
import com.project.main.entity.*;
import com.project.util.jsp.*;
import com.project.util.lang.*;
import com.project.ccs.posmaster.*;
public class CmdShift extends Control implements I_Language
{
public static int RSLT_OK = 0;
public static int RSLT_UNKNOWN_ERROR = 1;
public static int RSLT_EST_CODE_EXIST = 2;
public static int RSLT_FORM_INCOMPLETE = 3;
public static String[][] resultText = {
{"Berhasil", "Tidak dapat diproses", "NoPerkiraan sudah ada", "Data tidak lengkap"},
{"Succes", "Can not process", "Duplicate Entry", "Data incomplete"}
};
private int start;
private String msgString;
private Shift shift;
private DbShift pstShift;
private JspShift jspShift;
int language = LANGUAGE_DEFAULT;
public CmdShift(HttpServletRequest request){
msgString = "";
shift = new Shift();
try{
pstShift = new DbShift(0);
}catch(Exception e){;}
jspShift = new JspShift(request, shift);
}
private String getSystemMessage(int msgCode){
switch (msgCode){
case I_CONExceptionInfo.MULTIPLE_ID :
//this.jspShift.addError(jspShift.JSP_FIELD_shift_id, resultText[language][RSLT_EST_CODE_EXIST] );
return resultText[language][RSLT_EST_CODE_EXIST];
default:
return resultText[language][RSLT_UNKNOWN_ERROR];
}
}
private int getControlMsgId(int msgCode){
switch (msgCode){
case I_CONExceptionInfo.MULTIPLE_ID :
return RSLT_EST_CODE_EXIST;
default:
return RSLT_UNKNOWN_ERROR;
}
}
public int getLanguage(){ return language; }
public void setLanguage(int language){ this.language = language; }
public Shift getShift() { return shift; }
public JspShift getForm() { return jspShift; }
public String getMessage(){ return msgString; }
public int getStart() { return start; }
public int action(int cmd , long oidShift){
msgString = "";
int excCode = I_CONExceptionInfo.NO_EXCEPTION;
int rsCode = RSLT_OK;
switch(cmd){
case JSPCommand.ADD :
break;
case JSPCommand.SAVE :
if(oidShift != 0){
try{
shift = DbShift.fetchExc(oidShift);
}catch(Exception exc){
}
}
jspShift.requestEntityObject(shift);
if(jspShift.errorSize()>0) {
msgString = JSPMessage.getMsg(JSPMessage.MSG_INCOMPLATE);
return RSLT_FORM_INCOMPLETE ;
}
if(shift.getOID()==0){
try{
long oid = pstShift.insertExc(this.shift);
}catch(CONException dbexc){
excCode = dbexc.getErrorCode();
msgString = getSystemMessage(excCode);
return getControlMsgId(excCode);
}catch (Exception exc){
msgString = getSystemMessage(I_CONExceptionInfo.UNKNOWN);
return getControlMsgId(I_CONExceptionInfo.UNKNOWN);
}
}else{
try {
long oid = pstShift.updateExc(this.shift);
}catch (CONException dbexc){
excCode = dbexc.getErrorCode();
msgString = getSystemMessage(excCode);
}catch (Exception exc){
msgString = getSystemMessage(I_CONExceptionInfo.UNKNOWN);
}
}
break;
case JSPCommand.EDIT :
if (oidShift != 0) {
try {
shift = DbShift.fetchExc(oidShift);
} catch (CONException dbexc){
excCode = dbexc.getErrorCode();
msgString = getSystemMessage(excCode);
} catch (Exception exc){
msgString = getSystemMessage(I_CONExceptionInfo.UNKNOWN);
}
}
break;
case JSPCommand.ASK :
if (oidShift != 0) {
try {
shift = DbShift.fetchExc(oidShift);
} catch (CONException dbexc){
excCode = dbexc.getErrorCode();
msgString = getSystemMessage(excCode);
} catch (Exception exc){
msgString = getSystemMessage(I_CONExceptionInfo.UNKNOWN);
}
}
break;
case JSPCommand.DELETE :
if (oidShift != 0){
try{
long oid = DbShift.deleteExc(oidShift);
if(oid!=0){
msgString = JSPMessage.getMessage(JSPMessage.MSG_DELETED);
excCode = RSLT_OK;
}else{
msgString = JSPMessage.getMessage(JSPMessage.ERR_DELETED);
excCode = RSLT_FORM_INCOMPLETE;
}
}catch(CONException dbexc){
excCode = dbexc.getErrorCode();
msgString = getSystemMessage(excCode);
}catch(Exception exc){
msgString = getSystemMessage(I_CONExceptionInfo.UNKNOWN);
}
}
break;
default :
}
return rsCode;
}
}
| true
|
e084d3a37087bfe2a2412a7155a650f593370cbf
|
Java
|
kickUp/dash
|
/src/main/java/controller/json/Courses.java
|
UTF-8
| 1,157
| 2.171875
| 2
|
[] |
no_license
|
package controller.json;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import entity.Course;
import freemarker.log.Logger;
import service.CourseService;
import annotation.Logn;
@Controller("jsonCourses")
@RequestMapping(value = "/json/courses")
public class Courses {
Logger log = Logger.getLogger(Courses.class.getCanonicalName());
@Autowired
CourseService courseService;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public Object getCourses() {
log.info("------- json courses ---------");
List<Course> courses = courseService.getCourses();
log.info("Size: " + courses.size());
return courses;
}
public String toString() {
return "Courses controller class";
}
}
| true
|
fb1c520b0328b451e1fefa6971bc1aacbf70e9f4
|
Java
|
wskyt/carrot2
|
/applications/carrot2-webapp/src/org/carrot2/webapp/filter/QueryWordHighlighter.java
|
UTF-8
| 6,597
| 2.203125
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-bsd-ack-carrot2"
] |
permissive
|
/*
* Carrot2 project.
*
* Copyright (C) 2002-2016, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.webapp.filter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.carrot2.core.Document;
import org.carrot2.core.IControllerContext;
import org.carrot2.core.ProcessingComponentBase;
import org.carrot2.core.ProcessingException;
import org.carrot2.core.attribute.AttributeNames;
import org.carrot2.core.attribute.Init;
import org.carrot2.core.attribute.Internal;
import org.carrot2.core.attribute.Processing;
import org.carrot2.util.attribute.Attribute;
import org.carrot2.util.attribute.Bindable;
import org.carrot2.util.attribute.Input;
import org.carrot2.util.attribute.Output;
import org.carrot2.util.attribute.Required;
import org.carrot2.shaded.guava.common.base.Joiner;
import org.carrot2.shaded.guava.common.base.Strings;
import org.carrot2.shaded.guava.common.collect.Lists;
/**
* Highlights query words in documents using the <b> HTML tag. Highlighting is
* performed on the fields specified in {@link #fields}, the results are saved in fields
* with names suffixed by {@link #HIGHLIGHTED_FIELD_NAME_SUFFIX}.
*/
@Bindable
public class QueryWordHighlighter extends ProcessingComponentBase
{
/**
* Suffix appended
*/
public static final String HIGHLIGHTED_FIELD_NAME_SUFFIX = "-highlight";
/**
* Enable or disable query highlighter.
*/
@Init
@Processing
@Input
@Attribute(key = "QueryWordHighlighter.enabled")
public boolean enabled = true;
/**
* Enable or disable query highlighter.
*/
@Init
@Processing
@Input
@Attribute(key = "QueryWordHighlighter.maxContentLength")
public int maxContentLength = Integer.MAX_VALUE;
/**
* A regular expression that disables highlighting for certain terms.
*/
@Init
@Input
@Attribute(key = "QueryWordHighlighter.dontHighlightPattern")
public String dontHighlightPattern;
private Pattern dontHighlightPatternCompiled;
/**
* Query-sanitize pattern (any matches are replaced with an empty string).
*/
@Init
@Input
@Attribute(key = "QueryWordHighlighter.querySanitizePattern")
public String querySanitizePattern = "[\"'()]";
private Pattern querySanitizePatternCompiled;
/**
* Query that produced the documents, optional. If query is blank, no processing will
* be performed.
*/
@Processing
@Input
@Internal
@Attribute(key = AttributeNames.QUERY)
public String query = null;
/**
* {@link org.carrot2.core.Document}s to highlight query words in.
*/
@Processing
@Input
@Output
@Required
@Internal
@Attribute(key = AttributeNames.DOCUMENTS)
public List<Document> documents;
/**
* Fields of the {@link org.carrot2.core.Document} that should have the query words highlighted.
*/
@Init
@Input
@Attribute
public Collection<String> fields = Arrays.asList(new String []
{
Document.TITLE, Document.SUMMARY
});
@Override
public void init(IControllerContext context)
{
super.init(context);
if (dontHighlightPattern != null) {
dontHighlightPatternCompiled = Pattern.compile(dontHighlightPattern);
}
if (querySanitizePattern != null) {
querySanitizePatternCompiled = Pattern.compile(querySanitizePattern);
}
}
@Override
public void process() throws ProcessingException
{
if (!enabled)
{
return;
}
if (query == null)
{
query = "";
}
// Create regexp patterns for each query word
final String [] queryTerms = querySanitizePatternCompiled
.matcher(query).replaceAll("")
.split("\\s+");
Pattern queryPattern = null;
List<String> patterns = Lists.newArrayList();
for (String queryTerm : queryTerms)
{
if (Strings.isNullOrEmpty(queryTerm))
{
continue;
}
if (dontHighlightPatternCompiled != null &&
dontHighlightPatternCompiled.matcher(queryTerm).matches())
{
continue;
}
patterns.add("(" + Pattern.quote(escapeLtGt(queryTerm)) + ")");
}
if (patterns.size() > 0)
{
queryPattern = Pattern.compile(
Joiner.on("|").join(patterns), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
}
// As we're going to modify documents, we need to copy them to
// avoid ConcurrentModificationExceptions.
final List<Document> inputDocuments = documents;
final List<Document> outputDocuments = Lists
.newArrayListWithCapacity(inputDocuments.size());
for (Document document : inputDocuments)
{
final Document clonedDocument = document.clone();
for (String fieldName : fields)
{
highlightQueryTerms(clonedDocument, fieldName, queryPattern);
}
outputDocuments.add(clonedDocument);
}
documents = outputDocuments;
}
private void highlightQueryTerms(Document document, String fieldName, Pattern queryPattern)
{
String field = (String) document.getField(fieldName);
if (StringUtils.isBlank(field))
{
return;
}
if (field.length() > maxContentLength)
{
field = field.substring(0, maxContentLength) + "...";
}
field = escapeLtGt(field);
if (queryPattern != null) {
Matcher matcher = queryPattern.matcher(field);
field = matcher.replaceAll("<b>$0</b>");
}
document.setField(fieldName + HIGHLIGHTED_FIELD_NAME_SUFFIX, field);
}
private static final Pattern LT_PATTERN = Pattern.compile("<");
private static final Pattern GT_PATTERN = Pattern.compile(">");
private String escapeLtGt(String field)
{
field = LT_PATTERN.matcher(field).replaceAll("<");
field = GT_PATTERN.matcher(field).replaceAll(">");
return field;
}
}
| true
|
9cbb67e2d8036536dc74136fbb3c8eee2a24a452
|
Java
|
Absink/Assisenior
|
/assisenior/src/com/assisenior/model/Room.java
|
UTF-8
| 1,233
| 2.25
| 2
|
[] |
no_license
|
package com.assisenior.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the contact database table.
*
*/
@Entity
@Table(name="room")
@NamedQuery(name="Room.findAll", query="SELECT r FROM Room r")
public class Room implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private int maxDurationOfPresence;
private int timeOfEntry;
private int for_person;
public Room() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMaxDurationOfPresence() {
return maxDurationOfPresence;
}
public void setMaxDurationOfPresence(int maxDurationOfPresence) {
this.maxDurationOfPresence = maxDurationOfPresence;
}
public int getTimeOfEntry() {
return timeOfEntry;
}
public void setTimeOfEntry(int timeOfEntry) {
this.timeOfEntry = timeOfEntry;
}
public int getFor_person() {
return for_person;
}
public void setFor_person(int for_person) {
this.for_person = for_person;
}
}
| true
|
341313f64f1007b531be9de0a41aa513dc847524
|
Java
|
jcansdale/MyORM
|
/src/main/java/com/wangtingzheng/myorm/entity/DatabaseEntity.java
|
UTF-8
| 1,499
| 2.640625
| 3
|
[] |
no_license
|
package com.wangtingzheng.myorm.entity;
import com.wangtingzheng.myorm.exception.TableClassNotFoundException;
import com.wangtingzheng.myorm.reflection.DatabaseReflection;
import java.util.ArrayList;
import java.util.List;
/**
* @author WangTingZheng
* @date 2020/7/8 16:23
* @features
*/
public class DatabaseEntity {
List<TableEntity> tableEntities = new ArrayList<>();
List<Class> tableClasses;
Class database;
public DatabaseEntity(Class database) {
this.database = database;
this.tableClasses = getTablesClass(database);
}
public List<Class> getTableClasses() {
return tableClasses;
}
public List<Class> getTablesClass(Class clazz){
List<Class> tableClazz = new ArrayList<>();
try {
tableClazz = new DatabaseReflection(clazz).getTableClass();
} catch (TableClassNotFoundException e) {
e.printStackTrace();
}
return tableClazz;
}
public DatabaseEntity(List<TableEntity> tableEntities) {
this.tableEntities = tableEntities;
}
public DatabaseEntity() {
}
public List<TableEntity> getTableEntities() {
return tableEntities;
}
public void setTableEntities(List<TableEntity> tableEntities) {
this.tableEntities = tableEntities;
}
public void addTableEntity(TableEntity tableEntity){
tableEntities.add(tableEntity);
}
public int getSize(){
return tableEntities.size();
}
}
| true
|
9c4471f095d9c709f4ed9c0787469e75eb8f08b4
|
Java
|
organization-gu/cloud-alibaba
|
/alibaba-business/user-center/src/main/java/com/lanswon/usercenter/controller/user/BonusController.java
|
UTF-8
| 966
| 2.046875
| 2
|
[] |
no_license
|
package com.lanswon.usercenter.controller.user;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BonusController {
// private final UserService userService;
//
// @PutMapping("/add-bonus")
// public User addBonus(@RequestBody UserAddBonseDTO userAddBonseDTO) {
// Integer userId = userAddBonseDTO.getUserId();
// userService.addBonus(
// UserAddBonusMsgDTO.builder()
// .userId(userId)
// .bonus(userAddBonseDTO.getBonus())
// .description("兑换分享...")
// .event("BUY")
// .build()
// );
// return this.userService.findById(userId);
// }
}
| true
|
6d77c3f89cb8516826aa801d6aeff7ad346983fb
|
Java
|
MaxiGO/RepositorioClub
|
/ProyectoClub/src/ar/com/ProyectoClub/Persistencia/IDao/ICajaDAO.java
|
UTF-8
| 212
| 1.617188
| 2
|
[] |
no_license
|
package ar.com.ProyectoClub.Persistencia.IDao;
import ar.com.ProyectoClub.Dominio.Caja;
import ar.com.ProyectoClub.Persistencia.Dao.IGenericDAO;
public interface ICajaDAO extends IGenericDAO<Caja, Integer> {
}
| true
|
9a618bb80295d10468babb511398a0d5675e0ab2
|
Java
|
224107/trolleyhood
|
/app/src/main/java/com/example/trolleyhood/UserAddress.java
|
UTF-8
| 474
| 2.25
| 2
|
[] |
no_license
|
package com.example.trolleyhood;
import com.google.android.gms.maps.model.LatLng;
public class UserAddress {
public String street, buildingNo, apartmentNo, city;
public LatLng latLng;
public UserAddress(String street, String buildingNo, String apartmentNo, String city, LatLng latLng) {
this.street = street;
this.buildingNo = buildingNo;
this.apartmentNo = apartmentNo;
this.city = city;
this.latLng = latLng;
}
}
| true
|
2629c48a1d14fef25dc0a19edb29d4b004ffdd9f
|
Java
|
MaffezzoIIi/apiSpring
|
/src/main/java/br/com/senai/api/model/EntregaDTO.java
|
UTF-8
| 479
| 1.742188
| 2
|
[] |
no_license
|
package br.com.senai.api.model;
import br.com.senai.domain.model.StatusEntrega;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Setter
@Getter
public class EntregaDTO {
private long id;
private PessoaEntregaDTO pessoa;
private DestinatarioDTO destinatario;
private BigDecimal taxa;
private LocalDateTime dataPedido;
private LocalDateTime dataFinalizado;
private StatusEntrega status;
}
| true
|
d9a54363eed2fedf2007b16bc4833985fa1d4510
|
Java
|
wangzhennan/nio
|
/src/main/java/com/cmcc/syw/Varargs.java
|
UTF-8
| 649
| 2.78125
| 3
|
[] |
no_license
|
package com.cmcc.syw;
import java.util.LinkedList;
import java.util.List;
/**
* Created by sunyiwei on 2016/1/28.
*/
public class Varargs {
private static void test(String... args){
for (String arg : args) {
System.out.println(arg);
}
}
public static void main(String[] args) {
List<String> varargs = new LinkedList<String>();
varargs.add("Hello");
varargs.add("world");
varargs.add("fkdaslkf");
varargs.add("fdaslk");
varargs.add("fujian");
String[] strings = (String[])varargs.toArray(new String[varargs.size()]);
test(strings);
}
}
| true
|
11df51912b9329cbbda27a26da93598cbc9cf613
|
Java
|
syjk129/Travel-Assistant-Planner
|
/src/main/java/edu/gatech/TAP/controller/CreateAccountServlet.java
|
UTF-8
| 4,555
| 2.765625
| 3
|
[] |
no_license
|
package edu.gatech.TAP.controller;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet(urlPatterns={
"/list", // GET
"/create", // POST
"/delete/*" // DELETE
})
public class CreateAccountServlet extends HttpServlet { // JDK 6 and above only
// The doGet() runs once per HTTP GET request to this servlet.
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Get a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");//.newInstance();
// Step 1: Create a database "Connection" object
// For MySQL
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tapdb", "myuser", "xxxx"); // <<== Check
// Step 2: Create a "Statement" object inside the "Connection"
stmt = conn.createStatement();
// add account
int passhash = request.getParameter("Password").hashCode();
String sqlStatement = "insert into account values (" + "'" + request.getParameter("firstName") + "', '"
+ request.getParameter("lastName") + "', '" + request.getParameter("Email") +
"', '" + request.getParameter("Username") + "', '" + passhash + "')";
String findDuplicate = "select * from account where username = '" + request.getParameter("Username") + "'";
ResultSet isDuplicate = stmt.executeQuery(findDuplicate);
String duplicateUser = null;
if(isDuplicate.next()) {
duplicateUser = isDuplicate.getString("username");
}
if(duplicateUser == null){
int rset = stmt.executeUpdate(sqlStatement);// Send the query to the server
response.sendRedirect("indexAccountCreated.jsp");
// out.println("<html>");
// out.println("<head>");
// out.println("<title>TAP: Travel Advisor & Planner</title>");
// out.println("<link rel=\"stylesheet\"; href=\"box.css\">");
// out.println("</head>");
//
// out.println("<body bgcolor=white>");
//
// out.println("<table border=\"0\" cellpadding=\"10\" align=\"center\">");
// out.println("<tr>");
// out.println("<td align=center>");
// out.println("<img src=\"tapIcon.jpg\">");
// out.println("</td>");
// out.println("<td style=\"text-align: center;\">");
//
// out.println("<h2>Account Created!</h2>");
// out.println("</td>");
// out.println("</tr>");
// out.println("</table>");
} else {
out.println("<html>");
out.println("<head>");
out.println("<title>TAP: Travel Advisor & Planner</title>");
out.println("<link rel=\"stylesheet\"; href=\"box.css\">");
out.println("</head>");
out.println("<body bgcolor=white>");
out.println("<table border=\"0\" cellpadding=\"10\" align=\"center\">");
out.println("<tr>");
out.println("<td align=center>");
out.println("<img src=\"tapIcon.jpg\">");
out.println("</td>");
out.println("<td style=\"text-align: center;\">");
out.println("<h2>User Account Already Exists Please Try Again.</h2>");
out.println("</td>");
out.println("</tr>");
out.println("</table>");
}
//get new page
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("index.html");
dispatcher.forward(request,response);
} catch (SQLException ex) {
ex.printStackTrace();
out.println(ex);
} catch (Exception cex) { //ClassNotFoundException
cex.printStackTrace();
} finally {
out.close();
try {
// Step 5: Close the Statement and Connection
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
| true
|
93447e2a5f9be967e3ed29b4ea4849a9590ab175
|
Java
|
YashMathur1/ccinapp
|
/ccinapp/src/net/jpa/repository/JPAVWTrafficRouting.java
|
UTF-8
| 522
| 1.898438
| 2
|
[] |
no_license
|
package net.jpa.repository;
import net.persist.bean.VWTrafficRouting;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface JPAVWTrafficRouting extends JpaRepository<VWTrafficRouting, Long>{
@Query("select b from VWTrafficRouting b where b.trafiicRoutingId=:trafiicRoutingId")
VWTrafficRouting findVWTrafficRoutingByTraffingId(@Param("trafiicRoutingId")Integer trafiicRoutingId);
}
| true
|
163d3747064047adb5b72ebc55cdef83926916df
|
Java
|
buaaabs/BotServer
|
/src/hha/aiml/BotEmotion.java
|
UTF-8
| 3,376
| 2.53125
| 3
|
[] |
no_license
|
package hha.aiml;
import bitoflife.chatterbean.AliceBot;
public class BotEmotion {
Robot bot;
int vitality; // 活跃度 困倦-兴奋
int happiness; // 快乐度 忧伤-快乐
int confidence;// 置信度 不确定-确定
int mighty; // 强势度 恐惧-愤怒
// 范围均是0~10000
// 性格 情感变化率? 0-1000%
int vitality_d;
int happiness_d;
int confidence_d;
int mighty_d;
// 不确定性 百分比 0-1000%
int vitality_u;
int happiness_u;
int confidence_u;
int mighty_u;
public void init(Robot _bot) {
bot = _bot;
vitality = (int) (N_rand(5000.0, 50.0) + 0.5);
happiness = (int) (N_rand(5000.0, 50.0) + 0.5);
confidence = (int) (N_rand(5000.0, 50.0) + 0.5);
mighty = (int) (N_rand(5000.0, 50.0) + 0.5);
vitality_d = (int) (N_rand(80.0, 5.0) + 0.5);
happiness_d = (int) (N_rand(80.0, 5.0) + 0.5);
confidence_d = (int) (N_rand(80.0, 5.0) + 0.5);
mighty_d = (int) (N_rand(80.0, 5.0) + 0.5);
vitality_u = (int) (N_rand(15.0, 9.0) + 0.5);
happiness_u = (int) (N_rand(15.0, 9.0) + 0.5);
confidence_u = (int) (N_rand(15.0, 9.0) + 0.5);
mighty_u = (int) (N_rand(15.0, 9.0) + 0.5);
}
public void UpdateEmotion()
{
bot.setProperty("Emotion", "");
}
public int normalization(int value) {
if (value < 0)
return 0;
if (value > 10000)
return 10000;
return value;
}
public int getVitality() {
return vitality;
}
public void setVitality(int vitality) {
this.vitality = normalization(vitality);
}
public void changeVitality(int vitality) {
this.vitality += normalization(vitality) * vitality_d * 0.01;
this.vitality += normalization(vitality) * vitality_u
* N_rand(0, 1) * 0.01;
this.vitality = normalization(this.vitality);
}
public int getHappiness() {
return happiness;
}
public void setHappiness(int happiness) {
happiness = normalization(happiness);
}
public void changeHappiness(int happiness) {
this.happiness += normalization(happiness) * happiness_d * 0.01;
this.happiness += normalization(happiness) * happiness_u
* N_rand(0, 1) * 0.01;
this.happiness = normalization(this.happiness);
}
public int getConfidence() {
return confidence;
}
public void setConfidence(int confidence) {
this.confidence = normalization(confidence);
}
public void changeConfidence(int confidence) {
this.confidence += normalization(confidence) * confidence_d
* 0.01;
this.confidence += normalization(confidence) * confidence_u
* N_rand(0, 1) * 0.01;
this.confidence = normalization(this.confidence);
}
public int getMighty() {
return mighty;
}
public void setMighty(int mighty) {
this.mighty = normalization(mighty);
}
public void changeMighty(int mighty) {
this.mighty += normalization(mighty) * mighty_d * 0.01;
this.mighty += normalization(mighty) * mighty_u * N_rand(0, 1)
* 0.01;
this.mighty = normalization(this.mighty);
}
static java.util.Random r = new java.util.Random();
// 正态分布随机数产生
public static double N_rand(double miu, double sigma2) {
return r.nextGaussian() * Math.sqrt(sigma2) + miu;
}
// 泊松分布随机数的产生,代码如下: (未测试)
public static double P_rand(double Lamda) { // 泊松分布
double x = 0, b = 1, c = Math.exp(-Lamda), u;
do {
u = Math.random();
b *= u;
if (b >= c)
x++;
} while (b >= c);
return x;
}
}
| true
|
dfbce36eb7133bab2184a8f2920356680c0fd67b
|
Java
|
N-Nandhitha/Rewards-Program
|
/rewardpointapp/src/main/java/com/bskm/springboot/model/Message.java
|
UTF-8
| 1,041
| 2.484375
| 2
|
[] |
no_license
|
package com.bskm.springboot.model;
import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonFormat;
public class Message {
String errorId;
String message;
String type;
@JsonFormat(pattern = "dd/MM/yyyy hh:mm:ss a")
private LocalDateTime timeStamp;
public Message(String errorId, String message, String type, LocalDateTime timeStamp) {
super();
this.errorId = errorId;
this.message = message;
this.type = type;
this.timeStamp = timeStamp;
}
public String getErrorId() {
return errorId;
}
public void setErrorId(String errorId) {
this.errorId = errorId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public LocalDateTime getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(LocalDateTime timeStamp) {
this.timeStamp = timeStamp;
}
}
| true
|
fe25b007925e8c7a6e5da7c961239b41714c4a45
|
Java
|
madang01/gitcodda
|
/codda2/core/common/src/main/java/kr/pe/codda/common/message/builder/info/MessageArrayInfo.java
|
UTF-8
| 6,302
| 2.4375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package kr.pe.codda.common.message.builder.info;
import kr.pe.codda.common.type.MessageItemInfoType;
/**
* 배열 정보 클래스. 배열 이름, 배열 크기, 배열에 속한 항목 그룹 정보를 가지고 있다.
*
* @author Won Jonghoon
*
*/
public class MessageArrayInfo extends AbstractMessageItemInfo {
private OrderedMessageItemSet orderedItemSet = new OrderedMessageItemSet();
private String arrayName = null;
private String arrayFirstUpperName = null;
/**
* 배열의 반복 횟수 지정 방식(cnttype)은 2가지가 있다.<br/>
* (1) 직접(direct) : 고정 크기 지정방식으로 배열 반복 횟수에는 배열의 반복 횟수 값이 저장되며,<br/>
* (2) 참조(reference) : 가변 크기 지정방식으로 배열 반복 횟수는 참조하는 항목의 값이다.
*/
private String arrayCntType = null;
/**
* 배열의 반복 횟수(cntvalue) "배열의 반복 횟수 지정 방식"이 직접(direct) 이면 배열 반복 횟수를 반환하며,<br/>
* 참조(reference)일 경우에는 참조하는 항목 이름을 반환한다.<br/>
* 참조하는 항목은 숫자형으로 배열과 같은 단계로 반듯이 앞에 나와야 한다.<br/>
* 이렇게 앞에 나와야 하는 이유는 배열 정보를 읽어와서 <br/>
* 배열 정보를 저장하기 전에 참조 변수가 같은 레벨에서 존재하며 숫자형인지 판단을 하기 위해서이다.<br/>
* 메시지 정보 파일을 순차적으로 읽기 때문에 배열 뒤에 위치하면 알 수가 없다
*/
private String arrayCntValue = null;
/**
* 생성자
*
* @param arrayName
* 배열 이름
* @param arrayCntType
* 배열의 반복 횟수 지정 방식
* @param arrayCntValue
* 배열 반복 횟수
*/
public MessageArrayInfo(String arrayName, String arrayCntType, String arrayCntValue) throws IllegalArgumentException {
if (null == arrayName) {
throw new IllegalArgumentException("the parmamter arrayName is null");
}
if (null == arrayCntType) {
throw new IllegalArgumentException("the parmamter arrayCntType is null");
}
if (null == arrayCntValue) {
throw new IllegalArgumentException("the parmamter arrayCntValue is null");
}
if (arrayName.length() < 2) {
String errorMessage = new StringBuilder()
.append("the number[")
.append(arrayName.length())
.append("] of character of the parameter arrayName is less than two").toString();
throw new IllegalArgumentException(errorMessage);
}
if (arrayCntType.equals("direct")) {
int arrayCount = -1;
if (null != arrayCntValue) {
try {
arrayCount = Integer.parseInt(arrayCntValue);
} catch (NumberFormatException num_e) {
String errorMessage = new StringBuilder("fail to parses the string argument(=this array item[")
.append(arrayName).append("]'s attribute 'cntvalue' value[")
.append(arrayCntValue).append("]) as a signed decimal integer")
.append("").toString();
throw new IllegalArgumentException(errorMessage);
}
}
if (arrayCount <= 0) {
String errorMessage = new StringBuilder("this array item[")
.append(arrayName).append("]'s attribute 'cntvalue' value[")
.append(arrayCntValue).append("] is less than or equals to zero")
.append("").toString();
throw new IllegalArgumentException(errorMessage);
}
} else if (arrayCntType.equals("reference")) {
/** nothing */
} else {
String errorMessage = new StringBuilder("this array item[")
.append(arrayName).append("]'s attribute 'cnttype' value[")
.append(arrayCntType).append("] is not an element of direction set[direct, reference]").toString();
throw new IllegalArgumentException(errorMessage);
}
this.arrayName = arrayName;
this.arrayFirstUpperName = arrayName.substring(0, 1).toUpperCase() + arrayName.substring(1);
this.arrayCntType = arrayCntType;
this.arrayCntValue = arrayCntValue;
}
/**
* 배열의 반복 횟수 지정 방식을 반환한다.
*
* @return 배열의 반복 횟수 지정 방식
*/
public String getArrayCntType() {
return arrayCntType;
}
/**
* 배열 반복 횟수를 반환한다.
*
* @return 배열 반복 횟수
*/
public String getArrayCntValue() {
return arrayCntValue;
}
/**
* 배열 이름을 반환한다.
*
* @return 배열 이름
*/
public String getArrayName() {
return arrayName;
}
@Override
public String getFirstUpperItemName() {
return arrayFirstUpperName;
}
public OrderedMessageItemSet getOrderedItemSet() {
return orderedItemSet;
}
/******************* AbstractItemInfo start ***********************/
@Override
public String getItemName() {
return arrayName;
}
@Override
public MessageItemInfoType getMessageItemInfoType() {
return MessageItemInfoType.ARRAY;
}
/******************* AbstractItemInfo end ***********************/
@Override
public String toString() {
StringBuffer strBuff = new StringBuffer();
strBuff.append("{ arrayName=[");
strBuff.append(arrayName);
strBuff.append("], arrayCntType=[");
strBuff.append(arrayCntType);
strBuff.append("], arrayCntValue=[");
strBuff.append(arrayCntValue);
strBuff.append("], {");
strBuff.append(orderedItemSet.toString());
strBuff.append("}}");
return strBuff.toString();
}
}
| true
|
4da278d36173ab9941087ee81a3dfe8598925327
|
Java
|
Ikos3k/VirtualMachine
|
/src/main/java/me/ANONIMUS/jvm/interfaces/JVMOpcodes.java
|
UTF-8
| 604
| 1.742188
| 2
|
[] |
no_license
|
package me.ANONIMUS.jvm.interfaces;
public interface JVMOpcodes {
byte IGNORE = -1;
byte CLEAR_CACHE = 0;
byte ADD = 1;
byte SUB = 2;
byte MUL = 3;
byte DIV = 4;
byte REM = 5;
byte XOR = 6;
byte OR = 7;
byte LT = 8;
byte EQ = 9;
byte LOAD = 13;
byte STORE = 14;
byte RETURN = 15;
byte NEGATIVE = 16;
byte LDC = 18;
//native methods
byte PRINT = 19;
byte LENGTH = 20;
byte TO_LOWERCASE = 21;
byte TO_UPPERCASE = 22;
byte STR_REVERSE = 23;
byte TO_STRING = 24;
byte TO_NUMBER = 25;
byte HASHCODE = 26;
}
| true
|
8d9b072c71286a5ed5301954ba7fdec269d25c6a
|
Java
|
AlKaliada/Java_Basics_UpSkill_Lab_1
|
/src/com/epam/kaliada/oop/task2/Main.java
|
UTF-8
| 623
| 2.90625
| 3
|
[] |
no_license
|
package com.epam.kaliada.oop.task2;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
Product apples = new Product("apple", 2.99, 7);
Product oranges = new Product("orange", 3.45, 5);
Payment payment = new Payment();
payment.addProduct(apples);
payment.addProduct(oranges);
System.out.println(payment.findTheAmountToPay());
Payment.Transaction transaction = payment.new Transaction();
transaction.payByCash(17);
transaction.payByCreditCard(21.17);
transaction.payByCreditCard();
}
}
| true
|
1853ccd9cb83a066dbb7508443ff664a7cb42a95
|
Java
|
lamianlbe/mangosta-android
|
/app/src/main/java/inaka/com/mangosta/utils/TimeCalculation.java
|
UTF-8
| 3,003
| 2.59375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
package inaka.com.mangosta.utils;
import android.content.Context;
import android.support.annotation.VisibleForTesting;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Duration;
import org.joda.time.Period;
import java.util.Date;
import java.util.Locale;
import inaka.com.mangosta.R;
public class TimeCalculation {
public static String getTimeStringAgoSinceDate(Context context, Date date) {
DateTime postDate = new DateTime(date, DateTimeZone.getDefault());
return getTimeStringAgoSinceDateTime(context, postDate);
}
private static String getTimeStringAgoSinceDateTime(Context context, DateTime dateTime) {
DateTime now = new DateTime(DateTimeZone.getDefault());
Period period = new Period(dateTime, now);
String date;
int count;
if (period.getYears() >= 1) {
date = context.getResources().getQuantityString(R.plurals.date_years_ago, period.getYears());
count = period.getYears();
} else if (period.getMonths() >= 1) {
date = context.getResources().getQuantityString(R.plurals.date_months_ago, period.getMonths());
count = period.getMonths();
} else if (period.getWeeks() >= 1) {
date = context.getResources().getQuantityString(R.plurals.date_weeks_ago, period.getWeeks());
count = period.getWeeks();
} else if (period.getDays() >= 1) {
date = context.getResources().getQuantityString(R.plurals.date_days_ago, period.getDays());
count = period.getDays();
} else if (period.getHours() >= 1) {
date = context.getResources().getQuantityString(R.plurals.date_hours_ago, period.getHours());
count = period.getHours();
} else if (period.getMinutes() >= 1) {
date = context.getResources().getQuantityString(R.plurals.date_minutes_ago, period.getMinutes());
count = period.getMinutes();
} else if (period.getSeconds() >= 3) {
date = String.format(Locale.getDefault(), context.getString(R.string.date_seconds_ago), period.getSeconds());
count = period.getSeconds();
} else {
return " " + context.getString(R.string.date_seconds_now);
}
return String.format(Locale.getDefault(), date, count);
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
static boolean isMinutesDiffMax(DateTime dateTime1, DateTime dateTime2, int maxMinutes) {
Period period = new Period(dateTime1, dateTime2);
Duration duration = period.toDurationFrom(dateTime1);
return Math.abs(duration.toStandardMinutes().getMinutes()) <= maxMinutes;
}
public static boolean wasMinutesAgoMax(Date date, int maxMinutes) {
DateTime now = new DateTime(DateTimeZone.getDefault());
DateTime dateTime = new DateTime(date, DateTimeZone.getDefault());
return isMinutesDiffMax(dateTime, now, maxMinutes);
}
}
| true
|
b5c2185b201f08f5bf8b6318f6d4b02e47b7e148
|
Java
|
Bronski/ExtraHardMode
|
/src/me/ryanhamshire/ExtraHardMode/BlockPhysicsCheckTask.java
|
UTF-8
| 1,737
| 2.859375
| 3
|
[] |
no_license
|
package me.ryanhamshire.ExtraHardMode;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
public class BlockPhysicsCheckTask implements Runnable {
Block block;
int recursionCount;
public BlockPhysicsCheckTask(Block block, int recursionCount)
{
this.block = block;
this.recursionCount = recursionCount;
}
@Override
public void run()
{
block = block.getWorld().getBlockAt(block.getLocation());
boolean fall = false;
Material material = block.getType();
if( (block.getRelative(BlockFace.DOWN).getType() == Material.AIR || block.getRelative(BlockFace.DOWN).isLiquid() || block.getRelative(BlockFace.DOWN).getType() == Material.TORCH) &&
(material == Material.SAND || material == Material.GRAVEL || ExtraHardMode.instance.config_moreFallingBlocks.contains(material)))
{
ExtraHardMode.applyPhysics(block);
fall = true;
}
if(fall || this.recursionCount == 0)
{
if(recursionCount < 10)
{
Block neighbor = block.getRelative(BlockFace.UP);
ExtraHardMode.physicsCheck(neighbor, recursionCount + 1, false);
neighbor = block.getRelative(BlockFace.DOWN);
ExtraHardMode.physicsCheck(neighbor, recursionCount + 1, false);
neighbor = block.getRelative(BlockFace.EAST);
ExtraHardMode.physicsCheck(neighbor, recursionCount + 1, false);
neighbor = block.getRelative(BlockFace.WEST);
ExtraHardMode.physicsCheck(neighbor, recursionCount + 1, false);
neighbor = block.getRelative(BlockFace.NORTH);
ExtraHardMode.physicsCheck(neighbor, recursionCount + 1, false);
neighbor = block.getRelative(BlockFace.SOUTH);
ExtraHardMode.physicsCheck(neighbor, recursionCount + 1, false);
}
}
}
}
| true
|
601cb8ee6222becab3a87ae4de49adcb3bc4a72b
|
Java
|
sefafard/SimpleRealApp
|
/Manager.java
|
UTF-8
| 852
| 3.21875
| 3
|
[] |
no_license
|
public class Manager extends Employee implements primWork {
public static int mgrWorkHrsPerWeek = 50;
public static int mgrBreakHrsPerWeek = 10;
Manager (String job, int workHrsPerWeek, int breakHrsPerWeek) {
super (job, mgrWorkHrsPerWeek, mgrBreakHrsPerWeek);
workHrsPerWeek = mgrWorkHrsPerWeek;
breakHrsPerWeek = mgrBreakHrsPerWeek;
// System.out.printf("Manager constructor for job %s with hrs/wk = %d and breakhrs = %d\n", job, workHrsPerWeek, breakHrsPerWeek);
}
// methods
public void primaryWork() {
System.out.println("My job is: "+ job +".");
System.out.println("I primarily supervise others' work.");
// System.out.println("I work aproximately "+workHrsPerWeek+" hours per week and am allowed breaks for up to "+breakHrsPerWeek+ " hours per week.");
}
}
| true
|
cbc6c598eec0f792584e6ffa96c25f30a0482384
|
Java
|
MyGithub-wu/LearnWebservice
|
/Server_CXF_Spring/src/wxj/ws/Interector/CheckUserInterector.java
|
GB18030
| 1,105
| 2.296875
| 2
|
[] |
no_license
|
package wxj.ws.Interector;
import javax.xml.namespace.QName;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;
public class CheckUserInterector extends AbstractPhaseInterceptor<SoapMessage> {
public CheckUserInterector() {
super(Phase.PRE_PROTOCOL);
// TODO Auto-generated constructor stub
}
@Override
public void handleMessage(SoapMessage msg) throws Fault {
Header header=msg.getHeader(new QName("head"));
Element head=(Element) header.getObject();
String name=head.getElementsByTagName("name").item(0).getTextContent();
String password =head.getElementsByTagName("password").item(0).getTextContent();
if("wuxiaojing".equals(name) && "123456".equals(password)) {
System.out.println("Server ͨ");
return;
}
System.out.println("Server ûͨ");
throw new Fault(new RuntimeException("һȷû"));
}
}
| true
|
ca053af0e6b5be1a58e2f9e30578079a1c595931
|
Java
|
sesto/HomeArchive
|
/src/main/java/be/ordina/sest/homearchive/service/FileService.java
|
UTF-8
| 1,584
| 2.21875
| 2
|
[] |
no_license
|
package be.ordina.sest.homearchive.service;
/**
* Service downloads, uploads and modifies files
*/
import java.io.IOException;
import java.util.List;
import be.ordina.sest.homearchive.model.RequestResponseDocument;
import be.ordina.sest.homearchive.model.UploadDocument;
import com.mongodb.gridfs.GridFSDBFile;
public interface FileService {
/**
* Downloads file by id
*
* @param downloadDocument query document {@link be.ordina.sest.homearchive.model.RequestResponseDocument}
* @return GridFSDBFile
* @throws IOException
*/
GridFSDBFile downloadFileById(final RequestResponseDocument downloadDocument) throws IOException;
/**
*
* Searches for documents in db
*
* @param document query document {@link be.ordina.sest.homearchive.model.RequestResponseDocument}
* @return {@link RequestResponseDocument}
*/
List<RequestResponseDocument> findDocuments(final RequestResponseDocument document);
/**
*
* Uploads file
*
* @param document {@link UploadDocument}
* @throws IOException
*/
void uploadFile(final UploadDocument document) throws IOException;
/**
*
* Uploads file
*
* @param id id of the document
*/
public void deleteDocument(final String id);
/**
*
* udates metadata
*
* @param id id of the document
* @param document {@link be.ordina.sest.homearchive.model.RequestResponseDocument}
*/
RequestResponseDocument updateDocument(final String id, final RequestResponseDocument document);
}
| true
|
41f7905bb064c4741bd2b5fe4c5c180050ac0c61
|
Java
|
dector/ure
|
/src/main/java/ure/ui/panels/StatusPanel.java
|
UTF-8
| 2,066
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
package ure.ui.panels;
import com.google.common.eventbus.Subscribe;
import ure.math.UColor;
import ure.render.URenderer;
import ure.sys.events.TimeTickEvent;
import java.util.HashMap;
public class StatusPanel extends UPanel {
int textRows,textColumns;
int charWidth, charHeight;
HashMap<String,TextFrag> texts;
public StatusPanel(int padx, int pady, UColor fg, UColor bg, UColor borderc) {
super(padx,pady,fg,bg,borderc);
bus.register(this);
texts = new HashMap<String,TextFrag>();
charWidth = config.getTextWidth();
charHeight = config.getTextHeight();
textRows = (pixelw-padx) / config.getTextWidth();
textColumns = (pixelh-pady) / config.getTextHeight();
}
public void addText(String name, String text, int row, int col) {
addTextFrag(new TextFrag(name, text, row, col, fgColor));
}
public void addText(String name, String text, int row, int col, UColor color) {
addTextFrag(new TextFrag(name, text, row, col, color));
}
void addTextFrag(TextFrag frag) {
texts.put(frag.name, frag);
}
public void setText(String name, String text) {
TextFrag frag = texts.get(name);
frag.text = text;
}
@Override
public void drawContent() {
renderer.setFont(URenderer.FontType.TEXT_FONT);
for (String textName : texts.keySet()) {
TextFrag frag = texts.get(textName);
renderer.drawString(frag.row * charWidth + padX, (frag.col + 1) * charHeight + padY, frag.color, frag.text);
}
renderer.setFont(URenderer.FontType.TILE_FONT);
}
@Subscribe
public void hearTimeTick(TimeTickEvent event) {
if (commander.player() != null) {
setText("turn", "turn " + Integer.toString(event.turn));
setText("time", commander.timeString(true, " "));
setText("location", commander.cartographer.describeLabel(commander.player().area().getLabel()));
setText("name", commander.player().getName());
}
}
}
| true
|
afb96105bef18d4867f03ad02b8fc018ad916388
|
Java
|
mwong56/ScreenResolutionChanger
|
/app/src/main/java/com/brianvalente/screenresolutionchanger/widget/BottomNavigationBar.java
|
UTF-8
| 2,524
| 2.203125
| 2
|
[] |
no_license
|
package com.brianvalente.screenresolutionchanger.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.brianvalente.screenresolutionchanger.R;
import java.util.ArrayList;
/**
* Created by brianvalente on 7/19/16.
*/
public class BottomNavigationBar extends LinearLayout {
private Context mContext;
private AttributeSet mAttributeSet;
private BottomNavigationBarItem mActualItem;
private ArrayList<BottomNavigationBarItem> mItems = new ArrayList<>();
private int mDefaultItemId;
public BottomNavigationBar(Context context) {
super(context);
init(context);
}
public BottomNavigationBar(Context context, AttributeSet attrs) {
super(context, attrs);
mAttributeSet = attrs;
init(context);
}
public BottomNavigationBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mAttributeSet = attrs;
init(context);
}
public BottomNavigationBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mAttributeSet = attrs;
init(context);
}
private void init(Context ctx) {
mContext = ctx;
if (mAttributeSet != null) {
TypedArray a = mContext.obtainStyledAttributes(mAttributeSet, R.styleable.BottomNavigationBar);
mDefaultItemId = a.getResourceId(R.styleable.BottomNavigationBar_bnb_defaultItem, 0);
a.recycle();
}
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
for (int i = 0; i < getChildCount(); i++) {
BottomNavigationBarItem item = (BottomNavigationBarItem) getChildAt(i);
mItems.add(item);
}
mActualItem = (BottomNavigationBarItem) findViewById(mDefaultItemId);
if (mActualItem == null) mActualItem = mItems.get(0);
mActualItem.setActiveInanimated();
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
}
| true
|
31646a3cdb03b06ee08f6746aebd50a5533edc33
|
Java
|
zhanglubin721/hms
|
/provider-service/src/main/java/com/wuyaofei/providerservice/controller/UserController.java
|
UTF-8
| 723
| 1.945313
| 2
|
[] |
no_license
|
package com.wuyaofei.providerservice.controller;
import com.wuyaofei.providerservice.service.TestUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private TestUserService testUserService;
@GetMapping("/findUsernameById/{id}")
public String findUsernameById(@PathVariable("id") Long id) {
return testUserService.findUsernameById(id);
}
}
| true
|
c38f6909cbb748fcb09307264862fe9801fabb30
|
Java
|
dj49846917/studyJava
|
/day20/code/FileTest.java
|
UTF-8
| 1,236
| 3.75
| 4
|
[] |
no_license
|
package com.itheima_02;
import java.io.File;
/*
* 需求: 输出指定目录下的所有java文件名(包含子目录)
*
*/
public class FileTest {
public static void main(String[] args) {
// File f = new File("src\\com\\itheima");
// File f = new File("src\\com\\itheima\\FileDemo.java"); // 用这个会报错
// method2(f);
File f2 = new File("src");
method(f2);
}
public static void method(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File item : files) {
// 判断是否是文件
if (item.isFile()) {
// 判断是否是Java文件
if (item.getName().endsWith(".java")) {
System.out.println(item.getName());
}
}else{
// 是一个目录对象
method(item);
}
}
}
}
// 输出指定目录下的所有java文件名(不包含子目录)
public static void method2(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File item : files) {
// 判断是否是文件
if (item.isFile()) {
// 判断是否是Java文件
if (item.getName().endsWith(".java")) {
System.out.println(item.getName());
}
}
}
}
}
}
| true
|
87a4fb69cb5c962a134799680268f170dd2a66ad
|
Java
|
RealgodJJ/IMTao
|
/app/src/main/java/reagodjj/example/com/imtao/adapter/MainMenuAdapter.java
|
UTF-8
| 1,917
| 2.28125
| 2
|
[] |
no_license
|
package reagodjj.example.com.imtao.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import reagodjj.example.com.imtao.R;
import reagodjj.example.com.imtao.entity.MainFragmentMainMenu;
public class MainMenuAdapter extends RecyclerView.Adapter<MainMenuViewHolder> {
private Context context;
private List<MainFragmentMainMenu> mainFragmentMenus;
public MainMenuAdapter(Context context, List<MainFragmentMainMenu> mainFragmentMenus) {
this.context = context;
this.mainFragmentMenus = mainFragmentMenus;
}
@SuppressLint("InflateParams")
@NonNull
@Override
public MainMenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new MainMenuViewHolder(LayoutInflater.from(context)
.inflate(R.layout.fragment_main_main_menu_item, null));
}
@Override
public void onBindViewHolder(@NonNull MainMenuViewHolder holder, int position) {
MainFragmentMainMenu mainFragmentMenu = mainFragmentMenus.get(position);
holder.ivMenuIcon.setImageResource(mainFragmentMenu.getIcon());
holder.tvItemName.setText(mainFragmentMenu.getItemName());
}
@Override
public int getItemCount() {
return mainFragmentMenus != null ? mainFragmentMenus.size() : 0;
}
}
class MainMenuViewHolder extends RecyclerView.ViewHolder {
ImageView ivMenuIcon;
TextView tvItemName;
MainMenuViewHolder(View itemView) {
super(itemView);
ivMenuIcon = itemView.findViewById(R.id.iv_main_item_icon);
tvItemName = itemView.findViewById(R.id.tv_main_item_name);
}
}
| true
|
c1fb04069476dd33bab0f52fcc222d0cb68be19b
|
Java
|
HelgaSigga/Pipes
|
/app/src/main/java/com/example/quima/pipes/SQliteHelper.java
|
UTF-8
| 1,421
| 2.703125
| 3
|
[] |
no_license
|
package com.example.quima.pipes;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* Created by Quima on 12/02/2015.
*/
class SQLiteHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "valves.db";
public static final int DATABASE_VERSION = 1;
private boolean databaseInitialized;
public SQLiteHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
databaseInitialized = true;
}
@Override
public void onCreate(SQLiteDatabase database){
database.execSQL(ValveTable.createStatement());
database.execSQL(ValveTypeTable.createStatement());
databaseInitialized = false;
}
public boolean isInitialized(){
return databaseInitialized;
}
public void databaseHasBeenInitialized(){
databaseInitialized = true;
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion){
Log.w(SQLiteHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS " + ValveTable.getTableName());
database.execSQL("DROP TABLE IF EXISTS " + ValveTypeTable.getTableName());
onCreate(database);
}
}
| true
|
98dc26b4f8e4149ad6b70f27740505b156da0298
|
Java
|
henrycm/Spring-JSF-Mongo
|
/src/main/java/com/mongo/seguridad/vista/UserMB.java
|
UTF-8
| 4,854
| 2.109375
| 2
|
[] |
no_license
|
package com.mongo.seguridad.vista;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.primefaces.event.RowEditEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mongo.seguridad.modelo.Permission;
import com.mongo.seguridad.modelo.Role;
import com.mongo.seguridad.modelo.User;
import com.mongo.seguridad.service.SeguridadService;
@Component
@ViewScoped
public class UserMB implements Serializable {
private static final long serialVersionUID = 1L;
private Logger logger = Logger.getLogger(UserMB.class);
@Autowired
private SeguridadService bo;
private User usr = new User();
private Role role = new Role();
private Permission permission = new Permission();
private List<Role> roles;
private List<User> users;
private List<Permission> permissions;
private List<String> selected_roles;
private List<String> selected_permissions;
@PostConstruct
public void init() {
roles = bo.listRoles();
users = bo.listUser();
permissions = bo.listPermissions();
logger.debug("No. Usuarios:" + users.size());
}
public void addRole() {
setRole(new Role());
}
public void addUsr() {
setUsr(new User());
}
public void addPermission() {
permission = new Permission();
}
public void guardar() {
usr.setRoles(new ArrayList<Role>());
for (String s : selected_roles)
for (Role r : roles) {
if (r.getId().equals(s)) {
usr.getRoles().add(r);
break;
}
}
bo.saveUser(usr);
users = bo.listUser();
}
public void eliminarUsr(User u) {
bo.deleteUser(u);
users = bo.listUser();
crearMensaje("Eliminar", "Usuario eliminado:" + u.getUsername());
}
public void guardarRole() {
role.setPermissions(new ArrayList<Permission>());
for (String s : selected_permissions)
for (Permission p : permissions) {
if (p.getId().equals(s)) {
role.getPermissions().add(p);
break;
}
}
try {
bo.saveRole(role);
roles = bo.listRoles();
} catch (Exception e) {
logger.warn(e);
crearMensaje("Guardar", e.getMessage());
}
}
public void eliminarRole(Role r) {
try {
bo.deleteRole(r);
roles = bo.listRoles();
crearMensaje("Eliminar", "Role eliminado:" + r.getName());
} catch (Exception e) {
logger.warn(e);
crearMensaje("Eliminar", e.getMessage());
}
}
public void eliminarPermission(Permission p) {
try {
bo.deletePermission(p);
permissions = bo.listPermissions();
crearMensaje("Eliminar", "Permiso eliminado:" + p.getName());
} catch (Exception e) {
logger.warn(e);
crearMensaje("Eliminar", e.getMessage());
}
}
public void onRowEdit(RowEditEvent event) {
permission = (Permission) event.getObject();
guardarPermission();
}
public void guardarPermission() {
try {
bo.savePermission(permission);
permissions = bo.listPermissions();
crearMensaje("Permiso guardado", permission.getName());
} catch (Exception e) {
logger.warn(e);
crearMensaje("Guardar", e.getMessage());
}
}
private void crearMensaje(String tipo, String msg) {
FacesMessage msg_ = new FacesMessage(tipo, msg);
FacesContext.getCurrentInstance().addMessage(null, msg_);
}
// --------------------------------
public List<User> getLista() {
return users;
}
public User getUsr() {
return usr;
}
public void setUsr(User usr) {
this.usr = usr;
selected_roles = new ArrayList<String>();
if (usr.getRoles() != null)
for (Role r : usr.getRoles())
selected_roles.add(r.getId());
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
selected_permissions = new ArrayList<String>();
if (role.getPermissions() != null)
for (Permission p : role.getPermissions())
selected_permissions.add(p.getId());
}
public List<Permission> getPermissions() {
return permissions;
}
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
}
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
public List<String> getSelected_roles() {
return selected_roles;
}
public void setSelected_roles(List<String> selected_roles) {
this.selected_roles = selected_roles;
}
public List<String> getSelected_permissions() {
return selected_permissions;
}
public void setSelected_permissions(List<String> selected_permissions) {
this.selected_permissions = selected_permissions;
}
}
| true
|
e9ccd605a48e331af2317b1ebfd10b6a7ae9de6a
|
Java
|
PPloyIXVII/cbsdSlideNo3
|
/netbeans/VetoDemo/src/veto/Police.java
|
UTF-8
| 557
| 2.78125
| 3
|
[] |
no_license
|
package veto;
import java.beans.*;
public class Police
implements VetoableChangeListener {
private static final int MAXSPEED = 85;
private static final int MINSPEED = 0;
public Police() {
}
public void vetoableChange(PropertyChangeEvent pce)
throws PropertyVetoException {
if(pce.getPropertyName().equals("speed")) {
int speed = (Integer)pce.getNewValue();
if(speed < MINSPEED || speed > MAXSPEED) {
String msg = "Speed out of range";
throw new PropertyVetoException(msg, pce);
}
}
}
}
| true
|
b30116010623176e6c8a87c87a70a520c7cbd7f8
|
Java
|
xuejun-yang/learn-demo
|
/src/main/java/com/smarts/netty/NioTimeServer.java
|
UTF-8
| 342
| 2.03125
| 2
|
[] |
no_license
|
package com.smarts.netty;
/**
* Created by yangxuejun
* on 16-11-14 下午8:59
*/
public class NioTimeServer {
public static void main(String[] args) {
int port = 8080;
MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);
new Thread(timeServer,"Nio-MultiplexertimeServer-001").start();
}
}
| true
|
a29375249ca346002dce2306d3266dd70915c3ee
|
Java
|
ralph831005/FOOP-homework
|
/hw3/src/ComputerPlayer.java
|
UTF-8
| 312
| 2.984375
| 3
|
[] |
no_license
|
import java.util.Random;
class ComputerPlayer extends Player{
private Random random;
ComputerPlayer(int n){
name = (new StringBuilder("Player")).append(n).toString();
random = new Random();
}
public int pick(int select_range){
return random.nextInt(select_range);
}
}
| true
|
0e7d0d57b0f0f120c7573e4485e032b93381ca57
|
Java
|
lkwdzh/kline
|
/src/com/stock/StockMonitrorResult.java
|
UTF-8
| 908
| 2.78125
| 3
|
[] |
no_license
|
package com.stock;
public class StockMonitrorResult {
private int tradeNumber;
public int getTradeNumber() {
return tradeNumber;
}
public void setTradeNumber(int tradeNumber) {
this.tradeNumber = tradeNumber;
}
public String getStockID() {
return stockID;
}
public void setStockID(String stockID) {
this.stockID = stockID;
}
public boolean isBuy() {
return buy;
}
public void setBuy(boolean buy) {
this.buy = buy;
}
private String stockID;
private boolean buy;
public String toString() {
return "StockId = " + stockID + " TradeNumber = " + tradeNumber
+ " isBuy = " + buy + " currentPrice = " + tradePrice;
}
private double tradePrice;
public double getTradePrice() {
return tradePrice;
}
public void setTradePrice(double tradePrice) {
this.tradePrice = tradePrice;
}
public double getTradeMoney() {
return this.tradeNumber * this.tradePrice;
}
}
| true
|
71a2a4b89cfdc0d257bbd0a409c9f756f84f9925
|
Java
|
0615cholpon/practice
|
/src/Arrays/StringArrayforColors.java
|
UTF-8
| 374
| 3.421875
| 3
|
[] |
no_license
|
package Arrays;
import java.util.Arrays;
public class StringArrayforColors {
public static void main(String[] args) {
//Create String Array for the colors;
String [] colors = {"white", "blue", "red", "black"};
for(int i = 0; i < colors.length; i++) {
if(colors[i].length() >= 4) {
System.out.println(colors[i]);
}
}
}
}
| true
|
20e34c23a1435e6913ad462a21d6d7869a905ab8
|
Java
|
buketsenturk/DesignPattens
|
/StateDesignPatten/PresentationLayer/ShoppingApp.java
|
UTF-8
| 414
| 2.03125
| 2
|
[] |
no_license
|
package g01.ceng431.hw2.presentationLayer;
import java.io.IOException;
import org.json.simple.parser.ParseException;
import g01.ceng431.hw2.businessLayer.ShoppingOperations;
public class ShoppingApp {
public static void main(String[] args) throws IOException, ParseException {
ShoppingOperations shoppingOperations = new ShoppingOperations();
shoppingOperations.start();
}
}
| true
|
4b51e0e23d51a5666f3402e50ac28f55a345d805
|
Java
|
CnrGames/JobTutorxx
|
/trabalhopooo1/src/Menu.java
|
UTF-8
| 286
| 1.835938
| 2
|
[] |
no_license
|
public class Menu
{
Tarefas tr;
Vizualizacoes vs;
public Menu ()
{
tr = new Tarefas();
vs = new Vizualizacoes();
tr.LerFicheiroTexto();
vs.verVooLongo(tr.getLista());
vs.verTodosBilhetes(tr.getLista());
vs.verCadaTipo(tr.getLista());
}
}
| true
|
810274eb69c2be6290005bba160f9a2c5bc34c65
|
Java
|
streamblocks/streamblocks-graalvm
|
/language/src/main/java/ch/epfl/vlsc/truffle/cal/nodes/expression/LetExprNode.java
|
UTF-8
| 718
| 2.4375
| 2
|
[
"UPL-1.0"
] |
permissive
|
package ch.epfl.vlsc.truffle.cal.nodes.expression;
import com.oracle.truffle.api.frame.VirtualFrame;
import ch.epfl.vlsc.truffle.cal.nodes.CALExpressionNode;
import ch.epfl.vlsc.truffle.cal.nodes.CALStatementNode;
public final class LetExprNode extends CALExpressionNode {
@Child
private CALExpressionNode body;
@Child
private CALStatementNode head;
// FIXME add parameters and return type
public LetExprNode(CALStatementNode head, CALExpressionNode body) {
this.head = head;
this.body = body;
}
// FIXME return
@Override
public Object executeGeneric(VirtualFrame frame) {
head.executeVoid(frame);
return body.executeGeneric(frame);
}
}
| true
|
b04119bb93bcd9f4844fa071541068e7c459ffc6
|
Java
|
huluobo11/sonake
|
/admin-api/src/main/java/com/hc/admin/common/PageUtils.java
|
UTF-8
| 1,969
| 2.359375
| 2
|
[
"MIT"
] |
permissive
|
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.hc.admin.common;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.List;
/**
* 分页工具类
*
* @author Mark sunlightcs@gmail.com
*/
public class PageUtils implements Serializable {
private static final long serialVersionUID = 1L;
//总记录数
private int total;
//每页记录数
private int pageSize;
//总页数
private int pages;
//当前页数
private int pageNo;
//列表数据
private List<?> list;
/**
* 分页
* @param list 列表数据
* @param totalCount 总记录数
* @param pageSize 每页记录数
* @param currPage 当前页数
*/
public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.total = totalCount;
this.pageSize = pageSize;
this.pageNo = currPage;
this.pages = (int)Math.ceil((double)totalCount/pageSize);
}
public PageUtils(List<?> list , int pageSize, int currPage) {
this.list = list;
this.pageSize = pageSize;
this.pageNo = currPage;
}
/**
* 分页
*/
public PageUtils(IPage<?> page) {
this.list = page.getRecords();
this.total = (int)page.getTotal();
this.pageSize = (int)page.getSize();
this.pageNo = (int)page.getCurrent();
this.pages = (int)page.getPages();
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
| true
|
c59a14f8d7408f214655e7c1a70033acb939d775
|
Java
|
morningblu/HWFramework
|
/DVC-AN20_EMUI10.1.1/src/main/java/com/huawei/android/view/DragEventEx.java
|
UTF-8
| 781
| 1.789063
| 2
|
[] |
no_license
|
package com.huawei.android.view;
import android.content.ClipData;
import android.content.ClipDescription;
import android.view.DragEvent;
import com.android.internal.view.IDragAndDropPermissions;
public class DragEventEx {
public static DragEvent obtain(int action, float x, float y, Object localState, ClipDescription description, ClipData data, IDragAndDropPermissions dragAndDropPermissions, boolean result) {
return DragEvent.obtain(action, x, y, localState, description, data, dragAndDropPermissions, result);
}
public static DragEvent obtain(int action, float x, float y, Object localState, ClipDescription description, ClipData data, boolean result) {
return DragEvent.obtain(action, x, y, localState, description, data, null, result);
}
}
| true
|
99a8b156aa4238c0e19355628712ce174d5c078b
|
Java
|
EquipoTimeLimitCvds/2020-2-PROYCVDS-TimeLimit
|
/src/main/java/edu/eci/cvds/TimeLimit/services/UserServices.java
|
UTF-8
| 428
| 1.875
| 2
|
[] |
no_license
|
package edu.eci.cvds.TimeLimit.services;
import edu.eci.cvds.TimeLimit.exceptions.TimeLimitExceptions;
import edu.eci.cvds.TimeLimit.model.User;
import java.util.List;
public interface UserServices {
//public List<User> getUsers() throws TimeLimitExceptions;
public User getUser (String nombre) throws TimeLimitExceptions;
public boolean validateLogin(String nombre, String clave) throws TimeLimitExceptions;
}
| true
|
11512b8ca939b7df46435d2e777abeb1972937c2
|
Java
|
LeshaTuruto/MyTwitter
|
/Likeshowoff/src/main/java/Test1.java
|
UTF-8
| 741
| 2.125
| 2
|
[] |
no_license
|
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "Test1")
public class Test1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rDispatcher=request.getRequestDispatcher("/status");
rDispatcher.forward(request, response);
}
}
| true
|
257a59563f0eb4cefd1f63f6d965e3742f146c63
|
Java
|
felipe125/APP_Pagos
|
/src/main/java/co/edu/polijic/app_pagos/model/RegistroTransaccion.java
|
UTF-8
| 4,659
| 1.867188
| 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 co.edu.polijic.app_pagos.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author felipe
*/
@Entity
@Table(name = "registro_transaccion")
@TableGenerator(name="registroTransaccionGenerator", initialValue=1, allocationSize=2500)
@NamedQueries({
@NamedQuery(name = "RegistroTransaccion.findAll", query = "SELECT r FROM RegistroTransaccion r"),
@NamedQuery(name = "RegistroTransaccion.findByCdregistro", query = "SELECT r FROM RegistroTransaccion r WHERE r.cdregistro = :cdregistro"),
@NamedQuery(name = "RegistroTransaccion.findByOpestado", query = "SELECT r FROM RegistroTransaccion r WHERE r.opestado = :opestado"),
@NamedQuery(name = "RegistroTransaccion.findByFefechatransaccion", query = "SELECT r FROM RegistroTransaccion r WHERE r.fefechatransaccion = :fefechatransaccion"),
@NamedQuery(name = "RegistroTransaccion.findByDsobservaciones", query = "SELECT r FROM RegistroTransaccion r WHERE r.dsobservaciones = :dsobservaciones")})
public class RegistroTransaccion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="registroTransaccionGenerator")
@Basic(optional = false)
@Column(name = "cdregistro")
private Integer cdregistro;
@Basic(optional = false)
@Column(name = "opestado")
private String opestado;
@Basic(optional = false)
@Column(name = "fefechatransaccion")
@Temporal(TemporalType.DATE)
private Date fefechatransaccion;
@Basic(optional = false)
@Column(name = "dsobservaciones")
private String dsobservaciones;
@JoinColumn(name = "cdtransaccion", referencedColumnName = "cdtransaccion")
@ManyToOne(optional = false)
private Transaccion cdtransaccion;
public RegistroTransaccion() {
}
public RegistroTransaccion(Integer cdregistro) {
this.cdregistro = cdregistro;
}
public RegistroTransaccion(Integer cdregistro, String opestado, Date fefechatransaccion, String dsobservaciones) {
this.cdregistro = cdregistro;
this.opestado = opestado;
this.fefechatransaccion = fefechatransaccion;
this.dsobservaciones = dsobservaciones;
}
public Integer getCdregistro() {
return cdregistro;
}
public void setCdregistro(Integer cdregistro) {
this.cdregistro = cdregistro;
}
public String getOpestado() {
return opestado;
}
public void setOpestado(String opestado) {
this.opestado = opestado;
}
public Date getFefechatransaccion() {
return fefechatransaccion;
}
public void setFefechatransaccion(Date fefechatransaccion) {
this.fefechatransaccion = fefechatransaccion;
}
public String getDsobservaciones() {
return dsobservaciones;
}
public void setDsobservaciones(String dsobservaciones) {
this.dsobservaciones = dsobservaciones;
}
public Transaccion getCdtransaccion() {
return cdtransaccion;
}
public void setCdtransaccion(Transaccion cdtransaccion) {
this.cdtransaccion = cdtransaccion;
}
@Override
public int hashCode() {
int hash = 0;
hash += (cdregistro != null ? cdregistro.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof RegistroTransaccion)) {
return false;
}
RegistroTransaccion other = (RegistroTransaccion) object;
if ((this.cdregistro == null && other.cdregistro != null) || (this.cdregistro != null && !this.cdregistro.equals(other.cdregistro))) {
return false;
}
return true;
}
@Override
public String toString() {
return "co.edu.polijic.app_pagos.model.RegistroTransaccion[ cdregistro=" + cdregistro + " ]";
}
}
| true
|
32a386a74d9c961fd8550d8acaae769cc7029015
|
Java
|
randy-wong/school_projects
|
/CS311Project1/UniversalFSA.java
|
UTF-8
| 7,320
| 3.515625
| 4
|
[] |
no_license
|
///*
// * This program was compiled using Eclipse on Windows 7
// * To run the program, place the input file in the same directory of the source file.
// *
// * Name: Jose Lascano
// * Project 1
// * Due: 01/29/2014
// * Course: CS-311-WR14
// *
// * Description:
// * This implementation of project 1 reads input from a file then stores the values in various
// * variables that are passed along to the driver class. After initializing the variables in the
// * constructor, the program keeps looping in main inputing strings into the nfa to see if it's
// * in its particular language. When the scanner reads a # it moves on to the next machine. The
// * way I'm reading strings into the nfa is I convert them to type char then convert the again to
// * type int.
// */
//
//import java.io.File;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.Scanner;
//
//public class UniversalFSA {
//
// // declaration of variables
// private int state = 0, symbol; // initial state = 0
// private String string, transitions[], states, alphabet, fin;
// private char uniSymbol;
//
// private static int number = 0;
//
// // constructor
// UniversalFSA(String string, String finalStates,
// ArrayList<String> transitions, String alpha, String states) {
// this.string = string;
// this.states = states;
// convert(transitions);
// this.fin = finalStates;
// this.alphabet = alpha;
// message();
// }
//
// // convert the transition from ArrayList to an array
// private void convert(ArrayList<String> transitions2) {
// // TODO Auto-generated method stub
// transitions = new String[transitions2.size()];
// for (int x = 0; x < transitions2.size(); x++) {
// transitions[x] = transitions2.get(x);
// }
// }
//
// // FSA machine
// public void fsa(String str) {
//
// this.string = str;
// int x = 0;
// state = 0;
//
// while (x < str.length()) {
// uniSymbol = str.charAt(x);
// symbol = getSymbol();
// state = getNextState();
// if (symbol != -99 && x < string.length() - 1) {
// if (state == -1) {
// reject();
// x++;
// break;
// }
// x++;
// } else {
// if (x == string.length() - 1 && !isFinal()) {
// x++;
// reject();
// break;
// } else if (isFinal() && x == string.length() - 1) {
// accept();
// x++;
// break;
// }
// x++;
// }
// }// end while loop
// }
//
// // print the accepted string
// private void accept() {
// // TODO Auto-generated method stub
// System.out.println(string + "\t\t\t\tAccept");
// }
//
// // print the rejected string
// private void reject() {
// // TODO Auto-generated method stub
// System.out.println(string + "\t\t\tReject");
// }
//
// // check if it's in the final state
// public boolean isFinal() {
// // TODO Auto-generated method stub
// int one;
// char a;
// for (int x = 0; x < fin.length(); x++) {
//
// a = (char) fin.charAt(x);
// one = Character.getNumericValue(a);
// if (state == one)
// return true;
// }
//
// return false;
// }
//
// // return the next state
// public int getNextState() {
// // TODO Auto-generated method stub
// char a, b, c;
// int one, two, three;
// for (int x = 0; x < transitions.length; x++) {
// a = (char) transitions[x].charAt(1);
// b = (char) transitions[x].charAt(3);
// one = Character.getNumericValue(a);
// two = Character.getNumericValue(b);
//
// // charAt(1) is the current state in the array, charAt(3) the symbol
// if (one == this.state && two == this.symbol) {
// // if both the current state and symbol are in array, return new
// // state
// c = (char) transitions[x].charAt(5);
// three = Character.getNumericValue(c);
// return three;
// }
// }
//
// // otherwise, return trap state
// return -1;
// }
//
// // this gets the unicode value from the string and returns an int for the
// // symbol
// public int getSymbol() {
// // TODO Auto-generated method stub
//
// if (alphabet.length() > 10) {
// // symbol is a digit
// if (uniSymbol >= 48 && uniSymbol <= 57) {
// return 1;
// }
// // symbol is a letter
// else if (uniSymbol >= 65 && uniSymbol <= 90) {
// return 0;
// }
// // symbol is a letter
// else if (uniSymbol >= 97 && uniSymbol <= 122) {
// return 0;
// }
// // symbol is a hyphen
// else if (uniSymbol == 45) {
// return 2;
// }
// // symbol is an underscore
// else if (uniSymbol == 95) {
// return 3;
// }
// // symbol is a period
// else if (uniSymbol == 46) {
// return 4;
// }
// // symbol is @
// else if (uniSymbol == 64) {
// return 5;
// }
//
// // symbol is $
// else if (uniSymbol == 36) {
// return 6;
// } else
// return -99;
// }
//
// else if (alphabet.length() < 4) {
// // symbol is a
// if (uniSymbol == 97) {
// return 0;
// }
// // symbol is b
// else if (uniSymbol == 98) {
// return 1;
// }
// } else if (alphabet.length() == 5) {
// if (uniSymbol == 48)
// return 0;
// else if (uniSymbol == 49)
// return 1;
// else if (uniSymbol == 50)
// return 2;
// else
// return -99;
// }
// return -99;
// }
//
// private void message() {
//
// System.out.println("\nFinate State Automaton #" + ++number
// + "\n1) Number Of States: " + states + "\n2) Final States: "
// + fin + "\n3) Alphabet: " + alphabet + "\n4) Transitions: ");
//
// for (int x = 0; x < transitions.length; x++) {
// System.out.println("\t" + transitions[x]);
// }
// System.out.println("5) strings: ");
// }
//
// /*************************************************************
// *************************************************************
// ************************** MAIN*******************************
// *************************************************************
// ************************************************************/
// public static void main(String args[]) throws IOException {
//
// ArrayList<String> trans = new ArrayList<String>();
// String string, alpha, states, fin;
//
// // open file
// File file = new File("input.txt");
// Scanner scanner = new Scanner(file);
//
// while (scanner.hasNext()) {
// // put info from file to variables
// states = scanner.nextLine();
// fin = scanner.nextLine();
// alpha = scanner.nextLine();
// string = scanner.nextLine();
//
// // fill up the transition table in ArrayList
// // using '(' because input file is formatted that way
// while (string.charAt(0) == '(') {
// trans.add(string);
// string = scanner.nextLine();
// if (string.length() < 2) {
// break;
// }
// }
//
// UniversalFSA driver = new UniversalFSA(string, fin, trans, alpha,
// states);
// // read Strings into NFA. # means new machine
// while (!string.equals("#")) {
// // System.out.println("I'm in here now!");
// driver.fsa(string);
// // if # is next symbol break the while loop
// if (string.equals("#")) {
// break;
// }
// string = scanner.nextLine();
// }
// trans = new ArrayList<String>();
// }
// scanner.close();
// }
//}
| true
|
cdb1b55dd882f47c03a486506540b7658e97e798
|
Java
|
ramonsantos/server-status
|
/src/ramonsantos/server_status/service/ServerStatusService.java
|
UTF-8
| 1,539
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
package ramonsantos.server_status.service;
import java.io.IOException;
import ramonsantos.server_status.util.OSDataCollector;
public class ServerStatusService implements IServerStatusService {
private OSDataCollector osDataCollector;
public ServerStatusService() {
this.osDataCollector = new OSDataCollector();
}
public String getUptime() throws IOException {
return this.osDataCollector.getUptime();
}
@Override
public String getOSInfo() throws IOException {
return this.osDataCollector.getOSInfo();
}
public String getKernelInfo() throws IOException {
return this.osDataCollector.getKernelInfo();
}
@Override
public Integer getTotalMemory() throws IOException {
return Integer.parseInt(this.osDataCollector.getMemoryInfo()[0]);
}
@Override
public Integer getFreeMemory() throws IOException {
return Integer.parseInt(this.osDataCollector.getMemoryInfo()[2]);
}
@Override
public Integer getUsedMemory() throws IOException {
return Integer.parseInt(this.osDataCollector.getMemoryInfo()[1]);
}
public Integer getBuffCaheMemory() throws IOException {
return Integer.parseInt(this.osDataCollector.getMemoryInfo()[3]);
}
@Override
public Integer getTotalDisk() throws IOException {
return this.getFreeDisk() + this.getUsedDisk();
}
@Override
public Integer getFreeDisk() throws IOException {
return this.osDataCollector.getFreeSpaceDisk();
}
@Override
public Integer getUsedDisk() throws IOException {
return this.osDataCollector.getUsedSpaceDisk();
}
}
| true
|
1a9c690c04d90345fb9d7b514d2049844470786c
|
Java
|
ivives/pmmgit
|
/inicioComponentes/src/JListTest.java
|
UTF-8
| 1,229
| 2.859375
| 3
|
[] |
no_license
|
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
//nuevos eventos de swing
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListTest {
public static void main(String[] args) {
JFrame f=new JFrame();
f.setTitle("JListTest");
f.setSize(200,230);
f.getContentPane().setLayout(new FlowLayout());
String labels[] = { "OPCION_1", "OPCION_2", "OPCION_3", "OPCION_4",
"OPCION_5", "OPCION_6", "OPCION_7", "OPCION_8",
"OPCION_9", "OPCION_10" };
JList lista = new JList(labels);
//f.getContentPane().add(lista);
JScrollPane scrollPane = new JScrollPane(lista);
f.getContentPane().add(scrollPane);
ListSelectionListener listSelectionListener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent ev) {
JList list = (JList) ev.getSource();
int indice = list.getSelectedIndex();
Object valor = list.getSelectedValue();
System.out.println("Indice=> " + indice + "valor=> " + valor);
}
};
lista.addListSelectionListener(listSelectionListener);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}// end main()
}
| true
|
78c580f268a589144c64ad66cfc16366323c7a81
|
Java
|
IgnacioHdzCz/springcore
|
/Spring1/src/main/java/pbas/ignacio/servicio/Servicio.java
|
UTF-8
| 101
| 2.046875
| 2
|
[] |
no_license
|
package pbas.ignacio.servicio;
public interface Servicio {
public void saludo(String nombre);
}
| true
|
9ec2d0f1132f833f34aea8633edb5d941d5fb3c3
|
Java
|
zhuliangyu/210-Java-Assign1
|
/src/main/ca/ubc/cs/inventory/InventoryItem.java
|
UTF-8
| 1,425
| 3.671875
| 4
|
[] |
no_license
|
package ca.ubc.cs.inventory;
// TODO: fix code for Step 3
// Represents an inventory item with a description, cost in cents and a count of the number currently in stock
public class InventoryItem {
private String description;
private int costInCents;
private int numInStock;
// REQUIRES: costInCents > 0
// EFFECTS: constructs and inventory item with given description and cost in cents
public InventoryItem(String description, int costInCents) {
this.description = description;
this.costInCents = costInCents;
this.numInStock = 0;
}
// REQUIRES: numItems > 0
// MODIFIES: this
// EFFECTS: adds numItems items to the stock of this inventory item
public void addStock(int numItems) {
numInStock += numItems;
}
// REQUIRES: numItems <= getNumInStock()
// MODIFIES: this
// EFFECTS: removes numItems items from the stock of this inventory item
public void removeFromStock(int numItems) {
numInStock -= numItems;
}
// REQUIRES: costInCents > 0
// MODIFIES: this
// EFFECTS: sets the price of this inventory item to costInCents
public void setPrice(int costInCents) {
this.costInCents = costInCents;
}
// getters
public String getDescription() { return description;}
public int getCostInCents() { return costInCents; }
public int getNumInStock() { return numInStock; }
}
| true
|
8bf653f91ecdee42d0e5fd22ad62b08c1498d12a
|
Java
|
PanPain/foundationPlatform
|
/hbase/src/main/java/edu/xd/ridelab/foundationplatform/hbaseconf/HBaseConfig.java
|
UTF-8
| 1,873
| 2.546875
| 3
|
[] |
no_license
|
package edu.xd.ridelab.foundationplatform.hbaseconf;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import java.io.IOException;
/**
* HBase配置类,用于获取HBase配置,连接
*
* @author QiHaiyang
* @date 2018/5/7
*/
public class HBaseConfig {
private static Configuration conf = null;
private static Connection conn = null;
static {
conf = HBaseConfiguration.create();
conf.set("hbase.master", ReadHBaseConf.getProperty("HBASE_MASTER"));
conf.set("hbase.zookeeper.quorum", ReadHBaseConf.getProperty("HBASE_ZOOKEEPER_QUORUM"));
conf.set("hbase.zookeeper.property.clientport", "2181");
try {
conn = ConnectionFactory.createConnection(conf);
} catch (IOException e) {
System.out.println("HBase获取连接失败");
e.printStackTrace();
}
}
private HBaseConfig() {
}
/**
* 获取HBase配置
*
* @return Configuration
*/
public static Configuration getConfig() {
return conf;
}
/**
* 获取HBase连接
*
* @return Connection
*/
public static Connection getConn() {
return conn;
}
/**
* 通过表名获取对应的HBase连接
*
* @param tableName
* @return Table
*/
public static Table getConnectionByTableName(String tableName) {
try {
return conn.getTable(TableName.valueOf(tableName));
} catch (IOException e) {
System.out.println("HBase获取表的连接失败");
e.printStackTrace();
}
return null;
}
}
| true
|
0e05357dffeacf2167c0187aa35d67914ebe3c55
|
Java
|
manasi1779/DistributedSystems
|
/Distributed Systems/Tapestry/src/AcceptRequest.java
|
UTF-8
| 31,688
| 2.671875
| 3
|
[] |
no_license
|
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;
public class AcceptRequest extends Thread {
final int maxIndices = 10;
static ServerSocket aServerSocket;
static int port = 12345;
int port2 = 54321;
static Node myNode;
public AcceptRequest( Node aNode )
{
myNode = aNode;
try
{
aServerSocket = new ServerSocket(port);
}
catch ( Exception e)
{
e.printStackTrace();
}
}
public void run()
{
try
{
while(true) {
Socket clnt = aServerSocket.accept();
BufferedReader din = new BufferedReader (
new InputStreamReader (clnt.getInputStream()));
String operation = din.readLine();
if ( operation.equalsIgnoreCase("join"))
{
System.out.println("A new node wants to join");
String nameOfNode = din.readLine();
String id = din.readLine();
System.out.println("Received name " + nameOfNode + " id " + id);
addToMyRoutingTable( nameOfNode, id );
sendFiles(nameOfNode, clnt);
din.close();
clnt.close();
}
else if ( operation.equalsIgnoreCase("insert"))
{
String fileName = din.readLine();
String fileHash = din.readLine();
System.out.println("Received fileName " + fileName + " with hash " + fileHash);
int hashIndex0 = Character.getNumericValue(fileHash.charAt(0));
int hashIndex1 = Character.getNumericValue(fileHash.charAt(1));
findDestination(hashIndex0, hashIndex1, fileName, fileHash, din);
din.close();
clnt.close();
}
else if ( operation.equalsIgnoreCase("addFile"))
{
//add the file on self
System.out.println("Going to store file on myself");
String fileName = din.readLine();
String fileHash = din.readLine();
addFile(fileName, fileHash, din);
din.close();
clnt.close();
}
else if ( operation.equalsIgnoreCase("search"))
{
String fileName = din.readLine();
String fileHash = din.readLine();
String requestor = din.readLine();
String path = din.readLine();
System.out.println("Have to search for " + fileName + " with hash " + fileHash);
int hashIndex0 = Character.getNumericValue(fileHash.charAt(0));
int hashIndex1 = Character.getNumericValue(fileHash.charAt(1));
findFileLocation(hashIndex0, hashIndex1, fileName, fileHash, requestor, path);
din.close();
clnt.close();
}
else if ( operation.equalsIgnoreCase("searchOnMe"))
{
String fileName = din.readLine();
String fileHash = din.readLine();
String requestor = din.readLine();
String path = din.readLine();
searchFile(fileName, fileHash, requestor, path);
}
else
{
din.close();
clnt.close();
}
}
}
catch ( Exception e )
{
e.printStackTrace();
}
}
public void searchFile(String theFileName, String fileHash, String requestor, String route)
{
//direct search on present node
try
{
String path = System.getProperty("user.home");
String myName = InetAddress.getLocalHost().getHostName();
path += "/" + myName;
String fullPath = path + "/" + theFileName;
File fileToFind = new File(fullPath);
if ( fileToFind.exists() && fileToFind.isFile())
{
String operation = "SearchResult\n";
byte[] opArr = new byte[(int) operation.length()];
opArr = operation.getBytes();
String fileExists = "True\n";
String fileNameForClient = theFileName + "\n";
byte[] foundArr = new byte[(int) fileExists.length()];
foundArr = fileExists.getBytes();
byte[] fNArr = new byte[(int) fileNameForClient.length()];
fNArr = fileNameForClient.getBytes();
byte[] fileContents = new byte[(int) fileToFind.length()];
FileInputStream fisToClient = new FileInputStream
(fileToFind);
BufferedInputStream bisClient = new BufferedInputStream
(fisToClient);
bisClient.read(fileContents, 0, fileContents.length);
String requestorHost = requestor + ".cs.rit.edu";
Socket sock = new Socket(requestorHost, port2);
String toSendToClient = route + "\n"; //trail
byte[] cliArr = new byte[(int) toSendToClient.length()];
cliArr = toSendToClient.getBytes();
OutputStream os = sock.getOutputStream();
os.write(opArr, 0, opArr.length);
os.write(foundArr, 0, foundArr.length);
os.write(cliArr, 0, cliArr.length);
os.write(fNArr, 0, fNArr.length);
os.write(fileContents, 0, fileContents.length);
os.flush();
bisClient.close();
fisToClient.close();
sock.close();
}
else
{
String operation = "SearchResult\n";
byte[] opArr = new byte[(int) operation.length()];
opArr = operation.getBytes();
String fileExists = "False\n";
byte[] foundArr = new byte[(int) fileExists.length()];
foundArr = fileExists.getBytes();
String requestorHost = requestor + ".cs.rit.edu";
Socket sock = new Socket(requestorHost, port2);
OutputStream os = sock.getOutputStream();
os.write(opArr, 0, opArr.length);
os.write(foundArr, 0, foundArr.length);
os.flush();
sock.close();
}
}
catch ( Exception e)
{
e.printStackTrace();
}
}
public void searchFileOnParticularNode(String nodeName, String fileName, String fileHash, String requestor, String path) {
//send direct search on only this node. No need to check surrogate
try
{
String host = nodeName + ".cs.rit.edu";
Socket mySock = new Socket(host, port);
OutputStream os = mySock.getOutputStream();
String operation = "searchOnMe\n";
fileHash += "\n";
requestor += "\n";
path += "\n";
byte[] operationArr = new byte[(int) operation.length()];
operationArr = operation.getBytes();
byte[] hashArr = new byte[(int) fileHash.length()];
hashArr = fileHash.getBytes();
byte[] reqArr = new byte[(int) requestor.length()];
reqArr = requestor.getBytes();
byte[] pathArr = new byte[(int) path.length()];
pathArr = path.getBytes();
String myfileName = fileName + "\n";
byte[] fName = new byte[(int) myfileName.length()];
fName = myfileName.getBytes();
os.write(operationArr, 0, operationArr.length);
os.write(fName, 0, fName.length);
os.write(hashArr, 0, hashArr.length);
os.write(reqArr, 0, reqArr.length);
os.write(pathArr, 0, pathArr.length);
os.flush();
os.close();
mySock.close();
}
catch ( Exception e )
{
System.err.println(e.getMessage());
}
}
private void beginSearchOnAnotherNode(String nodeName, String fileName, String fileHash, String requestor,
String path) {
//will resend search req to that node
try
{
String host = nodeName + ".cs.rit.edu";
Socket mySock = new Socket(host, port);
OutputStream os = mySock.getOutputStream();
String operation = "search\n";
fileHash += "\n";
requestor += "\n";
path += "\n";
byte[] operationArr = new byte[(int) operation.length()];
operationArr = operation.getBytes();
byte[] hashArr = new byte[(int) fileHash.length()];
hashArr = fileHash.getBytes();
byte[] reqArr = new byte[(int) requestor.length()];
reqArr = requestor.getBytes();
byte[] pathArr = new byte[(int) path.length()];
pathArr = path.getBytes();
String myfileName = fileName + "\n";
byte[] fName = new byte[(int) myfileName.length()];
fName = myfileName.getBytes();
os.write(operationArr, 0, operationArr.length);
os.write(fName, 0, fName.length);
os.write(hashArr, 0, hashArr.length);
os.write(reqArr, 0, reqArr.length);
os.write(pathArr, 0, pathArr.length);
os.flush();
os.close();
mySock.close();
}
catch ( Exception e )
{
System.err.println(e.getMessage());
}
}
public void findFileLocation(int hash0, int hash1, String fileName, String fileHash, String requestor, String path)
{
int currentNodeID0 = Character.getNumericValue(myNode.ID.charAt(0));
int currentNodeID1 = Character.getNumericValue(myNode.ID.charAt(1));
//First index matched
if ( currentNodeID0 == hash0 )
{
if ( currentNodeID1 == hash1 )
{
System.out.println("Found exact match with myself. Have to search in my directory " + myNode.name);
if ( ! myNode.name.equalsIgnoreCase("glados"))
{
path += " -> " + myNode.name;
}
searchFile(fileName, fileHash, requestor, path);
}
//Look for exact match with second index
else if ( myNode.levelOne[hash1].size() != 0)
{
//We found an exact match
System.out.println("Found exact match at " + myNode.levelOne[hash1].get(0)
+ " with name " + myNode.levelOneNodeNames[hash1].get(0));
/*if ( path.equals("empty"))
{
path = myNode.name;
}
else if ( !path.contains(myNode.name))
{
path += " -> " + myNode.name;
}*/
if ( ! myNode.name.equalsIgnoreCase("glados"))
{
path += " -> " + myNode.levelOneNodeNames[hash1].get(0);
}
searchFileOnParticularNode(myNode.levelOneNodeNames[hash1].get(0), fileName, fileHash, requestor, path);
//addFileToAnotherNode(fileName, fileHash, din, myNode.levelOneNodeNames[hash1].get(0));
}
//Exact match for second digit is not present, got to look for next available one in level one
else
{
System.out.println("No exact match found, so going to check for a surrogate");
boolean foundIndex = false;
int savedIndex = -1;
String nodeName = "";
int currentDifference = hash1 - currentNodeID1;
int parsingDifference = 100;
for ( int temp = hash1; temp < maxIndices; temp++ )
{
if ( myNode.levelOne[temp].size() > 0)
{
parsingDifference = hash1 - temp;
if ( parsingDifference >= 0 && (parsingDifference < currentDifference || currentDifference < 0 ) )
{
savedIndex = temp;
foundIndex = true;
}
}
}
if ( !foundIndex )
{
for ( int temp = 0; temp < hash1; temp++ )
{
if ( myNode.levelOne[temp].size() > 0)
{
parsingDifference = hash1 - temp;
if ( parsingDifference >= 0 && (parsingDifference < currentDifference || currentDifference < 0 ) )
{
savedIndex = temp;
foundIndex = true;
}
}
}
}
if ( !foundIndex )
{
System.out.println("No other is closer, have to check on myself " + myNode.name);
if ( ! myNode.name.equalsIgnoreCase("glados"))
{
path += " -> " + myNode.name;
}
searchFile(fileName, fileHash, requestor, path);
}
//Found some surrogate
else
{
String nameOfTheNode = "";
if ( myNode.levelOne[savedIndex].size() > 1 )
{
int minDistance = 100;
int sizeToParse = myNode.levelOne[savedIndex].size();
int parsed = 0;
int position;
while ( parsed < sizeToParse )
{
int currentDistance;
int theHashOfNode = Character.getNumericValue(myNode.levelOne[savedIndex].get(parsed).charAt(1));
currentDistance = hash1 - theHashOfNode;
if ( currentDistance >= 0 && currentDistance < minDistance )
{
position = parsed;
minDistance = currentDistance;
nameOfTheNode = myNode.levelOneNodeNames[savedIndex].get(parsed);
}
parsed++;
}
}
else
{
nameOfTheNode = myNode.levelOneNodeNames[savedIndex].get(0);
}
System.out.println("Found surrogate " + nameOfTheNode);
//if ( ! myNode.name.equalsIgnoreCase("glados"))
//{
path += " -> " + nameOfTheNode;
//}
searchFileOnParticularNode(nameOfTheNode, fileName, fileHash, requestor, path);
}
}
}//End of first index matched
//First itself did not match so look for first index match
else
{
System.out.println("First index has not matched. So now I need to look for someone starting woth first index");
if ( myNode.levelZero[hash0].size() != 0 )
{
//found match with 0th index, so ping any one of these. We will ping first one
System.out.println("This node matched index 0 digit. Transferring request to " + myNode.levelZero[hash0].get(0)
+ " with name " + myNode.levelZeroNodeNames[hash0].get(0));
//sendFileToAnotherNode(fileName, fileHash, din, myNode.levelZeroNodeNames[hash0].get(0));
beginSearchOnAnotherNode(myNode.levelZeroNodeNames[hash0].get(0), fileName, fileHash, requestor, path);
}
else
{
System.out.println("Nobody with first index match. So need to look for a surrogate.");
//System.out.println("No exact match found, so going to check for a surrogate");
boolean foundIndex = false;
int savedIndex = -1;
String nodeName = "";
int currentDifference = hash0 - currentNodeID0;
//System.out.println("My difference " + currentDifference );
int parsingDifference = 100;
for ( int temp = hash0; temp < maxIndices ; temp++ )
{
if ( myNode.levelZero[temp].size() > 0)
{
parsingDifference = hash0 - temp;
if ( parsingDifference >= 0 && (parsingDifference < currentDifference || currentDifference < 0 ) )
{
savedIndex = temp;
foundIndex = true;
}
}
}
if ( !foundIndex )
{
for ( int temp = 0; temp < hash0; temp++ )
{
if ( myNode.levelZero[temp].size() > 0)
{
parsingDifference = hash0 - temp;
if ( parsingDifference >= 0 && (parsingDifference < currentDifference || currentDifference < 0 ) )
{
savedIndex = temp;
foundIndex = true;
}
}
}
}
if ( !foundIndex )
{
System.out.println("No other is closer, going to search on myself " + myNode.name);
if ( ! myNode.name.equalsIgnoreCase("glados"))
{
path += " -> " + myNode.name;
}
searchFile(fileName, fileHash, requestor, path);
}
else
{
String nameOfTheNode = "";
if ( myNode.levelZero[savedIndex].size() > 1 )
{
//System.out.println("There is more than 1 node at this index");
int minDistance = 100;
int sizeToParse = myNode.levelZero[savedIndex].size();
int parsed = 0;
int position;
while ( parsed < sizeToParse )
{
int currentDistance;
int nodeHash = Integer.parseInt(myNode.levelZero[savedIndex].get(parsed));
int totalFileHash = (hash0 * 10) + hash1;
//int theHashOfNode = Character.getNumericValue(myNode.levelZero[savedIndex].get(parsed).charAt(1));
//currentDistance = hash0 - theHashOfNode;
currentDistance = totalFileHash - nodeHash;
System.out.println("For " + myNode.levelZeroNodeNames[savedIndex].get(parsed) + " the diff is " + currentDifference);
if ( currentDistance >= 0 && currentDistance < minDistance )
{
position = parsed;
minDistance = currentDistance;
nameOfTheNode = myNode.levelZeroNodeNames[savedIndex].get(parsed);
}
parsed++;
}
}
else
{
nameOfTheNode = myNode.levelZeroNodeNames[savedIndex].get(0);
}
System.out.println("Found a surrogate " + nameOfTheNode);
//if ( ! myNode.name.equalsIgnoreCase("glados"))
//{
path += " -> " + nameOfTheNode;
//}
searchFileOnParticularNode(nameOfTheNode, fileName, fileHash, requestor, path);
//addFileToAnotherNode(fileName, fileHash, din, nameOfTheNode);
}
}
}
}
public void addFile(String fileName, String fileHash, BufferedReader din)
{
try
{
String filePath = System.getProperty("user.home");
String myName = myNode.name;
filePath += "/" + myName;
File theDir = new File(filePath);
// if the directory does not exist, create it
if (!theDir.exists()) {
//System.out.println("creating directory: " + filePath);
boolean result = false;
try {
theDir.mkdirs();
result = true;
}
catch(SecurityException se) {
System.err.println(se.getMessage());
}
if(result) {
//System.out.println("DIR created");
}
}
else {
//System.out.println("DIR exists");
}
PrintWriter out = new PrintWriter(filePath + "/" + fileName);
String myStringRead;
while ((myStringRead = din.readLine()) != null)
{
out.println(myStringRead);
}
out.close();
System.out.println("File created at " + filePath);
}
catch ( Exception e )
{
e.printStackTrace();
}
}
public void addFileToAnotherNode(String fileName, String fileHash, BufferedReader din, String nodeName) {
try
{
String hostName = nodeName + ".cs.rit.edu";
Socket insertClient = new Socket(hostName, port);
BufferedReader myReader = new BufferedReader (
new InputStreamReader (insertClient.getInputStream()));
OutputStream os = insertClient.getOutputStream();
String theOp = "addFile\n";
byte[] theOpArr = new byte[(int) theOp.length()];
theOpArr = theOp.getBytes();
String fileWithNewLine = fileName + "\n";
String fileHashWithNewLine = fileHash + "\n";
byte[] fNameArr = new byte[(int) fileWithNewLine.length()];
fNameArr = fileWithNewLine.getBytes();
byte[] fHashArr = new byte[(int) fileHashWithNewLine.length()];
fHashArr = fileHashWithNewLine.getBytes();
os.write(theOpArr, 0, theOpArr.length);
os.write(fNameArr, 0, fNameArr.length);
os.write(fHashArr, 0, fHashArr.length);
String myStringRead;
while ((myStringRead = din.readLine()) != null)
{
myStringRead += "\n";
byte[] toWrite = new byte[(int) myStringRead.length()];
toWrite = myStringRead.getBytes();
os.write(toWrite, 0, toWrite.length);
}
os.flush();
os.close();
insertClient.close();
}
catch ( Exception e)
{
e.printStackTrace();
}
}
public void sendFileToAnotherNode(String fileName, String fileHash, BufferedReader din, String nodeName) {
try
{
String hostName = nodeName + ".cs.rit.edu";
Socket insertClient = new Socket(hostName, port);
BufferedReader myReader = new BufferedReader (
new InputStreamReader (insertClient.getInputStream()));
OutputStream os = insertClient.getOutputStream();
String theOp = "insert\n";
byte[] theOpArr = new byte[(int) theOp.length()];
theOpArr = theOp.getBytes();
String fileWithNewLine = fileName + "\n";
String fileHashWithNewLine = fileHash + "\n";
byte[] fNameArr = new byte[(int) fileWithNewLine.length()];
fNameArr = fileWithNewLine.getBytes();
byte[] fHashArr = new byte[(int) fileHashWithNewLine.length()];
fHashArr = fileHashWithNewLine.getBytes();
os.write(theOpArr, 0, theOpArr.length);
os.write(fNameArr, 0, fNameArr.length);
os.write(fHashArr, 0, fHashArr.length);
String myStringRead;
while ((myStringRead = din.readLine()) != null)
{
myStringRead += "\n";
byte[] toWrite = new byte[(int) myStringRead.length()];
toWrite = myStringRead.getBytes();
os.write(toWrite, 0, toWrite.length);
}
os.flush();
os.close();
insertClient.close();
}
catch ( Exception e)
{
e.printStackTrace();
}
}
public void findDestination(int hash0, int hash1, String fileName, String fileHash, BufferedReader din)
{
int currentNodeID0 = Character.getNumericValue(myNode.ID.charAt(0));
int currentNodeID1 = Character.getNumericValue(myNode.ID.charAt(1));
//First index matched
if ( currentNodeID0 == hash0 )
{
if ( currentNodeID1 == hash1 )
{
System.out.println("Found exact match with myself. Obj will be stored with me " + myNode.name);
addFile(fileName, fileHash, din);
}
//Look for exact match with second index
else if ( myNode.levelOne[hash1].size() != 0)
{
//We found an exact match
System.out.println("Found exact match at " + myNode.levelOne[hash1].get(0)
+ " with name " + myNode.levelOneNodeNames[hash1].get(0));
addFileToAnotherNode(fileName, fileHash, din, myNode.levelOneNodeNames[hash1].get(0));
}
//Exact match for second digit is not present, got to look for next available one in level one
else
{
System.out.println("No exact match found, so going to check for a surrogate");
boolean foundIndex = false;
int savedIndex = -1;
String nodeName = "";
int currentDifference = hash1 - currentNodeID1;
int parsingDifference = 100;
for ( int temp = hash1; temp < maxIndices; temp++ )
{
if ( myNode.levelOne[temp].size() > 0)
{
parsingDifference = hash1 - temp;
if ( parsingDifference >= 0 && (parsingDifference < currentDifference || currentDifference < 0 ) )
{
savedIndex = temp;
foundIndex = true;
}
}
}
if ( !foundIndex )
{
for ( int temp = 0; temp < hash1; temp++ )
{
if ( myNode.levelOne[temp].size() > 0)
{
parsingDifference = hash1 - temp;
if ( parsingDifference >= 0 && (parsingDifference < currentDifference || currentDifference < 0 ) )
{
savedIndex = temp;
foundIndex = true;
}
}
}
}
if ( !foundIndex )
{
System.out.println("No other is closer, going to store on myself " + myNode.name);
addFile(fileName, fileHash, din);
}
//Found some surrogate
else
{
String nameOfTheNode = "";
if ( myNode.levelOne[savedIndex].size() > 1 )
{
int minDistance = 100;
int sizeToParse = myNode.levelOne[savedIndex].size();
int parsed = 0;
int position;
while ( parsed < sizeToParse )
{
int currentDistance;
int theHashOfNode = Character.getNumericValue(myNode.levelOne[savedIndex].get(parsed).charAt(1));
currentDistance = hash1 - theHashOfNode;
if ( currentDistance >= 0 && currentDistance < minDistance )
{
position = parsed;
minDistance = currentDistance;
nameOfTheNode = myNode.levelOneNodeNames[savedIndex].get(parsed);
}
parsed++;
}
}
else
{
nameOfTheNode = myNode.levelOneNodeNames[savedIndex].get(0);
}
System.out.println("Found surrogate " + nameOfTheNode);
addFileToAnotherNode(fileName, fileHash, din, nameOfTheNode);
}
}
}//End of first index matched
//First itself did not match so look for first index match
else
{
System.out.println("First index has not matched. So now I need to look for someone starting woth first index");
if ( myNode.levelZero[hash0].size() != 0 )
{
//found match with 0th index, so ping any one of these. We will ping first one
System.out.println("This node matched index 0 digit. Transferring request to " + myNode.levelZero[hash0].get(0)
+ " with name " + myNode.levelZeroNodeNames[hash0].get(0));
sendFileToAnotherNode(fileName, fileHash, din, myNode.levelZeroNodeNames[hash0].get(0));
}
else
{
System.out.println("Nobody with first index match. So need to look for a surrogate.");
boolean foundIndex = false;
int savedIndex = -1;
String nodeName = "";
int currentDifference = hash0 - currentNodeID0;
int parsingDifference = 100;
for ( int temp = hash0; temp < maxIndices ; temp++ )
{
if ( myNode.levelZero[temp].size() > 0)
{
parsingDifference = hash0 - temp;
if ( parsingDifference >= 0 && (parsingDifference < currentDifference || currentDifference < 0 ) )
{
savedIndex = temp;
foundIndex = true;
}
}
}
if ( !foundIndex )
{
for ( int temp = 0; temp < hash0; temp++ )
{
if ( myNode.levelZero[temp].size() > 0)
{
parsingDifference = hash0 - temp;
if ( parsingDifference >= 0 && (parsingDifference < currentDifference || currentDifference < 0 ) )
{
savedIndex = temp;
foundIndex = true;
}
}
}
}
if ( !foundIndex )
{
System.out.println("No other is closer, going to store on myself " + myNode.name);
addFile(fileName, fileHash, din);
}
else
{
String nameOfTheNode = "";
if ( myNode.levelZero[savedIndex].size() > 1 )
{
//System.out.println("There is more than 1 node at this index");
int minDistance = 100;
int sizeToParse = myNode.levelZero[savedIndex].size();
int parsed = 0;
int position;
while ( parsed < sizeToParse )
{
int currentDistance;
int nodeHash = Integer.parseInt(myNode.levelZero[savedIndex].get(parsed));
int totalFileHash = (hash0 * 10) + hash1;
//int theHashOfNode = Character.getNumericValue(myNode.levelZero[savedIndex].get(parsed).charAt(1));
//currentDistance = hash0 - theHashOfNode;
currentDistance = totalFileHash - nodeHash;
System.out.println("For " + myNode.levelZeroNodeNames[savedIndex].get(parsed) + " the diff is " + currentDifference);
if ( currentDistance >= 0 && currentDistance < minDistance )
{
position = parsed;
minDistance = currentDistance;
nameOfTheNode = myNode.levelZeroNodeNames[savedIndex].get(parsed);
}
parsed++;
}
}
else
{
nameOfTheNode = myNode.levelZeroNodeNames[savedIndex].get(0);
}
System.out.println("Found a surrogate " + nameOfTheNode);
addFileToAnotherNode(fileName, fileHash, din, nameOfTheNode);
}
}
}
}
public void addToMyRoutingTable(String nameOfNode, String id) {
int level0 = Character.getNumericValue(id.charAt(0));
int level1 = Character.getNumericValue(id.charAt(1));
//System.out.println("First index " + level0);
//System.out.println("Second index " + level1);
myNode.addToTable(0, level0, id, nameOfNode);
//myNode.level0.add(level0, id);
int myLevel0= Character.getNumericValue(myNode.ID.charAt(0));
if ( myLevel0 == level0 )
{
myNode.addToTable(1, level1, id, nameOfNode);
//myNode.level1.add(level1, id);
}
//if I am root, add new node to other nodes tables as well
if ( myNode.name.equalsIgnoreCase("glados"))
{
try
{
for ( int temp = 0; temp < maxIndices; temp++ )
{
if ( myNode.levelZero[temp].size() > 0 )
{
int size = myNode.levelZero[temp].size();
int count = 0;
//There may be many nodes at same index
while ( count < size )
{
String currentHost = myNode.getNeighborName (0,temp, count);
//System.out.println("Adding to " + currentHost);
//for current node, add every neighbor
for ( int innerTemp = 0; innerTemp < maxIndices; innerTemp++ )
{
if ( myNode.levelZero[innerTemp].size() > 0 )
{
int innerSize = myNode.levelZero[innerTemp].size();
int currentCount = 0;
while ( currentCount < innerSize )
{
String neighbor = myNode.getNeighborName (0,innerTemp, currentCount);
String neighborID = myNode.getNeighborID(0, innerTemp, currentCount);
//System.out.println("Neighbor " + neighbor);
if ( !currentHost.equalsIgnoreCase(neighbor) )
{
String hostNameToSend = currentHost + ".cs.rit.edu";
Socket mySocket = new Socket ( hostNameToSend, port );
OutputStream os = mySocket.getOutputStream();
String operation = "join\n";
String myName = neighbor + "\n";
String idToSend = neighborID + "\n";
//id += "\n";
byte[] opArr = new byte[(int) operation.length()];
opArr = operation.getBytes();
byte[] nameArr = new byte[(int) myName.length()];
nameArr = myName.getBytes();
byte[] idArr = new byte[(int) idToSend.length()];
idArr = idToSend.getBytes();
os.write(opArr, 0, opArr.length);
os.write(nameArr, 0, nameArr.length);
os.write(idArr, 0, idArr.length);
os.flush();
System.out.println("Waiting for response");
Scanner sc = new Scanner(mySocket.getInputStream());
while(!sc.hasNext());
String response = sc.nextLine();
System.out.println(response);
if(response.equals("FILES"))
NodeOperations.receiveFiles(mySocket);
os.close();
mySocket.close();
}
currentCount++;
}
}
}
count++;
}
}
}
}
catch ( Exception e)
{
e.printStackTrace();
}
}
}
/**
* Files sent by root upon getting added
*/
public void sendFiles(String destNode, Socket s){
ArrayList<String> fileNames = reRoute(""+getHash(destNode));
PrintWriter pw = null ;
OutputStream os = null;
OutputStreamWriter osr = null;
try {
os = s.getOutputStream();
osr = new OutputStreamWriter(os);
pw = new PrintWriter(os, true);
if(fileNames.size() == 0){
osr.write("NONE\n");
osr.flush();
return;
}
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
pw.println("FILES\n");
pw.println(fileNames.size());
File existingFiles[] = null;
File homedir = new File(System.getProperty("user.home"));
File path;
try {
path = new File(homedir.getAbsolutePath()+"/"+InetAddress.getLocalHost().getHostName()+"/");
existingFiles = path.listFiles();
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
try {
for(int i = 0; i < existingFiles.length; i++){
if(fileNames.contains(existingFiles[i].getName())){
System.out.println("Sending file"+existingFiles[i].getName());
pw.println(existingFiles[i].getName());
pw.println(existingFiles[i].length());
FileInputStream fileInputStream = new FileInputStream(existingFiles[i]);
byte[] fileBytes = new byte[(int) existingFiles[i].length()];
fileInputStream.read(fileBytes);
os.write(fileBytes);
os.flush();
existingFiles[i].delete();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* check whether file at this node have files for new node's hash
*/
public ArrayList<String> reRoute(String newNodeHash){
System.out.println("Checking rerouting");
String path = System.getProperty("user.home");
String myName;
ArrayList<String> copyFiles = new ArrayList<String>();
int ownHash = Integer.parseInt(myNode.ID);
int newHash = Integer.parseInt(newNodeHash);
try {
myName = InetAddress.getLocalHost().getHostName();
path += "/" + myName;
File theDir = new File(path);
String fileNames[] = theDir.list();
if(fileNames!=null)
for(int i =0; i < fileNames.length; i++){
int fileHash = getHash(fileNames[i]);
if(newerIsCloser(ownHash, fileHash, newHash)){
copyFiles.add(fileNames[i]);
System.out.println("Transferring file "+fileNames[i]);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return copyFiles;
}
public static int getHash(String name){
int hash = name.hashCode();
hash = hash % 100;
if(hash < 0)
hash = hash * -1;
return hash;
}
public boolean newerIsCloser(int ownHash, int fileHash, int newHash){
boolean result = false;
int dif1 = ownHash -fileHash, dif2 = newHash-fileHash;
if(dif1 <0)
dif1*=-1;
if(dif2<0)
dif2*=-1;
if( fileHash/10 == newHash/10 && fileHash/10 != ownHash/10 || fileHash/10 == newHash/10 && dif2 < dif1)
result = true;
return result;
}
}
| true
|
3e719e82aa2d022ff179290e8b2f3dec5f2fcef1
|
Java
|
edgardespinoza/RxAndroid
|
/app/src/androidTest/java/everis/rx/com/rxandroid/sumarTesting.java
|
UTF-8
| 5,188
| 2.015625
| 2
|
[] |
no_license
|
package everis.rx.com.rxandroid;
import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.replaceText;
import static android.support.test.espresso.action.ViewActions.scrollTo;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class sumarTesting {
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void sumarTesting() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction textInputEditText = onView(
withId(R.id.id_a));
textInputEditText.perform(scrollTo(), replaceText("1"), closeSoftKeyboard());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction textInputEditText2 = onView(
withId(R.id.id_b));
textInputEditText2.perform(scrollTo(), replaceText("2"), closeSoftKeyboard());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatButton = onView(
allOf(withId(R.id.idsumar), withText("sumar"),
withParent(withId(R.id.layout_adicion))));
appCompatButton.perform(scrollTo(), click());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatButton2 = onView(
allOf(withId(R.id.btn_next), withText("Siguiente"), isDisplayed()));
appCompatButton2.perform(click());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction textInputEditText3 = onView(
withId(R.id.id_a));
textInputEditText3.perform(scrollTo(), replaceText("4"), closeSoftKeyboard());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction textInputEditText4 = onView(
withId(R.id.id_b));
textInputEditText4.perform(scrollTo(), replaceText("2"), closeSoftKeyboard());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatButton3 = onView(
allOf(withId(R.id.idsumar), withText("Restar"),
withParent(withId(R.id.layout_adicion))));
appCompatButton3.perform(scrollTo(), click());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatButton4 = onView(
allOf(withId(R.id.btn_next), withText("Siguiente"), isDisplayed()));
appCompatButton4.perform(click());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction textInputEditText5 = onView(
withId(R.id.id_a));
textInputEditText5.perform(scrollTo(), replaceText("5"), closeSoftKeyboard());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction textInputEditText6 = onView(
withId(R.id.id_b));
textInputEditText6.perform(scrollTo(), replaceText("4"), closeSoftKeyboard());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatButton5 = onView(
allOf(withId(R.id.idsumar), withText("Multiplicar"),
withParent(withId(R.id.layout_adicion))));
appCompatButton5.perform(scrollTo(), click());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatButton6 = onView(
allOf(withId(R.id.btn_next), withText("Siguiente"), isDisplayed()));
appCompatButton6.perform(click());
}
}
| true
|
23a37f5710afc47e2ba2c4217cd088b36da9df3b
|
Java
|
Game-Designing/Custom-Football-Game
|
/sources/com/google/android/gms/internal/ads/zzbgh.java
|
UTF-8
| 1,356
| 1.554688
| 2
|
[
"MIT"
] |
permissive
|
package com.google.android.gms.internal.ads;
import android.annotation.TargetApi;
import android.net.Uri;
@TargetApi(16)
@zzard
public final class zzbgh extends zzbgl {
/* renamed from: h */
private final String f25306h = null;
public zzbgh(zzbdf zzbdf, String str) {
super(zzbdf);
}
/* access modifiers changed from: protected */
/* renamed from: c */
public final zzhn mo30562c(String str) {
zzjp zzjp;
zzjp zzjt = new zzjt(this.f25277a, this.f25278b);
if (((Boolean) zzyt.m31536e().mo29599a(zzacu.f24188vd)).booleanValue()) {
zzjp = new zzbeh(this.f25277a, zzjt, new C8828Ee(this));
} else {
zzjp = zzjt;
}
zzig zzig = new zzig(Uri.parse(str), zzjp, "video/webm".equals(this.f25306h) ? new zzjg() : new zziv(), 2, ((Integer) zzyt.m31536e().mo29599a(zzacu.f23914D)).intValue());
return zzig;
}
/* access modifiers changed from: protected */
/* renamed from: c */
public final int mo30561c() {
return 0;
}
/* access modifiers changed from: 0000 */
/* renamed from: b */
public final /* synthetic */ void mo30560b(boolean z, long j) {
zzbdf zzbdf = (zzbdf) this.f25279c.get();
if (zzbdf != null) {
zzbbm.f25064a.execute(new C8849Fe(zzbdf, z, j));
}
}
}
| true
|
4d833b5dd152d6d3372a8579cc1ce3d6fd4ea86e
|
Java
|
Amanbirla18/Selenium_Cucumber
|
/src/Runner/Testrunner.java
|
UTF-8
| 909
| 1.679688
| 2
|
[] |
no_license
|
package Runner;
import java.io.File;
import java.io.IOException;
import org.junit.runner.RunWith;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import com.cucumber.listener.Reporter;
import com.sun.jna.platform.FileUtils;
@RunWith(Cucumber.class)
@CucumberOptions(features = {"features"}, glue ={"Steps"}, plugin = {"com.cucumber.listener.ExtentCucumberFormatter:C:\\Selenium_Workspace\\Cucumber_Selenium\\Reports\\Reports.html"})
public class Testrunner {
public static void teardown() {
Reporter.loadXMLConfig(new File("src/test/resources/extent-config.xml"));
Reporter.setSystemInfo("user", System.getProperty("user.name"));
Reporter.setSystemInfo("windows", "Windows 7");
Reporter.setTestRunnerOutput("Sample test runner output message");
}
}
| true
|
5d58a24e547209fecdc60601ca09b87e7a346a89
|
Java
|
LouisCollet/Golflc
|
/src/main/java/find/FindBlocking.java
|
UTF-8
| 2,190
| 2.671875
| 3
|
[] |
no_license
|
package find;
import entite.Blocking;
import entite.Player;
import static interfaces.Log.LOG;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import utils.DBConnection;
public class FindBlocking{
final private static String CLASSNAME = Thread.currentThread().getStackTrace()[1].getClassName();
public Blocking find(Player player, Connection conn) throws SQLException, Exception{
PreparedStatement ps = null;
ResultSet rs = null;
try{
LOG.info("entering FindBlocking for player = " + player.getIdplayer());
LOG.info("connection = " + conn);
String bl = utils.DBMeta.listMetaColumnsLoad(conn, "blocking");
String query =
"SELECT " + bl +
" from blocking"
+ " where BlockingPlayerId = ?"
;
ps = conn.prepareStatement(query);
ps.setInt(1, player.getIdplayer());
utils.LCUtil.logps(ps);
rs = ps.executeQuery();
rs.last(); //on récupère le numéro de la ligne
LOG.info("ResultSet FindBlocking has " + rs.getRow() + " lines.");
if(rs.getRow() > 1)
{ throw new Exception(" -- More than one Blocking = " + rs.getRow() ); }
rs.beforeFirst(); //on replace le curseur avant la première ligne
//LOG.info("just before while ! ");
Blocking a = null;
while(rs.next()){
a = entite.Blocking.mapBlocking(rs);
}
return a;
}catch(Exception ex){
String err = "-- Exception in ! " + CLASSNAME + " / " + ex.toString() + "/";
LOG.error(err);
return null;
} // end catch
finally{
DBConnection.closeQuietly(null, null, rs, ps);
}
} // end method find
public static void main(String[] args) throws Exception , Exception{
Connection conn = new DBConnection().getConnection();
Player player = new Player();
player.setIdplayer(206658);
Blocking blocking = new FindBlocking().find(player, conn);
LOG.info("Blocking found = " + blocking);
DBConnection.closeQuietly(conn, null, null, null);
}// end main
} // end class
| true
|
0643cd5086d9feeda9a8832962615e68f5d53ff2
|
Java
|
alexmorral/university
|
/java/src/MainProgram.java
|
UTF-8
| 293
| 2.046875
| 2
|
[] |
no_license
|
import views.CtrlPresentacion;
public class MainProgram {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CtrlPresentacion mainWindow = new CtrlPresentacion();
mainWindow.initPresentation();
}
});
}
}
| true
|
093e8da951583277d140fe59284ec75b0bf72f50
|
Java
|
YangJinnnn/LeetCode
|
/阿里/src/com/yang/project/Main2.java
|
UTF-8
| 884
| 3.171875
| 3
|
[] |
no_license
|
package com.yang.project;
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long a = in.nextLong();
long b = in.nextLong();
long c = in.nextLong();
System.out.println(solution(a, b, c));
}
public static long solution(long a, long b, long c){
double a2 = Math.sqrt(a);
double a3 = Math.pow(a, 1.0 / 3.0);
double b2 = Math.sqrt(b);
double b3 = Math.pow(b, 1.0 / 3.0);
long res = 0;
for (long x = a2%1==0?(long)a2:((long)a2+1); x < (b2%1==0?b2+1:b2); x++) {
for (long y = a3%1==0?(long)a3:((long)a3+1); y < (b3%1==0?b3+1:b3); y++) {
if(Math.abs(Math.pow(x, 2) - Math.pow(y, 3)) <= c){
res++;
}
}
}
return res;
}
}
| true
|
dde5be7685f979d640cc78c4ea99c6ddc50f161a
|
Java
|
LiadDoh/MobileProjectHW
|
/app/src/main/java/com/example/hw1/ui/Activity_Game.java
|
UTF-8
| 6,184
| 2.375
| 2
|
[] |
no_license
|
package com.example.hw1.ui;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.example.hw1.R;
import com.example.hw1.helpers.Base_Activity;
import com.example.hw1.helpers.DeckHelper;
import com.example.hw1.helpers.UIHelper;
import com.example.hw1.objects.Card;
import java.util.ArrayList;
public class Activity_Game extends Base_Activity {
private static final int POPUP_ACTIVITY_REQUEST_CODE = 527;//Snake Case
private final String TAG = "ActivityMain";//Paskal Case
public TextView game_LBL_name_1;
public TextView game_LBL_name_2;
public Button game_BTN_step;
private ImageView game_IMG_dice;
private ArrayList<Card> deck;
private final char[] LETTERS = {'c', 'd', 'h', 's'};
private AnimationDrawable frameAnimation;
private boolean firstClick = true;
private MediaPlayer shuffle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Log.d(TAG, "onCreate:Start");
findViews();
initViews();
}
public void findViews() {
game_LBL_name_1 = findViewById(R.id.game_LBL_name_1);
game_LBL_name_2 = findViewById(R.id.game_LBL_name_2);
game_LBL_score1 = findViewById(R.id.game_LBL_score1);
game_LBL_score2 = findViewById(R.id.game_LBL_score2);
game_BTN_step = findViewById(R.id.game_BTN_step);
game_IMG_player_card1 = findViewById(R.id.game_IMG_player_card1);
game_IMG_player_card2 = findViewById(R.id.game_IMG_player_card2);
game_IMG_dice = findViewById(R.id.game_IMG_dice);
game_BAR_progress = findViewById(R.id.game_BAR_progress);
claps= MediaPlayer.create(this,R.raw.claps);
shuffle= MediaPlayer.create(this,R.raw.shuffle);
}
public void initViews() {
UIHelper.convertIMG(this, R.drawable.aces, game_IMG_player_card1);
UIHelper.convertIMG(this, R.drawable.aces, game_IMG_player_card2);
deck = DeckHelper.createDeck(this, LETTERS);
game_BTN_step.setOnClickListener(v -> {
if (firstClick) {
firstClick = false;
startPopUpActivity();
} else {
if(shuffle.isPlaying())
shuffle.pause();
game_BTN_step.setEnabled(false);
rollDice();
}
});
}
public void startPopUpActivity() {
startActivityForResult(new Intent(Activity_Game.this, Activity_Popup.class), 527);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == POPUP_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) { // Activity.RESULT_OK
// get String data from Intent
String[] returnString = data.getStringArrayExtra("keyName");
// set text view with string
game_LBL_name_1.setText(returnString[0]);
game_LBL_name_2.setText(returnString[1]);
game_BTN_step.setText("Start");
shuffle.start();
}
else
firstClick = true;
}
else
firstClick = true;
}
private void rollDice() {
game_IMG_dice.setImageResource(R.drawable.animation);
frameAnimation = (AnimationDrawable) game_IMG_dice.getDrawable();
frameAnimation.start();
checkIfAnimationDone();
}
private void checkIfAnimationDone() {
int timeBetweenChecks = 300;
Handler handler = new Handler();
handler.postDelayed(() -> {
if (frameAnimation.getCurrent() != frameAnimation.getFrame(frameAnimation.getNumberOfFrames() - 1)) {
checkIfAnimationDone();
} else if (!deck.isEmpty()) {
DeckHelper.drawCards(Activity_Game.this, deck);
game_BAR_progress.incrementProgressBy(1);
rollDice();
} else {
claps.start();
game_BTN_step.setEnabled(true);
game_BTN_step.setText("Finish");
game_BTN_step.setOnClickListener(v -> startEndGameActivity());
}
}, timeBetweenChecks);
}
private void startEndGameActivity() {
Intent intent = new Intent(Activity_Game.this, Activity_Winner.class);
if (DeckHelper.player1_score > DeckHelper.player2_score) {
intent.putExtra("winner", new String[]{"1", game_LBL_name_1.getText().toString(), game_LBL_score1.getText().toString()});
} else if (DeckHelper.player1_score < DeckHelper.player2_score) {
intent.putExtra("winner", new String[]{"2", game_LBL_name_2.getText().toString(), game_LBL_score2.getText().toString()});
} else {
intent.putExtra("winner", new String[]{"Both Wins", game_LBL_name_1.getText().toString(), game_LBL_name_2.getText().toString(), game_LBL_score2.getText().toString()});
}
startActivity(intent);
finish();
}
@Override
protected void onStart() {
super.onStart();
DeckHelper.player1_score = 0;
DeckHelper.player2_score = 0;
game_BAR_progress.setProgress(0);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onPause() {
super.onPause();
if(claps.isPlaying())
claps.pause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
| true
|
903f026b39bead9c28c2f26617c08bbdf483cda4
|
Java
|
Tuckle/AdvancedProgramming
|
/Lab9_Database/TeamController.java
|
UTF-8
| 1,737
| 3.375
| 3
|
[] |
no_license
|
package AdvancedProgramming.Lab9_Database;
import java.sql.*;
import java.util.Random;
/**
* Created by apiriu on 5/15/2017.
*/
public class TeamController {
private Random randomGenerator = new Random();
private String insertStmt = "insert into teams(name) values (?)";
private String inputCharacters = "qwertyuiopasdfghjklzxcvbnmQWERTYUaeIouUIOPASDFGHJKLZXCVBNM";
public void create(String teamName) throws SQLException {
Connection con = Database.getConnection();
try (PreparedStatement pstmt = con.prepareStatement("insert into teams (name) values (?)")) {
pstmt.setString(1, teamName);
pstmt.executeUpdate();
}
con.commit();
}
private String getRandomString(String characters, int length)
{
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(randomGenerator.nextInt(characters.length()));
}
return new String(text);
}
public Integer findByName(String teamName) throws SQLException {
Connection con = Database.getConnection();
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery("select id from teams where name='" + teamName + "'");
Integer id = rs.next() ? rs.getInt(1) : null;
rs.close();
return id;
}
}
public void generateRandomTeams(Integer numberOfTeams) {
for(Integer i = 0; i < numberOfTeams; i++){
try {
create(getRandomString(inputCharacters, randomGenerator.nextInt(50)));
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
| true
|
004554d6aa856e4511a9e24be99ce5f641a282b1
|
Java
|
leizhaoyeye/leizhaoyeye
|
/src/main/java/com/example/zhaolei/service/UserService.java
|
UTF-8
| 457
| 1.84375
| 2
|
[] |
no_license
|
package com.example.zhaolei.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.zhaolei.model.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
import java.awt.print.Pageable;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author yuan
* @since 2020-07-08
*/
public interface UserService extends IService<User> {
public IPage<User> getUserList(long page, long size,User user);
}
| true
|
90c74fb8bd5012dc6e7ffb312c7e57b12593be71
|
Java
|
markus512/stardust.engine
|
/stardust-engine-base/src/main/java/org/eclipse/stardust/common/SplicingIterator.java
|
UTF-8
| 1,894
| 2.5
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2011 SunGard CSA LLC and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* SunGard CSA LLC - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.stardust.common;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An Iterator which glues two Iterators together in a chain.
*
* @author ubirkemeyer
* @version $Revision$
*/
public class SplicingIterator<E> implements Iterator<E>
{
private boolean turnAround = false;
private Iterator<? extends E> i1;
private Iterator<? extends E> i2;
/**
* @param i1 The first Iterator or null.
* @param i2 The second Iterator or null.
*/
public SplicingIterator(Iterator<? extends E> i1, Iterator<? extends E> i2)
{
this.i1 = i1;
this.i2 = i2;
}
public boolean hasNext()
{
if (!turnAround)
{
if (i1 != null && i1.hasNext())
{
return true;
}
turnAround = true;
}
return i2 != null && i2.hasNext();
}
public E next()
{
if (!turnAround)
{
if (i1 != null && i1.hasNext())
{
return i1.next();
}
turnAround = true;
}
if (i2 == null)
{
throw new NoSuchElementException();
}
return i2.next();
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
| true
|
c5590c00f22baef170f4a2b69d39c35707decc0d
|
Java
|
samuel-clemens/BlogIT
|
/src/main/java/com/malinowski/blog/web/controllers/HomeController.java
|
UTF-8
| 1,547
| 2.203125
| 2
|
[] |
no_license
|
package com.malinowski.blog.web.controllers;
import com.malinowski.blog.model.Post;
import com.malinowski.blog.repositories.interfaces.PagingPostRepository;
import com.malinowski.blog.repositories.interfaces.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by Jakub on 02.12.2016.
*/
@Controller
@RequestMapping("/")
public class HomeController {
private PostRepository postRepository;
@Autowired
private PagingPostRepository pagingPostRepository;
@Autowired
public HomeController(PostRepository postRepository) {
this.postRepository = postRepository;
}
@GetMapping
public String home(Model model, Pageable pageable){
model.addAttribute("posts5", postRepository.getLast(5));
List<Post> latest3posts = postRepository.getLast(5).stream()
.limit(3).collect(Collectors.toList());
model.addAttribute("posts3", latest3posts);
/*Page<Post> posts = pagingPostRepository.findAll(pageable);
model.addAttribute("post", posts);*/
return "home";
}
@GetMapping("error")
public String error(){
return "notFound";
}
}
| true
|
e1738b30f126a426015a96190e1959ff255a2aee
|
Java
|
iodsp/addesk
|
/uaa/src/main/java/org/iodsp/uaa/mapper/ResourceMapper.java
|
UTF-8
| 1,003
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.iodsp.uaa.mapper;
import org.apache.ibatis.annotations.*;
import org.iodsp.uaa.entity.Resource;
import java.util.List;
@Mapper
public interface ResourceMapper {
@Insert("INSERT INTO oauth_resources(resource_id, name) VALUES(#{id}, #{name})")
void insert(Resource resource);
@Update("UPDATE oauth_resources set name=#{name} where resource_id=#{id}")
int update(Resource resource);
@Select("select * from oauth_resources where resource_id=#{id}")
@Results({
@Result(property = "id", column = "resource_id"),
@Result(property = "name", column = "name")
})
Resource findResourceById(@Param("id") String id);
@Select("select * from oauth_resources")
@Results({
@Result(property = "id", column = "resource_id"),
@Result(property = "name", column = "name")
})
List<Resource> findResource();
@Delete("DELETE from oauth_resources where resource_id=#{id}")
int deleteResource(String id);
}
| true
|
8465b872c2842ff9d79b43e260e2a04a9f344bdd
|
Java
|
pugfish1992/hammock
|
/javario-processor/src/main/java/com/pugfish1992/javario/MetaDataUtils.java
|
UTF-8
| 1,385
| 2.703125
| 3
|
[] |
no_license
|
package com.pugfish1992.javario;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.TypeName;
import javax.lang.model.element.Element;
import javax.lang.model.element.VariableElement;
/**
* Created by daichi on 10/25/17.
*/
class MetaDataUtils {
private static final ClassName stringClass = ClassName.get(String.class);
private MetaDataUtils() {}
static TypeName getVariableType(VariableElement element) {
return TypeName.get(element.asType());
}
static String getVariableName(VariableElement element) {
return element.getSimpleName().toString();
}
/**
* In this library, int, long, boolean, String are supported.
*/
static boolean isSupportedType(TypeName typeName) {
return typeName.equals(TypeName.INT) ||
typeName.equals(TypeName.LONG) ||
typeName.equals(TypeName.BOOLEAN) ||
typeName.equals(stringClass);
}
static boolean isIntType(TypeName typeName) {
return TypeName.INT.equals(typeName);
}
static boolean isLongType(TypeName typeName) {
return TypeName.LONG.equals(typeName);
}
static boolean isBooleanType(TypeName typeName) {
return TypeName.BOOLEAN.equals(typeName);
}
static boolean isStringType(TypeName typeName) {
return typeName.equals(stringClass);
}
}
| true
|
0838e7a2636b651f1dd2f830aaa17ecd545df9ed
|
Java
|
Eskiller93/ProyectoDesarrollo
|
/src/main/java/model/Articulo.java
|
UTF-8
| 2,066
| 2.109375
| 2
|
[] |
no_license
|
package model;
public class Articulo {
private int idArticulos;
private String modeloSKU;
private String marca;
private String tallasDisponibles;
private int Precio;
private String Detalle;
private int cantidad;
private String ubicacion;
public Articulo() {
}
public Articulo(String modeloSKU, String marca, String tallasDisponibles, int Precio, String Detalle, int cantidad, String ubicacion) {
this.modeloSKU = modeloSKU;
this.marca = marca;
this.tallasDisponibles = tallasDisponibles;
this.Precio = Precio;
this.Detalle = Detalle;
this.cantidad = cantidad;
this.ubicacion = ubicacion;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public String getUbicacion() {
return ubicacion;
}
public void setUbicacion(String ubicacion) {
this.ubicacion = ubicacion;
}
public String getDetalle() {
return Detalle;
}
public void setDetalle(String Detalle) {
this.Detalle = Detalle;
}
public int getIdArticulos() {
return idArticulos;
}
public void setIdArticulos(int idArticulos) {
this.idArticulos = idArticulos;
}
public String getModeloSKU() {
return modeloSKU;
}
public void setModeloSKU(String modeloSKU) {
this.modeloSKU = modeloSKU;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getTallasDisponibles() {
return tallasDisponibles;
}
public void setTallasDisponibles(String tallasDisponibles) {
this.tallasDisponibles = tallasDisponibles;
}
public int getPrecio() {
return Precio;
}
public void setPrecio(int Precio) {
this.Precio = Precio;
}
}
| true
|
0005e22ce08b27257d4dde3c3f8d71caf4dd90bd
|
Java
|
johnteow/spring-oauth2-swagger
|
/src/main/java/com/drucare/persistence/entity/UserEntity.java
|
UTF-8
| 5,323
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.drucare.persistence.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import org.hibernate.annotations.Type;
import org.springframework.security.core.userdetails.UserDetails;
@Entity
public class UserEntity implements Serializable, UserDetails {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 8825646974241476909L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private String imageUrl;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
/** The username. */
@Column(name = "username", nullable = false, unique = true)
private String username;
/** The password. */
@Column(name = "password", nullable = false, length = 1000)
private String password;
/** The authorities. */
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "user_authorities", joinColumns = { @JoinColumn(name = "user_id", nullable = false, updatable = false) }, inverseJoinColumns = {
@JoinColumn(name = "authority_id", nullable = false, updatable = false) })
private Set<AuthorityEntity> authorities = new HashSet<AuthorityEntity>(0);
/** The account non expired. */
@Column(name = "accountNonExpired")
@Type(type = "yes_no")
private boolean accountNonExpired;
/** The credentials non expired. */
@Column(name = "credentialsNonExpired")
@Type(type = "yes_no")
private boolean credentialsNonExpired;
/** The enabled. */
@Column(name = "enabled")
@Type(type = "yes_no")
private boolean enabled;
/** The account non locked. */
@Column(name = "accountNonLocked")
@Type(type = "yes_no")
private boolean accountNonLocked;
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public Set<AuthorityEntity> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<AuthorityEntity> authorities) {
this.authorities = authorities;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public void setAccountNonExpired(boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (email == null ? 0 : email.hashCode());
result = prime * result + (username == null ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UserEntity other = (UserEntity) obj;
if (email == null) {
if (other.email != null) {
return false;
}
} else if (!email.equals(other.email)) {
return false;
}
if (username == null) {
if (other.username != null) {
return false;
}
} else if (!username.equals(other.username)) {
return false;
}
return true;
}
}
| true
|
f0bf4fd5cee6ab4a56a9147e5ef6d6fc41bbe23b
|
Java
|
niknetniko/intellij-elixir
|
/src/org/elixir_lang/structure_view/element/modular/Protocol.java
|
UTF-8
| 1,435
| 2.1875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.elixir_lang.structure_view.element.modular;
import com.intellij.navigation.ItemPresentation;
import org.elixir_lang.psi.call.Call;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.elixir_lang.psi.call.name.Function.DEFPROTOCOL;
import static org.elixir_lang.psi.call.name.Module.KERNEL;
/**
* A protocol definition
*/
public class Protocol extends Module {
/*
* Static Methods
*/
public static boolean is(Call call) {
return call.isCallingMacro(KERNEL, DEFPROTOCOL, 2);
}
/*
* Constructors
*/
/**
*
* @param call a top-level {@code Kernel.defprotocol/2} call.
*/
public Protocol(@NotNull Call call) {
super(call);
}
/**
* @param parent the parent {@link Module} or {@link org.elixir_lang.structure_view.element.Quote} that scopes
* {@code call}.
* @param call the {@code Kernel.defprotocol/2} call nested in {@code parent}.
*/
public Protocol(@Nullable Modular parent, @NotNull Call call) {
super(parent, call);
}
/**
* Returns the presentation of the tree element.
*
* @return the element presentation.
*/
@NotNull
@Override
public ItemPresentation getPresentation() {
return new org.elixir_lang.navigation.item_presentation.modular.Protocol(location(), navigationItem);
}
}
| true
|
bfcb720174b2f3b0ff94305ee6e11347fb44bcc3
|
Java
|
SkyAphid/MiscTools
|
/MiscTools/src/main/java/nokori/tools/AtomSnippetGenerator.java
|
UTF-8
| 21,426
| 2.640625
| 3
|
[] |
no_license
|
package nokori.tools;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Stack;
/**
* This class will allow you to select a Java class file and generate corresponding Atom snippets for them. It's intended to be used with LuaJava implementations where
* you'll frequently be calling Java code from Lua, and wanted a documented method of calling them from Atom. This is so that you're not constantly referring to your Java
* code when working in Lua, and you can get auto-complete suggestions on the fly.
*/
public class AtomSnippetGenerator {
private static final String PROJECT_PATH = "D:/Projects/Eclipse Workspace/Git Projects/RobotFarm/RobotFarmGame/src/main/java/nokori/robotfarm/";
private static final String LUA_TOOLS_PACKAGE = PROJECT_PATH + "lua/tools/";
public static final void main(String[] args) {
/*
* Configuration settings for the snippet generator are hosted below.
*
* Insert the names of classes and their locations into the below array, and the generator will locate them and generate snippet documentation for them at runtime.
*/
//Globals names paired with their respective files
//Instantiated globals start with lowercase letters, static ones start with capital letters
//The order of the classes are the same as they are in Robot Farm's LuaManager class for clarity purposes.
String[][] globals = new String[][]{
//Lua tools
{"entityTools", LUA_TOOLS_PACKAGE + "LuaEntityTools.java"},
{"gameTools", LUA_TOOLS_PACKAGE + "LuaGameTools.java"},
{"hudTools", LUA_TOOLS_PACKAGE + "LuaHUDTools.java"},
{"itemTools", LUA_TOOLS_PACKAGE + "LuaItemTools.java"},
{"playerTools", LUA_TOOLS_PACKAGE + "LuaPlayerTools.java"},
{"worldTools", LUA_TOOLS_PACKAGE + "LuaWorldTools.java"},
{"itemDatabase", PROJECT_PATH + "item/database/ItemDatabase.java"},
//Java utilities
{"JavaArray", LUA_TOOLS_PACKAGE + "JavaArray.java"},
{"JavaUtil", LUA_TOOLS_PACKAGE + "JavaUtil.java"},
//Entity creation tools
{"QuickEntity", PROJECT_PATH + "entity/util/QuickEntity.java"},
{"NPCGenerator", PROJECT_PATH + "world/generators/NPCGenerator.java"},
//Stats & Items
{"Element", PROJECT_PATH + "battle/element/Element.java"},
{"ElementalAffinity", PROJECT_PATH + "battle/element/ElementalAffinity.java"},
{"Stat", PROJECT_PATH + "battle/stats/Stat.java"},
{"ItemCategoryID", PROJECT_PATH + "battle/element/Element.java"},
{"AgriculturalToolType", PROJECT_PATH + "item/AgriculturalToolType.java"},
{"TriggerEffect", PROJECT_PATH + "item/TriggerEffect.java"},
{"Property", PROJECT_PATH + "bestiary/Property.java"},
{"CreatureVariant", PROJECT_PATH + "bestiary/CreatureVariant.java"},
//Sprites & Variants
{"SpriteSheetID", PROJECT_PATH + "sprites/SpriteSheetID.java"},
{"AokobotVariant", PROJECT_PATH + "bestiary/AokobotVariant.java"},
{"MonsterVariant", PROJECT_PATH + "bestiary/MonsterVariant.java"},
//GeneralStats Entity Component
{"GeneralStats", PROJECT_PATH + "entity/components/GeneralStats.java"},
{"EntityType", PROJECT_PATH + "entity/descriptors/EntityType.java"},
{"Job", PROJECT_PATH + "entity/descriptors/Job.java"},
{"UniquePointer", PROJECT_PATH + "entity/descriptors/UniquePointer.java"},
{"Gender", PROJECT_PATH + "entity/descriptors/Gender.java"},
{"Alignment", PROJECT_PATH + "entity/descriptors/Alignment.java"},
//Inventory Entity Component
{"Inventory", PROJECT_PATH + "entity/components/Inventory.java"},
//Personality Entity Component
{"Personality", PROJECT_PATH + "entity/components/Personality.java"},
{"PersonalityTrait", PROJECT_PATH + "entity/components/PersonalityTrait.java"},
//Memory Entity Component
{"Memory", PROJECT_PATH + "entity/components/Memory.java"},
{"Mood", PROJECT_PATH + "entity/components/Memory.java"},
//Portrait Entity Component
{"Portrait", PROJECT_PATH + "entity/components/Portrait.java"},
{"PortraitGenderTag", PROJECT_PATH + "entity/components/PortraitGenderTag.java"},
//WorldRegistry
{"WorldRegistrySettingFlag", PROJECT_PATH + "world/WorldRegistrySettingFlag.java"},
};
//Snippets that are just generated as-is from the below array. These are for classes like built-in java ones where we can't read the source file.
//Array Order: SnippetName, SnippetPrefix, SnippetBody, SnippetDescription
String[][] manualSnippets = new String[][]{
{"random", "random", "random", "A coerced copy of a Java Random object, allowing access to its arguably better tools than Lua's counterpart. "
+ "Look up its own documentation for more information."},
};
//Create filter for functions I want to be ignored - such as inner anonymous callbacks & functions
ArrayList<String> functionFilter = new ArrayList<>();
functionFilter.add("callback()");
functionFilter.add("select()");
functionFilter.add("select(index)");
functionFilter.add("getName()");
functionFilter.add("getDesc()");
//This will be adding to the front of the output. Adding in the header directly to the generator allows for me to just use CTRL-A, CTRL-V for pasing into the snippets CSON file.
String fileHeader = "'.source.lua':\n" +
"\n" +
"\t#This snippets file will allow the user to shortcut all of the functions available in the Robot Farm API\n" +
"\t#I'd normally go all out and make some sort of proper auto-complete system, but I don't think it's worth the effort when this works good enough\n" +
"\t#I use underscores to denote the usual lua colon (denoting functions) because Atom's autocomplete system cancels itself out if you actually use a colon, sorry about that\n";
/*
* Begin Generation
*/
String snippetOutput = fileHeader;
//Generated snippets from java files
for (int i = 0; i < globals.length; i++){
snippetOutput += "\t#" + globals[i][0] + " Globals\n";
String generatedSnippet = run(globals[i][1], globals[i][0], functionFilter);
if (generatedSnippet == null || generatedSnippet.trim().isEmpty()) {
snippetOutput += "\t#(No documentation available)\n\n";
} else {
snippetOutput += "\n" + generatedSnippet;
}
}
//Manually created snippets
for (int i = 0; i < manualSnippets.length; i++){
snippetOutput += "\t#" + manualSnippets[i][0] + " Globals\n\n";
snippetOutput += generateSnippet(manualSnippets[i][0], manualSnippets[i][1], manualSnippets[i][2], manualSnippets[i][3]);
}
/*
* Copy and paste the results into the clipboard.
*/
StringSelection selection = new StringSelection(snippetOutput);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
System.out.println("\nCopied snippets to clipboard.");
}
public static String run(String classPath, String globalsName, ArrayList<String> functionFilter){
// I just input the settings manually like this, it's faster
File classFile = new File(classPath);
try {
String content = new String(Files.readAllBytes(classFile.toPath()));
/*
* Build enumerator key snippets for the given content
*/
String[][] enumKeys = getEnumKeys(classPath, content);
/*
* Build function snippets for the given content
*/
//Fetch function names and put them into Stacks
//The indices of each Stack correspond to each other
Stack<String> rawFunctions = new Stack<>();
Stack<String> snippetFunctions = new Stack<>();
Stack<String> descriptions = new Stack<>();
getFunctions(content, rawFunctions, snippetFunctions, descriptions, functionFilter);
Collections.reverse(rawFunctions);
Collections.reverse(snippetFunctions);
Collections.reverse(descriptions);
String snippets = "";
if (!rawFunctions.isEmpty()) {
snippets = buildSnippets(globalsName, enumKeys, rawFunctions, snippetFunctions, descriptions);
}
return snippets;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Fetches an array of the key entries and their comments (if applicable)
*/
public static String[][] getEnumKeys(String classPath, String content) {
System.out.println("Starting getEnumKeys() ------------------------------------------------------------------------");
String header = content.substring(0, content.indexOf("{") + 1);
if (header.contains("enum")) {
System.out.println(classPath.replace(PROJECT_PATH, "") + " verified as an enumerator. Extracting keys into Atom snippets...");
/*
* Remove the header, leaving the enum keys at the top of the string
*/
String headerlessContent = content.replace(header, "");
/*
* Process the headerlessContent into the "raw keys," or the section of the class containing all of the enum keys
*/
int keysEnd = headerlessContent.indexOf(";");
if (keysEnd == -1) {
//Some enum classes don't use a semi-colon to end them, but rather the whole class is just a set of enum keys. In which case, we'll use the ending bracket to find the end.
keysEnd = headerlessContent.indexOf("}");
}
/*
* Create the raw keys. Remove tabs. Remove empty constructors (e.g. objects being inserted into enumerators)
*/
String rawKeys = headerlessContent.substring(0, keysEnd).replace("\t", "").replace("()", "");
/*
* Check if the enum uses constructors. Remove them to prevent the following split() call from getting confused by constructor function arguments
*/
while (rawKeys.contains("(") && rawKeys.contains(")")) {
int start = rawKeys.indexOf("(");
int end = rawKeys.indexOf(")") + 1;
String constructor = rawKeys.substring(start, end);
rawKeys = rawKeys.replace(constructor, "");
}
/*
* Finally, build the array of isolated keys & comments
*/
String[] keys = rawKeys.split(",");
String[] comments = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
//By default we just set the comment to be nothing.
comments[i] = "";
//Trim the keys entry to work with a cleaner string
String trimmedKey = keys[i].trim();
/*
* Debug printouts: starting outputs
*/
//System.err.println();
//System.err.println("Starting Processing on Enum Entry " + i);
//System.err.println("Trimmed Unprocessed Key: [" + trimmedKey + "]");
/*
* SINGLE LINE COMMENT PROCESSOR
*/
if (trimmedKey.startsWith("//")) {
//Isolate comment
comments[i] = trimmedKey.substring(0, lineSeparatorIndex(trimmedKey));
//Remove comment from key entry
keys[i] = keys[i].replace(comments[i], "");
//Clean up comment
comments[i] = comments[i].replaceFirst("//", "");
}
/*
* MULTI-LINE COMMENT PROCESSOR
*/
if (trimmedKey.startsWith("/*")) {
//Isolate comment
comments[i] = keys[i].substring(0, keys[i].indexOf("*/") + 2);
//Remove comment from key entry
keys[i] = keys[i].replace(comments[i], "");
//Clean up comment
comments[i] = comments[i].replace("/*" + System.lineSeparator(), "")
.replace("*/", "")
.replaceFirst("\\* ", "")
.replace(System.lineSeparator() + " * ", "; ");
}
/*
* FINAL CLEANUP OF PROCESSED ENUM KEYS AND COMMENTS
*/
comments[i] = comments[i].trim();
keys[i] = keys[i].replace(System.lineSeparator(), "").trim();
/*
* Debug printouts: Final processed outputs
*/
//System.err.println("Processed Final Enum Key: [" + keys[i] + "]");
//System.err.println("Processed Output Comment: [" + comments[i] + "]");
}
/*
* Print the result
*/
System.out.println("Result:");
for (int i = 0; i < keys.length; i++) {
System.out.println("Index: " + i + " Key: " + keys[i] + " Comment: " + comments[i]);
}
System.out.println("");
return new String[][] {keys, comments};
} else {
System.out.println(classPath.replace(PROJECT_PATH, "") + " is not an enumerator. Aborting.\n");
}
return null;
}
/**
* Get the index of the line separator in the string. I had to add the shitty workaround below because the string sometimes has a different new line character than what
* the System gives back to us.
*/
private static int lineSeparatorIndex(String s) {
int lineSepIndex = s.indexOf(System.lineSeparator());
if (lineSepIndex == -1) {
lineSepIndex = s.indexOf("\n");
}
return lineSepIndex;
}
/**
* Fetches a list of functions from a class file that can be inserted into a .txt file for use by <code>buildSnippets()</code>
*
* Keep in mind that it's not perfect and may need human trimming.
*/
public static void getFunctions(String content, Stack<String> rawFunctions, Stack<String> snippetFunctions, Stack<String> descriptions, ArrayList<String> functionFilter) {
System.out.println("Starting getFunctions() ------------------------------------------------------------------------");
/*
* Split the file by new line and read each line for function names
*/
String[] splitContent = content.split("\n");
for (int i = 0; i < splitContent.length; i++) {
/*
*
* STEP 1: Begin basic setup & weed out undesirable content
*
*/
String f = splitContent[i];
//These originally were : \tpublic static & \tpublic, but some classes don't have this formatting, so I'm removing the tab characters for now.
String startTag = f.contains("static") ? "public static " : "public ";
String endTag = "{";
int start = f.indexOf(startTag);
int end = f.indexOf(endTag, start);
// This weeds out undesirable content (non-functions)
if (start == -1 || end == -1) {
continue;
}
/*
* STEP 2: Fetches the comment above the function if there is one and use it as
* a description for the snippet
*/
String description = "";
int upIterator = i - 1;
String singleLineCommentTag = "//";
String multiLineCommentStartTag = "*/";
String multiLineCommentBodyTag = "\t *";
String multiLineCommentEndTag = "*/";
String multiLineCommentParameter = "* @";
descIterator:
while (upIterator >= 0) {
String d = splitContent[upIterator];
//Checks the current line for a comment. If no comment is found, end the description search.
if (d.startsWith(singleLineCommentTag)) {
//One line comment
description += d.replace(singleLineCommentTag, "");
} else if (d.contains(multiLineCommentStartTag) || d.contains(multiLineCommentBodyTag) || d.contains(multiLineCommentEndTag)) {
//Multi-line comment (ignores parameter/return-type lines)
if (!d.contains(multiLineCommentParameter)) {
description += d.replace(multiLineCommentStartTag, "").replace(multiLineCommentBodyTag, "").replace(multiLineCommentEndTag, "");
}
} else {
break descIterator;
}
upIterator--;
}
description = description.replace("\t", "").replace("\n", "").replace("\r", "").trim();
/*
*
*
* STEP 3: Find public functions and isolate them
*
*
*/
// We keep two versions of the function on hand:
// function: a version without Atom tab stops (used for naming the snippets
// later)
// snippetFunction: a version with Atom tab stops (e.g. the ${1:argument} bits)
// (for making the snippets later)
String function, snippetFunction;
// 1) Find the "public void functionName()" bit, remove the "public", this
// leaves us with "void functionName()"
// 2) Jump to the first space after that to isolate and remove the return type,
// ideally leaving us with "functionName()"
function = f.substring(start, end).replace(startTag, "");
function = function.substring(function.indexOf(" ") + 1);
/*
*
* STEP 4: Next, we isolate the arguments and simplify it down to a prettier
* form for the Atom snippet
*
*/
int parenthesisStart = function.indexOf("(");
int parenthesisEnd = function.indexOf(")");
// If there are no parenthesis, it's not a function (it might be a class name
// that made it through)
if (parenthesisStart == -1 || parenthesisEnd == -1) {
continue;
}
// This will make the following edits easier
parenthesisStart++;
parenthesisEnd++;
String arguments = function.substring(parenthesisStart, parenthesisEnd);
String[] argumentsArray = arguments.split(" ");
snippetFunction = function = function.replace(arguments, "").trim();
/*
*
* STEP 5: Re-add the variable names back in without the types (shortens the
* name and cleans it up)
*
* From here we also start separating the snippetFunction/rawFunction operations
*
*/
int modulo = 2;
int tabStops = 1;
for (int j = 0; j < argumentsArray.length; j++) {
if (j % modulo == 0) {
continue;
}
// Create the raw function without the snippet syntax
function += argumentsArray[j].replace("(", "").replace(")", "");
// Create a version of the function with snippet tab stops for ease of use
snippetFunction += "${" + tabStops + ":"
+ argumentsArray[j].replace("(", "").replace(")", "").replace(",", "},");
tabStops++;
// Clean up the functions after
if (function.endsWith(",")) {
if (j + modulo < argumentsArray.length) {
function += " ";
snippetFunction += " ";
} else {
function = function.substring(0, function.length() - 1);
snippetFunction = snippetFunction.substring(0, snippetFunction.length() - 1);
}
}
}
/*
*
*
* STEP 6: Finalization and cleanup
*
*
*/
// Add the final ending parenthesis in and close the tab stops (if there's more
// than just the one at the end)
function += ")";
if (tabStops > 1) {
snippetFunction += "}";
}
snippetFunction += ")$" + tabStops;
// If the final function is in the filter, don't add it
if (functionFilter.contains(function)) {
System.out.println(function + " is in the function filter. Skipping...\n");
continue;
}
System.out.println("Result: ");
System.out.println("Raw Function: " + function);
System.out.println("Snippet Function: " + snippetFunction);
System.out.println("Description: " + description);
if (!rawFunctions.contains(function)) {
// Add function to the list if its not already in there
rawFunctions.push(function);
snippetFunctions.push(snippetFunction);
descriptions.push(description);
System.out.println("Added to list. Continuing...");
} else {
System.out.println("Duplicate entry detected. Continuing...");
}
System.out.println();
}
if (rawFunctions.isEmpty()) {
System.out.println("No functions found. Continuing...");
}
}
/**
* Automatically generates a snippets .cson file beside the given .txt file of functionNames. The functions must be separated by new lines (\n), which is
* done automatically by <code>getFunctions()</code>. The filename is the assumed name of the globals that the snippets are being generated for.
*/
public static String buildSnippets(String globalsName, String[][] enumKeys, Stack<String> rawFunctions, Stack<String> snippetFunctions, Stack<String> descriptions) {
System.out.println("\nStarting buildSnippets(): ------------------------------------------------------------------------");
String snippets = "";
String functionSeparator = ":";
//Create enum key snippets (if applicable)
if (enumKeys != null) {
for (int i = 0; i < enumKeys.length; i++) {
snippets += generateSnippet(globalsName + functionSeparator + enumKeys[0][i],
globalsName + "_" + enumKeys[0][i],
globalsName + functionSeparator + enumKeys[0][i], enumKeys[1][i]);
}
}
//Create function snippets (if applicable)
while(!rawFunctions.isEmpty()) {
String rawFunction = rawFunctions.pop();
String snippetFunction = snippetFunctions.pop();
String description = descriptions.pop();
snippets += generateSnippet(globalsName + functionSeparator + rawFunction,
globalsName + "_" + rawFunction,
globalsName + functionSeparator + snippetFunction, description);
}
System.out.print(snippets);
return snippets;
}
public static String generateSnippet(String snippetName, String snippetPrefix, String snippetBody, String snippetDescription){
String snippet = "";
snippet += "\t'" + snippetName + "':";
snippet += "\n\t\t'prefix': '" + snippetPrefix + "'";
snippet += "\n\t\t'body': '" + snippetBody + "'";
snippet += "\n\t\t'description': '" + parseCSONSpecialCharacters(snippetDescription) + "'";
snippet += "\n\n";
return snippet;
}
public static String parseCSONSpecialCharacters(String s){
StringBuilder b = new StringBuilder(s);
boolean quoteSwitch = false;
for (int i = 0; i < s.length(); i++){
char c = b.charAt(i);
if (c == '\'') {
b.setCharAt(i, '’');
}
if (c == '\"'){
if (quoteSwitch){
b.setCharAt(i, '”');
} else{
b.setCharAt(i, '“');
}
quoteSwitch = !quoteSwitch;
}
}
return b.toString();
}
}
| true
|
4721653abfeccea447f21c04284b7dd8726814be
|
Java
|
fh-swf/Aufgabe10
|
/Aufgabe10/src/de/fhswf/verwaltung/Database.java
|
ISO-8859-1
| 13,176
| 2.96875
| 3
|
[] |
no_license
|
package de.fhswf.verwaltung;
import java.io.File;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import de.fhswf.db.Testdb;
public class Database {
private static final String DataBaseFileName = "project_hsql_db";
private static final File DataBaseFile = new File(DataBaseFileName+".script");
private Testdb dataBase;
private Integer id;
/**
* Initialisiert eine HSQL-Datenbank. Beim erstmaligem Starten der Datenbank wird eine neue
* Struktur angelegt. Andernfalls wird die bestehende Struktur geladen.
*/
private void initDataBase() {
// Abfangen der moeglichen SQL-Exceptions
boolean DB_exists = DataBaseFile.isFile();
System.out.println(String.valueOf(DB_exists) + ", Datenbank vorhanden! ");
try {
// Starten der Datenbank
dataBase = new Testdb(DataBaseFileName);
// Prfen ob DataBaseFile noch nicht angelegt wurde
if(!DB_exists){
// Anlegen einer neuen Tabellenstruktur, falls die Datenbank noch nicht besteht.
update(
"CREATE TABLE student ( " +
"id INTEGER, " +
"name VARCHAR(30), " +
"vorname VARCHAR(30), " +
"email VARCHAR(40), " +
// "plz INTEGER, " +
// "ort VARCHAR(30), " +
// "adresse VARCHAR(50), " +
")");
update(
"CREATE TABLE company ( " +
"id INTEGER IDENTITY, " +
"name VARCHAR(50), " +
// "plz INTEGER, " +
// "ort VARCHAR(30), " +
// "adresse VARCHAR(50), " +
"kontaktp VARCHAR(30), " +
// "mail VARCHAR(30), " +
// "tel VARCHAR(30), " +
// "fax VARCHAR(30), " +
")");
update(
"CREATE TABLE project ( " +
"id INTEGER IDENTITY, " +
"thema VARCHAR(30), " +
"beschreibung VARCHAR(30), " +
// "skizze VARCHAR(255), " +
")");
// Fllen der Tabelle mit Eintrgen
update("INSERT INTO student(id, name, vorname, email) VALUES(10018333, 'Schmidt', 'Anton', 'a.s@gmail.com')");
update("INSERT INTO student(id, name, vorname, email) VALUES(10018344, 'Braun', 'Hans', 'h.b@alice.de')");
update("INSERT INTO company(name, kontaktp) VALUES('Braun AG', 'Dipl. Ing. Meyer')");
update("INSERT INTO company(name, kontaktp) VALUES('Siemens AG', 'Dipl. Ing. Mueller')");
update("INSERT INTO project(thema, beschreibung) VALUES('Rsiersoftware', 'Software')");
update("INSERT INTO project(thema, beschreibung) VALUES('SPS-Software', 'Software')");
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
/**
* Sendet einen SQL-Ausdruck ab. Bitte fr CREATE, DROP, INSERT und UPDATE benutzen.
*
* @param expression
* SQL-Ausdruck
*/
public void update(String expression){
if(dataBase == null)
throw new IllegalAccessError("Bitte erst initDataBase() ausfhren");
try {
this.dataBase.update(expression);
} catch (SQLException e) {
System.out.println("Fehler in folgendem Statement:");
System.out.println(expression);
e.printStackTrace();
}
}
/**
* Schliet alle Verbindungen und beendet die Datenbank.
*/
public void shutdown(){
try {
dataBase.shutdown();
} catch (SQLException e) {
System.out.println("Fehler beim Beenden der Datenbank:");
e.printStackTrace();
}
}
/**
* Default Constructor.
*/
public Database(){
initDataBase();
}
@SuppressWarnings("deprecation")
public void load(MainWindow parent)
{
try {
System.out.println("--- TABELLE 1 ---");
// Ausgeben aller Personen ber ein ResultSet
ResultSet rs1 = dataBase.query("SELECT * FROM fahrer");
while (rs1.next()) {
Integer id = rs1.getInt("id");
String name = rs1.getString("name");
String vorname = rs1.getString("vorname");
String email = rs1.getString("email");
ClassStudent classStudent = new ClassStudent(name, vorname, email);
classStudent.setFahrer_ID(id);
classStudent.setEdited(0);
parent.addClassStudent(classStudent);
parent.tableDataStudent.addRow(classStudent, parent);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(name);
stringBuilder.append(", ");
stringBuilder.append(vorname);
stringBuilder.append(", ");
stringBuilder.append(email);
System.out.println(stringBuilder.toString());
}
System.out.println("--- TABELLE 2 ---");
// Ausgeben aller Personen ber ein ResultSet
ResultSet rs2 = dataBase.query("SELECT * FROM fahrzeug");
while (rs2.next()) {
id = rs2.getInt("id");
String kennzeichen = rs2.getString("kennzeichen");
Date erstzulassung = rs2.getDate("erstzulassung");
ClassCompany classCompany = new ClassCompany(kennzeichen, erstzulassung);
classCompany.setFahrzeug_ID(id);
classCompany.setEdited(0);
parent.addClassCompany(classCompany);
parent.tableDataCompany.addRow(classCompany, parent);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(kennzeichen);
stringBuilder.append(", ");
stringBuilder.append(erstzulassung.getDay());
stringBuilder.append(".");
stringBuilder.append(erstzulassung.getMonth()+1);
stringBuilder.append(".");
stringBuilder.append(erstzulassung.getYear());
System.out.println(stringBuilder.toString());
}
System.out.println("--- TABELLE 3 ---");
// Ausgeben aller Personen ber ein ResultSet
ResultSet rs3 = dataBase.query("SELECT * FROM fahrer_fahrzeug");
while (rs3.next()) {
id = rs3.getInt("id");
Integer fahrerId = rs3.getInt("fahrer_id");
Integer fahrzeugId = rs3.getInt("fahrzeug_id");
ClassProject classProject = new ClassProject(fahrerId, fahrzeugId);
classProject.setBez_ID(id);
parent.addClassProject(classProject);
parent.tableDataProject.addRow(classProject, parent);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(id);
stringBuilder.append(", ");
stringBuilder.append(fahrerId);
stringBuilder.append(" : ");
stringBuilder.append(fahrzeugId);
System.out.println(stringBuilder.toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// @SuppressWarnings("deprecation")
// public void write(MainWindow parent)
// {
// System.out.println("delete Drivers...");
// for ( ClassStudent classStudent : parent.classStudentMapDel )
// {
// System.out.println(classStudent.toString());
// if(classStudent.getFahrer_ID() != null)
// update("DELETE FROM fahrer WHERE id = " + classStudent.getFahrer_ID()
// );
// }
// System.out.println(parent.classStudentMapDel.size() + " deleted Drivers...");
//
// System.out.println("writing Driver...");
// for ( ClassStudent classStudent : parent.classStudentMap )
// {
// Date date = new Date(classStudent.getFueSeit().getYear(), classStudent.getFueSeit().getMonth(), classStudent.getFueSeit().getDate());
// System.out.println(classStudent.toString());
// if (classStudent.getEdited() == 1)
// update("UPDATE fahrer " +
// "SET (name, fKlasse, fseit) = ('" +
// classStudent.getName() + "', '" +
// classStudent.getFueKlasse() + "', '" +
// date.toString() + "') " +
// "WHERE id = " + classStudent.getFahrer_ID()
// );
//
// if (classStudent.getEdited() == 3)
// update("INSERT INTO fahrer(name, fklasse, fseit) " +
// "VALUES('" +
// classStudent.getName() + "', '" +
// classStudent.getFueKlasse() + "', '" +
// date.toString() + "')"
// );
// }
// System.out.println(parent.classCompanyMap.size() + " written Driver...");
//
//
// System.out.println("delete Cars...");
// for ( ClassCompany classCompany : parent.classCompanyMapDel )
// {
// System.out.println(classCompany.toString());
// if(classCompany.getFahrzeug_ID() != null)
// update("DELETE FROM fahrzeug WHERE id = " + classCompany.getFahrzeug_ID()
// );
// }
// System.out.println(parent.classCompanyMapDel.size() + " deleted Cars...");
//
// System.out.println("writing Cars...");
// for ( ClassCompany classCompany : parent.classCompanyMap )
// {
// Date date = new Date(classCompany.getErstzulassung().getYear(), classCompany.getErstzulassung().getMonth(), classCompany.getErstzulassung().getDate());
// System.out.println(classCompany.toString());
// if (classCompany.getEdited() == 1)
// update("UPDATE fahrzeug " +
// "SET (kennzeichen, erstzulassung) = ('" +
// classCompany.getKennzeichen() + "', '" +
// date.toString() + "') " +
// "WHERE id = " + classCompany.getFahrzeug_ID()
// );
//
// if (classCompany.getEdited() == 3)
// update("INSERT INTO fahrzeug(kennzeichen, erstzulassung) " +
// "VALUES('" +
// classCompany.getKennzeichen() + "', '" +
// date.toString() + "')"
// );
// }
// System.out.println(parent.classCompanyMap.size() + " written Cars...");
//
// System.out.println("delete Relations...");
// for ( ClassProject classProject : parent.classProjectMapDel )
// {
// System.out.println(classProject.toString());
// if(classProject.getBez_ID() != null)
// update("DELETE FROM fahrer_fahrzeug WHERE id = " + classProject.getBez_ID()
// );
// }
// System.out.println(parent.classProjectMapDel.size() + " deleted Cars...");
//
//
// System.out.println("writing Relations...");
// for ( ClassProject classProject : parent.classProjectMap )
// {
// System.out.println(classProject.toString());
// if (classProject.getNeu())
// update("INSERT INTO fahrer_fahrzeug(fahrer_id, fahrzeug_id) " +
// "VALUES('" +
// classProject.getDriverId() + "', '" +
// classProject.getCarId() + "')"
// );
// }
// System.out.println(parent.classProjectMap.size() + "written Relations...");
// }
public void runTestSzenario(){
try {
System.out.println("--- TESTFALL 1 ---");
System.out.println("--- TABELLE 1 ---");
// Ausgeben aller Personen im Terminal
dataBase.dumpQuery("SELECT * FROM student");
System.out.println("--- TABELLE 2 ---");
// Ausgeben aller Personen im Terminal
dataBase.dumpQuery("SELECT * FROM company");
System.out.println("--- TABELLE 3 ---");
// Ausgeben aller Personen im Terminal
dataBase.dumpQuery("SELECT * FROM project");
System.out.println("--- TESTFALL 2 ---");
System.out.println("--- TABELLE 1 ---");
// Ausgeben aller Personen ber ein ResultSet
ResultSet rs1 = dataBase.query("SELECT * FROM student");
while (rs1.next()) {
String name = rs1.getString("name");
String vorname = rs1.getString("vorname");
String email = rs1.getString("email");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(name);
stringBuilder.append(", ");
stringBuilder.append(vorname);
stringBuilder.append(", ");
stringBuilder.append(email);
System.out.println(stringBuilder.toString());
}
// System.out.println("--- TABELLE 2 ---");
// // Ausgeben aller Personen ber ein ResultSet
// ResultSet rs2 = dataBase.query("SELECT * FROM company");
//
// while (rs2.next()) {
// String kennzeichen = rs2.getString("kennzeichen");
// Date erstzulassung = rs2.getDate("erstzulassung");
// StringBuilder stringBuilder = new StringBuilder();
// stringBuilder.append(kennzeichen);
// stringBuilder.append(", ");
// stringBuilder.append(erstzulassung.getDay());
// stringBuilder.append(".");
// stringBuilder.append(erstzulassung.getMonth());
// stringBuilder.append(".");
// stringBuilder.append(erstzulassung.getYear());
// System.out.println(stringBuilder.toString());
// }
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Database dbh = new Database();
dbh.runTestSzenario();
dbh.shutdown();
}
}
| true
|
765f6b9ad5888b02ccb818c5bc1007ea4fe72408
|
Java
|
DamonChow/Demo
|
/mybatis/mybatis-common/src/main/java/com/damon/dao/BlogMapper.java
|
UTF-8
| 217
| 1.585938
| 2
|
[] |
no_license
|
package com.damon.dao;
import com.damon.vo.Blog;
import org.mybatis.spring.annotation.MapperScan;
/**
* Created by Damon on 2017/5/16.
*/
@MapperScan
public interface BlogMapper {
Blog getBlogByID(int id);
}
| true
|
a7073f22f466b35491d7444ae98176cf2ab6baa6
|
Java
|
enrico404/GestioneCampionati
|
/src/gestionecampionati/grafica/inserimento_risultati/InsRis/InsRisPanel.java
|
UTF-8
| 2,393
| 2.671875
| 3
|
[] |
no_license
|
package gestionecampionati.grafica.inserimento_risultati.InsRis;
import gestionecampionati.Campionato;
import gestionecampionati.grafica.MainFrame;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
/**
* Scheletro del pannello per l'inserimento dei risulati nel caso degli sport: calcio, basket
* utile per gestire al meglio il layout della schermata e recuperare i vari dati necessari
* @author Enrico
*/
public class InsRisPanel extends JPanel {
private JPanel menu;
private Campionato c;
private MainFrame f;
private InsRisPanelUP panelUp;
private InsRisPanelCenter panelCenter;
private InsRisPanelDown panelDown;
/**
* Costruttore del pannello scheletro inserimento risultati
* @param menu pannello menu, per il pulsante indietro
* @param c struttura dati da aggiornare
* @param f frame in cui inserire i vari pannelli
*/
public InsRisPanel(JPanel menu, Campionato c, MainFrame f) {
super();
this.menu = menu;
this.c = c;
this.f = f;
panelUp = new InsRisPanelUP(c);
panelCenter = new InsRisPanelCenter();
panelDown = new InsRisPanelDown(c, this, menu, f);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.add(Box.createRigidArea(new Dimension(0, 100)));
this.add(panelUp);
this.add(Box.createRigidArea(new Dimension(0, 40)));
this.add(panelCenter);
this.add(Box.createRigidArea(new Dimension(0, 60)));
this.add(panelDown);
}
public InsRisPanelUP getPanelUp() {
return panelUp;
}
public void setPanelUp(InsRisPanelUP panelUp) {
this.panelUp = panelUp;
}
public InsRisPanelCenter getPanelCenter() {
return panelCenter;
}
public void setPanelCenter(InsRisPanelCenter panelCenter) {
this.panelCenter = panelCenter;
}
public InsRisPanelDown getPanelDown() {
return panelDown;
}
public void setPanelDown(InsRisPanelDown panelDown) {
this.panelDown = panelDown;
}
@Override
public void paint(Graphics g){
super.paint(g);
}
}
| true
|
2104d974ce3c201d6dfa7a2f9aa6e0032a34bc66
|
Java
|
fg-meizhi/fg-TestGit
|
/sc_backrestore/src/main/java/com/ibmboc/server_conf/config/ConfigUtil.java
|
UTF-8
| 939
| 2.453125
| 2
|
[] |
no_license
|
package com.ibmboc.server_conf.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* <类简介><br>
* <p/>
* <类详细描述><br>
* <p/>
* Created by IntelliJ IDEA.
* User: MeiZhi
* Date: 14-10-1
* Time: 下午4:26
*/
public class ConfigUtil {
static Logger logger = LoggerFactory.getLogger(ConfigUtil.class);
private static String filePath = "backrestore-config.properties";
public static String get(String key) {
Properties props = new Properties();
InputStream in = ConfigUtil.class.getClassLoader().getResourceAsStream(filePath);
String value = null;
try {
props.load(in);
value = props.getProperty(key);
} catch (IOException e) {
logger.error("读取配置文件{}失败!", filePath, e);
}
return value;
}
}
| true
|
e534321a54d1e6d7b7a6c463dce4cfe1a61822f7
|
Java
|
Salma15/pixelcareBeta_app
|
/app/src/main/java/com/fdc/pixelcare/Activities/Home/HospitalSearchActivity.java
|
UTF-8
| 15,152
| 1.609375
| 2
|
[] |
no_license
|
package com.fdc.pixelcare.Activities.Home;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.fdc.pixelcare.Adapters.Home.HospitalAdapter;
import com.fdc.pixelcare.Adapters.Home.HospitalSeachMapAdapter;
import com.fdc.pixelcare.DataModel.HospitalList;
import com.fdc.pixelcare.Network.APIClass;
import com.fdc.pixelcare.Network.APIParam;
import com.fdc.pixelcare.R;
import com.fdc.pixelcare.Utils.AppController;
import com.fdc.pixelcare.Utils.AppUtils;
import com.fdc.pixelcare.Utils.MHConstants;
import com.fdc.pixelcare.Utils.ShareadPreferenceClass;
import com.fdc.pixelcare.Views.CustomTextViewItalic;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by SALMA on 21-12-2018.
*/
public class HospitalSearchActivity extends AppCompatActivity implements View.OnClickListener {
public static final String REQUEST_TAG = "HospitalSearchActivity";
SharedPreferences sharedPreferences;
ShareadPreferenceClass shareadPreferenceClass;
int USER_ID, USER_LOGINTYPE;
String USER_NAME, USER_EMAIL, USER_MOBILE, USER_LOCATION, SPECIALIZATION_LIST, DOCTORS_LIST, HOSPITAL_MAP_LIST;
int SELECTED_CITY_ID = 0, SELECTED_SPEC_ID = 0, SELECTED_FILTER_TYPE = 0;
double SELECTED_GEO_LATITUDE = 0.00, SELECTED_GEO_LONGITUDE = 0.00;
AutoCompleteTextView _header_seach_autotext;
ImageView _header_search_cancel;
List<HospitalList> hospitalListArraylist = new ArrayList<>();
RecyclerView recyclerView_hospitallist;
HospitalAdapter adapter;
CustomTextViewItalic no_data;
Gson gson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_map);
hospitalListArraylist = new ArrayList<>();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Bundle b = getIntent().getExtras();
String title = b.getString("title");
setTitle(title);
shareadPreferenceClass = new ShareadPreferenceClass(HospitalSearchActivity.this);
sharedPreferences = shareadPreferenceClass.getSharedPreferences(HospitalSearchActivity.this);
if(sharedPreferences !=null) {
USER_ID = sharedPreferences.getInt(MHConstants.PREF_USER_ID, 0);
USER_NAME = sharedPreferences.getString(MHConstants.PREF_USER_NAME, "");
USER_EMAIL = sharedPreferences.getString(MHConstants.PREF_USER_EMAIL, "");
USER_MOBILE = sharedPreferences.getString(MHConstants.PREF_USER_MOBILE, "");
USER_LOCATION = sharedPreferences.getString(MHConstants.PREF_USER_LOCATION, "");
USER_LOGINTYPE = sharedPreferences.getInt(MHConstants.PREF_USER_LOGINTYPE, 0);
SPECIALIZATION_LIST = sharedPreferences.getString(MHConstants.PREF_SPECIALIZATION_LIST, "");
DOCTORS_LIST = sharedPreferences.getString(MHConstants.PREF_DOCTORS_LIST, "");
HOSPITAL_MAP_LIST = sharedPreferences.getString(MHConstants.PREF_HOSPITALS_MAP_LIST, "");
SELECTED_CITY_ID = sharedPreferences.getInt(MHConstants.PREF_CITY_ID, 0);
SELECTED_SPEC_ID = sharedPreferences.getInt(MHConstants.PREF_SPECIALTY_ID, 0);
SELECTED_FILTER_TYPE = sharedPreferences.getInt(MHConstants.PREF_HOME_FILTER, 0);
SELECTED_GEO_LATITUDE = Double.parseDouble(sharedPreferences.getString(MHConstants.PREF_MY_LATITUDE, ""));
SELECTED_GEO_LONGITUDE = Double.parseDouble(sharedPreferences.getString(MHConstants.PREF_MY_LONGITUDE, ""));
Log.d(AppUtils.TAG , " *********** HospitalSearchActivity **************** ");
Log.d(AppUtils.TAG + " UserID: ", String.valueOf(USER_ID));
Log.d(AppUtils.TAG + " name: ", USER_NAME);
Log.d(AppUtils.TAG + " email: ", USER_EMAIL);
Log.d(AppUtils.TAG + " MOBILE: ", USER_MOBILE);
Log.d(AppUtils.TAG + " Location: ", USER_LOCATION);
}
initializationView();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
private void initializationView() {
hospitalListArraylist = new ArrayList<>();
_header_seach_autotext = (AutoCompleteTextView) findViewById(R.id.search_autocompletetext);
_header_seach_autotext.setHint("Search Hospital Here...");
_header_search_cancel = (ImageView) findViewById(R.id.search_cancel);
_header_search_cancel.setOnClickListener(this);
_header_search_cancel.setVisibility(View.GONE);
Gson gson = new Gson();
if (HOSPITAL_MAP_LIST.equals("")) {} else {
hospitalListArraylist = gson.fromJson(HOSPITAL_MAP_LIST, new TypeToken<List<HospitalList>>() {
}.getType());
}
recyclerView_hospitallist = (RecyclerView) findViewById(R.id.search_recycleriew);
no_data = (CustomTextViewItalic) findViewById(R.id.search_noresult);
no_data.setVisibility(View.GONE);
adapter = new HospitalAdapter(HospitalSearchActivity.this, hospitalListArraylist);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(HospitalSearchActivity.this);
recyclerView_hospitallist.setLayoutManager(mLayoutManager);
recyclerView_hospitallist.setItemAnimator(new DefaultItemAnimator());
recyclerView_hospitallist.setHasFixedSize(true);
recyclerView_hospitallist.setItemViewCacheSize(20);
recyclerView_hospitallist.setDrawingCacheEnabled(true);
recyclerView_hospitallist.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
_header_seach_autotext.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
_header_search_cancel.setVisibility(View.GONE);
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
String search_result = _header_seach_autotext.getText().toString();
collectHospitalSearchResultFromServer(search_result);
return true;
}
return false;
}
});
_header_seach_autotext.setThreshold(1);//will start working from first character
_header_seach_autotext.setTextColor(getResources().getColor(R.color.colorPrimary));
final HospitalSeachMapAdapter adapter = new HospitalSeachMapAdapter(HospitalSearchActivity.this, R.layout.activity_search_map_item, R.id.lbl_name, hospitalListArraylist);
_header_seach_autotext.setAdapter(adapter);
_header_seach_autotext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.notifyDataSetChanged();
_header_search_cancel.setVisibility(View.VISIBLE);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.search_cancel:
_header_search_cancel.setVisibility(View.GONE);
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
adapter = new HospitalAdapter(HospitalSearchActivity.this, hospitalListArraylist);
recyclerView_hospitallist.setAdapter(adapter);
adapter.notifyDataSetChanged();
break;
}
}
private void collectHospitalSearchResultFromServer(final String search_result) {
Log.d(AppUtils.TAG + " search_result: ", search_result);
Log.d(AppUtils.TAG + " SELECT_CITY_ID: ", String.valueOf(SELECTED_CITY_ID));
Log.d(AppUtils.TAG + " GEO_LATITUDE: ", String.valueOf(SELECTED_GEO_LATITUDE));
Log.d(AppUtils.TAG + " GEO_LONGITUDE: ", String.valueOf(SELECTED_GEO_LONGITUDE));
Log.d(AppUtils.TAG + " SELECT_SPEC_ID: ", String.valueOf(SELECTED_SPEC_ID));
Log.d(AppUtils.TAG + " HOME_FILT_TYPE: ", String.valueOf(SELECTED_FILTER_TYPE));
final ProgressDialog progressDialog = new ProgressDialog(HospitalSearchActivity.this, ProgressDialog.THEME_HOLO_LIGHT);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Searching Result...");
progressDialog.show();
hospitalListArraylist.clear();
hospitalListArraylist = new ArrayList<>();
int socketTimeout = 30000; // 30 seconds. You can change it
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
StringRequest stringRequest = new StringRequest(Request.Method.POST, APIClass.DRS_HOST_HOSPITALS_MAP_NEW_SEARCH_LIST,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(AppUtils.TAG, "map list: "+ response.toString());
if(response != null) {
JSONObject jsonObject = null;
JSONArray jsonArray, jsonArray1, jsonArray2;
try {
jsonObject = new JSONObject(response);
String staus_res = jsonObject.getString("status");
if (staus_res.equals("true")) {
jsonArray = jsonObject.getJSONArray("hospital_list");
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = jsonArray.getJSONObject(i);
hospitalListArraylist.add(new HospitalList(jObject.getInt("hosp_id"),jObject.getString("hosp_name"),
jObject.getString("hosp_addrs"),jObject.getString("hosp_city"),jObject.getString("hosp_state"),
jObject.getString("hosp_country"),jObject.getString("hosp_contact"),jObject.getString("hosp_email"),
jObject.getString("geo_latitude"),jObject.getString("geo_longitude"),jObject.getString("hosp_logo"),
0));
}
Log.d(AppUtils.TAG, " resultsize: " + hospitalListArraylist.size());
refreshRecyclerViews(hospitalListArraylist);
} else {
no_data.setVisibility(View.VISIBLE);
no_data.setText("No Hospital Records Found !!!");
}
}
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put(APIParam.KEY_API, APIClass.API_KEY);
map.put(APIParam.KEY_LOGIN_ID, String.valueOf(USER_ID));
map.put("search_string", search_result);
map.put(APIParam.KEY_HOME_CITY_ID, String.valueOf(SELECTED_CITY_ID));
map.put(APIParam.KEY_HOME_LATITUDE, String.valueOf(SELECTED_GEO_LATITUDE));
map.put(APIParam.KEY_HOME_LONGITUDE, String.valueOf(SELECTED_GEO_LONGITUDE));
map.put(APIParam.KEY_HOME_SPEC_ID, String.valueOf(SELECTED_SPEC_ID));
map.put(APIParam.KEY_PAGINATION, String.valueOf(1));
map.put(APIParam.KEY_HOME_FILTER_TYPE, String.valueOf(SELECTED_FILTER_TYPE));
return map;
}
};
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = AppController.getInstance(HospitalSearchActivity.this).
getRequestQueue();
AppController.getInstance(HospitalSearchActivity.this).addToRequestQueue(stringRequest);
}
private void refreshRecyclerViews(List<HospitalList> hospitalListArraylist) {
adapter = new HospitalAdapter(HospitalSearchActivity.this, hospitalListArraylist);
recyclerView_hospitallist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
| true
|
46ab994255ff465ae847ed9a5d8f0008541373bf
|
Java
|
cdai/interview
|
/1-algorithm/13-leetcode/java/src/advanced/datastructure/cache/lc146_lrucache/LRUCache_TLE.java
|
UTF-8
| 2,262
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
package advanced.datastructure.cache.lc146_lrucache;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
/**
* TLE...
*/
public class LRUCache_TLE {
public static void main(String[] args) {
LRUCache_TLE cache = new LRUCache_TLE(2);
System.out.println("get(2): " + cache.get(2));
System.out.println(cache.data);
System.out.println(cache.freq);
System.out.println("set(2,6)");
cache.set(2, 6);
System.out.println(cache.data);
System.out.println(cache.freq);
System.out.println("get(1): " + cache.get(1));
System.out.println(cache.data);
System.out.println(cache.freq);
System.out.println("set(1,5)");
cache.set(1, 5);
System.out.println(cache.data);
System.out.println(cache.freq);
System.out.println("set(1,2)");
cache.set(1, 2);
System.out.println(cache.data);
System.out.println(cache.freq);
System.out.println("get(1): " + cache.get(1));
System.out.println(cache.data);
System.out.println(cache.freq);
System.out.println("get(2): " + cache.get(2));
System.out.println(cache.data);
System.out.println(cache.freq);
}
private Map<Integer, Integer> data;
private Queue<Integer> freq;
private int capacity;
private int size;
public LRUCache_TLE(int capacity) {
this.data = new HashMap<>();
this.freq = new LinkedList<>();
this.capacity = capacity;
}
public int get(int key) {
if (!data.containsKey(key)) {
return -1;
}
freq.remove(key); // O(N) time to search for object with key
freq.offer(key);
return data.get(key);
}
public void set(int key, int value) {
if (data.containsKey(key)) { // Update an old k-v
freq.remove(key);
freq.offer(key);
data.put(key, value);
} else { // Insert a new k-v
if (size == capacity) {
data.remove(freq.poll());
size--;
}
freq.offer(key);
data.put(key, value);
size++;
}
}
}
| true
|
15cd650c5bf5756621bd0190f89ba5c7069da50b
|
Java
|
LuFengShan/java8
|
/src/main/java/com/java8/collection/IdentityHashMapDemo.java
|
UTF-8
| 1,072
| 3.265625
| 3
|
[] |
no_license
|
package com.java8.collection;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* @Author sgx
* @Date 2019/5/24 14:13
* @Version
**/
public class IdentityHashMapDemo {
public static void main(String[] args) {
String address = "http://localhost:";
//address + "/alarmFaultsPlatform/alarmFaultsTimeFlag.do"
Map<String, String> alarmParams = new IdentityHashMap<>();//初始化容器的大小
alarmParams.put(address + "/alarmFaultsPlatform/alarmFaultsTimeFlag.do", "week");
alarmParams.put(address + "/alarmFaultsPlatform/alarmFaultsTimeFlag.do", "month");
alarmParams.put(address + "/alarmFaultsPlatform/alarmFaultsTimeFlag.do", "quarter");
alarmParams.entrySet().forEach(kv -> System.out.println(kv.getKey() + " : " + kv.getValue()));
System.out.println(alarmParams.size());
String str1 = "ABC";
String str2 = new String("ABC");
System.out.println(str1 == str2);
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
str1 = null;
str2 = null;
str1 = "ABC";
System.out.println(str1.hashCode());
}
}
| true
|
1e6b62d411d2de486e973a726a1f9cffc88ca62b
|
Java
|
TheMatrixMage/DekuScrums
|
/RequalifyAVote.java
|
UTF-8
| 1,910
| 2.53125
| 3
|
[] |
no_license
|
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Toolkit;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import java.awt.Color;
public class RequalifyAVote extends JFrame {
private JPanel contentPane;
private JTextField textFieldID;
private JButton btnSubmit;
/**
* Create the frame.
*/
public RequalifyAVote() {
setResizable(false);
setFont(new Font("Arial", Font.PLAIN, 18));
setIconImage(Toolkit.getDefaultToolkit().getImage(CreateElection.class.getResource("/images/Deku_Link_Artwork.png")));
setTitle("Requalify Vote");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(50, 50, 250, 265);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Requalify Vote", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBounds(12, 13, 220, 178);
contentPane.add(panel);
panel.setLayout(null);
JLabel lblID = new JLabel("Voter's ID to Requalify:");
lblID.setBounds(12, 23, 168, 16);
panel.add(lblID);
textFieldID = new JTextField();
textFieldID.setColumns(10);
textFieldID.setBounds(12, 52, 168, 22);
panel.add(textFieldID);
btnSubmit= new JButton("Submit");
btnSubmit.setBounds(80, 204, 97, 25);
contentPane.add(btnSubmit);
}
public JButton getSubmitButton()
{
return btnSubmit;
}
public String getElectionName()
{
return textFieldID.getText();
}
}
| true
|
004f70f6a48e3d40602e5e68bafe7e217ecc12bf
|
Java
|
WonderFannn/WFJxSmartHome
|
/JxSmartHome/src/com/jinxin/jxsmarthome/cmd/entity/PackageMessage.java
|
UTF-8
| 2,232
| 2.6875
| 3
|
[] |
no_license
|
package com.jinxin.jxsmarthome.cmd.entity;
import com.jinxin.datan.local.util.StringUtil;
import com.jinxin.jxsmarthome.cmd.Constants;
/**
* 用于本地通信的信息包装对象
* @author TangLOng
* @company 金鑫智慧
*/
public class PackageMessage implements java.io.Serializable{
private static final long serialVersionUID = 6597046168524393175L;
//协议版本号
private String version;
//协议命令,0=请求(REQUEST),1=应答(RESPONSE),2=心跳(KEEPLIVED),3=终端 状态上报(REPORT)
private Integer cmd;
//指令长度指令长度字符串转换成Integer类型
private String contenLength;
//指令内容
private String content;
public PackageMessage(){
}
public PackageMessage(String content) {
this(Constants.LOCAL_VERSION_1, Constants.LOCAL_CMD_RESPONSE, content);
}
public PackageMessage (String version, Integer cmd, String content ) {
this.version = version;
this.cmd = cmd;
this.content = content;
this.setContenLength();
}
@Override
public String toString ( ) {
StringBuffer sb = new StringBuffer();
sb.append( "version:" ).append( version ).append( ", " );
sb.append( "cmd:" ).append( cmd ).append( ", " );
sb.append( "contenLength:" ).append( contenLength );
sb.append( "content:" ).append( content );
return sb.toString();
}
////////////////////////////////////////////////////
// getters and setters
////////////////////////////////////////////////////
public String getVersion ( ) {
return version;
}
public void setVersion ( String version ) {
this.version = version;
}
public Integer getCmd ( ) {
return cmd;
}
public void setCmd ( Integer cmd ) {
this.cmd = cmd;
}
public String getContenLength() {
return contenLength;
}
public void setContenLength() {
int length = Constants.LOCAL_SERIAL_LENGTH_A + content.length();
String str = StringUtil.getFixedLengthStrFromInt(length, Constants.LOCAL_CONTENLENGTH);
this.contenLength = str;
}
public String getContent ( ) {
return content;
}
public void setContent ( String content ) {
this.content = content;
this.setContenLength();
}
}
| true
|
fe52e2f7fe09aa30fe3e3324a110c78cfcefe3ba
|
Java
|
ribeirorafael/Material-Themed-Navigation-drawer-for-pre-lollipops
|
/app/src/main/java/in/raynstudios/materialtheme/MainActivity.java
|
UTF-8
| 11,006
| 1.796875
| 2
|
[] |
no_license
|
package in.raynstudios.materialtheme;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.app.Fragment;
import android.graphics.Typeface;
import android.net.Uri;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v7.widget.SearchView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity
implements
Fragment1.OnFragment1InteractionListener,
Fragment2.OnFragment2InteractionListener,
Fragment3.OnFragment3InteractionListener,
Fragment4.OnFragment4InteractionListener
{
/* Define vars */
ActionBarDrawerToggle mDrawerToggle;
int temppos;
DrawerLayout mDrawerLayout;
ListView mListView,mListViewSecondary;
private String[] mNavDrawerPrimaryList,mNavDrawerSecondaryList;
private NavDrawerListViewAdapter mAdapter;
SearchView searchView;
String[] frags = {
"in.raynstudios.materialtheme.Fragment1",
"in.raynstudios.materialtheme.Fragment2",
"in.raynstudios.materialtheme.Fragment3",
"in.raynstudios.materialtheme.Fragment4"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set toolbar as ActionBar
Toolbar mToolbar = (Toolbar) findViewById(R.id.custom_home_toolbar);
setSupportActionBar(mToolbar);
//find DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Get List Views
mListView = (ListView) findViewById(R.id.drawerListMain);
mListViewSecondary = (ListView) findViewById(R.id.drawerListSecondary);
// Get array of strings
mNavDrawerPrimaryList = getResources().getStringArray(R.array.navDrawerPrimaryList);
mNavDrawerSecondaryList = getResources().getStringArray(R.array.navDrawerSecondaryList);
// Setting string array to Drawer list
//mListView.setAdapter(new ArrayAdapter<String>(this,R.layout.drawerlistitem,mNavDrawerPrimaryList));
// Setting to nav drawer primary list view to custom adapter
mAdapter = new NavDrawerListViewAdapter(this);
mListView.setAdapter(mAdapter);
// Set secondary nav drawer list view
mListViewSecondary.setAdapter(new ArrayAdapter<String>(this,R.layout.drawerlistitem,mNavDrawerSecondaryList));
// Setting item click listeners for primary and secondary listviews
mListView.setOnItemClickListener(new DrawerPrimaryClickListener());
mListViewSecondary.setOnItemClickListener(new DrawerSecondaryClickListener());
// setting drawertoggle
mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,mToolbar,R.string.app_name,R.string.app_name){
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
// Setting drawer toggle listener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
// Set searchView hint
/*
MenuItem menuItem = menu.findItem(R.id.action_search);
searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setQueryHint(getString(R.string.search_actionbar_title));
*/
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}else if(id == R.id.action_search){
Intent intent = new Intent(this,SearchActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.START|Gravity.LEFT)){
mDrawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
@Override
public void onFragmentInteraction(Uri uri) {
Log.d("Fragment: ",""+uri.toString());
}
/**
* Created by rajat on 28/12/14.
* This will respond for Primary ListView
*/
public class DrawerPrimaryClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
selectItem(position);
// Set textView color
resetAllPrimaryTextViews(); // to reset all textviews in primary listview
View row = view;
TextView txtView = (TextView)view.findViewById(R.id.strListView);
txtView.setTypeface(null, Typeface.BOLD);
txtView.setTextColor(getResources().getColor(R.color.nav_drawer_list_text_selected));
ImageView imgView = (ImageView)view.findViewById(R.id.imgListView);
imgView.setColorFilter(getResources().getColor(R.color.nav_drawer_list_text_selected));
}
/* This resets all textviews to default typeface NORMAL */
private void resetAllPrimaryTextViews() {
for(int i=0;i<mListView.getChildCount();i++){
View view = mListView.getChildAt(i);
TextView txtView = (TextView)view.findViewById(R.id.strListView);
txtView.setTypeface(null, Typeface.NORMAL);
txtView.setTextColor(getResources().getColor(R.color.nav_drawer_list_text));
ImageView imgView = (ImageView)view.findViewById(R.id.imgListView);
imgView.setColorFilter(getResources().getColor(R.color.nav_drawer_list_text));
}
}
/* Function to swap fragments on item clicks */
private void selectItem(final int position){
Log.d("Output: Item selected ",""+mNavDrawerPrimaryList[position]);
getSupportActionBar().setTitle(mNavDrawerPrimaryList[position]);
// Close the drawer
if(mDrawerLayout.isDrawerOpen(Gravity.START|Gravity.LEFT)){
mDrawerLayout.closeDrawers();
// Set appropriate Fragment
FragmentTransaction fragTx = getFragmentManager().beginTransaction();
fragTx.replace(R.id.main_fragment_container, Fragment.instantiate(MainActivity.this,frags[position]));
fragTx.commit();
}
// Set selected state for this item
//final int pos = position;
mListView.post(new Runnable() {
@Override
public void run() {
mListView.requestFocusFromTouch();
mListView.setSelection(position);
}
});
return;
}
}
/**
* Created by rajat on 28/12/14.
* This will respond for Primary ListView
*/
public class DrawerSecondaryClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
selectItem(position);
}
/* Function to swap fragments on item clicks */
private void selectItem(final int position){
Log.d("Output: Item selected ",""+mNavDrawerSecondaryList[position]);
//getSupportActionBar().setTitle(mNavDrawerSecondaryList[position]);
// Close the drawer
if(mDrawerLayout.isDrawerOpen(Gravity.START|Gravity.LEFT)){
mDrawerLayout.closeDrawers();
// Raise toast
Toast.makeText(getApplicationContext(),"Invoke "+mNavDrawerSecondaryList[position]+" activity",Toast.LENGTH_SHORT).show();
return;
}
}
}
/**
* NavDrawerListViewAdapter for showing icons in nav drawer
*/
public class NavDrawerListViewAdapter extends BaseAdapter{
private Context ctx;
String[] listItems;
int[] images = {
R.drawable.ic_action_name2,
R.drawable.ic_tag,
R.drawable.ic_headphone,
R.drawable.ic_action_name
};
public NavDrawerListViewAdapter(Context ctx){
this.ctx = ctx;
listItems = ctx.getResources().getStringArray(R.array.navDrawerPrimaryList);
}
@Override
public int getCount() {
return listItems.length;
}
@Override
public Object getItem(int i) {
return listItems[i];
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_listview,parent,false);
}else{
row = convertView;
}
TextView txtView = (TextView)row.findViewById(R.id.strListView);
ImageView imgView = (ImageView)row.findViewById(R.id.imgListView);
txtView.setText(listItems[position]);
imgView.setImageResource(images[position]);
return row;
}
}
}
| true
|
294b9976d815c00dd074f1b56a26d684f65de08a
|
Java
|
AnDevCba/GitHubMVP
|
/app/src/main/java/com/andevcba/githubmvp/presentation/show_repos/view/ShowReposFragment.java
|
UTF-8
| 6,824
| 2.03125
| 2
|
[] |
no_license
|
package com.andevcba.githubmvp.presentation.show_repos.view;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import com.andevcba.githubmvp.R;
import com.andevcba.githubmvp.presentation.GitHubMVPApplication;
import com.andevcba.githubmvp.presentation.add_repos.AddReposActivity;
import com.andevcba.githubmvp.presentation.di.PresentationComponent;
import com.andevcba.githubmvp.presentation.show_repos.ShowReposContract;
import com.andevcba.githubmvp.presentation.show_repos.model.RepoUI;
import com.andevcba.githubmvp.presentation.show_repos.model.ReposByUsernameUI;
import com.andevcba.githubmvp.presentation.show_repos.model.StickyHeaderUI;
import com.andevcba.githubmvp.presentation.show_repos.presenter.ShowReposPresenter;
import com.andevcba.githubmvp.presentation.views.custom.ImageDialog;
import com.brandongogetap.stickyheaders.StickyLayoutManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
/**
* Shows a list of repos grouped by username and sorted alphabetically.
*
* @author lucas.nobile
*/
public class ShowReposFragment extends Fragment implements ShowReposContract.View {
public interface OnItemSelectedListener {
void onStickyHeaderSelected(StickyHeaderUI stickyHeaderUI);
void onRepoSelected(RepoUI repo);
void onImageSelected(ImageView circleImageView);
}
private static final int REQUEST_ADD_REPOS = 1;
private static final String KEY_REPOS_BY_USERNAME = "repos_by_username";
@Inject
ShowReposPresenter presenter;
private ReposAdapter adapter;
private RecyclerView rvShowRepos;
private ImageDialog dialogFragment;
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
@Override
public void onStickyHeaderSelected(StickyHeaderUI stickyHeaderUI) {
presenter.goToGitHubUsernamePage(stickyHeaderUI.getName());
}
@Override
public void onRepoSelected(RepoUI repo) {
presenter.goToGitHubRepoPage(repo.getUrl());
}
@Override
public void onImageSelected(ImageView circleImageView) {
dialogFragment = new ImageDialog();
dialogFragment.show(getFragmentManager()
.beginTransaction()
.addSharedElement(circleImageView, circleImageView.getTransitionName()), "ImageDialog");
}
};
public static ShowReposFragment newInstance() {
return new ShowReposFragment();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inject dependencies
this.getPresentationComponent().inject(this);
presenter.attachView(this);
adapter = new ReposAdapter(new ArrayList<ViewType>(), R.string.empty_show_repos_message, itemSelectedListener, getContext());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_show_repos, container, false);
setUpRecyclerView(view);
setUpFloatingActionButton();
return view;
}
private void setUpRecyclerView(View view) {
rvShowRepos = (RecyclerView) view.findViewById(R.id.rv_show_repos);
rvShowRepos.setAdapter(adapter);
rvShowRepos.setHasFixedSize(true);
// Set layout manager
StickyLayoutManager layoutManager = new StickyLayoutManager(getContext(), adapter);
layoutManager.elevateHeaders(true);
rvShowRepos.setLayoutManager(layoutManager);
}
private void setUpFloatingActionButton() {
// Set up floating action button
FloatingActionButton fab =
(FloatingActionButton) getActivity().findViewById(R.id.fab_add_repos);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
presenter.goToAddReposScreen();
}
});
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
ReposByUsernameUI reposByUsernameUI = savedInstanceState.getParcelable(KEY_REPOS_BY_USERNAME);
presenter.restoreStateAndShowRepos(reposByUsernameUI);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_REPOS_BY_USERNAME, presenter.getUiModel());
}
@Override
public void onResume() {
super.onResume();
presenter.loadAllRepos();
}
@Override
public void showRepos(ReposByUsernameUI uiModel, boolean goToTop) {
if (goToTop) {
rvShowRepos.smoothScrollToPosition(0);
}
List<ViewType> items = uiModel.getViewTypes();
adapter.addAll(items);
}
@Override
public void navigateToAddReposScreen() {
Intent intent = new Intent(getContext(), AddReposActivity.class);
startActivityForResult(intent, REQUEST_ADD_REPOS);
getActivity().overridePendingTransition(R.anim.right_in, R.anim.left_out);
;
}
@Override
public void browseGitHubUsernamePage(String url) {
Uri uri = Uri.parse(url);
browse(uri);
}
@Override
public void browseGitHubRepoPage(String url) {
Uri uri = Uri.parse(url);
browse(uri);
}
@Override
public void showError(String error) {
Snackbar.make(getView(), getString(R.string.error_loading_repos_message), Snackbar.LENGTH_LONG).show();
}
private void browse(Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (REQUEST_ADD_REPOS == requestCode && Activity.RESULT_OK == resultCode) {
Snackbar.make(getView(), getString(R.string.repos_saved_message), Snackbar.LENGTH_SHORT).show();
}
}
private PresentationComponent getPresentationComponent() {
return ((GitHubMVPApplication) getActivity().getApplication()).getPresentationComponent();
}
}
| true
|
aeb659ba737030e19ce2e30775ff492c0b13a883
|
Java
|
Silvern29/Coding-Campus-Log
|
/Kino/src/at/redlinghaus/Shop.java
|
UTF-8
| 1,796
| 3.25
| 3
|
[] |
no_license
|
package at.redlinghaus;
public class Shop {
String[] artArr = {"Popcorn", "Cola", "Bier", "Haribo"};
double[] priceArr = {4.20, 2.30, 2.10, 3.20};
int[] anzArr = {1, 1, 1, 2};
double brieftasche = 50.00;
double total = 0;
public void bon() {
for (int i = 0; i < artArr.length; i++) {
if (anzArr[i] != 0) {
System.out.printf(" %-8s\t%2d x %4.2f EUR%n %6.2f EUR%n", artArr[i], anzArr[i], priceArr[i], anzArr[i] * priceArr[i]);
total += anzArr[i] * priceArr[i];
}
}
System.out.println("-----------------------------------");
System.out.printf(" Gesamt %6.2f EUR%n", total);
System.out.printf(" Gegeben %6.2f EUR%n%n", brieftasche);
int rnd = (int) Math.floor(Math.random()*500);
boolean isPrim = true;
boolean isRound = false;
if (rnd % 10 == 0) {
isRound = true;
isPrim = false;
}
if (!isRound) {
for (int i = rnd - 1; i > 1; i--) {
if (rnd % i == 0) {
isPrim = false;
}
}
}
System.out.printf(" Deine Zufallszahl ist %d. Dies ist %s.%n", rnd, isRound ? "eine runde Zahl" : isPrim ? "eine Primzahl" : "keine Glückszahl");
if (isPrim || isRound) {
System.out.println(" Gratuliuere! Du hast gewonnen und zahlst nichts für deinen Einkauf!");
} else if (brieftasche - total >= 0) {
System.out.printf(" Zurück %6.2f EUR%n", brieftasche - total);
brieftasche -= total;
} else {
System.out.printf(" Es fehlen noch %.2f EUR!%n", total - brieftasche);
}
}
}
| true
|
5b4c6080c9c25f5f6966d8a3bab3fc15cf91060c
|
Java
|
dkwonh/kangdapp
|
/app/src/main/java/kangwon/cs/kangdapp/SchoolCalendarFragment.java
|
UTF-8
| 3,109
| 2.390625
| 2
|
[] |
no_license
|
package kangwon.cs.kangdapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.GridView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by KHJ on 2016-10-30.
*/
public class SchoolCalendarFragment extends Fragment {
private GridAdapter gridAdapter;
private ArrayList<String> dayList;
private GridView gridView;
private Calendar mCal;
public String string;
private final String TAG = "TAG";
int position;
protected CalendarParser calendarParser;
protected WebView webview;
public static SchoolCalendarFragment newInstance(int i) {
SchoolCalendarFragment S = new SchoolCalendarFragment();
Bundle args = new Bundle();
args.putInt("position",i);
S.setArguments(args);
return S;
}
public int getShownIndex() {
return getArguments().getInt("position", 0);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.school_calendar_num, container, false);
position = getShownIndex();
webview = (WebView)v.findViewById(R.id.webView11);
calendarParser = new CalendarParser(webview, position + 1);
//tvDate = (TextView)findViewById(R.id.tv_date);
gridView = (GridView)v.findViewById(R.id.gridview);
long now = System.currentTimeMillis();
final Date date = new Date(now);
final SimpleDateFormat curYearFormat = new SimpleDateFormat("yyyy", Locale.KOREA);
final SimpleDateFormat curMonthFormat = new SimpleDateFormat("MM", Locale.KOREA);
final SimpleDateFormat curDayFormat = new SimpleDateFormat("dd", Locale.KOREA);
dayList = new ArrayList<String>();
mCal = Calendar.getInstance();
mCal.set(Integer.parseInt(curYearFormat.format(date)), position + 1, 1);
int dayNum = mCal.get(Calendar.DAY_OF_WEEK);
for (int i = 1; i < dayNum; i++) {
dayList.add("");
}
/*gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position <= 5 + mCal.get(Calendar.DAY_OF_WEEK))
gridView.setSelection(gridView.getSelectedItemPosition() + 1);
}
});*/
setCalendarDate(mCal.get(Calendar.MONTH) + 1);
gridAdapter = new GridAdapter(v.getContext(), dayList, position);
gridView.setAdapter(gridAdapter);
calendarParser.jsoupAsyncTask.execute();
return v;
}
private void setCalendarDate(int month) {
mCal.set(Calendar.MONTH, month - 1);
for (int i = 0; i < mCal.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
dayList.add("" + (i + 1));
}
}
}
| true
|
b7e0cc5a459ec298544f546fc0c0f0c40ecf22d3
|
Java
|
Maveto/EjerciciosPDMauricioVejarano
|
/src/main/java/_ejerciciosPractica2/ejercicio1/CareTaker.java
|
UTF-8
| 318
| 2.609375
| 3
|
[] |
no_license
|
package _ejerciciosPractica2.ejercicio1;
import java.util.ArrayList;
import java.util.List;
public class CareTaker {
private List<BackUp> backUps = new ArrayList<>();
public void addBackUp(BackUp b){
backUps.add(b);
}
public BackUp getBackUp(int i){
return backUps.get(i);
}
}
| true
|
21be2ea070153149e78429472bb0a8a13f7e41b8
|
Java
|
yangchengly/av-samples
|
/pomadmin/src/main/java/com/avaya/pim/services/pomagentapiservice/GetContactDataFromListFaultInfo.java
|
GB18030
| 1,942
| 2.078125
| 2
|
[] |
no_license
|
package com.avaya.pim.services.pomagentapiservice;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>anonymous complex type Java ࡣ
*
* <p>ģʽƬָڴеԤݡ
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="FaultMsg" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="RetCode" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"faultMsg",
"retCode"
})
@XmlRootElement(name = "GetContactDataFromListFaultInfo")
public class GetContactDataFromListFaultInfo {
@XmlElement(name = "FaultMsg", required = true)
protected String faultMsg;
@XmlElement(name = "RetCode")
protected int retCode;
/**
* ȡfaultMsgԵֵ
*
* @return
* possible object is
* {@link String }
*
*/
public String getFaultMsg() {
return faultMsg;
}
/**
* faultMsgԵֵ
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFaultMsg(String value) {
this.faultMsg = value;
}
/**
* ȡretCodeԵֵ
*
*/
public int getRetCode() {
return retCode;
}
/**
* retCodeԵֵ
*
*/
public void setRetCode(int value) {
this.retCode = value;
}
}
| true
|
d6126842af7af7834b5408c5bd794cdf9a8ccf35
|
Java
|
Sage-Bionetworks/Synapse-Warehouse-Workers
|
/src/main/java/org/sagebionetworks/warehouse/workers/model/CertifiedQuizQuestionRecord.java
|
UTF-8
| 2,483
| 2.578125
| 3
|
[] |
no_license
|
package org.sagebionetworks.warehouse.workers.model;
/**
* This class represents the certified quiz question record.
*
* While capturing the passing record snapshot in a json format,
* there are many fields that are not being used to generate meaningful metrics.
* This class only contains the fields that are used to generate metrics.
*
* A unique passing record contains 10 certified quiz question record.
*
* A certified quiz question record represents user answer to one question in
* the certified user quiz. It has information about the quiz, the question,
* and either the user answered the question correct or not.
*
* @author kimyentruong
*
*/
public class CertifiedQuizQuestionRecord {
private Long responseId;
private Long questionIndex;
private Boolean isCorrect;
public Long getResponseId() {
return responseId;
}
public void setResponseId(Long responseId) {
this.responseId = responseId;
}
public Long getQuestionIndex() {
return questionIndex;
}
public void setQuestionIndex(Long questionIndex) {
this.questionIndex = questionIndex;
}
public Boolean getIsCorrect() {
return isCorrect;
}
public void setIsCorrect(Boolean isCorrect) {
this.isCorrect = isCorrect;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((isCorrect == null) ? 0 : isCorrect.hashCode());
result = prime * result
+ ((questionIndex == null) ? 0 : questionIndex.hashCode());
result = prime * result
+ ((responseId == null) ? 0 : responseId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CertifiedQuizQuestionRecord other = (CertifiedQuizQuestionRecord) obj;
if (isCorrect == null) {
if (other.isCorrect != null)
return false;
} else if (!isCorrect.equals(other.isCorrect))
return false;
if (questionIndex == null) {
if (other.questionIndex != null)
return false;
} else if (!questionIndex.equals(other.questionIndex))
return false;
if (responseId == null) {
if (other.responseId != null)
return false;
} else if (!responseId.equals(other.responseId))
return false;
return true;
}
@Override
public String toString() {
return "CertifiedQuizQuestionRecord [responseId=" + responseId
+ ", questionIndex=" + questionIndex + ", isCorrect="
+ isCorrect + "]";
}
}
| true
|