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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ccff6daa7d428646a10a55ddab0ee6317e9cf3ba
|
Java
|
scala804/javaFX-EquivalenceClass
|
/src/main/java/com/autoTest/javaFXEquivalenceClass/model/DecimalTypeBean.java
|
UTF-8
| 4,447
| 2.140625
| 2
|
[] |
no_license
|
package com.autoTest.javaFXEquivalenceClass.model;
public class DecimalTypeBean {
private String uuid;
private String fieldOtherType;
private String fieldType;
private String fieldLength;
private String orderNumber;
private String fieldID;
private String fieldName;
private String choiceFieldEmpty;
private String fieldNormalData;
private String precision;
private String decimalBeyondLowerBoundaryValue;
private String beyondLowerBoundaryExpectedResults;
private String isNullExpectedResults;
private String decimalBeyondUpperBoundaryValue;
private String beyondUpperBoundaryExpectedResults;
private String decimalIsFormatExpectedResults;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getFieldOtherType() {
return fieldOtherType;
}
public void setFieldOtherType(String fieldOtherType) {
this.fieldOtherType = fieldOtherType;
}
public String getfieldType() {
return fieldType;
}
public void setfieldType(String fieldType) {
this.fieldType = fieldType;
}
public String getFieldLength() {
return fieldLength;
}
public void setFieldLength(String fieldLength) {
this.fieldLength = fieldLength;
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public String getFieldID() {
return fieldID;
}
public void setFieldID(String fieldID) {
this.fieldID = fieldID;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldType() {
return fieldType;
}
public void setFieldType(String fieldType) {
this.fieldType = fieldType;
}
public String getChoiceFieldEmpty() {
return choiceFieldEmpty;
}
public void setChoiceFieldEmpty(String choiceFieldEmpty) {
this.choiceFieldEmpty = choiceFieldEmpty;
}
public String getFieldNormalData() {
return fieldNormalData;
}
public void setFieldNormalData(String fieldNormalData) {
this.fieldNormalData = fieldNormalData;
}
public String getPrecision() {
return precision;
}
public void setPrecision(String precision) {
this.precision = precision;
}
public String getDecimalBeyondLowerBoundaryValue() {
return decimalBeyondLowerBoundaryValue;
}
public void setDecimalBeyondLowerBoundaryValue(String decimalBeyondLowerBoundaryValue) {
this.decimalBeyondLowerBoundaryValue = decimalBeyondLowerBoundaryValue;
}
public String getBeyondLowerBoundaryExpectedResults() {
return beyondLowerBoundaryExpectedResults;
}
public void setBeyondLowerBoundaryExpectedResults(String beyondLowerBoundaryExpectedResults) {
this.beyondLowerBoundaryExpectedResults = beyondLowerBoundaryExpectedResults;
}
public String getIsNullExpectedResults() {
return isNullExpectedResults;
}
public void setIsNullExpectedResults(String isNullExpectedResults) {
this.isNullExpectedResults = isNullExpectedResults;
}
public String getDecimalBeyondUpperBoundaryValue() {
return decimalBeyondUpperBoundaryValue;
}
public void setDecimalBeyondUpperBoundaryValue(String decimalBeyondUpperBoundaryValue) {
this.decimalBeyondUpperBoundaryValue = decimalBeyondUpperBoundaryValue;
}
public String getBeyondUpperBoundaryExpectedResults() {
return beyondUpperBoundaryExpectedResults;
}
public void setBeyondUpperBoundaryExpectedResults(String beyondUpperBoundaryExpectedResults) {
this.beyondUpperBoundaryExpectedResults = beyondUpperBoundaryExpectedResults;
}
public String getDecimalIsFormatExpectedResults() {
return decimalIsFormatExpectedResults;
}
public void setDecimalIsFormatExpectedResults(String decimalIsFormatExpectedResults) {
this.decimalIsFormatExpectedResults = decimalIsFormatExpectedResults;
}
}
| true
|
9dd7694e63d13314f08ac880aa356f3a9d93ffd2
|
Java
|
WOQUQ/LeetcodeSolution
|
/solutions/test300_309/Test301.java
|
UTF-8
| 2,509
| 3.5625
| 4
|
[] |
no_license
|
package test300_309;
import java.util.*;
public class Test301 {
// BFS
Set<String> _set = new LinkedHashSet<String>();
public List<String> removeInvalidParentheses(String s) {
if(checker(s)){
ArrayList<String> list = new ArrayList<String>();
list.add(s);
return list;
}
Set<String> currSet = new LinkedHashSet<String>();
currSet.add(s);
bfs(currSet);
ArrayList<String> res = new ArrayList<String>(_set.size());
for(String temp : _set){
res.add(temp);
}
return res;
}
private void bfs(Set<String> currSet){
Set<String> nextSet = new LinkedHashSet<String>();
for(String s : currSet){
if(s.length() <= 1){
if(s.equals("(") || s.equals(")")){
continue;
}
_set.add(s);
}
else{
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == '(' || s.charAt(i) == ')'){
StringBuffer temp = new StringBuffer();
if(i > 0)
temp.append(s.substring(0, i));
if(i < s.length() - 1)
temp.append(s.substring(i+1, s.length()));
String str = temp.toString();
if(checker(str)){
_set.add(str);
}else{
nextSet.add(str);
}
}
}
}
}
if( _set.isEmpty()){
if(nextSet.isEmpty()){
_set.add("");
return;
}
bfs(nextSet);
}
}
private boolean checker(String str) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
char temp = str.charAt(i);
if (temp == '(')
stack.add(temp);
else if (temp == ')') {
if (stack.isEmpty())
return false;
stack.pop();
}
}
if(stack.isEmpty())
return true;
return false;
}
// DFS
public static void main(String[] args) {
Test301 test = new Test301();
System.out.println(test.removeInvalidParentheses("()"));
}
}
| true
|
0d0b95fcfdb5550a67930de4c74a074e1f0c8462
|
Java
|
Renzojrp/mobile-android
|
/app/src/main/java/pe/com/mucontact/models/Publication.java
|
UTF-8
| 3,687
| 2.375
| 2
|
[] |
no_license
|
package pe.com.mucontact.models;
import com.orm.SugarRecord;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by romer on 26/6/2017.
*/
public class Publication extends SugarRecord{
private String _id;
private String instrument;
private String description;
private String locationReference;
private String createdAt;
private String craftmen;
private User user;
public Publication() {
}
public Publication(String _id, String instrument, String description, String locationReference, String createdAt, String craftmen, User user) {
this._id = _id;
this.instrument = instrument;
this.description = description;
this.locationReference = locationReference;
this.createdAt = createdAt;
this.craftmen = craftmen;
this.user = user;
}
public String get_id() {
return _id;
}
public Publication set_id(String _id) {
this._id = _id;
return this;
}
public String getInstrument() {
return instrument;
}
public Publication setInstrument(String instrument) {
this.instrument = instrument;
return this;
}
public String getDescription() {
return description;
}
public Publication setDescription(String description) {
this.description = description;
return this;
}
public String getLocationReference() {
return locationReference;
}
public Publication setLocationReference(String locationReference) {
this.locationReference = locationReference;
return this;
}
public String getCreatedAt() {
return createdAt;
}
public Publication setCreatedAt(String createdAt) {
this.createdAt = createdAt;
return this;
}
public String getCraftmen() {
return craftmen;
}
public Publication setCraftmen(String craftmen) {
this.craftmen = craftmen;
return this;
}
public String getContext() {
return "On " + getCreatedAt().substring(0,10) +
(getLocationReference().isEmpty() ? "" :
" at " + getLocationReference());
}
public static Publication build(JSONObject jsonPublication, User user) {
if(jsonPublication == null) return null;
Publication publication = new Publication();
try {
publication.set_id(jsonPublication.getString("_id"))
.setInstrument(jsonPublication.getString("instrument"))
.setDescription(jsonPublication.getString("description"))
.setCreatedAt(jsonPublication.getString("date"))
.setLocationReference(jsonPublication.getString("locationAt"))
.setUser(user);
return publication;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public static List<Publication> build(JSONArray jsonPublications, User user) {
if(jsonPublications == null) return null;
int length = jsonPublications.length();
List<Publication> publications = new ArrayList<>();
for(int i = 0; i < length; i++)
try {
publications.add(Publication.build(jsonPublications.getJSONObject(i), user));
} catch (JSONException e) {
e.printStackTrace();
}
return publications;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
| true
|
555b8bb64dd6875f65a566cb51e042ac85e52361
|
Java
|
AlinaS95/MeetupApplication
|
/MeetupApplication/src/net/meetup/controller/UpdateTaskServlet.java
|
UTF-8
| 2,656
| 2.171875
| 2
|
[] |
no_license
|
package net.meetup.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.time.LocalDate;
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 net.meetup.utils.JDBCUtils;
@WebServlet("/UpdateTask")
public class UpdateTaskServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/meetup";
String user = "root";
String psw = "";
String taskID = request.getParameter("taskID");
String taskName = request.getParameter("taskName");
String description = request.getParameter("description");
LocalDate dueDate = LocalDate.parse(request.getParameter("dueDate"));
String taskStatus = request.getParameter("taskStatus");
String assignee = request.getParameter("assignee");
String internalInquiries = request.getParameter("internalInquiries");
String completion = request.getParameter("completion");
String wID = request.getParameter("wID");
String userSID = request.getParameter("userSID");
if (taskID != null) {
Connection con = null;
PreparedStatement ps = null;
int idTask = Integer.parseInt(taskID);
try {
Class.forName(driverName);
con = DriverManager.getConnection(url, user, psw);
String sql = "Update tasks set taskID=?,taskName=?,description=?,dueDate=?, taskStatus=?, assignee=?, internalInquiries=?, completion=?, wID=?, userSID=? where taskID=" + taskID;
ps = con.prepareStatement(sql);
ps.setString(1, taskID);
ps.setString(2, taskName);
ps.setString(3, description);
ps.setDate(4, JDBCUtils.getSQLDate(dueDate));
ps.setString(5, taskStatus);
ps.setString(6, assignee);
ps.setString(7, internalInquiries);
ps.setString(8, completion);
ps.setString(9, wID);
ps.setString(10, userSID);
ps.executeUpdate();
response.sendRedirect("list.jsp?wID="+wID);
} catch (Exception e) {
out.println(e);
}
}
}
}
| true
|
aa6eb4ecabdd81e5b1f4d2e6b31f2f79ce3ecf35
|
Java
|
csinva/mini-games
|
/BattleFight/src/Deathmatch.java
|
UTF-8
| 32,909
| 1.984375
| 2
|
[] |
no_license
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.text.*;
import java.io.*;
import java.util.Scanner;
public class Deathmatch extends JPanel{
BufferedImage buff, radar;
Graphics g, m;
Rectangle p;
ScoreboardMatch s;
ScoreboardRightMatch s2;
Enemy[] enemies=new Enemy[5];
boolean u,r,d,l,move,space,grenade,ranked,added=false;
AccountListener AL;
boolean kListenerOn=true;
int length=20;
int level,deaths,grenadeCount,boxTime,eSpeed,eHealth,eNum,eFrequency,numKillStreaks,killStreak,skill,pShotFrequency=0;
int kills,numRemaining,numAlive,slower,slower2,pslower,pauser,theCounter=0;
JButton scores;
int startTime=19;
int time=startTime+4;
int accuracy=4;/////////////////////////////////////change based on comp speed
double hits, shots=0;
JLabel[] labels=new JLabel[5];
int[] labelCounters=new int[5];
int numUBullets=300;
int numEBullets=30;
String name;
int numGrenades=30;
int[] eKills={0,0,0,0,0,0};
int[] eDeaths={0,0,0,0,0,0};
Color[] eCols={Color.red,Color.cyan,new Color(238,207,12),Color.black,new Color(230,12,238),Color.green};
Bullet[] eBullets=new Bullet[numEBullets];
Bullet[] uBullets=new Bullet[numUBullets];
Grenade[] grenades=new Grenade[numGrenades];
Color tr=new Color(244,161,19,175);
int[][] map=new int[800][800];
ScoreboardEnd sE;
int numBoxes=4;
int[] boxStopTime=new int[numBoxes];
Box[] boxes=new Box[numBoxes];
JLabel label, label2;
JPanel panel, screen;
Timer t, timer;
//Ball ball;
public Deathmatch(int skillLevel,boolean b,String fjk){//speed was 10 health was 6
name=fjk;
ranked=b;
skill=skillLevel;
pShotFrequency=5+(skillLevel/60);
eNum=2+skillLevel/300;
eSpeed=6+(skillLevel+150)/300;
eHealth=(5+skillLevel+75)/100+2;
eFrequency=37-((skillLevel+30)/80);
screen = new JPanel();
screen.setOpaque(true);
Color mhz=new Color(244,0,255,255);
screen.setBackground(mhz);
screen.setBounds(0,0,800,1200);
screen.setVisible(true);
add(screen);
for(int x=0;x<numEBullets;x++)
eBullets[x]=new Bullet(0,0,6,20,Color.black,1);
for(int x=0;x<numUBullets;x++){
uBullets[x]=new Bullet(0,0,6,40,Color.black,1);
uBullets[x].setOn(0);
}
for(int x=0;x<numGrenades;x++)
grenades[x]=new Grenade(0,0,0,10,Color.black,1);
for(int x=0;x<5;x++){
labels[x]=new JLabel("");
labels[x].setVisible(false);
labels[x].setForeground(Color.green);
}
boxes[0]=new Box(330,385,15,1);
boxes[1]=new Box(450,385,15,1);
boxes[2]=new Box(330,500,15,1);
boxes[3]=new Box(450,500,15,1);
for(int x=0;x<4;x++){
boxStopTime[x]=0;
boxes[x].setOn(1);
}
buff=new BufferedImage(800,800,BufferedImage.TYPE_INT_RGB);
g=buff.getGraphics();
radar=new BufferedImage(1000,1000,BufferedImage.TYPE_INT_RGB);
m=buff.getGraphics();
m.setColor(Color.black);
m.fillRect(0,0,1000,1000);
setFocusable(true);
setGrid();
drawBackground(level);
repaint();
p=new Rectangle(40,40,20,3,Color.green);
p.setGun(2);
p.setShotFrequency(pShotFrequency);
for(int x=0;x<numUBullets;x++)
uBullets[x].setOn(0);
p.setShot(0);
p.draw(g);
setLayout(null);
JButton reset=new JButton("Reset");
reset.setHorizontalAlignment(SwingConstants.LEFT);
reset.addActionListener(new ResetListener());
reset.setFocusable(false);
add(reset);
reset.setBounds(700,850,70,30);
JButton back=new JButton("Menu");
back.setHorizontalAlignment(SwingConstants.LEFT);
back.addActionListener(new BackListener());
back.setFocusable(false);
add(back);
back.setEnabled(true);
back.setBounds(700,890,65,30);
JButton pause=new JButton("| |");
pause.addActionListener(new PauseListener());
pause.setFocusable(false);
add(pause);
pause.setForeground(Color.yellow);
pause.setBackground(Color.black);
pause.setBounds(10,890,70,30);
s=new ScoreboardMatch(0);
add(s);
s.setBounds(0,860,800,150);
s2=new ScoreboardRightMatch();
add(s2);
s2.setBounds(800,0,120,960);
panel=new JPanel();
add(panel);
panel.setBounds(0,0,800,1000);
panel.setForeground(tr);
panel.setBackground(tr);
panel.setVisible(false);
JLabel resume=new JLabel("Press Button to Keep Playing");
resume.setForeground(Color.green);
panel.add(resume);
JButton play=new JButton("Resume");
play.addActionListener(new ResumeListener());
panel.add(play);
scores=new JButton("High Scores");
scores.setFocusable(false);
scores.setBounds(20,100,800,200);
panel.add(scores);
timer = new Timer(1000,new ClockListener());
timer.start();
addKeyListener(new Key());
setFocusable(true);
label=new JLabel("Game Over");
add(label);
label.setBounds(50,50,1000,750);
label.setFont(new Font("Times New Roman",Font.ITALIC,400));
label.setForeground(Color.white);
label.setVisible(false);
firstLevel();
if(!ranked)
scores.setEnabled(false);
//ball = new Ball(400,400,50,Color.black,15,15);
}
//////////////////////////////////////////////////////////////////////////////////////////LISTENERS
private class PauseListener implements ActionListener{
public void actionPerformed(ActionEvent e){
pause();
}
}
private class ResumeListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(time<=0)
label.setVisible(true);
resume();
}
}
private class BackListener implements ActionListener{
public void actionPerformed(ActionEvent e){
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Object source = e.getSource();
if (source instanceof Component) {
Component c = (Component) source;
Frame frame1 = JOptionPane.getFrameForComponent(c);
if(frame1 != null){
frame1.dispose();
frame1.setVisible(false);
}
}
////////////////THIS CODE WAS BORROWED//////////////http://www.dreamincode.net/forums/topic/162705-dispose-a-frame-from-an-inner-class/////
JFrame frame = new JFrame("Battle");
frame.setSize(800,835);
frame.setLocation(200, 50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Menu());
frame.setVisible(true);
}
}
private class ClockListener implements ActionListener{
public void actionPerformed(ActionEvent e){
time--;
if(time>startTime){
label.setFont(new Font("Times New Roman",Font.ITALIC,500));
label.setForeground(Color.white);
screen.add(label);
label.setVisible(true);
label.setText(""+(time-startTime));
}
else if(time==startTime){
label.setVisible(false);
label.setFont(new Font("Vivaldi",Font.ITALIC,170));
label.setForeground(Color.orange);
t = new Timer(15,new TimerListener());
t.start();
die();
deaths--;
}
else if(time>startTime-5){
DecimalFormat d = new DecimalFormat("00");
int display=startTime-5;
label.setText(""+display/60+":"+d.format(display%60)+"remaining");
label.setVisible(true);
}
else if(time<30&&time>27){
label.setText("30 secs left!");
label.setVisible(true);
}
else if(time<=0){
label.setVisible(true);
}
else{
label.setText("Game Over");
label.setVisible(false);
}
if(time<=startTime)
s.update(time,skill);
if(time==0)
end();
}
}
private class ResetListener implements ActionListener{
public void actionPerformed(ActionEvent e){
added=false;
scores.removeActionListener(AL);
level=0;
kills=deaths=0;
u=r=d=l=false;
kListenerOn=true;
slower=slower2=kills=deaths=killStreak=0;
p.setX(40);
p.setY(40);
label.setVisible(false);
p.setHealth(100);
firstLevel();
time=startTime+4;
timer.restart();
Color mhz=new Color(244,0,255,255);
screen.setBackground(mhz);
screen.setVisible(true);
resume();
if(t!=null)
t.stop();
if(sE!=null)
panel.remove(sE);
for(int x=0;x<eKills.length;x++){
eKills[x]=0;
eDeaths[x]=0;
}
if(label2!=null)
label2.setVisible(false);
}
}
private class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
p.setShotFrequency(pShotFrequency);
if(move==true){
setDirection();
moveRect(p);
p.toggle();
}
if(space){
if(p.getShot()==p.getShotFrequency()){
p.setShot(0);
shoot(p);
}
}
p.setShot(p.getShot()+1);
slower++;
if(slower==8){
moveEnemies();
slower=0;
}
slower2++;
if(slower2==65){
if(p.getHealth()<100)
p.setHealth(p.getHealth()+1);
slower2=0;
}
if(p.getAlive()){
drawBackground(level);
p.draw(g);
}
else
drawBackground(level,-1);
for(int x=0;x<numRemaining;x++){
if(enemies[x].getAlive())
enemies[x].draw(g);
}
for(int x=0;x<numUBullets;x++){
if(uBullets[x].getOn()==1){
moveBullet(uBullets[x]);
uBullets[x].draw(g);
if(uBullets[x].getOn()==1){
for(int a=0;a<numRemaining;a++){
if(enemies[a].getAlive())
shot(enemies[a],uBullets[x],a);
}
}
}
}
for(int y=0;y<numRemaining;y++){
for(int x=0;x<numEBullets;x++){
if(eBullets[x].getOn()==1){
moveBullet(eBullets[x]);
eBullets[x].draw(g);
if(p.getAlive())
shot(p,eBullets[x],numRemaining);
if(y!=eBullets[x].getShooter())
shot(enemies[y],eBullets[x],y);
}
}
}
for(int x=0;x<numGrenades;x++){
if(grenades[x].getOn()==1){
moveGrenade(grenades[x]);
grenades[x].draw(g);
for(int a=0;a<numRemaining;a++){
if(enemies[a].getAlive()&&grenades[x].getLifeTime()>140)
shot(enemies[a],grenades[x],a);
}
if(grenades[x].getLifeTime()==200)//when it is done exploding
grenades[x].setOn(2);
}
}
update();
// if(numAlive<numRemaining)
// nextLevel();
boxTime++;
manageBoxes(boxTime);
manageLabels();
if(slower2%accuracy==0)
//ball();
// ball.draw(g);
;
if(!p.getAlive()){
theCounter+=4;
if(theCounter>=255){
theCounter=0;
p.setAlive(true);
screen.setVisible(false);
kListenerOn=true;
}
else{
screen(theCounter);
p.draw(g,theCounter);
g.setColor(Color.black);
int backwards=255-theCounter;
g.drawOval(p.getX()-backwards/2+10,p.getY()-backwards/2+15,backwards,backwards);
backwards=backwards*3;
g.drawOval(p.getX()-backwards/2+10,p.getY()-backwards/2+15,backwards,backwards);
g.drawLine(p.getX()-backwards/2+10,p.getY()+15,p.getX()+backwards/2+10,p.getY()+15);
g.drawLine(p.getX()+10,p.getY()-backwards/2,p.getX()+10,p.getY()+backwards/2+30);
}
}
if(time<=0){
add(label);
label.setVisible(true);
}
repaint();
}
}
private class Key extends KeyAdapter{///////////////////////////////////////////////KEYS
public void keyReleased(KeyEvent e)
{
switch(e.getKeyCode()){
case KeyEvent.VK_UP:u=false;break;
case KeyEvent.VK_RIGHT:r=false;break;
case KeyEvent.VK_DOWN:d=false;break;
case KeyEvent.VK_LEFT:l=false;break;
case KeyEvent.VK_SPACE:space=false;break;
case KeyEvent.VK_SLASH:space=false;break;
case KeyEvent.VK_G:grenade=false;break;
}
if(!u&&!r&&!d&&!l)
move=false;
}
public void keyPressed(KeyEvent e){
if(kListenerOn){
switch(e.getKeyCode()){
case KeyEvent.VK_UP:
u=true;move=true;break;
case KeyEvent.VK_RIGHT:
r=true;move=true;break;
case KeyEvent.VK_DOWN:
d=true;move=true;break;
case KeyEvent.VK_LEFT:
l=true;move=true;break;
case KeyEvent.VK_SPACE:
space=true;break;
case KeyEvent.VK_SLASH:
space=true;break;
case KeyEvent.VK_G:
shootGrenade(p);break;
}
}
}
}
public void setDirection(){
if(u&&r)
p.setDir(2);
else if(d&&r)
p.setDir(4);
else if(d&&l)
p.setDir(6);
else if(u&&l)
p.setDir(8);
else if(r&&l){
if(p.getDir()==3){
p.setDir(7);
r=false;
}
else{
p.setDir(3);
l=false;
}
}
else if(u&&d){
if(p.getDir()==1){
p.setDir(5);
u=false;
}
else{
p.setDir(1);
d=false;
}
}
else if(u)
p.setDir(1);
else if(r)
p.setDir(3);
else if(d)
p.setDir(5);
else if(l)
p.setDir(7);
}
public boolean shot(Rectangle one, Bullet two, int eNum){////////////////////////////////////////////////COLLIDE METHODS
if((Math.abs(two.getX()-(one.getX()+length/2))<=length/2+two.getLength())&&
Math.abs(two.getY()-(one.getY()+25+two.getLength()/2))<=25+two.getLength()/2){
if(two.isABullet()&&!two.isGrenade()&&!two.isExploding())
two.setOn(2);
one.react();
if(one.isEnemy()){
one.setHealth(one.getHealth()-1);
int save=one.getDir();
one.setDir(two.getDir());
moveRect(one);
moveRect(one);
one.setDir(save);
hits++;
if(two.getShooter()!=100)
one.setHealth(one.getHealth()-6);
if(one.getHealth()<=0){
one.setAlive(false);
numAlive--;
nextLevel();
eDeaths[eNum]++;
if(two.getShooter()==100){
kills++;
killStreak++;
addLabel("+Kills",one.getX(),one.getY());
int k=killStreak/4;
if(k>0&&killStreak%4==0){
if(k==1)
numKillStreaks++;
addLabel("+KILLSTREAK x "+k,one.getX()-200,one.getY());/////////////fix this
}
}
else{
eKills[two.getShooter()]++;
}
}
}
else{
if(!two.isGrenade())
one.setHealth(one.getHealth()-20);
else if(two.isGrenadable()){
one.setHealth(one.getHealth()-30);
two.setGrenadable(false);
}
if(p.getHealth()<=0){
die();
eKills[two.getShooter()]++;
}
}
return true;
}
return false;
}
public boolean collided(Enemy one){
if(Math.abs((one.getX()+length/2)-(p.getX()+length/2))<=length&&Math.abs(one.getY()-p.getY())<=50){
return true;
}
return false;
}
public boolean collided(Box box){
if(Math.abs((p.getX()+length/2)-(box.getX()+box.getLength()/2))<=length/2+box.getLength()/2&&
Math.abs((p.getY()+length/2-box.getLength()/2)-box.getY())<=25+box.getLength()/2){
return true;
}
return false;
}
// public void ball(){
// int random=(int)(Math.random()*255);
// int random1=(int)(Math.random()*255);
// int random2=(int)(Math.random()*255);
// ball.setColor(new Color(random,random1,random2));
// ball.move(780,780);
// }
public void manageBoxes(int time){////////////////////////////////////////////MANAGING BOXES AND LABELS
for(int x=0;x<numBoxes;x++){
if(boxes[x].getOn()==1){
boxes[x].draw(g);
if(collided(boxes[x])){
boxes[x].setOn(2);
p.setHealth(100);
addLabel("+Health",boxes[x].getX(),boxes[x].getY());
}
}
else if(boxes[x].getOn()==2){
boxStopTime[x]=time;
boxes[x].setOn(0);
}
else if(time-boxStopTime[x]==500)
boxes[x].setOn(1);
else if(boxes[x].getLifeSpan()<0){
boxStopTime[x]=time;
boxes[x].setOn(1);
boxes[x].setLifeSpan(2000);
}
}
}
public void manageLabels(){
for(int x=0;x<5;x++){
if(labels[x].isVisible()){
labelCounters[x]--;
if(labelCounters[x]==0)
labels[x].setVisible(false);
}
}
}
public void addLabel(String text, int x, int y){
for(int c=0;c<5;c++){
if(!labels[c].isVisible()){
labels[c]=new JLabel(text);
labels[c].setFont(new Font("Serif",Font.BOLD,40));
labels[c].setBounds(x,y,500,65);
if(text.equalsIgnoreCase("+deaths"))
labels[c].setForeground(Color.red);
else
labels[c].setForeground(Color.green);
add(labels[c]);
labels[c].setVisible(true);
labelCounters[c]=40;
break;
}
}
}
public void pause(){
kListenerOn=false;///////////////////////////////////switch for focusable
if(t!=null)
t.stop();
timer.stop();
panel.setVisible(true);
panel.setFocusable(false);
}
public void resume(){
panel.setVisible(false);
kListenerOn=true;
if(t!=null)
t.start();
timer.start();
setFocusable(true);
}
public void moveRect(Rectangle a){ ///////////////////////////////////////MOVING AND SHOOTING
int oldX=a.getX();
int oldY=a.getY();
a.move();
int newX=a.getX();
int newY=a.getY();
if(map[newY-1][newX-1]==1||
map[newY-1][newX+19]==1||
map[newY+49][newX-1]==1||
map[newY+15][newX+19]==1||
map[newY+15][newX-1]==1||
map[newY+34][newX+19]==1||
map[newY+34][newX-1]==1||
map[newY+49][newX+19]==1){
a.setX(oldX);
a.setY(oldY);
}
}
public void moveBullet(Bullet a){
int oldX=a.getX();
int oldY=a.getY();
a.move();
int newX=a.getX();
int newY=a.getY();
if(a.getX()>775||a.getX()<20||a.getY()>775||a.getY()<=20)
if(a.isRocket())
a.setExploding(true);
else
a.setOn(2);
else if(map[newY-1][newX-10]==1||
map[newY-1][newX+length-10]==1||
map[newY+length][newX-10]==1||
map[newY+length][newX+length-10]==1
)
if(a.isRocket())
a.setExploding(true);
else
a.setOn(2);
}
public void moveGrenade(Grenade a){
grenadeCount++;
int oldX=a.getX();
int oldY=a.getY();
int l=a.getLifeTime();
switch(a.getDIR()){
case 1:
case 5:
if(l<15){
a.setSpeed(5);
a.move();
}
else if(l<25){
a.setSpeed(4);
a.move();
}
else if(l<35){
a.setSpeed(3);
a.move();
}
else if(l<45){
a.setSpeed(4);
a.move();
}break;
case 3:
if(l<15){
if(grenadeCount%2==0)
a.setDir(2);
else
a.setDir(3);
a.setSpeed(5);
a.move();
}
else if(l<20){
a.setDir(3);
a.setSpeed(4);
a.move();
}
else if(l<50){
if(grenadeCount%2==0)
a.setDir(4);
else
a.setDir(3);
a.setSpeed(3);
a.move();
}break;
case 7:
if(l<15){
if(grenadeCount%2==0)
a.setDir(8);
else
a.setDir(7);
a.setSpeed(5);
a.move();
}
else if(l<20){
a.setDir(7);
a.setSpeed(4);
a.move();
}
else if(l<50){
if(grenadeCount%2==0)
a.setDir(6);
else
a.setDir(7);
a.setSpeed(3);
a.move();
}break;
case 2:
if(l<15){
if(grenadeCount%2==0)
a.setDir(1);
else
a.setDir(2);
a.setSpeed(5);
a.move();
}
else if(l<20){
a.setDir(2);
a.setSpeed(4);
a.move();
}
else if(l<50){
if(grenadeCount%2==0)
a.setDir(3);
else
a.setDir(4);
a.setSpeed(3);
a.move();
}break;
case 8:
if(l<15){
if(grenadeCount%2==0)
a.setDir(1);
else
a.setDir(8);
a.setSpeed(5);
a.move();
}
else if(l<20){
a.setDir(8);
a.setSpeed(4);
a.move();
}
else if(l<50){
if(grenadeCount%2==0)
a.setDir(7);
else
a.setDir(6);
a.setSpeed(3);
a.move();
}break;
case 4:
if(l<15){
if(grenadeCount%2==0)
a.setDir(3);
else
a.setDir(4);
a.setSpeed(5);
a.move();
}
else if(l<20){
a.setDir(4);
a.setSpeed(4);
a.move();
}break;
case 6:
if(l<15){
if(grenadeCount%2==0)
a.setDir(7);
else
a.setDir(6);
a.setSpeed(5);
a.move();
}
else if(l<20){
a.setDir(6);
a.setSpeed(4);
a.move();
}break;
}
int newX=a.getX();
int newY=a.getY();
if(a.getX()>775||a.getX()<20||a.getY()>775||a.getY()<20){
a.setX(oldX);
a.setY(oldY);
}
else if(map[newY-1][newX-1]==1||
map[newY-1][newX+length-1]==1||
map[newY+length][newX-1]==1||
map[newY+length][newX+length-1]==1
){
a.setX(oldX);
a.setY(oldY);
}
}
public void moveEnemies(){
for(int x=0;x<numRemaining;x++){
if(enemies[x].getAlive()&&enemies[x].getAttacking()==0){
int oldX=enemies[x].getX();
int oldY=enemies[x].getY();
if(p.getX()<enemies[x].getX()){//if player is on left
if(enemies[x].getY()>p.getY()){//if player is above
if(Math.random()<.5)
enemies[x].setDir(8);
else
enemies[x].setDir(7);
}
else{
if(Math.random()<.5)
enemies[x].setDir(6);
else
enemies[x].setDir(7);
}
}
else{ //if player is on the right
if(enemies[x].getY()>p.getY()){//if player is above
if(Math.random()<.5)
enemies[x].setDir(2);
else
enemies[x].setDir(3);
}
else{
if(Math.random()<.5)
enemies[x].setDir(4);
else
enemies[x].setDir(3);
}
}
if(p.getX()<200&&enemies[x].getX()<200||//for columns that are open
p.getX()>200&p.getX()<350&&enemies[x].getX()>200&&enemies[x].getX()<350||
p.getX()>350&&p.getX()<600&&p.getY()<600&&enemies[x].getX()>350&&enemies[x].getX()<600&&enemies[x].getY()<600||
p.getY()<200&&p.getX()<600&&enemies[x].getY()<200&&enemies[x].getX()<600|//for rows that are open
p.getY()>600&&p.getX()>200&&enemies[x].getY()>600&&enemies[x].getX()>200){
if(Math.abs(p.getX()-enemies[x].getX())<8){ //this can be extended so it works for diagonals
double random=Math.random();
if(random<.7){
if(p.getY()>enemies[x].getY())
enemies[x].setDir(5);
if(p.getY()<enemies[x].getY())
enemies[x].setDir(1);
}
else if(random<.85)
enemies[x].setDir(3);
else
enemies[x].setDir(7);
}
if(Math.abs(p.getY()-enemies[x].getY())<8){
double rando=Math.random();
if(rando<.7){
if(p.getX()>enemies[x].getX())
enemies[x].setDir(3);
if(p.getX()<enemies[x].getX())
enemies[x].setDir(5);
}
else if(rando<.85)
enemies[x].setDir(1);
else
enemies[x].setDir(5);
}
}
moveRect(enemies[x]);
}
if(enemies[x].isAShooter()&&enemies[x].getShot()>=enemies[x].getShotFrequency()){/////////////////maybe not
shoot(enemies[x], x);
enemies[x].setShot(0);
}
}
}
public void shoot(Rectangle k){
int fireX=k.getX()+length/2;
int fireY=k.getY();
switch(k.getDir()){
case 2:
case 8:fireY=fireY+13;
break;
case 4:
case 6:fireY=fireY+25;
break;
case 3:
case 7:fireY=fireY+20;
break;
case 1:
case 5:fireX=fireX-3;
break;
}
int b=0;
if(!k.isAShooter()){
for(int x=0;x<numUBullets;x++){
if(uBullets[x].getOn()==0){
uBullets[x].setOn(1);
b=x;
shots++;
break;
}
}
uBullets[b].setX(fireX);
uBullets[b].setY(fireY);
uBullets[b].setDir(k.getDir());
uBullets[b].setColor(k.getBulletColor());
}
if(k.isAShooter()){
for(int x=0;x<numEBullets;x++){
if(eBullets[x].getOn()!=1){
eBullets[x].setOn(1);
b=x;
break;
}
}
eBullets[b].setX(fireX);
eBullets[b].setY(fireY);
eBullets[b].setDir(k.getDir());
eBullets[b].setColor(k.getBulletColor());
eBullets[b].setSpeed(1);
eBullets[b].setLength(7);
}
}
public void shootGrenade(Rectangle k){
int fireX=k.getX()+length/2;
int fireY=k.getY();
switch(k.getDir()){
case 2:
case 8:fireY=fireY+13;
break;
case 4:
case 6:fireY=fireY+25;
break;
case 3:
case 7:fireY=fireY+20;
break;
case 1:
case 5:fireX=fireX-3;
break;
}
int b=0;
for(int x=0;x<numGrenades;x++){
if(grenades[x].getOn()==0){
grenades[x].setOn(1);
b=x;
break;
}
}
grenades[b].setX(fireX);
grenades[b].setY(fireY);
grenades[b].setDir(k.getDir());
grenades[b].setDIR(k.getDir());
grenades[b].setSpeed(6);
grenades[b].setLength(7);
moveGrenade(grenades[b]);
}
public void shoot(Rectangle k, int e){
int fireX=k.getX()+length/2;
int fireY=k.getY();
switch(k.getDir()){
case 2:
case 8:fireY=fireY+13;
break;
case 4:
case 6:fireY=fireY+25;
break;
case 3:
case 7:fireY=fireY+20;
break;
case 1:
case 5:fireX=fireX-3;
break;
}
int b=0;
if(k.isAShooter()){
for(int x=0;x<numEBullets;x++){
if(eBullets[x].getOn()!=1){
eBullets[x].setOn(1);
b=x;
break;
}
}
eBullets[b].setX(fireX);
eBullets[b].setY(fireY);
eBullets[b].setDir(k.getDir());
eBullets[b].setColor(k.getBulletColor());
eBullets[b].setSpeed(1);
eBullets[b].setLength(7);
eBullets[b].setShooter(e);
}
}
public void drawBackground(int lev){///////////////////////////////////////////////////BACKGROUND AND LEVELS
ImageIcon i;
switch(eNum){
case 1:
case 2:i=new ImageIcon("pics/sky.jpg");break;
case 3:
case 4:i=new ImageIcon("pics/tiger.jpg");break;
case 5:i=new ImageIcon("pics/Desert.jpg");break;
default:i=new ImageIcon("pics/fire.jpg");break;
}
g.setColor(new Color(0,0,1));
g.drawImage(i.getImage(),0,0,800,800,null);
g.fillRect(0,0,800,length);
g.fillRect(0,0,length,800);
g.fillRect(0,800-length,800,800);
g.fillRect(800-length,0,800,800);
}
public void drawBackground(int lev, int x){
g.setColor(Color.white);
g.fillRect(0,0,800,800);
g.setColor(new Color(0,0,1));
g.fillRect(0,0,800,length);
g.fillRect(0,0,length,800);
g.fillRect(0,800-length,800,800);
g.fillRect(800-length,0,800,800);
}
public void firstLevel(){
level++;
numRemaining=numAlive=eNum;//lined up on the right
int myX=50;
int myY=50;
for(int x=0;x<numRemaining;x++){
myX=(int)(Math.random()*760+20);
myY=(int)(Math.random()*760+20);
while(myX<50||myX>750||myY<50||myY>730){
myX=(int)(Math.random()*730+30);
myY=(int)(Math.random()*650+30);
}
enemies[x]=new Shooter(myX,myY,20,eSpeed,eCols[x]);
enemies[x].setHealth(eHealth);
enemies[x].setHEALTH(eHealth);
enemies[x].setShotFrequency(eFrequency);
enemies[x].draw(g);
}
}
public void nextLevel(){
int myX=0;
int myY=0;
for(int x=0;x<numRemaining;x++){
if(!enemies[x].getAlive()){
myX=(int)(Math.random()*760+20);
myY=(int)(Math.random()*760+20);
while(myX<50||myX>750||myY<50||myY>730){
myX=(int)(Math.random()*730+30);
myY=(int)(Math.random()*650+30);
}
enemies[x]=new Shooter(myX,myY,20,eSpeed,eCols[x]);
enemies[x].setShotFrequency(eFrequency);
enemies[x].setHealth(eHealth);
enemies[x].setHEALTH(eHealth);
enemies[x].draw(g);
}
}
}
public void die(){//////////////////////////////////////////////////////////////////////////////MISC
int myX=(int)(Math.random()*760+20);
int myY=(int)(Math.random()*760+20);
while(myX<50||myX>750||myY<50||myY>730){
myX=(int)(Math.random()*730+30);
myY=(int)(Math.random()*650+30);
}
p=new Rectangle(myX,myY,20,3,Color.green);
p.setGun(2);
p.setShotFrequency(pShotFrequency);
p.setGun(2);
p.setBulletColor(Color.green);
for(int x=0;x<numUBullets;x++)
uBullets[x].setOn(0);
for(int x=0;x<numGrenades;x++){
if(grenades[x].getOn()!=1)
grenades[x].setOn(0);
}
p.setShot(0);
p.draw(g);
deaths++;
addLabel("+deaths",p.getX(),p.getY());
killStreak=0;
screen(0);
screen.setVisible(true);
p.setAlive(false);
u=d=l=r=space=false;
kListenerOn=false;
}
public void screen(int t){
screen.setBackground(new Color(244,t,255,200));
}
public void end(){//////////////////////////////////////////////////////////////////////////////MISC
screen.setVisible(false);
label.setText("Game Over");
label.setVisible(true);
panel.setBackground(Color.black);
panel.setVisible(true);
panel.add(label);
eKills[numRemaining]=kills;
eDeaths[numRemaining]=deaths;
sE=new ScoreboardEnd();
int change=sE.update(kills,numKillStreaks,deaths,eKills,eDeaths,numRemaining,eCols);
skill+=change;
if(skill>1000)
skill=1000;
if(skill<0)
skill=0;
if(change>-1)
label2=new JLabel("Skill+"+change+" = "+skill);
else
label2=new JLabel("Skill"+change+" = "+skill);
label2.setBounds(50,400,1000,200);
label2.setFont(new Font("Times New Roman",Font.ITALIC,75));
label2.setForeground(Color.green);
label2.setVisible(true);
panel.add(label2);
eNum=2+skill/300;
eSpeed=6+(skill+150)/300;
eHealth=(5+skill+75)/100+2;
eFrequency=37-((skill+30)/80);
sE.setBackground(tr);
panel.add(sE);
kListenerOn=false;
t.stop();
timer.stop();
if(!added){
AL=new AccountListener(skill);
scores.addActionListener(AL);
added=true;
}
s.update(time,skill);
}
private class AccountListener implements ActionListener{//start the game
int myX=0;
public AccountListener(int f){
myX=f;
}
public void actionPerformed(ActionEvent e){
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Object source = e.getSource();
if (source instanceof Component) {
Component c = (Component) source;
Frame frame1 = JOptionPane.getFrameForComponent(c);
if(frame1 != null){
frame1.dispose();
frame1.setVisible(false);
}
}
////////////////THIS CODE WAS BORROWED//////////////http://www.dreamincode.net/forums/topic/162705-dispose-a-frame-from-an-inner-class/////
JFrame frame = new JFrame("BattleFight");
frame.setSize(920,960);
frame.setLocation(200, 0);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new DAccount(1,skill));
frame.setVisible(true);
}
}
public void paintComponent(Graphics a){
int scale=2;
int bx=0;
int by=0;
a.drawImage(radar, -200,-200,10000,1000,null);
bx=(160-p.getX())*scale;
if(bx>0)
bx=0;
if(bx<-785)
bx=-785;
by=(160-p.getY())*scale;
if(by>0)
by=0;
if(by<-785)
by=-785;
a.drawImage(buff,bx,by,800*scale,800*scale,null);
//g.setColor(new Color(0,0,1,225));
//g.fillRect(0,0,800,800);
//a.drawImage(buff,600,600,200,200,null);
//a.drawImage(buff, 0, 60, 800, 800, null);
}
public void update(){
s.update(time,skill);
int score=kills*100+(level-1)*100;
if(score<0)
score=0;
s2.update();
}
public void setGrid(){
for(int x=0;x<800;x++){
for(int y=0;y<800;y++){
map[x][y]=0;
}
}
for(int y=0;y<20;y++){
for(int x=0;x<800;x++){
map[y][x]=1; //top
map[x][y]=1; //left
map[799-y][x]=1; //bottom
map[x][799-y]=1; //right
}
}
}
}
| true
|
5ab498b0b968cffff76e50d8a7665ec5af85efe4
|
Java
|
anony-mous131415/api
|
/api-service/src/test/java/io/revx/api/common/TestAllSingltonBean.java
|
UTF-8
| 1,231
| 1.945313
| 2
|
[] |
no_license
|
package io.revx.api.common;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;
import io.revx.api.ApiMainApplication;
import io.revx.api.config.SwaggerConfig;
import io.revx.core.RestTemplateErrorHandler;
import springfox.documentation.spring.web.plugins.Docket;
@RunWith(SpringJUnit4ClassRunner.class)
public class TestAllSingltonBean {
@Test
public void testRestTemplateBean() throws Exception {
ApiMainApplication main = new ApiMainApplication();
main.errorHandler = new RestTemplateErrorHandler();
main.run("test");
RestTemplate rt = main.restTemplate();
assertNotNull(rt);
}
@Test
public void testRoleHierarchy() throws Exception {
ApiMainApplication main = new ApiMainApplication();
RoleHierarchy restBean = main.roleHierarchy();
assertNotNull(restBean);
}
@Test
public void testSwaggerConfig() throws Exception {
SwaggerConfig main = new SwaggerConfig();
Docket bean = main.api();
assertNotNull(bean);
}
}
| true
|
766cb2dafd8a22dd9b4311dcf53d99a3f0055b46
|
Java
|
xuezhongwei/LearnJava
|
/src/main/java/my/utils/RedisUtils.java
|
UTF-8
| 2,009
| 2.8125
| 3
|
[] |
no_license
|
package my.utils;
import java.util.Collections;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.params.SetParams;
public final class RedisUtils {
private static JedisPool pool = null;
private static final String LOCK_SUCCESS = "OK";
private static final Long RELEASE_SUCCESS = 1L;
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(10);
config.setMaxIdle(5);
config.setMaxWaitMillis(5000);
// testOnBorrow:在提取一个jedis实例时,是否提前进行验证操作;如果为true,则得到的jedis实例均是可用的
// 如果为false,则得到的jedis实例不一定可用
config.setTestOnBorrow(true);
String host = "localhost";
int port = 6379;
pool = new JedisPool(config, host, port);
}
/**
* 获得分布式琐
*/
public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String value, int expireTime) {
SetParams setParams = new SetParams();
// if not exist 设置了此参数,则相当于setnx
setParams.nx();
// 设置key的失效时间
setParams.px(expireTime);
String result = jedis.set(lockKey, value, setParams);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
return false;
}
/**
* 释放分布式琐
*/
public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {
// 使用lua脚本,为了保证操作的原子性
// 释放锁,不能简单通过key来释放锁,还要校验value
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
}
| true
|
11407896dd69a121009a51b3caab74648082b2e3
|
Java
|
shurvitz/aws-athena-query-federation
|
/athena-docdb/src/main/java/com/amazonaws/athena/connectors/docdb/integ/DocDbIntegTestHandler.java
|
UTF-8
| 3,810
| 2.234375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*-
* #%L
* athena-docdb
* %%
* Copyright (C) 2019 - 2021 Amazon Web Services
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.amazonaws.athena.connectors.docdb.integ;
import com.amazonaws.athena.connectors.docdb.DocDBConnectionFactory;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.google.common.collect.ImmutableList;
import com.mongodb.client.MongoClient;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.io.OutputStream;
/**
* This Lambda function handler is only used within the DocumentDB integration tests. The Lambda function,
* when invoked, will generate a MongoDB database, table, and insert values.
* The invocation of the Lambda function must include the following environment variables:
* default_docdb - The connection string used to connect to the DocumentDB cluster (e.g. mongodb://...).
* database_name - The MongoDB database name.
* table_name - The MongoDB collection name.
*/
public class DocDbIntegTestHandler
implements RequestStreamHandler
{
public static final String HANDLER = "com.amazonaws.athena.connectors.docdb.integ.DocDbIntegTestHandler";
private static final Logger logger = LoggerFactory.getLogger(DocDbIntegTestHandler.class);
private final DocDBConnectionFactory connectionFactory;
private final String connectionString;
private final String databaseName;
private final String tableName;
public DocDbIntegTestHandler()
{
connectionFactory = new DocDBConnectionFactory();
connectionString = System.getenv("default_docdb");
databaseName = System.getenv("database_name");
tableName = System.getenv("table_name");
}
@Override
public final void handleRequest(InputStream inputStream, OutputStream outputStream, Context context)
{
logger.info("handleRequest - enter");
try (MongoClient mongoClient = connectionFactory.getOrCreateConn(connectionString)) {
mongoClient.getDatabase(databaseName)
.getCollection(tableName)
.insertOne(new Document()
.append("_id", "1")
.append("title", "The Matrix")
.append("year", Integer.valueOf(1999))
.append("cast", ImmutableList.of("Keanu Reeves", "Laurence Fishburn", "Carrie-Anne Moss",
"Hugo Weaving")));
mongoClient.getDatabase(databaseName)
.getCollection(tableName)
.insertOne(new Document()
.append("_id", "2")
.append("title", "Interstellar")
.append("year", Integer.valueOf(2014))
.append("cast", ImmutableList.of("Matthew McConaughey", "John Lithgow", "Ann Hathaway",
"David Gyasi", "Michael Caine", "Jessica Chastain", "Matt Damon", "Casey Affleck")));
logger.info("Documents inserted successfully.");
}
catch (Exception e) {
logger.error("Error setting up MongoDB table {}", e.getMessage(), e);
}
logger.info("handleRequest - exit");
}
}
| true
|
1bd7645c1d89d504069d9febb65f15bcfa94bda6
|
Java
|
ramdhanrizki/pelatihanjava
|
/src/Kasus2/GenericTag.java
|
UTF-8
| 585
| 2.71875
| 3
|
[] |
no_license
|
package Kasus2;
public class GenericTag<E> {
private E data1;
private E data2;
private E temp;
public E getData1() {
return data1;
}
public void setData1(E data1) {
this.data1 = data1;
}
public E getData2() {
return data2;
}
public void setData2(E data2) {
this.data2 = data2;
}
public E getTemp() {
return temp;
}
public void setTemp(E temp) {
this.temp = temp;
}
public void tukarData(){
temp = data1;
data1 = data2;
data2 = temp;
}
}
| true
|
3d3f6c96de862d8a6f3060c296ce510f0602644b
|
Java
|
VynnykVV/introduction.hw2
|
/src/main/java/school/lemon/changerequest/java/introduction/hw2/Task7.java
|
UTF-8
| 325
| 2.453125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package school.lemon.changerequest.java.introduction.hw2;
public class Task7 {
public static int countEvens(int[] arr) {
int count =0;
if(arr==null){return 0;}
for(int i=0; i<arr.length; i++){
if (arr[i]%2==0||arr[i]==0){count=count+1;}
}
return count;
}
}
| true
|
c89d96db3bbd010f8fc6c4ec875f47fb259bdfcd
|
Java
|
Carsonq/FinalProject472
|
/app/src/main/java/csc472/depaul/edu/finalproject/db/TransactionCategory.java
|
UTF-8
| 705
| 2.359375
| 2
|
[] |
no_license
|
package csc472.depaul.edu.finalproject.db;
import android.arch.persistence.room.ColumnInfo;
public class TransactionCategory {
@ColumnInfo(name = "transaction_category")
private String transactionCategory;
@ColumnInfo(name = "category_amount")
private double categoryAmount;
public String getTransactionCategory() {
return transactionCategory;
}
public void setTransactionCategory(String transactionCategory) {
this.transactionCategory = transactionCategory;
}
public double getCategoryAmount() {
return categoryAmount;
}
public void setCategoryAmount(double categoryAmount) {
this.categoryAmount = categoryAmount;
}
}
| true
|
c87030096db8477e081ccd8bee78f5e1062fc80e
|
Java
|
rajkboddupally/Datastructures-Algorithms
|
/src/arrays/MatrixDiagnonalSort.java
|
UTF-8
| 2,726
| 3.828125
| 4
|
[] |
no_license
|
package arrays;
/*
A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].
Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.
Example 1:
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
Example 2:
Input: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]
Output: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
1 <= mat[i][j] <= 100
*/
import java.util.*;
public class MatrixDiagnonalSort {
public static void main(String[] args) {
int[][] mat = {{3, 3, 1, 1}, {2, 2, 1, 2}, {1, 1, 1, 2}};
print(mat);
System.out.println();
System.out.println();
//int[][] sortedMat = diagonalSort(mat);
//row sort
for (int i = 0; i < mat.length; i++) {
diagonalSort1(mat, i, 0);
}
//column
for (int i = 0; i < mat[0].length; i++) {
diagonalSort1(mat, 0, i);
}
print(mat);
}
private static void print(int[][] sortedMat) {
for (int i = 0; i < sortedMat.length; i++) {
for (int j = 0; j < sortedMat[0].length; j++) {
System.out.print(sortedMat[i][j] + " ");
}
System.out.println();
}
}
private static int[][] diagonalSort(int[][] mat) {
Map<Integer, PriorityQueue<Integer>> map = new HashMap<>();
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
map.computeIfAbsent(i - j, k -> new PriorityQueue<>()).add(mat[i][j]);
}
}
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
mat[i][j] = map.get(i - j).poll();
}
}
return mat;
}
private static int[][] diagonalSort1(int[][] mat, int r, int c) {
int rowLength = mat.length;
int colLength = mat[0].length;
List<Integer> list = new ArrayList<>();
for (int i = r, j = c; i < rowLength && j < colLength; i++, j++) {
list.add(mat[i][j]);
}
Collections.sort(list);
for (Integer i:list) {
mat[r++][c++] = i;
}
return mat;
}
}
| true
|
0522e8352c5efb46db3c5fe6c8233ba67a7293e6
|
Java
|
sruan2/five-hundred-card-game
|
/tests/comp303/fivehundred/ai/TestBasicBiddingStrategy.java
|
UTF-8
| 10,005
| 2.75
| 3
|
[] |
no_license
|
package comp303.fivehundred.ai;
import static comp303.fivehundred.util.AllCards.*;
import static comp303.fivehundred.util.AllBids.*;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import comp303.fivehundred.ai.basic.BasicBiddingStrategy;
import comp303.fivehundred.model.Bid;
import comp303.fivehundred.model.Hand;
/**
* @author Stephanie Pataracchia 260407002
*/
public class TestBasicBiddingStrategy
{
Bid pBid;
Bid[] pBids1 = new Bid[0];
Bid[] pBids2 = new Bid[3];
Bid[] pBids3 = new Bid[3];
Bid[] pBids4 = new Bid[3];
Hand pHand;
BasicBiddingStrategy bidding;
@Before
public void init()
{
// not partner nor opponent has bid Diamonds
pBids2[0] = new Bid(0);
pBids2[1] = new Bid(5);
pBids2[2] = new Bid(11);
// partner has bid Diamonds
pBids3[0] = new Bid(0);
pBids3[1] = new Bid(2);
pBids3[2] = new Bid(11);
// opponent has bid Diamonds
pBids4[0] = new Bid(0);
pBids4[1] = new Bid(5);
pBids4[2] = new Bid(2);
pHand = new Hand();
bidding = new BasicBiddingStrategy();
}
/********************************
* #1 BIDDING first
********************************/
// bid 7 diamonds
// 9 pts= 4(HJo) + 2(RJ) + 1(Ace) +2(threshold)
@Test
public void firstBid06()
{
pHand.add(aHJo);
pHand.add(aJD);
pHand.add(aAD);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6D);
pHand.add(a7D);
pHand.add(a5S);
pHand.add(a5H);
pHand.add(a5C);
assertEquals(bidding.selectBid(pBids1, pHand), aBid7D);
}
// bid 7 diamonds
// 10 pts= 3(LJo) + 2(RJ) + 2(LJ) + 1(K) +2(threshold)
@Test
public void firstBid07()
{
pHand.add(aLJo);
pHand.add(aJD);
pHand.add(aJH);
pHand.add(aKD);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6D);
pHand.add(a7S);
pHand.add(a5H);
pHand.add(a5C);
assertEquals(bidding.selectBid(pBids1, pHand), aBid7D);
}
// bid 8 diamonds
// 11 pts= 3(LJo) + 2(RJ) + 2(LJ) + 1(K) + 1(Ace) +2(threshold)
@Test
public void firstBid08()
{
pHand.add(aLJo);
pHand.add(aJD);
pHand.add(aJH);
pHand.add(aKD);
pHand.add(aAD);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6C);
pHand.add(a7S);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids1, pHand), aBid8D);
}
// bid 8 diamonds
// 12 pts= 3(LJo) + 2(RJ) + 2(LJ) + 1(K) +1(Q) +1(Ace) +2(threshold)
@Test
public void firstBid09()
{
pHand.add(aLJo);
pHand.add(aJD);
pHand.add(aJH);
pHand.add(aKD);
pHand.add(aQD);
pHand.add(aAD);
pHand.add(a9D);
pHand.add(a6C);
pHand.add(a7S);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids1, pHand), aBid8D);
}
// bid 9 diamonds
// 13 pts= 4(HJo) +3(LJo) + 2(LJ) + 4(threshold)
@Test
public void firstBid10()
{
pHand.add(aHJo);
pHand.add(aLJo);
pHand.add(aJH);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6D);
pHand.add(a7D);
pHand.add(a8D);
pHand.add(a9D);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids1, pHand), aBid9D);
}
// FIRST BID - NO TRUMP
// bid 7 no-trump
// 9 pts= 4(HJo) + 2(A)+ 2(A) + 1(Q)
@Test
public void firstNTBid06()
{
pHand.add(aHJo);
pHand.add(aAS);
pHand.add(aAD);
pHand.add(aQS);
pHand.add(a4H);
pHand.add(a4S);
pHand.add(a4C);
pHand.add(a5D);
pHand.add(a5C);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids1, pHand), aBid7N);
}
// bid 7 no-trump
// 10 pts= 2(A)+ 2(A) +2(A)+ 2(A) + 1(Q) + 1(J)
@Test
public void firstNTBid07()
{
pHand.add(aAH);
pHand.add(aAS);
pHand.add(aAD);
pHand.add(aAC);
pHand.add(aQH);
pHand.add(aJS);
pHand.add(a4C);
pHand.add(a5D);
pHand.add(a5C);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids1, pHand), aBid7N);
}
// bid 8 no-trump
// 10 pts= 1(Q) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J) + 1(J) + 2(A)
@Test
public void firstNTBid08()
{
pHand.add(aQH);
pHand.add(aQS);
pHand.add(aQD);
pHand.add(aQC);
pHand.add(aJH);
pHand.add(aJS);
pHand.add(aJD);
pHand.add(aJC);
pHand.add(aAS);
pHand.add(a4H);
assertEquals(bidding.selectBid(pBids1, pHand), aBid7N);
}
// bid 8 no-trump
// 11 pts= 4(HJo) + 3(LJo) + 2(A)+ 1(K) + 1(Q)
@Test
public void firstNTBid09()
{
pHand.add(aHJo);
pHand.add(aLJo);
pHand.add(aAD);
pHand.add(aKS);
pHand.add(aQS);
pHand.add(a4S);
pHand.add(a4C);
pHand.add(a5D);
pHand.add(a5C);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids1, pHand), aBid8N);
}
// bid 8 no-trump
// 11 pts= 3(LJo) + 1(K) + 1(Q) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J) + 1(J)
@Test
public void firstNTBid10()
{
pHand.add(aLJo);
pHand.add(aKS);
pHand.add(aQH);
pHand.add(aQS);
pHand.add(aQD);
pHand.add(aQC);
pHand.add(aJH);
pHand.add(aJS);
pHand.add(aJD);
pHand.add(aJC);
assertEquals(bidding.selectBid(pBids1, pHand), aBid8N);
}
/*****************************************
* #2 LAST BID - NO ONE BID SUIT
*******************************************/
// 9 pts= 4(HJo) + 2(RJ) + 1(Ace) + 2(threshold), but previous bids are better
@Test
public void lastBid06()
{
pHand.add(aHJo);
pHand.add(aJD);
pHand.add(aAD);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6D);
pHand.add(a7D);
pHand.add(a5S);
pHand.add(a5H);
pHand.add(a5C);
assertEquals(bidding.selectBid(pBids2, pHand), aBidPass);
}
// 13 pts= 4(HJo) + +3(LJo) + 2(LJ) + 4(threshold)
@Test
public void lastBid10()
{
pHand.add(aHJo);
pHand.add(aLJo);
pHand.add(aJH);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6D);
pHand.add(a7D);
pHand.add(a8D);
pHand.add(a9D);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids2, pHand), aBid9D);
}
// 9 pts= 4(HJo) + 2(A)+ 2(A) + 1(Q), but there is a better bid
@Test
public void lastNTBid06()
{
pHand.add(aHJo);
pHand.add(aAS);
pHand.add(aAD);
pHand.add(aQS);
pHand.add(a4H);
pHand.add(a4S);
pHand.add(a4C);
pHand.add(a5D);
pHand.add(a5C);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids2, pHand), aBidPass);
}
// 12 pts= 3(LJo) + 1(K) + 1(Q) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J) + 1(J)
@Test
public void lastNTBid10()
{
pHand.add(aLJo);
pHand.add(aKS);
pHand.add(aQH);
pHand.add(aQS);
pHand.add(aQD);
pHand.add(aQC);
pHand.add(aJH);
pHand.add(aJS);
pHand.add(aJD);
pHand.add(aJC);
assertEquals(bidding.selectBid(pBids2, pHand), aBid8N);
}
/******************************************
* #3 LAST BID - PARTNER BID SUIT
*******************************************/
// 9 pts= 4(HJo) + 2(RJ) + 1(Ace) + 1(threshold) +1(Partner), but there is a better bid
@Test
public void lastPartnerBid06()
{
pHand.add(aHJo);
pHand.add(aJD);
pHand.add(aAD);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6D);
pHand.add(a7H);
pHand.add(a5S);
pHand.add(a5H);
pHand.add(a5C);
assertEquals(bidding.selectBid(pBids3, pHand), aBidPass);
}
// 13 pts= 4(HJo) + +3(LJo) + 2(LJ) + 3(threshold) +1(Partner)
@Test
public void lastPartnerBid10()
{
pHand.add(aHJo);
pHand.add(aLJo);
pHand.add(aJH);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6D);
pHand.add(a7D);
pHand.add(a8D);
pHand.add(a9S);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids3, pHand), aBid9D);
}
// 9 pts= 4(HJo) + 2(A)+ 2(A) +1(Partner), but there is a better bid
@Test
public void lastPartnerNTBid06()
{
pHand.add(aHJo);
pHand.add(aAS);
pHand.add(aAD);
pHand.add(a7S);
pHand.add(a4H);
pHand.add(a4S);
pHand.add(a4C);
pHand.add(a5D);
pHand.add(a5C);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids3, pHand), aBidPass);
}
// 11 pts= 3(LJo) + 1(K) + 1(Q) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J)
@Test
public void lastPartnerNTBid10()
{
pHand.add(aLJo);
pHand.add(aKS);
pHand.add(aQH);
pHand.add(aQS);
pHand.add(aQD);
pHand.add(aQC);
pHand.add(aJH);
pHand.add(aJS);
pHand.add(aJD);
pHand.add(a4C);
assertEquals(bidding.selectBid(pBids3, pHand), aBid8N);
}
/******************************************
* #4 LAST BID - OPPONENT BID SUIT
******************************************/
// 9 pts= 4(HJo) + 2(RJ) + 1(Ace) + 3(threshold) -1(Opponent)
@Test
public void lastOpponentBid06()
{
pHand.add(aHJo);
pHand.add(aJD);
pHand.add(aAD);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6D);
pHand.add(a7D);
pHand.add(a8D);
pHand.add(a5H);
pHand.add(a5C);
assertEquals(bidding.selectBid(pBids4, pHand), aBid7D);
}
// 13 pts= 4(HJo) + +3(LJo) + 2(LJ) + 5(threshold) -1(Opponent)
@Test
public void lastOpponentBid10()
{
pHand.add(aHJo);
pHand.add(aLJo);
pHand.add(aJH);
pHand.add(a4D);
pHand.add(a5D);
pHand.add(a6D);
pHand.add(a7D);
pHand.add(a8D);
pHand.add(a9D);
pHand.add(aTD);
assertEquals(bidding.selectBid(pBids4, pHand), aBid9D);
}
// 9 pts= 4(HJo) + 2(A)+ 2(A) + 1(Q) + 1(Q) -1(Opponent)
@Test
public void lastOpponentNTBid06()
{
pHand.add(aHJo);
pHand.add(aAS);
pHand.add(aAD);
pHand.add(aQS);
pHand.add(aQC);
pHand.add(a4S);
pHand.add(a4C);
pHand.add(a5D);
pHand.add(a5C);
pHand.add(a5H);
assertEquals(bidding.selectBid(pBids4, pHand), aBid7N);
}
// 11 pts= 3(LJo) + 1(K) + 1(K) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J) + 1(J) -1(Opponent)
@Test
public void lastOpponentNTBid10()
{
pHand.add(aLJo);
pHand.add(aKS);
pHand.add(aKH);
pHand.add(aQS);
pHand.add(aQD);
pHand.add(aQC);
pHand.add(aJH);
pHand.add(aJS);
pHand.add(aJD);
pHand.add(aJC);
assertEquals(bidding.selectBid(pBids4, pHand), aBid8N);
}
}
| true
|
c443610532cab5248b862a532f94a91f9b402f34
|
Java
|
zachwo/newOracleWDP_win
|
/2021_04_23/src/com/deadLock/B.java
|
UTF-8
| 399
| 2.65625
| 3
|
[] |
no_license
|
package com.deadLock;
public class B {
public synchronized void useA(A a){
System.out.println("执行了B类的useA方法");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
a.funcA();
}
public synchronized void funcB(){
System.out.println("执行了B类的FuncB方法");
}
}
| true
|
34b856c80b0793d2d792a7518fd17e1034f12f06
|
Java
|
dandycheung/magnet
|
/magnet-processor/src/test/resources/GenerateRegistryForInstanceFactoriesTest/Implementation3_1.java
|
UTF-8
| 123
| 1.5625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package test;
import magnet.Instance;
@Instance(type = Interface3.class)
class Implementation3_1 implements Interface3 {}
| true
|
b3c44b706c2bb537f6215275cff688c00809d4d0
|
Java
|
github4n/jcob-service
|
/jcob-server/src/main/java/com/aicai/jcob/member/manager/impl/MemberLoginManagerImpl.java
|
UTF-8
| 3,066
| 2.234375
| 2
|
[] |
no_license
|
package com.aicai.jcob.member.manager.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.aicai.appmodel.domain.result.ModelResult;
import com.aicai.dao.GenericDao;
import com.aicai.jcob.member.common.domain.MemberLogin;
import com.aicai.jcob.member.common.domain.constant.MemberLoginType;
import com.aicai.jcob.member.manager.MemberLoginManager;
public class MemberLoginManagerImpl implements MemberLoginManager {
@Autowired
@Qualifier("memberDbDao")
private GenericDao memberDbDao;
@Override
public MemberLogin insertMemberLogin(MemberLogin memberLogin) {
memberDbDao.insertAndSetupId("MemberLoginMapper.insertSelective", memberLogin);
return memberLogin;
}
/*@Override
public MemberLogin updateMemberLogin(MemberLogin memberLogin) {
memberDbDao.updateByObj("MemberLoginMapper.updateByPrimaryKeySelective",memberLogin);
return memberLogin;
}*/
@Override
public MemberLogin queryMemberLoginById(int id) {
return (MemberLogin)memberDbDao.queryUnique("MemberLoginMapper.selectByPrimaryKey", id);
}
@Override
public MemberLogin queryMemberLoginByLoginTypeAndLoginId(
int loginType, String loginId) {
Map<String,Object> param = new HashMap<String,Object>();
param.put("loginType", loginType);
param.put("loginId", loginId);
return memberDbDao.queryUnique("MemberLoginMapper.queryMemberLoginByLoginTypeAndLoginId", param);
}
@Override
public int updateMemberLoginStatusById(int id, int status) {
Map<String,Object> param = new HashMap<String,Object>();
param.put("id", id);
param.put("status", status);
return memberDbDao.update("MemberLoginMapper.updateMemberLoginStatusById", param);
}
@Override
public int updateMemberLoginLoginIdById(int id, String loginId) {
Map<String,Object> param = new HashMap<String,Object>();
param.put("id", id);
param.put("loginId", loginId);
return memberDbDao.update("MemberLoginMapper.updateMemberLoginLoginIdById", param);
}
@Override
public ModelResult<MemberLogin> thirdIsAlreadyRegister(String loginId) {
ModelResult<MemberLogin> result = new ModelResult<MemberLogin>();
MemberLogin memberLogin = this.queryMemberLoginByLoginTypeAndLoginId(
MemberLoginType.aici_login_third.getIndex(), loginId);
result.setModel(memberLogin);
return result;
}
@Override
public List<MemberLogin> queryMemberLoginTokenByMemberId(Long memberId) {
Map<String,Object> param = new HashMap<String,Object>();
param.put("memberId", memberId);
return memberDbDao.queryList("MemberLoginMapper.queryMemberLoginTokenByMemberId", param);
}
@Override
public List<MemberLogin> queryMemberLoginByThirdLoginTypeAndLoginId(
int loginType, String loginId) {
Map<String,Object> param = new HashMap<String,Object>();
param.put("loginType", loginType);
param.put("loginId", loginId);
return memberDbDao.queryList("MemberLoginMapper.queryMemberLoginByLoginTypeAndLoginId", param);
}
}
| true
|
169e9ec71ad31090981f87201f110f157c4025db
|
Java
|
BallBoom/MyApi
|
/src/main/java/com/cn/controller/ComJobStuController.java
|
UTF-8
| 1,820
| 2.265625
| 2
|
[] |
no_license
|
package com.cn.controller;
import com.cn.entity.ComJobStu;
import com.cn.service.ComJobStuService;
import com.cn.utils.ResponseMsg;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
* (ComJobStu)表控制层
*
* @author kai
* @since 2018-11-29 11:55:23
*/
@CrossOrigin
@RestController
@RequestMapping(value="comJobStu",produces = "text/html;charset=utf-8")
public class ComJobStuController {
/**
* 服务对象
*/
@Resource
private ComJobStuService comJobStuService;
/**
* 通过主键查询单条数据
*
* @param id 主键
* @return 单条数据
*/
// @RequestMapping("selectOne/{id}")
// public String selectOne(@PathVariable Integer id) {
// Gson gson=new Gson();
// return gson.toJson(this.comJobStuService.queryById(id));
//
// }
/**
* 无条件查询全部数据
*
* @return 全部数据
*/
@RequestMapping("all")
public String all() {
Gson gson=new Gson();
return gson.toJson(this.comJobStuService.all());
}
/**
* 通过招聘ID查询所有应聘的学生
* @param jid 招聘ID
* @return 所有学生
*/
@RequestMapping(value = "getByJid",method = RequestMethod.GET)
public String queryJob(Integer jid){
List<ComJobStu> comJobStus=this.comJobStuService.queryByPId(jid);
if(comJobStus.size()!=0){
return ResponseMsg.success(comJobStus);
}else{
return ResponseMsg.fail();
}
}
}
| true
|
16a6259a425a31b0121d21c229651ee9ec9c99d7
|
Java
|
Pramod1008/demoserviceodata
|
/src/main/java/com/exampleodata/demo/model/EntityListClass.java
|
UTF-8
| 1,620
| 2.0625
| 2
|
[] |
no_license
|
package com.exampleodata.demo.model;
import java.util.List;
public class EntityListClass {
public String EntityTypeName;
public String EntitySet;
//public List<PropertyList> propertyList;
public String PropertiesName;
public String PropertiesType;
public EntityListClass(String entityTypeName, String entitySet, String propertiesName, String propertiesType, String navigationProperty) {
EntityTypeName = entityTypeName;
EntitySet = entitySet;
PropertiesName = propertiesName;
PropertiesType = propertiesType;
NavigationProperty = navigationProperty;
}
public String getPropertiesName() {
return PropertiesName;
}
public void setPropertiesName(String propertiesName) {
PropertiesName = propertiesName;
}
public String getPropertiesType() {
return PropertiesType;
}
public void setPropertiesType(String propertiesType) {
PropertiesType = propertiesType;
}
public String NavigationProperty ;
public String getEntityTypeName() {
return EntityTypeName;
}
public String getNavigationProperty() {
return NavigationProperty;
}
public void setNavigationProperty(String navigationProperty) {
NavigationProperty = navigationProperty;
}
public void setEntityTypeName(String entityTypeName) {
EntityTypeName = entityTypeName;
}
public String getEntitySet() {
return EntitySet;
}
public void setEntitySet(String entitySet) {
EntitySet = entitySet;
}
public EntityListClass() {
}
}
| true
|
30bac51fb9d8ea77904ccee9a9d8a2738f560460
|
Java
|
qshahrukh41/Furnico-2k17
|
/app/src/main/java/com/log2n/rentafurniture/HomeLoggedIn.java
|
UTF-8
| 3,648
| 2.25
| 2
|
[] |
no_license
|
package com.log2n.rentafurniture;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class HomeLoggedIn extends Activity implements View.OnClickListener {
private Button Search;
private TextView AdvancedSearch;
private EditText editText;
ViewPager viewPager;
customSwipe customSwip;
private Button Dropdown;
private int flag=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_home_logged_in);
Dropdown = (Button) findViewById(R.id.button22);
editText = (EditText) findViewById(R.id.editTextHomeSearch);
Search = (Button) findViewById(R.id.imageViewSearch);
Search.setOnClickListener(this);
AdvancedSearch = (TextView) findViewById(R.id.textView17);
AdvancedSearch.setOnClickListener(this);
Dropdown.setOnClickListener(this);
viewPager = (ViewPager) findViewById(R.id.viewPager);
customSwip = new customSwipe(this);
viewPager.setAdapter(customSwip);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(),2000,3000);
}
public class MyTimerTask extends TimerTask{
@Override
public void run(){
HomeLoggedIn.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if(viewPager.getCurrentItem()==0){
viewPager.setCurrentItem(1);
}
else if(viewPager.getCurrentItem()==1){
viewPager.setCurrentItem(2);
}
else if(viewPager.getCurrentItem()==2){
viewPager.setCurrentItem(3);
}
else if(viewPager.getCurrentItem()==3){
viewPager.setCurrentItem(4);
}
else if(viewPager.getCurrentItem()==4){
viewPager.setCurrentItem(0);
}
}
});
}
}
@Override
public void onClick(View view) {
if (view == Search){
String message = editText.getText().toString();
if (message.isEmpty()){
Toast.makeText(this, "Please enter keywords to search for!", Toast.LENGTH_SHORT).show();
//return;
}
else {
Intent intent = new Intent(HomeLoggedIn.this, Logged_In.class);
intent.putExtra("message2", message);
startActivity(intent);
}
}
if(view == AdvancedSearch)
{
startActivity(new Intent(HomeLoggedIn.this, AdvancedSearch.class));
}
if(view==Dropdown)
{
startActivity(new Intent(HomeLoggedIn.this, DropDownMenu.class));
}
}
@Override
public void onBackPressed()
{
if(flag==0)
{
Toast.makeText(this, "Press back again to exit" , Toast.LENGTH_SHORT).show();
flag=1;
}
else if(flag==1)
{
finishAffinity();
}
}
}
| true
|
3f5d5ea9cb07d9c57fca91ef26292605a89c1b47
|
Java
|
naufalfathur/ServiceMate
|
/app/src/main/java/com/example/servicemate/Payment.java
|
UTF-8
| 887
| 1.882813
| 2
|
[] |
no_license
|
package com.example.servicemate;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class Payment extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
getSupportActionBar().hide();
LinearLayout app_layer = (LinearLayout) findViewById (R.id.paid);
app_layer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(Payment.this, "Payment Successful", Toast.LENGTH_LONG).show();
startActivity(new Intent(Payment.this, paid.class));
}
});
}
}
| true
|
8fe1dab66cd3b66dafe078e1cb6ebf3ee7f84d63
|
Java
|
alipay/alipay-sdk-java-all
|
/v2/src/main/java/com/alipay/api/domain/ContractOrderSendLogDTO.java
|
UTF-8
| 1,548
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.alipay.api.domain;
import java.util.Date;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 合同订单发送&确认记录
*
* @author auto create
* @since 1.0, 2023-08-18 10:18:53
*/
public class ContractOrderSendLogDTO extends AlipayObject {
private static final long serialVersionUID = 4745373582599317417L;
/**
* 附件,逗号分隔的ResourceId
*/
@ApiField("files")
private String files;
/**
* 记录ID
*/
@ApiField("log_id")
private String logId;
/**
* 备注
*/
@ApiField("remark")
private String remark;
/**
* 发送时间
*/
@ApiField("send_time")
private Date sendTime;
/**
* 发送人工号
*/
@ApiField("sender")
private String sender;
/**
* 状态
*/
@ApiField("status")
private String status;
public String getFiles() {
return this.files;
}
public void setFiles(String files) {
this.files = files;
}
public String getLogId() {
return this.logId;
}
public void setLogId(String logId) {
this.logId = logId;
}
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Date getSendTime() {
return this.sendTime;
}
public void setSendTime(Date sendTime) {
this.sendTime = sendTime;
}
public String getSender() {
return this.sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
}
| true
|
b018549790c63db0d6d238f0c7db11e26be8d135
|
Java
|
dojustdo/p5Study
|
/src/main/java/com/study/io/disk/ObjectReaderWriterDemo.java
|
UTF-8
| 1,641
| 3.203125
| 3
|
[] |
no_license
|
package com.study.io.disk;
import java.io.*;
/**
* @author dxq
* @title: ObjectReaderWriterDemo
* @projectName reflex
* @description: 流的方式序列化,反序列化
* @date 2020/3/6 16:36
*/
public class ObjectReaderWriterDemo {
public static class User implements Serializable {
private String name;
private String ago;
public User(String name, String ago) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAgo() {
return ago;
}
public void setAgo(String ago) {
this.ago = ago;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", ago='" + ago + '\'' +
'}';
}
}
public static void main(String[] args) {
/*try (ObjectOutputStream objectOutputStream =
new ObjectOutputStream(new FileOutputStream("D:/user"))) {
// 序列化 被序列化的对象必须实现序列化接口
User user = new User("小明","12");
objectOutputStream.writeObject(user);
} catch (Exception e) {
}*/
try (ObjectInputStream objectInputStream =
new ObjectInputStream(new FileInputStream("D:/test.txt"))) {
//反序列化
User user = (User)objectInputStream.readObject();
System.out.println(user);
}catch (Exception e){
}
}
}
| true
|
7366eefc7a73f99fdbf6934f86d2d3de2906315a
|
Java
|
Wuming-ta/biliya
|
/ext-plugin-vip/src/main/java/com/jfeat/ext/plugin/vip/bean/CouponPrice.java
|
UTF-8
| 603
| 1.859375
| 2
|
[] |
no_license
|
package com.jfeat.ext.plugin.vip.bean;
import java.math.BigDecimal;
/**
* @author jackyhuang
* @date 2019/6/11
*/
public class CouponPrice {
private String couponId;
private BigDecimal couponPrice;
public String getCouponId() {
return couponId;
}
public CouponPrice setCouponId(String couponId) {
this.couponId = couponId;
return this;
}
public BigDecimal getCouponPrice() {
return couponPrice;
}
public CouponPrice setCouponPrice(BigDecimal couponPrice) {
this.couponPrice = couponPrice;
return this;
}
}
| true
|
dc3ad188332293d9ef5e16cfccaf6d92bc1531b8
|
Java
|
shuwenwei/2020-hackweek
|
/src/main/java/com/sww/pojo/Article.java
|
UTF-8
| 945
| 2.015625
| 2
|
[] |
no_license
|
package com.sww.pojo;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import java.util.Date;
/**
* @author sww
*/
@Data
@TableName("article")
public class Article {
@TableId(type = IdType.ASSIGN_ID)
@Null
private Long id;
@NotNull(message = "标题不能为空")
private String title;
/**
* 类型
* 0:swank
* 1:story
*/
@Null
private Integer articleType;
@Null
private Long authorId;
@NotNull(message = "内容不能为空")
private String content;
@Null
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@Null
@TableField(fill = FieldFill.INSERT_UPDATE, select = false)
private Date gmtModified;
@TableField(value = "is_delete", select = false, fill = FieldFill.INSERT)
@Null
@TableLogic
private Integer delete;
}
| true
|
99d67339a01ddd36932e06d560078a399715202a
|
Java
|
bth1994/CR-MicroLabs-Loops-NumbersTrianglesTables
|
/src/main/java/io/zipcoder/microlabs/mastering_loops/NumberUtilities.java
|
UTF-8
| 1,382
| 3.578125
| 4
|
[] |
no_license
|
package io.zipcoder.microlabs.mastering_loops;
public class NumberUtilities {
public static String getEvenNumbers(int start, int stop) {
git
StringBuilder evensOnly = new StringBuilder();
for(int i = start; i <= stop; i++) {
if(i % 2 == 0) {
evensOnly.append(i);
}
}
return evensOnly.toString();
}
public static String getOddNumbers(int start, int stop) {
StringBuilder oddsOnly = new StringBuilder();
for(int i = start; i <= stop; i++) {
if(i % 2 != 0) {
oddsOnly.append(i);
}
}
return oddsOnly.toString();
}
public static String getSquareNumbers(int start, int stop, int step) {
return getExponentiations(start, stop, step, 2);
}
public static String getRange(int start, int stop, int step) {
StringBuilder range = new StringBuilder();
for(int i = start; i < stop; i += step) {
range.append(i);
}
return range.toString();
}
public static String getExponentiations(int start, int stop, int step, int exponent) {
StringBuilder exponentials = new StringBuilder();
for(int i = start; i < stop; i += step) {
exponentials.append((int)Math.pow(i, exponent));
}
return exponentials.toString();
}
}
| true
|
d375ed05b0063488d9829ca0cda2a1c0617cd324
|
Java
|
deepakbhalla/json-api-examples
|
/src/main/java/json/app/App.java
|
UTF-8
| 2,756
| 3.0625
| 3
|
[] |
no_license
|
package json.app;
import java.util.ArrayList;
import com.google.gson.Gson;
import json.beans.UserData;
import json.utils.JsonUtils;
public class App {
private static final String IMPLICIT_JSON = "{\"userId\": 1, \"id\": 1, \"title\": \"this is the title\", \"body\": \"this is the body\" }";
private static final String JSON_USER = "json_inputs/user.txt";
private static final String JSON_USERS = "json_inputs/users.txt";
public static void main(String[] args) {
System.out.println("=================================================================");
System.out.println(" Example 1: JSON to Java Conversion with implicit Json String");
System.out.println("=================================================================");
System.out.println("----- JSON -----\n\n" + IMPLICIT_JSON);
UserData uData1 = JsonUtils.convertImplicitJSONToJavaObject(IMPLICIT_JSON);
System.out.println("\n------ Java Object ------\n\n" + uData1);
System.out.println("=================================================================");
System.out.println(" Example 2: JSON to Java Conversion with implicit Json String");
System.out.println("=================================================================");
System.out.println("----- JSON -----\n\n" + IMPLICIT_JSON);
UserData uData2 = JsonUtils.convertJsonFileDataToJavaObject(JSON_USER);
System.out.println("\n------ Java Object ------\n\n" + uData2);
System.out.println("=================================================================");
System.out.println(" Example 3: JSON to Java Conversion with implicit Json String");
System.out.println("=================================================================");
System.out.println("----- JSON -----\n\n" + IMPLICIT_JSON);
ArrayList<UserData> uData3 = JsonUtils.convertJsonArrayFileDataToJavaObject(JSON_USERS);
for (UserData data : uData3) {
System.out.println(data);
}
System.out.println("=================================================================");
System.out.println(" Example 4: JSON to Java Conversion with implicit Json String");
System.out.println("=================================================================");
System.out.println("----- JSON -----\n\n" + IMPLICIT_JSON);
UserData uData4 = JsonUtils.convertImplicitJSONToJavaObject(IMPLICIT_JSON);
System.out.println("\n------ Java Object ------\n\n" + uData4);
String uJson = new Gson().toJson(uData4);
System.out.println("\n--------- JSON --------\n" + uJson);
}
}
| true
|
d5b563686fc08c2090a4bc070baa470d07daef68
|
Java
|
zkesong/springboot
|
/springboot-mybatis/src/main/java/com/zks/springbootmybatis/controller/JdbcController.java
|
UTF-8
| 670
| 1.914063
| 2
|
[] |
no_license
|
package com.zks.springbootmybatis.controller;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author KeSong Zeng
* @version V1.0
* @e-mail kesongzeng@163.com
* @date 2018/3/9 16:50
* @Description:
*/
@RestController
public class JdbcController {
@Autowired
private SqlSession sqlSession;
@RequestMapping("getAll")
public String connect() {
return "success" + sqlSession.
selectOne("com.zks.springbootmybatis.dao.CityMapper.getAll");
}
}
| true
|
53efd12eb0696f82370cc04d0beef646920e5910
|
Java
|
cuchas/Exemplos-Android-HS
|
/app/src/main/java/br/com/cucha/myself2/data/OpcaoDAO.java
|
UTF-8
| 854
| 2.046875
| 2
|
[] |
no_license
|
package br.com.cucha.myself2.data;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import java.util.List;
/**
* Created by eduardocucharro on 04/02/18.
*/
@Dao
public interface OpcaoDAO {
@Query("SELECT * FROM opcao")
List<Opcao> getOpcoesSync();
@Query("SELECT * FROM opcao")
LiveData<List<Opcao>> getOpcoes();
@Insert(onConflict = OnConflictStrategy.REPLACE)
Long insert(Opcao opcao);
@Insert(onConflict = OnConflictStrategy.REPLACE)
Long[] insert(Opcao... opcao);
@Delete
int delete(Opcao opcao);
@Query("DELETE FROM opcao WHERE opcao_id = :id")
int delete(int id);
}
| true
|
0b0b49011ce0dcf1ef44c1f2fd0b605885142a77
|
Java
|
ILCandy/wooki
|
/src/main/java/com/wooki/system/amme/info/entity/AmmeterCurrentMonth.java
|
UTF-8
| 2,171
| 2.171875
| 2
|
[] |
no_license
|
package com.wooki.system.amme.info.entity;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.wooki.system.amme.device.entity.AmmeterDevice;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
*
* </p>
*
* @author whn
* @since 2018-02-02
*/
@TableName("ammeter_current_month")
public class AmmeterCurrentMonth extends Model<AmmeterCurrentMonth> {
private static final long serialVersionUID = 1L;
public AmmeterCurrentMonth(){}
public AmmeterCurrentMonth(AmmeterDevice ammeterDevice){
this.Uuid = ammeterDevice.getUuid();
// 新加入的电表,总电量就是expand中的总电量
this.allpower = ammeterDevice.getExpand().getAllpower();
if(ammeterDevice.getDeviceType()!=null)
this.type = ammeterDevice.getDeviceType();
}
public AmmeterCurrentMonth(AmmeterHourInfo ammeterHourInfo){
this.Uuid = ammeterHourInfo.getUuid();
this.allpower = ammeterHourInfo.getAllpower();
}
/**
* 电表Uuid
*/
private String Uuid;
/**
* 当前月的用电总量
*/
private Double allpower;
@TableField("add_time")
private Date addTime;
@TableField("update_time")
private Date updateTime;
private Integer type;
public String getUuid() {
return Uuid;
}
public void setUuid(String Uuid) {
this.Uuid = Uuid;
}
public Double getAllpower() {
return allpower;
}
public void setAllpower(Double allpower) {
this.allpower = allpower;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@Override
protected Serializable pkVal() {
return this.Uuid;
}
@Override
public String toString() {
return "AmmeterCurrentMonth{" +
"Uuid=" + Uuid +
", allpower=" + allpower +
", addTime=" + addTime +
", updateTime=" + updateTime +
"}";
}
}
| true
|
1b4520a1508b56276227d40af931589de908e328
|
Java
|
mahdyfalah/Book_Club
|
/src/main/java/com/example/book_club/model/Book.java
|
UTF-8
| 1,384
| 2.53125
| 3
|
[] |
no_license
|
package com.example.book_club.model;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
@Entity
@Data
@Table(name = "Book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer book_id;
private String isbn;
private String title;
private String publisher;
public Book() {
}
public Book(String isbn, String title, String publisher) {
this.isbn = isbn;
this.title = title;
this.publisher = publisher;
}
public Integer getBook_id() {
return book_id;
}
public void setBook_id(Integer book_id) {
this.book_id = book_id;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
@Override
public String toString() {
return "Book{" +
"book_id=" + book_id +
", isbn='" + isbn + '\'' +
", title='" + title + '\'' +
", publisher='" + publisher + '\'' +
'}';
}
}
| true
|
adf4dd0c4d364f598710b618cd6c4c7b7927a228
|
Java
|
Mygithub1203/flea-frame
|
/flea-frame-cache/src/main/java/com/huazie/frame/cache/redis/RedisPool.java
|
UTF-8
| 10,604
| 2.234375
| 2
|
[] |
no_license
|
package com.huazie.frame.cache.redis;
import com.huazie.frame.cache.common.CacheConstants;
import com.huazie.frame.cache.config.CacheParam;
import com.huazie.frame.cache.config.CacheParams;
import com.huazie.frame.cache.config.CacheServer;
import com.huazie.frame.cache.redis.config.RedisConfig;
import com.huazie.frame.common.CommonConstants;
import com.huazie.frame.common.util.CollectionUtils;
import com.huazie.frame.common.util.ObjectUtils;
import com.huazie.frame.common.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.util.Hashing;
import redis.clients.jedis.util.Sharded;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* <p> Flea Redis 连接池 </p>
*
* @author huazie
* @version 1.0.0
* @since 1.0.0
*/
public class RedisPool {
private static final ConcurrentMap<String, RedisPool> redisPools = new ConcurrentHashMap<String, RedisPool>();
private String poolName; // 连接池名
private ShardedJedisPool shardedJedisPool;
private RedisPool(String poolName) {
this.poolName = poolName;
}
/**
* <p> 获取Redis连接池实例 (指定连接池名)</p>
*
* @param poolName 连接池名
* @return Redis连接池实例对象
* @since 1.0.0
*/
public static RedisPool getInstance(String poolName) {
if (!redisPools.containsKey(poolName)) {
synchronized (redisPools) {
if (!redisPools.containsKey(poolName)) {
RedisPool redisPool = new RedisPool(poolName);
redisPools.putIfAbsent(poolName, redisPool);
}
}
}
return redisPools.get(poolName);
}
/**
* <p> 获取Redis连接池实例 (默认) </p>
*
* @return Redis连接池实例对象
* @since 1.0.0
*/
public static RedisPool getInstance() {
return getInstance(CommonConstants.FleaPoolConstants.DEFAULT_POOL_NAME);
}
/**
* <p> 默认初始化 </p>
*
* @since 1.0.0
*/
public void initialize() {
if (!CommonConstants.FleaPoolConstants.DEFAULT_POOL_NAME.equals(poolName)) {
throw new RuntimeException("采用默认初始化,请使用RedisPool##getInstance()");
}
RedisConfig redisConfig = RedisConfig.getConfig();
if (ObjectUtils.isEmpty(shardedJedisPool)) {
shardedJedisPool = new ShardedJedisPool(redisConfig.getJedisPoolConfig(), redisConfig.getServers(), redisConfig.getHashingAlg());
}
}
/**
* <p> 初始化 (非默认连接池) </p>
*
* @param cacheServerList 缓存服务器集
* @param cacheParams 缓存参数
* @since 1.0.0
*/
public void initialize(List<CacheServer> cacheServerList, CacheParams cacheParams) {
if (CommonConstants.FleaPoolConstants.DEFAULT_POOL_NAME.equals(poolName)) {
throw new RuntimeException("采用指定连接池名初始化,请使用RedisPool##getInstance(String poolName)");
}
if (CollectionUtils.isEmpty(cacheServerList)) {
return;
}
if (ObjectUtils.isEmpty(cacheParams) || CollectionUtils.isEmpty(cacheParams.getCacheParamList())) {
return;
}
// 1. 获取客户端连接池配置信息
JedisPoolConfig poolConfig = new JedisPoolConfig();
// Redis客户端Jedis连接池最大连接数
CacheParam poolMaxTotal = cacheParams.getCacheParam(CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_POOL_MAXTOTAL);
if (ObjectUtils.isEmpty(poolMaxTotal) || StringUtils.isBlank(poolMaxTotal.getValue())) {
throw new RuntimeException("请检查flea-cache-config.xml配置,【<cache-param key=" + CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_POOL_MAXTOTAL + " ></cache-param>】未配置或配置值为空");
}
poolConfig.setMaxTotal(Integer.parseInt(poolMaxTotal.getValue()));
// Redis客户端Jedis连接池最大空闲连接数
CacheParam poolMaxIdle = cacheParams.getCacheParam(CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_POOL_MAXIDLE);
if (ObjectUtils.isEmpty(poolMaxIdle) || StringUtils.isBlank(poolMaxIdle.getValue())) {
throw new RuntimeException("请检查flea-cache-config.xml配置,【<cache-param key=" + CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_POOL_MAXIDLE + " ></cache-param>】未配置或配置值为空");
}
poolConfig.setMaxIdle(Integer.parseInt(poolMaxIdle.getValue()));
// Redis客户端Jedis连接池最小空闲连接数
CacheParam poolMinIdle = cacheParams.getCacheParam(CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_POOL_MINIDLE);
if (ObjectUtils.isEmpty(poolMinIdle) || StringUtils.isBlank(poolMinIdle.getValue())) {
throw new RuntimeException("请检查flea-cache-config.xml配置,【<cache-param key=" + CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_POOL_MINIDLE + " ></cache-param>】未配置或配置值为空");
}
poolConfig.setMinIdle(Integer.parseInt(poolMinIdle.getValue()));
// Redis客户端Jedis连接池获取连接时的最大等待毫秒数
CacheParam poolMaxWaitMillis = cacheParams.getCacheParam(CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_POOL_MAXWAITMILLIS);
if (ObjectUtils.isEmpty(poolMaxWaitMillis) || StringUtils.isBlank(poolMaxWaitMillis.getValue())) {
throw new RuntimeException("请检查flea-cache-config.xml配置,【<cache-param key=" + CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_POOL_MAXWAITMILLIS + " ></cache-param>】未配置或配置值为空");
}
poolConfig.setMaxWaitMillis(Integer.parseInt(poolMaxWaitMillis.getValue()));
// 2. 获取服务器配置信息
// Redis客户端socket连接超时时间
CacheParam connectionTimeoutParam = cacheParams.getCacheParam(CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_CONNECTIONTIMEOUT);
if (ObjectUtils.isEmpty(connectionTimeoutParam) || StringUtils.isBlank(connectionTimeoutParam.getValue())) {
throw new RuntimeException("请检查flea-cache-config.xml配置,【<cache-param key=" + CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_CONNECTIONTIMEOUT + " ></cache-param>】未配置或配置值为空");
}
int connectionTimeout = Integer.parseInt(connectionTimeoutParam.getValue());
// Redis客户端socket读写超时时间
CacheParam soTimeoutParam = cacheParams.getCacheParam(CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_SOTIMEOUT);
if (ObjectUtils.isEmpty(soTimeoutParam) || StringUtils.isBlank(soTimeoutParam.getValue())) {
throw new RuntimeException("请检查flea-cache-config.xml配置,【<cache-param key=" + CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_SOTIMEOUT + " ></cache-param>】未配置或配置值为空");
}
int soTimeout = Integer.parseInt(soTimeoutParam.getValue());
// 遍历缓存服务器集
List<JedisShardInfo> servers = new ArrayList<JedisShardInfo>();
for (CacheServer cacheServer : cacheServerList) {
if (ObjectUtils.isNotEmpty(cacheServer)) {
String server = cacheServer.getServer();
if (StringUtils.isBlank(server)) {
throw new RuntimeException("请检查flea-cache-config.xml配置,【<cache-server group=" + poolName + " ></cache-server>】未配置缓存服务器");
}
String host = StringUtils.subStrBefore(server, server.indexOf(CommonConstants.SymbolConstants.COLON));
int port = Integer.parseInt(StringUtils.subStrLast(server, server.length() - server.indexOf(CommonConstants.SymbolConstants.COLON) - 1));
String weightStr = cacheServer.getWeight();
int weight;
if (StringUtils.isBlank(weightStr)) {
weight = Sharded.DEFAULT_WEIGHT;
} else {
weight = Integer.parseInt(weightStr);
}
JedisShardInfo jedisShardInfo = new JedisShardInfo(host, port, connectionTimeout, soTimeout, weight);
String password = cacheServer.getPassword();
if (ObjectUtils.isNotEmpty(password)) {
jedisShardInfo.setPassword(password);
}
servers.add(jedisShardInfo);
}
}
// 3. 获取Redis分布式hash算法
CacheParam hashingAlgParam = cacheParams.getCacheParam(CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_HASHINGALG);
if (ObjectUtils.isEmpty(hashingAlgParam) || StringUtils.isBlank(hashingAlgParam.getValue())) {
throw new RuntimeException("请检查flea-cache-config.xml配置,【<cache-param key=" + CacheConstants.RedisConfigConstants.REDIS_CACHE_PARAM_HASHINGALG + " ></cache-param>】未配置或配置值为空");
}
int alg = Integer.parseInt(hashingAlgParam.getValue());
Hashing hashingAlg;
if (CacheConstants.RedisConfigConstants.REDIS_CONFIG_HASHINGALG_MURMUR_HASH == alg) {
hashingAlg = Hashing.MURMUR_HASH;
} else if (CacheConstants.RedisConfigConstants.REDIS_CONFIG_HASHINGALG_MD5 == alg) {
hashingAlg = Hashing.MD5;
} else {
throw new RuntimeException("请检查flea-cache-config.xml配置,【<cache-param key=" + CacheConstants.MemCachedConfigConstants.MEMCACHED_CACHE_PARAM_INITCONN + " ></cache-param>】Redis分布式hash算法配置值非法");
}
if (ObjectUtils.isEmpty(shardedJedisPool)) {
shardedJedisPool = new ShardedJedisPool(poolConfig, servers, hashingAlg);
}
}
/**
* <p> 分布式Redis集群客户端连接池 </p>
*
* @return 分布式Redis集群客户端连接池
* @since 1.0.0
*/
public ShardedJedisPool getJedisPool() {
if (ObjectUtils.isEmpty(shardedJedisPool)) {
throw new RuntimeException("获取分布式Redis集群客户端连接池失败:请先调用initialize初始化");
}
return shardedJedisPool;
}
/**
* <p> 获取当前连接池名 </p>
*
* @return 连接池名
* @since 1.0.0
*/
public String getPoolName() {
return poolName;
}
}
| true
|
18a1658af968b59906684c1334d8d9f59040018a
|
Java
|
TheWizard91/Album_base_source_from_JADX
|
/sources/com/google/type/TimeOfDayOrBuilder.java
|
UTF-8
| 232
| 1.875
| 2
|
[] |
no_license
|
package com.google.type;
import com.google.protobuf.MessageLiteOrBuilder;
public interface TimeOfDayOrBuilder extends MessageLiteOrBuilder {
int getHours();
int getMinutes();
int getNanos();
int getSeconds();
}
| true
|
86018f51b8e407c776f8dc9f082df3a36bd87174
|
Java
|
wingsno1/warbanner
|
/app/src/main/java/cn/sun45/warbanner/framework/document/preference/BasePreference.java
|
UTF-8
| 1,931
| 2.578125
| 3
|
[] |
no_license
|
package cn.sun45.warbanner.framework.document.preference;
import android.content.SharedPreferences;
import android.text.TextUtils;
import java.lang.reflect.Field;
/**
* Created by Sun45 on 2019/10/28.
* SharedPreferences基础类
*/
public abstract class BasePreference {
public abstract String getName();
/**
* 获取Preference参数信息
*
* @param key
* @return
*/
public Field getField(String key) {
Field[] declaredFields = getClass().getDeclaredFields();
for (Field field : declaredFields) {
if (field.getName().equals(key)) {
return field;
}
}
throw new IllegalStateException("class \"" + getClass().getName() + "\" without field \"" + key);
}
/**
* 注册监听
*
* @param listener
*/
public void registListener(SharedPreferences.OnSharedPreferenceChangeListener listener) {
PreferenceManager.registListener(listener, getName());
}
/**
* 移除监听
*
* @param listener
*/
public void unregistListener(SharedPreferences.OnSharedPreferenceChangeListener listener) {
PreferenceManager.unregistListener(listener, getName());
}
/**
* 数据读取
*
* @param key
* @param <T>
* @return
*/
protected <T> T load(String key) {
if (TextUtils.isEmpty("key")) {
throw new IllegalStateException("load empty key from \"" + getClass().getName() + "\"");
}
return PreferenceManager.load(getClass(), key);
}
/**
* 数据存储
*
* @param key
* @param value
*/
protected void save(String key, Object value) {
if (TextUtils.isEmpty("key")) {
throw new IllegalStateException("save empty key to \"" + getClass().getName() + "\"");
}
PreferenceManager.save(getClass(), key, value);
}
}
| true
|
ae31bdc5f6b9912dcf4f519a66804a68f85a6760
|
Java
|
jay741025/Car-Pool-Server
|
/src/com/fet/carpool/serv/dto/AccountRegistrationBean.java
|
UTF-8
| 1,571
| 1.921875
| 2
|
[] |
no_license
|
package com.fet.carpool.serv.dto;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@XmlRootElement
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class AccountRegistrationBean {
private String accountId;
private String accountType;
private String accountName;
private String msisdn;
private String sim;
private String accountPic;
private String regClientType;
private String regClientId;
public String getAccountPic() {
return accountPic;
}
public void setAccountPic(String accountPic) {
this.accountPic = accountPic;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getMsisdn() {
return msisdn;
}
public void setMsisdn(String msisdn) {
this.msisdn = msisdn;
}
public String getSim() {
return sim;
}
public void setSim(String sim) {
this.sim = sim;
}
public String getRegClientType() {
return regClientType;
}
public void setRegClientType(String regClientType) {
this.regClientType = regClientType;
}
public String getRegClientId() {
return regClientId;
}
public void setRegClientId(String regClientId) {
this.regClientId = regClientId;
}
}
| true
|
465b78702ba201f73892ee62104e34cc43e34a14
|
Java
|
dipankarduttajava/l1
|
/ANUL/src/main/java/com/gtfs/pojo/ProjectMst.java
|
UTF-8
| 5,708
| 2.1875
| 2
|
[] |
no_license
|
package com.gtfs.pojo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "PROJECT_MST")
public class ProjectMst implements Serializable {
private Long id;
private String projectName;
private String address;
private Integer noOfFloor;
private Integer noOfFlat;
private Integer noOfCarPark;
private Integer noOfFlatAvlbl;
private Integer noOfCarParkAvlbl;
private Integer milestoneCompltd;
private String chqInFavour;
private Long createdBy;
private Long modifiedBy;
private Long deletedBy;
private Date createdDate;
private Date modifiedDate;
private Date deletedDate;
private String deleteFlag;
private Double carParkListedValue;
private List<FlatMst> flatMsts = new ArrayList<FlatMst>();
private List<ProjectMilestone> projectMilestones = new ArrayList<ProjectMilestone>();
/* GETTER SETTER */
@Id
@SequenceGenerator(name="PROJECT_MST_SEQ" , sequenceName="PROJECT_MST_SEQ")
@GeneratedValue(generator="PROJECT_MST_SEQ" , strategy = GenerationType.AUTO)
@Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="PROJECT_NAME" , length=100)
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
@Column(name="ADDRESS" , length=500)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Column(name = "NO_OF_FLOOR" , precision = 22, scale = 0)
public Integer getNoOfFloor() {
return noOfFloor;
}
public void setNoOfFloor(Integer noOfFloor) {
this.noOfFloor = noOfFloor;
}
@Column(name = "NO_OF_FLAT" , precision = 22, scale = 0)
public Integer getNoOfFlat() {
return noOfFlat;
}
public void setNoOfFlat(Integer noOfFlat) {
this.noOfFlat = noOfFlat;
}
@Column(name = "NO_OF_CAR_PARK" , precision = 22, scale = 0)
public Integer getNoOfCarPark() {
return noOfCarPark;
}
public void setNoOfCarPark(Integer noOfCarPark) {
this.noOfCarPark = noOfCarPark;
}
@Column(name = "NO_OF_FLAT_AVLBL" , precision = 22, scale = 0)
public Integer getNoOfFlatAvlbl() {
return noOfFlatAvlbl;
}
public void setNoOfFlatAvlbl(Integer noOfFlatAvlbl) {
this.noOfFlatAvlbl = noOfFlatAvlbl;
}
@Column(name = "NO_OF_CAR_PARK_AVLBL" , precision = 22, scale = 0)
public Integer getNoOfCarParkAvlbl() {
return noOfCarParkAvlbl;
}
public void setNoOfCarParkAvlbl(Integer noOfCarParkAvlbl) {
this.noOfCarParkAvlbl = noOfCarParkAvlbl;
}
@Column(name = "MILESTONE_COMPLTD" , precision = 22, scale = 0)
public Integer getMilestoneCompltd() {
return milestoneCompltd;
}
public void setMilestoneCompltd(Integer milestoneCompltd) {
this.milestoneCompltd = milestoneCompltd;
}
@Column(name = "CHQ_IN_FAVOUR" , precision = 22, scale = 0)
public String getChqInFavour() {
return chqInFavour;
}
public void setChqInFavour(String chqInFavour) {
this.chqInFavour = chqInFavour;
}
@Column(name = "CREATED_BY", precision = 22, scale = 0)
public Long getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
@Column(name = "MODIFIED_BY", precision = 22, scale = 0)
public Long getModifiedBy() {
return this.modifiedBy;
}
public void setModifiedBy(Long modifiedBy) {
this.modifiedBy = modifiedBy;
}
@Column(name = "DELETED_BY", precision = 22, scale = 0)
public Long getDeletedBy() {
return this.deletedBy;
}
public void setDeletedBy(Long deletedBy) {
this.deletedBy = deletedBy;
}
@Temporal(TemporalType.DATE)
@Column(name = "CREATED_DATE", length = 7)
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Temporal(TemporalType.DATE)
@Column(name = "MODIFIED_DATE", length = 7)
public Date getModifiedDate() {
return this.modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
@Temporal(TemporalType.DATE)
@Column(name = "DELETED_DATE", length = 7)
public Date getDeletedDate() {
return this.deletedDate;
}
public void setDeletedDate(Date deletedDate) {
this.deletedDate = deletedDate;
}
@Column(name = "DELETE_FLAG", length = 1)
public String getDeleteFlag() {
return this.deleteFlag;
}
public void setDeleteFlag(String deleteFlag) {
this.deleteFlag = deleteFlag;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "projectMst")
public List<FlatMst> getFlatMsts() {
return flatMsts;
}
public void setFlatMsts(List<FlatMst> flatMsts) {
this.flatMsts = flatMsts;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "projectMst")
public List<ProjectMilestone> getProjectMilestones() {
return projectMilestones;
}
public void setProjectMilestones(List<ProjectMilestone> projectMilestones) {
this.projectMilestones = projectMilestones;
}
@Column(name = "CAR_PARK_LISTED_VALUE" , precision = 22, scale = 0)
public Double getCarParkListedValue() {
return carParkListedValue;
}
public void setCarParkListedValue(Double carParkListedValue) {
this.carParkListedValue = carParkListedValue;
}
}
| true
|
4d1e3b7aa761267983d74454e0b6c338961539f2
|
Java
|
neetavarkala/miui_framework_clover
|
/android/os/IBatteryPropertiesRegistrar.java
|
UTF-8
| 7,517
| 1.648438
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
package android.os;
// Referenced classes of package android.os:
// IInterface, RemoteException, BatteryProperty, IBatteryPropertiesListener,
// Binder, IBinder, Parcel
public interface IBatteryPropertiesRegistrar
extends IInterface
{
public static abstract class Stub extends Binder
implements IBatteryPropertiesRegistrar
{
public static IBatteryPropertiesRegistrar asInterface(IBinder ibinder)
{
if(ibinder == null)
return null;
IInterface iinterface = ibinder.queryLocalInterface("android.os.IBatteryPropertiesRegistrar");
if(iinterface != null && (iinterface instanceof IBatteryPropertiesRegistrar))
return (IBatteryPropertiesRegistrar)iinterface;
else
return new Proxy(ibinder);
}
public IBinder asBinder()
{
return this;
}
public boolean onTransact(int i, Parcel parcel, Parcel parcel1, int j)
throws RemoteException
{
switch(i)
{
default:
return super.onTransact(i, parcel, parcel1, j);
case 1598968902:
parcel1.writeString("android.os.IBatteryPropertiesRegistrar");
return true;
case 1: // '\001'
parcel.enforceInterface("android.os.IBatteryPropertiesRegistrar");
registerListener(IBatteryPropertiesListener.Stub.asInterface(parcel.readStrongBinder()));
parcel1.writeNoException();
return true;
case 2: // '\002'
parcel.enforceInterface("android.os.IBatteryPropertiesRegistrar");
unregisterListener(IBatteryPropertiesListener.Stub.asInterface(parcel.readStrongBinder()));
parcel1.writeNoException();
return true;
case 3: // '\003'
parcel.enforceInterface("android.os.IBatteryPropertiesRegistrar");
i = parcel.readInt();
parcel = new BatteryProperty();
i = getProperty(i, parcel);
parcel1.writeNoException();
parcel1.writeInt(i);
if(parcel != null)
{
parcel1.writeInt(1);
parcel.writeToParcel(parcel1, 1);
} else
{
parcel1.writeInt(0);
}
return true;
case 4: // '\004'
parcel.enforceInterface("android.os.IBatteryPropertiesRegistrar");
scheduleUpdate();
return true;
}
}
private static final String DESCRIPTOR = "android.os.IBatteryPropertiesRegistrar";
static final int TRANSACTION_getProperty = 3;
static final int TRANSACTION_registerListener = 1;
static final int TRANSACTION_scheduleUpdate = 4;
static final int TRANSACTION_unregisterListener = 2;
public Stub()
{
attachInterface(this, "android.os.IBatteryPropertiesRegistrar");
}
}
private static class Stub.Proxy
implements IBatteryPropertiesRegistrar
{
public IBinder asBinder()
{
return mRemote;
}
public String getInterfaceDescriptor()
{
return "android.os.IBatteryPropertiesRegistrar";
}
public int getProperty(int i, BatteryProperty batteryproperty)
throws RemoteException
{
Parcel parcel;
Parcel parcel1;
parcel = Parcel.obtain();
parcel1 = Parcel.obtain();
parcel.writeInterfaceToken("android.os.IBatteryPropertiesRegistrar");
parcel.writeInt(i);
mRemote.transact(3, parcel, parcel1, 0);
parcel1.readException();
i = parcel1.readInt();
if(parcel1.readInt() != 0)
batteryproperty.readFromParcel(parcel1);
parcel1.recycle();
parcel.recycle();
return i;
batteryproperty;
parcel1.recycle();
parcel.recycle();
throw batteryproperty;
}
public void registerListener(IBatteryPropertiesListener ibatterypropertieslistener)
throws RemoteException
{
IBinder ibinder;
Parcel parcel;
Parcel parcel1;
ibinder = null;
parcel = Parcel.obtain();
parcel1 = Parcel.obtain();
parcel.writeInterfaceToken("android.os.IBatteryPropertiesRegistrar");
if(ibatterypropertieslistener == null)
break MISSING_BLOCK_LABEL_28;
ibinder = ibatterypropertieslistener.asBinder();
parcel.writeStrongBinder(ibinder);
mRemote.transact(1, parcel, parcel1, 0);
parcel1.readException();
parcel1.recycle();
parcel.recycle();
return;
ibatterypropertieslistener;
parcel1.recycle();
parcel.recycle();
throw ibatterypropertieslistener;
}
public void scheduleUpdate()
throws RemoteException
{
Parcel parcel = Parcel.obtain();
parcel.writeInterfaceToken("android.os.IBatteryPropertiesRegistrar");
mRemote.transact(4, parcel, null, 1);
parcel.recycle();
return;
Exception exception;
exception;
parcel.recycle();
throw exception;
}
public void unregisterListener(IBatteryPropertiesListener ibatterypropertieslistener)
throws RemoteException
{
IBinder ibinder;
Parcel parcel;
Parcel parcel1;
ibinder = null;
parcel = Parcel.obtain();
parcel1 = Parcel.obtain();
parcel.writeInterfaceToken("android.os.IBatteryPropertiesRegistrar");
if(ibatterypropertieslistener == null)
break MISSING_BLOCK_LABEL_28;
ibinder = ibatterypropertieslistener.asBinder();
parcel.writeStrongBinder(ibinder);
mRemote.transact(2, parcel, parcel1, 0);
parcel1.readException();
parcel1.recycle();
parcel.recycle();
return;
ibatterypropertieslistener;
parcel1.recycle();
parcel.recycle();
throw ibatterypropertieslistener;
}
private IBinder mRemote;
Stub.Proxy(IBinder ibinder)
{
mRemote = ibinder;
}
}
public abstract int getProperty(int i, BatteryProperty batteryproperty)
throws RemoteException;
public abstract void registerListener(IBatteryPropertiesListener ibatterypropertieslistener)
throws RemoteException;
public abstract void scheduleUpdate()
throws RemoteException;
public abstract void unregisterListener(IBatteryPropertiesListener ibatterypropertieslistener)
throws RemoteException;
}
| true
|
8543263cf7b64ef9d68f0ce69d05536e77d783cb
|
Java
|
KeKeZLei/ls_tbs
|
/src/main/java/com/lionsource/tbs/comm/dao/ManagerMapper.java
|
UTF-8
| 1,085
| 2.046875
| 2
|
[] |
no_license
|
package com.lionsource.tbs.comm.dao;
import com.lionsource.tbs.comm.model.Manager;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface ManagerMapper {
int deleteByPrimaryKey(Integer manaId);
int insert(Manager record);
Manager selectByPrimaryKey(Integer manaId);
List<Manager> selectAll();
int updateByPrimaryKey(Manager record);
//根据参数查询所有管理员
List<Manager> selectAllByParam(Map<String, Object> param);
//修改管理员状态
int updateState(Manager manager);
//根据登录名查询管理员
Manager selectByLoginname(String manaLoginname);
//根据手机号查询管理员
Manager selectByTel(String manaTel);
//根据角色编号查询管理员
List<Manager> selectByRoleId(Integer roleId);
//根据用户名密码查询管理员
Manager selectByParam(@Param("userName") String userName, @Param("password") String password);
//修改密码
int updatePwd(@Param("manaId") Integer manaId, @Param("pwd") String pwd);
}
| true
|
46bac293ca1da30882b0679ca26ee76df16e7a9b
|
Java
|
mohitajethwani/QuerySystem
|
/code/src/controler/MyServlet.java
|
UTF-8
| 12,961
| 2.4375
| 2
|
[] |
no_license
|
package controler;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
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 com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.QueryBuilder;
/**
* Servlet implementation class MyServlet
*/
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MongoClient mongoClient = null;
public DB db;
public DBCollection collection = null;
public DBCollection collection1 = null;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
System.out.println("in try");
if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017);
System.out.println("Mongo client: " + mongoClient);
System.out.println("client created");
}
db = mongoClient.getDB("test");
System.out.println("Connected");
}
catch (Exception e) {
}
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
String apiOrMashup = request.getParameter("apiOrMashup");
String criteria = request.getParameter("criteria");
String values = request.getParameter("value");
// String values[]=valueString.split(",");
/*
* for(int i=0; i<values.length; i++) { values[i]=values[i].trim();
* System.out.println(values[i]); }
*/
if (criteria.equals("keywords")) {
ArrayList<String> result=getByKeywords(apiOrMashup, values);
PrintWriter out = response.getWriter();
for (int i = 0; i < result.size(); i++) {
out.print(result.get(i) + "\n\n");
response.setContentType("text/html");
}
out.close();
}
else if (criteria.equals("year")) {
try {
ArrayList<String> result = getByYear(apiOrMashup, values);
PrintWriter out = response.getWriter();
for (int i = 0; i < result.size(); i++) {
out.print(result.get(i) + "\n\n");
response.setContentType("text/html");
}
out.close();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (criteria.equals("protocols")) {
ArrayList<String> result = getByProtocol(apiOrMashup, values);
PrintWriter out = response.getWriter();
for (int i = 0; i < result.size(); i++) {
out.print(result.get(i) + "\n");
response.setContentType("text/html");
}
out.close();
}
else if (criteria.equals("category")) {
ArrayList<String> result = getByCategory(apiOrMashup, values);
PrintWriter out = response.getWriter();
for (int i = 0; i < result.size(); i++) {
out.print(result.get(i) + "\n");
response.setContentType("text/html");
}
out.close();
}
else if (criteria.equals("tags")) {
ArrayList<String> result = getByTags(apiOrMashup, values);
PrintWriter out = response.getWriter();
for (int i = 0; i < result.size(); i++) {
out.print(result.get(i) + "\n\n");
response.setContentType("text/html");
}
out.close();
}
else if (criteria.equals("usedApis")) {
ArrayList<String> result=getByUsedApis(apiOrMashup, values);
PrintWriter out = response.getWriter();
for (int i = 0; i < result.size(); i++) {
out.print(result.get(i) + "\n\n");
response.setContentType("text/html");
}
out.close();
}
else {
// rating
String option = request.getParameter("ratingOptions");
ArrayList<String> result = getByRating(apiOrMashup, values, option);
PrintWriter out = response.getWriter();
for (int i = 0; i < result.size(); i++) {
out.print(result.get(i) + "\n\n");
response.setContentType("text/html");
}
out.close();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public ArrayList<String> getByKeywords(String apiOrMashup, String values) {
ArrayList<String> result=new ArrayList<String>();
String val[]=values.split(",");
String searchString="";
for(int i=0; i<val.length; i++) {
val[i]=val[i].trim();
val[i]="\""+val[i]+"\"";
searchString+=val[i];
}
if (apiOrMashup.equals("api")) {
DBCollection collection = db.getCollection("apiData");
BasicDBObject query=new BasicDBObject("$text",new BasicDBObject("$search",searchString));
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
} else {
DBCollection collection = db.getCollection("mashupData");
BasicDBObject query=new BasicDBObject("$text",new BasicDBObject("$search",searchString));
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
}
System.out.println(result.size());
return result;
}
public ArrayList<String> getByYear(String apiOrMashup, String values) throws ParseException {
ArrayList<String> result = new ArrayList<String>();
if (apiOrMashup.equals("api")) {
String startDate = values + "-01-01T00:00:00Z";
String endDate = values + "-12-31T23:59:59Z";
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println("lets parse");
Date date1 = (Date) simpleDateFormat1.parse(startDate);
System.out.println("one parsed");
Date date2 = (Date) simpleDateFormat1.parse(endDate);
BasicDBObject field = new BasicDBObject("updated", new BasicDBObject("$gte", date1).append("$lt", date2));
DBCollection collection = db.getCollection("apiData");
DBCursor cursor = collection.find(field);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
} else {
String startDate = values + "-01-01T00:00:00Z";
System.out.println(startDate);
String endDate = values + "-12-31T23:59:59Z";
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date1 = (Date) simpleDateFormat1.parse(startDate);
Date date2 = (Date) simpleDateFormat1.parse(endDate);
BasicDBObject field = new BasicDBObject("updated", new BasicDBObject("$gte", date1).append("$lt", date2));
DBCollection collection = db.getCollection("mashupData");
DBCursor cursor = collection.find(field);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
}
System.out.println(result.size());
return result;
}
public ArrayList<String> getByProtocol(String apiOrMashup, String values) {
ArrayList<String> result = new ArrayList<String>();
if (apiOrMashup.equals("api")) {
BasicDBObject field = new BasicDBObject();
field.put("protocols", java.util.regex.Pattern.compile(values, Pattern.CASE_INSENSITIVE));
DBCollection collection = db.getCollection("apiData");
DBCursor cursor = collection.find(field);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
} else {
result.add("There were no mashups retrieved");
}
System.out.println(result.size());
return result;
}
public ArrayList<String> getByCategory(String apiOrMashup, String values) {
ArrayList<String> result = new ArrayList<String>();
if (apiOrMashup.equals("api")) {
BasicDBObject field = new BasicDBObject();
field.put("category", java.util.regex.Pattern.compile(values, Pattern.CASE_INSENSITIVE));
DBCollection collection = db.getCollection("apiData");
DBCursor cursor = collection.find(field);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
} else {
result.add("There were no mashups retrieved");
}
return result;
}
public ArrayList<String> getByTags(String apiOrMashup, String values) {
ArrayList<String> result = new ArrayList<String>();
if (apiOrMashup.equals("api")) {
BasicDBObject field = new BasicDBObject();
List<String> list = new ArrayList<String>();
list.add(values);
field.put("tags", new BasicDBObject("$in", list));
DBCollection collection = db.getCollection("apiData");
DBCursor cursor = collection.find(field);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
} else {
BasicDBObject field = new BasicDBObject();
List<String> list = new ArrayList<String>();
list.add(values);
field.put("tags", new BasicDBObject("$in", list));
DBCollection collection1 = db.getCollection("mashupData");
DBCursor cursor = collection1.find(field);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
}
return result;
}
public ArrayList<String> getByUsedApis(String apiOrMashup, String values) {
ArrayList<String> result = new ArrayList<String>();
BasicDBObject field = new BasicDBObject();
if (apiOrMashup.equals("api")) {
result.add("There were no apis retrieved");
} else {
field = new BasicDBObject("APIs.apiName",values);
DBCollection collection1 = db.getCollection("mashupData");
DBCursor cursor = collection1.find(field);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
}
return result;
}
public ArrayList<String> getByRating(String apiOrMashup, String values, String option) {
Double rating = Double.parseDouble(values);
ArrayList<String> result = new ArrayList<String>();
BasicDBObject field = new BasicDBObject();
if (apiOrMashup.equals("api")) {
if (option.equals("equalTo")) {
field.put("rating", rating);
DBCollection collection = db.getCollection("apiData");
DBCursor cursor = collection.find(field);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
}
else if (option.equals("lessThan")) {
BasicDBObject query = new BasicDBObject();
query.put("rating", new BasicDBObject("$lt", rating));
DBCollection collection = db.getCollection("apiData");
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
}
else {
// greaterThan
BasicDBObject query = new BasicDBObject();
query.put("rating", new BasicDBObject("$gt", rating));
DBCollection collection = db.getCollection("apiData");
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
}
} else {
// mashup
if (option.equals("equalTo")) {
field.put("rating", rating);
DBCollection collection1 = db.getCollection("mashupData");
DBCursor cursor1 = collection1.find(field);
while (cursor1.hasNext()) {
System.out.println(result.add((String) cursor1.next().get("id")));
}
}
else if (option.equals("lessThan")) {
BasicDBObject query = new BasicDBObject();
query.put("rating", new BasicDBObject("$lt", rating));
DBCollection collection = db.getCollection("mashupData");
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
}
else {
// greaterThan
BasicDBObject query = new BasicDBObject();
query.put("rating", new BasicDBObject("$gt", rating));
DBCollection collection = db.getCollection("mashupData");
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println(result.add((String) cursor.next().get("id")));
}
}
}
return result;
}
}
| true
|
15eaed763b6725752b688f8a4024e6623b1329a7
|
Java
|
GollmerSt/TimerImportTool
|
/src/dvbviewertimerimport/dvbviewer/DVBViewerSetupXML.java
|
UTF-8
| 3,998
| 2.515625
| 3
|
[] |
no_license
|
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
package dvbviewertimerimport.dvbviewer;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.stream.StreamSource;
import dvbviewertimerimport.misc.ErrorClass;
import dvbviewertimerimport.xml.StackXML;
public class DVBViewerSetupXML {
private static final String NAME_XML_DVBVIEWER_SETUP = "setup.xml" ;
private static final StackXML< String > sectionPath = new StackXML< String >( "settings", "section" ) ;
private static final StackXML< String > entryPath = new StackXML< String >( "settings", "section", "entry" ) ;
private HashMap< String, HashMap< String, String > > map = null ;
DVBViewer dvbViewer ;
class StringRef
{
public String string = "" ;
}
DVBViewerSetupXML( DVBViewer dvbViewer )
{
this.dvbViewer = dvbViewer ;
}
void clear()
{
this.map = null ;
}
void readXML()
{
this.map = new HashMap< String, HashMap< String, String > >() ;
File f = new File( this.dvbViewer.getDVBViewerDataPath() + File.separator + NAME_XML_DVBVIEWER_SETUP ) ;
if ( ! f.exists() )
return ;
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
try {
XMLEventReader reader = inputFactory.createXMLEventReader( new StreamSource( f ) );
StackXML<String> stack = new StackXML<String>();
String data = "" ;
StringRef sectionName = new StringRef() ;
StringRef entryName = new StringRef() ;
StringRef ref = null ;
HashMap< String, String > entryMap = null ;
while( reader.hasNext() ) {
XMLEvent ev = reader.nextEvent();
if( ev.isStartElement() )
{
stack.push( ev.asStartElement().getName().getLocalPart() );
if ( stack.equals( DVBViewerSetupXML.sectionPath ) )
ref = sectionName ;
else if ( stack.equals( DVBViewerSetupXML.entryPath ) )
ref = entryName ;
@SuppressWarnings("unchecked")
Iterator<Attribute> iter = ev.asStartElement().getAttributes();
while( iter.hasNext() )
{
Attribute attr = iter.next() ;
String value = attr.getValue() ;
if ( attr.getName().getLocalPart().equals( "name" ) )
ref.string = value ;
}
if ( stack.equals( DVBViewerSetupXML.sectionPath ) )
{
if ( ! this.map.containsKey( sectionName.string ) )
this.map.put( sectionName.string, new HashMap< String, String >() ) ;
entryMap = this.map.get( sectionName.string ) ;
}
}
else if( ev.isEndElement() )
{
if ( stack.equals( DVBViewerSetupXML.entryPath ) )
{
entryMap.put( entryName.string, data ) ;
data = "" ;
}
stack.pop();
}
else if ( ev.isCharacters() )
{
if ( stack.equals( DVBViewerSetupXML.entryPath ) )
data += ev.asCharacters().getData() ;
}
}
reader.close();
} catch (XMLStreamException e) {
throw new ErrorClass( e, "Error on readin XML file \"" + f.getName()
+ ". Position: Line = " + Integer.toString( e.getLocation().getLineNumber() )
+ ", column = " + Integer.toString(e.getLocation().getColumnNumber()) ) ;
}
catch (Exception e) {
throw new ErrorClass( e, "Unexpected error on read XML file \"" + f.getName() ) ;
}
return ;
}
public String getSetupValue( String section, String name, String deflt )
{
if ( this.map == null )
this.readXML() ;
if ( ! this.map.containsKey( section ) )
return deflt ;
HashMap< String, String > entryMap = this.map.get( section ) ;
if ( ! entryMap.containsKey( name ) )
return deflt ;
return entryMap.get( name ) ;
}
}
| true
|
8bedc5a74df63748e23b78a53ac481d89b24b79d
|
Java
|
KG102/KanikaGupta_18csu102
|
/FOCP2/csvtojson/src/com/ncu/main/TestNameValidator.java
|
UTF-8
| 887
| 2.546875
| 3
|
[] |
no_license
|
import com.ncu.validators.*;
public class TestNameValidator
{
public static void main(String[]args)
{
NameValidator csvObject= new NameValidator();
boolean checkValidator= csvObject.nameValidator("example.csv","csv");
System.out.println(checkValidator);
checkValidator= csvObject.nameValidator("","csv");
System.out.println(checkValidator);
checkValidator= csvObject.nameValidator("example","csv");
System.out.println(checkValidator);
checkValidator= csvObject.nameValidator("example.csv","csv");
System.out.println(checkValidator);
checkValidator= csvObject.nameValidator("example1234567893464564423.csv","csv");
System.out.println(checkValidator);
checkValidator= csvObject.nameValidator("example@123.csv","csv");
System.out.println(checkValidator);
checkValidator= csvObject.nameValidator("example.doc","json");
System.out.println(checkValidator);
}
}
| true
|
ae4c423590a2f33eeb52d5806b427a1ee269dfd8
|
Java
|
Arles96/Sistema-Facturacion
|
/FacturationSystem/src/Models/Payment_Model.java
|
UTF-8
| 2,708
| 2.609375
| 3
|
[] |
no_license
|
package Models;
import Entities.Inventory;
import Entities.Payment;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author CJ
*/
public class Payment_Model extends Model {
@Override
public void insert(Object entity) {
super.connect();
Payment pay = (Payment) entity;
try {
PreparedStatement st = connect.prepareStatement("INSERT INTO pago (id_pago, numero_credito, abono, fecha) "
+ "values(?, ?, ?, ?)");
st.setString(1, "" + pay.getID());
st.setString(2, "" + pay.getCredit());
st.setString(3, "" + pay.getDeposit());
st.setString(4, pay.getDate());
st.execute();
} catch (Exception ex) {
}
super.close();
}
@Override
public void update(Object entity) {
super.connect();
Payment pay = (Payment) entity;
try {
PreparedStatement st = connect.prepareStatement("UPDATE pago set id_pago=?, numero_credito=?, abono=?, fecha=?");
st.setString(1, "" + pay.getID());
st.setString(2, "" + pay.getCredit());
st.setString(3, "" + pay.getDeposit());
st.setString(4, pay.getDate());
st.execute();
} catch (Exception ex) {
}
super.close();
}
@Override
public void delete(Object id) {
super.connect();
String idrtn = (String) id;
System.out.println(id);
try {
PreparedStatement st = connect.prepareStatement("DELETE FROM Pago "
+ "WHERE id_pago = ?");
st.setString(1, idrtn);
st.execute();
} catch (SQLException ex) {
Logger.getLogger(Payment_Model.class.getName()).log(Level.SEVERE, null, ex);
}
super.close();
}
public ArrayList<Payment> getView() {
ArrayList<Payment> view = new ArrayList();
super.connect();
try {
Statement st = connect.createStatement();
ResultSet rs = st.executeQuery("Select * from VW_PAGOS");
while (rs.next()) {
int ID = rs.getInt("id_pago");
int credit = rs.getInt("numero_credito");
float deposit = rs.getFloat("abono");
String date = rs.getString("fecha");
view.add(new Payment(ID, credit, deposit, date));
}
} catch (Exception ex) {
}
super.close();
return view;
}
}
| true
|
680c3cc0a5777481493cac5582efcc2488eed347
|
Java
|
tuwq/android_node
|
/basic/sharedPreferences/code/sharedpreferences/app/src/main/java/com/tuwq/sharedpreferences/MainActivity.java
|
UTF-8
| 2,495
| 2.46875
| 2
|
[] |
no_license
|
package com.tuwq.sharedpreferences;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText et_username;
EditText et_password;
Button btn_login;
CheckBox cb_isSave;
SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = this.findViewById(R.id.et_username);
et_password = this.findViewById(R.id.et_password);
btn_login = this.findViewById(R.id.btn_login);
cb_isSave = this.findViewById(R.id.cb_isSave);
btn_login.setOnClickListener(this);
/**
* arg1: 保存文件的名字
* arg2: 存储的模式
*/
sp = this.getSharedPreferences("info", MODE_PRIVATE);
boolean isChecked = sp.getBoolean("isChecked", false);
if (isChecked) {
String username = sp.getString("username", "");
String password = sp.getString("password", "");
et_username.setText(username);
et_password.setText(password);
}
cb_isSave.setChecked(isChecked);
}
@Override
public void onClick(View v) {
String username = et_username.getText().toString().trim();
String password = et_password.getText().toString().trim();
if (TextUtils.isEmpty(password) || TextUtils.isEmpty(username)) {
Toast.makeText(this, "用户名密码不能为空", Toast.LENGTH_SHORT).show();
} else {
SharedPreferences.Editor editor = sp.edit();
boolean checked = cb_isSave.isChecked();
if (checked) {
// 通过sp对象获取编辑器
editor.putString("username", username);
editor.putString("password", password);
}
editor.putBoolean("isChecked", checked);
// 调用commit后,所有的put方法才会保存到文件中
editor.commit();
Toast.makeText(this, "状态保存成功", Toast.LENGTH_SHORT).show();
}
}
}
| true
|
3633f60ab44a748d7f3be2fbadc67348ee01a253
|
Java
|
GHHMBird/HLJinRong
|
/app/src/main/java/com/haili/finance/helper/UserBusinessHelper.java
|
UTF-8
| 8,307
| 1.601563
| 2
|
[] |
no_license
|
package com.haili.finance.helper;
import com.haili.finance.business.user.AddBankCardRequest;
import com.haili.finance.business.user.AddBankCardResponse;
import com.haili.finance.business.user.BankListRequest;
import com.haili.finance.business.user.BankListResponse;
import com.haili.finance.business.user.ChangeLoginPsdRequest;
import com.haili.finance.business.user.ChangeLoginPsdResponse;
import com.haili.finance.business.user.ChangePhoneNumRequest;
import com.haili.finance.business.user.ChangePhoneNumResponse;
import com.haili.finance.business.user.CheckMessageCodeRequest;
import com.haili.finance.business.user.CheckMessageCodeResponse;
import com.haili.finance.business.user.GetInviteCodeRequest;
import com.haili.finance.business.user.GetInviteCodeResponse;
import com.haili.finance.business.user.GetRedPackageRequest;
import com.haili.finance.business.user.GetRedPackageResponse;
import com.haili.finance.business.user.LoginRequest;
import com.haili.finance.business.user.LoginResponse;
import com.haili.finance.business.user.MessageDetailRequest;
import com.haili.finance.business.user.MessageDetailResponse;
import com.haili.finance.business.user.MessageListRequest;
import com.haili.finance.business.user.MessageListResponse;
import com.haili.finance.business.user.MyBankCardRequest;
import com.haili.finance.business.user.MyBankCardResponse;
import com.haili.finance.business.user.MyInfoRequest;
import com.haili.finance.business.user.MyInviteFriendRequest;
import com.haili.finance.business.user.MyInviteFriendResponse;
import com.haili.finance.business.user.MyInviteMoneyRequest;
import com.haili.finance.business.user.MyInviteMoneyResponse;
import com.haili.finance.business.user.NewsNoticeDetailRequest;
import com.haili.finance.business.user.NewsNoticeDetailResponse;
import com.haili.finance.business.user.NewsNoticeRequest;
import com.haili.finance.business.user.NewsNoticeResponse;
import com.haili.finance.business.user.PayPasswordRequest;
import com.haili.finance.business.user.PayPasswordResponse;
import com.haili.finance.business.user.RealNameRequest;
import com.haili.finance.business.user.RealNameResponse;
import com.haili.finance.business.user.RegisterMsgCodeRequest;
import com.haili.finance.business.user.RegisterMsgCodeResponse;
import com.haili.finance.business.user.RegisterRequest;
import com.haili.finance.business.user.RemoveBankCardRequest;
import com.haili.finance.business.user.RemoveBankCardResponse;
import com.haili.finance.business.user.RetrievePasswordRequest;
import com.haili.finance.business.user.RetrievePasswordResponse;
import com.haili.finance.business.user.ShareInfoRequest;
import com.haili.finance.business.user.ShareInfoResponse;
import com.haili.finance.business.user.UpDateRequest;
import com.haili.finance.business.user.UpDateResponse;
import com.haili.finance.business.user.UserGetVerificationCodeRequest;
import com.haili.finance.business.user.UserGetVerificationCodeResponse;
import com.haili.finance.business.user.UserSendMsgBackReoponse;
import com.haili.finance.business.user.UserSendMsgBackRequest;
import com.haili.finance.business.user.VerifyCodeLoginRequest;
import com.haili.finance.http.InterfaceAPI;
import rx.Observable;
/*
* Created by lfu on 2017/2/22.
*/
public class UserBusinessHelper {
/*
* 注册
*/
public static Observable<LoginResponse> register(RegisterRequest request) {
return new InterfaceAPI().register(request);
}
/*
* 密码登录
*/
public static Observable<LoginResponse> pasLogin(LoginRequest request) {
return new InterfaceAPI().pasLogin(request);
}
/*
* 验证码登录
*/
public static Observable<LoginResponse> verifyCodeLogin(VerifyCodeLoginRequest request) {
return new InterfaceAPI().verifyCodeLogin(request);
}
/*
* 获取图形验证码
*/
public static Observable<UserGetVerificationCodeResponse> getImageCode(UserGetVerificationCodeRequest request) {
return new InterfaceAPI().getImageCode(request);
}
/*
* 获取短信验证码
*/
public static Observable<RegisterMsgCodeResponse> getMsgCode(RegisterMsgCodeRequest request) {
return new InterfaceAPI().getMsgCode(request);
}
/*
* 更改登录密码
*/
public static Observable<ChangeLoginPsdResponse> changeLoginPsd(ChangeLoginPsdRequest request) {
return new InterfaceAPI().changeLoginPsd(request);
}
//获取红包信息
public static Observable<GetRedPackageResponse> getRedPackage(GetRedPackageRequest request) {
return new InterfaceAPI().getRedPackage(request);
}
//获取邀请页面信息
public static Observable<GetInviteCodeResponse> getInviteInfo(GetInviteCodeRequest request) {
return new InterfaceAPI().getInviteInfo(request);
}
//实名认证第一步
public static Observable<RealNameResponse> realName(RealNameRequest request) {
return new InterfaceAPI().realName(request);
}
//绑卡/添加银行卡
public static Observable<AddBankCardResponse> addBankCard(AddBankCardRequest request) {
return new InterfaceAPI().addBankCard(request);
}
//分享功能
public static Observable<ShareInfoResponse> shareInfo(ShareInfoRequest request) {
return new InterfaceAPI().shareInfo(request);
}
//银行卡解绑
public static Observable<RemoveBankCardResponse> removeBankCard(RemoveBankCardRequest request) {
return new InterfaceAPI().removeBankCard(request);
}
//个人中心
public static Observable<LoginResponse> myInfo(MyInfoRequest request) {
return new InterfaceAPI().myInfo(request);
}
//银行卡开户行列表
public static Observable<BankListResponse> bankOpenList(BankListRequest request) {
return new InterfaceAPI().getOpenBankList(request);
}
//更新版本
public static Observable<UpDateResponse> upDateVersion(UpDateRequest request) {
return new InterfaceAPI().upDate(request);
}
//更改手机号
public static Observable<ChangePhoneNumResponse> changePhoneNum(ChangePhoneNumRequest request) {
return new InterfaceAPI().changePhoneNum(request);
}
//我的邀请人
public static Observable<MyInviteFriendResponse> myInviteFriend(MyInviteFriendRequest request) {
return new InterfaceAPI().myInviteFriendInfo(request);
}
//我的邀请奖励
public static Observable<MyInviteMoneyResponse> myInviteMoney(MyInviteMoneyRequest request) {
return new InterfaceAPI().myInviteMoney(request);
}
//我的银行卡管理
public static Observable<MyBankCardResponse> myBankCard(MyBankCardRequest request) {
return new InterfaceAPI().myBankCard(request);
}
//新闻/公告获取
public static Observable<NewsNoticeResponse> newsNoticeList(NewsNoticeRequest request) {
return new InterfaceAPI().newsNotice(request);
}
//新闻/公告详情
public static Observable<NewsNoticeDetailResponse> newsNoticeDetail(NewsNoticeDetailRequest request) {
return new InterfaceAPI().newsNoticeDetail(request);
}
//消息列表
public static Observable<MessageListResponse> getMessageList(MessageListRequest request) {
return new InterfaceAPI().getMessageList(request);
}
//消息详情
public static Observable<MessageDetailResponse> getMessageDetail(MessageDetailRequest request) {
return new InterfaceAPI().messageDetail(request);
}
//用户反馈
public static Observable<UserSendMsgBackReoponse> userMessageBack(UserSendMsgBackRequest request) {
return new InterfaceAPI().userMessageBack(request);
}
//支付密码
public static Observable<PayPasswordResponse> payPassword(PayPasswordRequest request) {
return new InterfaceAPI().payPassword(request);
}
//检查手机短信验证码
public static Observable<CheckMessageCodeResponse> checkMessageCode(CheckMessageCodeRequest request) {
return new InterfaceAPI().checkMessageCode(request);
}
//召回登录密码
public static Observable<RetrievePasswordResponse> retrivePassword(RetrievePasswordRequest request) {
return new InterfaceAPI().retrivePsd(request);
}
}
| true
|
d99ea81ad16f524ea09932c00af6eab8737d3f4a
|
Java
|
haliu/M6
|
/lib/jvm2acl2/preverify.java
|
UTF-8
| 2,536
| 2.859375
| 3
|
[] |
no_license
|
import java.util.*;
import java.io.*;
public class preverify {
private static int level =0;
private static String[] collectFileNames (String[] args) {
Vector files = new Vector();
String[] reslt = null;
try {
for (int i=0; i<args.length; i++) {
File cur = new File(args[i]);
System.out.println(args[i]);
if (cur.isDirectory()) {
String[] nextlevel=cur.list();
for (int j=0; j<nextlevel.length; j++) {
nextlevel[j]=(cur.getPath()+"/"+nextlevel[j]);
};
String[] names = collectFileNames(nextlevel);
for (int j=0; j<names.length; j++) {
files.addElement(names[j]);
};
}
else
files.addElement(cur.getPath());
};
reslt = new String[files.size()];
for (int i=0; i<files.size(); i++) {
reslt[i]=(String) files.get(i);
System.out.println(reslt[i]);
};
} catch (Exception e) {
System.out.println("File reading error!");
};
return reslt;
};
public static void main(String[] args) {
System.err.println("Preverify ");
if (args.length < 3) {
System.err.println("Usage: preverify <classpath> <outputdirectory> <file names>* [<package names>*]\n");
System.exit(0);
}
String[] input = new String[args.length-2];
for (int i=0; i< args.length-2; i++)
input[i]=args[i+2];
processFiles(args[0], args[1], collectFileNames(input));
};
private static void processFiles(String classpath, String output, String[] args) {
String command;
Runtime runtime = Runtime.getRuntime();
for (int i =0; i < args.length; i++) {
String cur = args[i];
int e = cur.lastIndexOf('.');
if (e!=-1) {
String suffix = cur.substring(e+1);
int pos = cur.indexOf("/")+1;
String toplevel;
String name;
if (pos !=0) {
// find the top level path. where the tree started.
toplevel = cur.substring(0, pos);
name = cur.substring(pos, e);
} else {
toplevel = ".";
name =cur.substring(0, e);
};
File dir = new File(toplevel);
if (suffix.equals("class")) {
command ="preverify -classpath "+ classpath +" -d "+output+" "+ name;
try {
System.out.println("processing ..." + cur+"\n use command\n"+command+"\n");
runtime.exec(command).waitFor();
} catch (IOException ee) {
System.out.println(ee.toString());
} catch (InterruptedException eee) {
System.out.println(eee);
};
};
};
};
};
};
| true
|
4885edb35caf3bc708dcd5f69bc79ca2b7cdab51
|
Java
|
DLennertz/codigosFaeterj
|
/java/Java/Lista1Java/Ex5.java
|
UTF-8
| 633
| 3.625
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class Ex5 {
public static void main(String[] args){
float maior;
System.out.println("Programa para calcular equacao de segundo grau (ax^2 + bx + c = 0)");
Scanner sc = new Scanner(System.in);
System.out.println("Digite o valor a : ");
int a = sc.nextInt();
System.out.println("Digite o valor b : ");
int b = sc.nextInt();
System.out.println("Digite o valor c : ");
int c = sc.nextInt();
System.out.println(a+"x^2 +" + b+"x +"+c);
System.out.println("Agora escolha o valor de x :");
int x = sc.nextInt();
System.out.println("Resultado = " + ((a+x*x)+(b*x)+c));
}
}
| true
|
88aa663bb3edaeef84baea7376c36abcc6e28884
|
Java
|
phoniex-fly/study-java
|
/study-DesignPattern/src/main/java/org/study/DesignPattern/factory/abstractfactory/factory/BJPizzaFactory.java
|
UTF-8
| 617
| 2.734375
| 3
|
[] |
no_license
|
package org.study.DesignPattern.factory.abstractfactory.factory;
import Study.DesignPattern.factory.abstractfactory.product.BJCheesePizza;
import Study.DesignPattern.factory.abstractfactory.product.BJPepperPizza;
import Study.DesignPattern.factory.abstractfactory.product.Pizza;
public class BJPizzaFactory implements PizzaFactory{
@Override
public void createCheesePizza() {
Pizza pizza = new BJCheesePizza();
pizza.add();
pizza.bak();
pizza.done();
}
@Override
public void createPepperPizza() {
Pizza pizza = new BJPepperPizza();
pizza.add();
pizza.bak();
pizza.done();
}
}
| true
|
c18f5ad9177f46e04dc40b5963f006c8e46e3763
|
Java
|
skytylon/WansViewPlus
|
/app/src/main/java/net/java/stun4j/attribute/OptionalAttribute.java
|
UTF-8
| 4,148
| 2.71875
| 3
|
[] |
no_license
|
/*
* Stun4j, the OpenSource Java Solution for NAT and Firewall Traversal.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.stun4j.attribute;
import net.java.stun4j.StunException;
import java.util.Arrays;
/**
* This class is used for representing attributes not explicitly supported by
* the stack. Such attributes will generally be kept in binary form and won't be
* subdued to any processing by the stack. One could use this class for both
* dealing with attributes in received messages, and generating messages
* containing attributes not explicitly supported by the stack.
* <p/>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Organisation: Louis Pasteur University, Strasbourg, France</p>
* <p>Network Research Team (http://www-r2.u-strasbg.fr)</p></p>
*
* @author Emil Ivov
* @version 0.1
*/
public class OptionalAttribute
extends Attribute {
byte[] attributeValue = null;
protected OptionalAttribute(char attributeType) {
super(attributeType);
}
/**
* Sets this attribute's fields according to attributeValue array.
*
* @param attributeValue a binary array containing this attribute's
* field values and NOT containing the attribute header.
* @param offset the position where attribute values begin (most often
* offset is equal to the index of the first byte after length)
* @param length the length of the binary array.
* @throws StunException if attrubteValue contains invalid data.
*/
void decodeAttributeBody(byte[] attributeValue, char offset, char length)
throws StunException {
this.attributeValue = new byte[length];
System.arraycopy(attributeValue, offset, this.attributeValue, 0, length);
}
/**
* Returns a binary representation of this attribute.
*
* @return a binary representation of this attribute.
*/
public byte[] encode() {
char type = getAttributeType();
byte binValue[] = new byte[HEADER_LENGTH + attributeValue.length];
//Type
binValue[0] = (byte) (type >> 8);
binValue[1] = (byte) (type & 0x00FF);
//Length
binValue[2] = (byte) (getDataLength() >> 8);
binValue[3] = (byte) (getDataLength() & 0x00FF);
System.arraycopy(attributeValue, 0,
binValue, HEADER_LENGTH, attributeValue.length);
return binValue;
}
/**
* Returns the length of this attribute's body.
*
* @return the length of this attribute's value.
*/
public char getDataLength() {
return (char) attributeValue.length;
}
/**
* Returns the human readable name of this attribute.
*
* @return this attribute's name.
*/
public String getName() {
return "Unknown Attribute";
}
/**
* Returns a reference to the unparsed body of this attribute.
*
* @return a reference to this attribute's unparsed value.
*/
public byte[] getBody() {
return attributeValue;
}
/**
* Copies the speicified byte array segment as the body of this attribute.
*
* @param body the body to copy
* @param offset the position to start
* @param length the length to copy
*/
public void setBody(byte[] body, int offset, int length) {
this.attributeValue = new byte[length];
System.arraycopy(body, offset, this.attributeValue, 0, length);
}
/**
* Compares two STUN Attributes. Two attributes are considered equal when they
* have the same type length and value.
*
* @param obj the object to compare this attribute with.
* @return true if the attributes are equal and false otherwise.
*/
public boolean equals(Object obj) {
if (obj == null
|| !(obj instanceof OptionalAttribute))
return false;
return
(obj == this
|| Arrays.equals(((OptionalAttribute) obj).
attributeValue, attributeValue));
}
}
| true
|
e39bb0d8d5500c6b93cbd918433281b60fc0607e
|
Java
|
jeewamp/ESBhive
|
/carbon-core/src/main/java/org/wso2/carbon/core/util/AnonymousSessionUtil.java
|
UTF-8
| 4,621
| 2.234375
| 2
|
[] |
no_license
|
package org.wso2.carbon.core.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonException;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import org.wso2.carbon.utils.TenantUtils;
/**
* When there is no authenticated session please use this calss to get the
* registry and realm.
*
* Usage : Password Callback Handler
*/
public class AnonymousSessionUtil {
private static Log log = LogFactory.getLog(AnonymousSessionUtil.class);
/**
* @deprecated
*/
public static UserRegistry getSystemRegistryByUserName(RegistryService registryService,
RealmService realmService, String userName) throws CarbonException {
try {
String tenantDomain = UserCoreUtil.getTenantDomain(realmService, userName);
return AnonymousSessionUtil.getSystemRegistryByDomainName(registryService, realmService,
tenantDomain);
} catch (UserStoreException e) {
throw new CarbonException(e.getMessage(), e);
}
}
/**
* @deprecated
*/
public static UserRegistry getUserRegistryByUserName(RegistryService registryService,
RealmService realmService, String userName) throws CarbonException {
try {
return registryService.getUserRegistry(userName);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new CarbonException(e.getMessage(), e);
}
}
/**
* @deprecated
*/
public static UserRegistry getSystemRegistryByDomainName(RegistryService registryService,
RealmService realmService, String domainName) throws CarbonException {
try {
int tenantId = realmService.getTenantManager().getTenantId(domainName);
if (tenantId < 0) {
throw new CarbonException("Invalid domain name");
}
if (!realmService.getTenantManager().isTenantActive(tenantId)) {
throw new CarbonException("Inactive tenant");
}
return registryService.getConfigSystemRegistry(tenantId);
} catch (UserStoreException e) {
log.error(e.getMessage(), e);
throw new CarbonException(e.getMessage(), e);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new CarbonException(e.getMessage(), e);
}
}
/**
* @deprecated
*/
public static UserRegistry getUserRegistry(RegistryService registryService, String userName)
throws CarbonException {
try {
return registryService.getUserRegistry(userName);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new CarbonException(e.getMessage(), e);
}
}
public static UserRealm getRealmByUserName(RegistryService registryService,
RealmService realmService, String userName) throws CarbonException {
try {
String tenantDomain = UserCoreUtil.getTenantDomain(realmService, userName);
return AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService,
tenantDomain);
} catch (UserStoreException e) {
throw new CarbonException(e.getMessage(), e);
}
}
public static UserRealm getRealmByTenantDomain(RegistryService registryService,
RealmService realmService, String tenantDomain) throws CarbonException {
try {
int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
if (tenantId < 0) {
throw new CarbonException("Invalid domain name");
}
if (!realmService.getTenantManager().isTenantActive(tenantId)) {
throw new CarbonException("Inactive tenant");
}
return registryService.getUserRealm(tenantId);
} catch (UserStoreException e) {
log.error(e.getMessage(), e);
throw new CarbonException(e.getMessage(), e);
} catch (RegistryException e) {
log.error(e.getMessage(), e);
throw new CarbonException(e.getMessage(), e);
}
}
}
| true
|
7ed51aa593a13f99d37108211d614469f491fe08
|
Java
|
dvsmahajan/websocket-java
|
/src/main/java/com/dvsapp/dvsfinalwebsocketapp/repository/IChatMessageRepository.java
|
UTF-8
| 1,041
| 1.976563
| 2
|
[] |
no_license
|
package com.dvsapp.dvsfinalwebsocketapp.repository;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.dvsapp.dvsfinalwebsocketapp.entity.ChatMessage;
import com.dvsapp.dvsfinalwebsocketapp.entity.MessageStatus;
public interface IChatMessageRepository extends JpaRepository<ChatMessage, Integer> {
long countBySenderIdAndRecipientIdAndStatus(String senderId, String recipientId, MessageStatus status);
List<ChatMessage> findByChatId(String chatId);
@Query("UPDATE ChatMessage cm SET cm.status= :status WHERE cm.senderId = :senderId AND cm.recipientId = :recipientId")
@Transactional
@Modifying
void updateDeliveryStatusBySenderNRecipientIdNStatus(@Param("senderId") String senderId, @Param("recipientId") String recipientId,@Param("status") MessageStatus delivered);
}
| true
|
a7a8951e20424d1af3ed63ef8f6d2113306a7ad4
|
Java
|
DanielMagik/Design-patterns
|
/src/creational/builder/components/enums/HouseType.java
|
UTF-8
| 140
| 1.945313
| 2
|
[] |
no_license
|
package creational.builder.components.enums;
public enum HouseType
{
DETACHED_HOUSE,
SEMI_DETACHED_HOUSE,
VILLA,
COTTAGE
}
| true
|
40feb0487dfe23da31fcd953fa05e5f3e86174b2
|
Java
|
sofi2002sofi/Lab6_db
|
/src/main/java/com/didula/controller/implementation/CourseController.java
|
UTF-8
| 2,633
| 2.375
| 2
|
[] |
no_license
|
package com.didula.controller.implementation;
import com.didula.controller.ControllerWithDTO;
import com.didula.domain.CourseEntity;
import com.didula.dto.CourseDTO;
import com.didula.service.implementation.CourseService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
public class CourseController implements ControllerWithDTO<CourseDTO, CourseEntity> {
private final CourseService courseService;
public CourseController(CourseService courseService) {
this.courseService = courseService;
}
@GetMapping(value = "/courses")
public ResponseEntity<List<CourseDTO>> getCourses() {
List<CourseEntity> courseEntities = courseService.getAll();
List<CourseDTO> courseDTOs = createDTOs(courseEntities);
return new ResponseEntity<>(courseDTOs, HttpStatus.OK);
}
@GetMapping(value = "/courses/{courseId}")
public ResponseEntity<CourseDTO> getCourse(@PathVariable Integer courseId) {
CourseEntity courseEntity = courseService.getById(courseId);
CourseDTO courseDTO = createDTO(courseEntity);
return new ResponseEntity<>(courseDTO, HttpStatus.OK);
}
@PostMapping(value = "/courses")
public ResponseEntity<CourseDTO> createCourse(@RequestBody CourseEntity courseEntity) {
CourseEntity newCourse = courseService.create(courseEntity);
CourseDTO courseDTO = createDTO(newCourse);
return new ResponseEntity<>(courseDTO, HttpStatus.CREATED);
}
@PutMapping(value = "/courses/{courseId}")
public ResponseEntity<CourseDTO> updateGender(@RequestBody CourseEntity courseEntity, @PathVariable Integer courseId) {
CourseEntity newCourse = courseService.update(courseEntity, courseId);
CourseDTO courseDTO = createDTO(newCourse);
return new ResponseEntity<>(courseDTO, HttpStatus.OK);
}
@DeleteMapping(value = "/courses/{courseId}")
public ResponseEntity<Void> deleteCourse(@PathVariable Integer courseId) {
courseService.delete(courseId);
return new ResponseEntity<>(HttpStatus.OK);
}
@Override
public List<CourseDTO> createDTOs(Iterable<CourseEntity> courseEntities) {
List<CourseDTO> courseDTOs = new ArrayList<>();
for (CourseEntity courseEntity : courseEntities) {
CourseDTO courseDTO = new CourseDTO(courseEntity);
courseDTOs.add(courseDTO);
}
return courseDTOs;
}
@Override
public CourseDTO createDTO(CourseEntity courseEntity) {
return new CourseDTO(courseEntity);
}
}
| true
|
2a6dab7dbce9b7d120417102f14c53bd4851c181
|
Java
|
top1select/MySQLCDC
|
/fountain-common/src/main/java/net/neoremind/fountain/eventposition/LocalFileDisposeEventPosition.java
|
UTF-8
| 5,529
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
package net.neoremind.fountain.eventposition;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.neoremind.fountain.thread.annotaion.UnThreadSafe;
/**
* 采用本地文件来记录gt id的{@link DisposeEventPosition DisposeEventPosition} 接口实现
*
* @author hexiufeng
*/
@UnThreadSafe
public class LocalFileDisposeEventPosition extends RegistableDisposeEventPosition implements DisposeEventPosition {
private static final Logger LOGGER = LoggerFactory.getLogger(LocalFileDisposeEventPosition.class);
private static final int LINE_MAX_SIZE = 1024;
protected static final String INFO_SEP = ":";
// 本地存储路径,需要在spring内配置
private String rootPath;
public LocalFileDisposeEventPosition() {
}
public LocalFileDisposeEventPosition(String rootPath) {
this.rootPath = rootPath;
}
@Override
public synchronized SyncPoint loadSyncPoint() {
byte[] info = readBytesInfo();
if (info == null) {
return null;
}
SyncPoint point = createSyncPoint();
point.parse(info);
return point;
}
@Override
public synchronized void saveSyncPoint(SyncPoint point) {
if (point == null) {
return;
}
ByteBuffer buf = ByteBuffer.wrap(point.toBytes());
writeCore(buf);
LOGGER.info("Save SyncPoint:{}", point);
}
/**
* 构建SyncPoint对象,继承类可以override该方法
*
* @return
*/
protected SyncPoint createSyncPoint() {
return new BaiduGroupIdSyncPoint();
}
/**
* 返回文件扩展名
*
* @return 文件扩展名,可能是null
*/
protected String getFileExt() {
return null;
}
/**
* 返回记录日志的对象
*
* @return {@link Logger} 对象
*/
protected Logger getLogger() {
return LOGGER;
}
/**
* 组装保存同步点的文件的 全路径名
*
* @return 文件的全路径名
*/
private String getFilePath() {
String ext = getFileExt();
if (ext == null) {
return rootPath + "/" + super.getInstanceName();
}
return rootPath + "/" + super.getInstanceName() + "." + ext;
}
/**
* 从文件中读取二进制数据
*
* @return 文件的二进制数据
*/
private byte[] readBytesInfo() {
String path = getFilePath();
File file = new File(path);
if (!file.exists()) {
return null;
}
FileChannel fc = null;
try {
FileInputStream fis = new FileInputStream(file);
fc = fis.getChannel();
ByteBuffer buf = ByteBuffer.allocate(LINE_MAX_SIZE);
buf.order(ByteOrder.LITTLE_ENDIAN);
int count = fc.read(buf);
if (count <= 0) {
return null;
}
byte[] readBytes = new byte[count];
buf.flip();
buf.get(readBytes);
return readBytes;
} catch (FileNotFoundException e) {
getLogger().error(null, e);
} catch (IOException e) {
getLogger().error(null, e);
} finally {
if (fc != null) {
try {
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 写二级制数据到文件
*
* @param buf {@link ByteBuffer}
*/
private void writeCore(ByteBuffer buf) {
checkRootPath();
String path = getFilePath();
File file = new File(path);
FileChannel fc = null;
try {
FileOutputStream fis = new FileOutputStream(file);
fc = fis.getChannel();
buf.order(ByteOrder.LITTLE_ENDIAN);
while (buf.remaining() > 0) {
fc.write(buf);
}
} catch (FileNotFoundException e) {
getLogger().error(null, e);
} catch (IOException e) {
getLogger().error(null, e);
} finally {
if (fc != null) {
try {
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 检查同步点文件路径是否存在
*/
private void checkRootPath() {
File dir = new File(rootPath);
if (!dir.exists() || !dir.isDirectory()) {
throw new RuntimeException("SyncPoint file parent path don't exist.");
}
}
public String getRootPath() {
return rootPath;
}
public void setRootPath(String rootPath) {
this.rootPath = rootPath;
}
public static void main(String[] args) {
LocalFileDisposeEventPosition dp = new LocalFileDisposeEventPosition();
dp.setRootPath("/Users/willw/Downloads/JavaProjects/fountain/logs");
dp.registerInstance("test00");
//dp.saveSyncPoint(new BaiduGroupIdSyncPoint(BigInteger.valueOf(100L)));
SyncPoint syncPoint = dp.loadSyncPoint();
System.out.println(new String(syncPoint.toBytes()));
}
}
| true
|
bdb3709ec8c1a1a436781e485fb887a87ded7a1f
|
Java
|
DongMeng0706/myblog
|
/src/main/java/com/dong/common/MvcConfig.java
|
UTF-8
| 1,630
| 1.8125
| 2
|
[] |
no_license
|
package com.dong.common;
import com.dong.common.interceptor.MyInterceptor;
import com.dong.util.FileAdd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.support.FormattingConversionServiceFactoryBean;
import org.springframework.web.servlet.config.annotation.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Configuration
@EnableConfigurationProperties(FileAdd.class)
public class MvcConfig implements WebMvcConfigurer {
@Autowired
FileAdd fileAdd;
@Override
public void addInterceptors (InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/admin/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** 图片传路径 */
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+fileAdd.getPath());
}
@Override
public void addViewControllers (ViewControllerRegistry registry) {
//registry.addViewController("/add").setViewName("admin/page/systemcolumn/system-add");
}
@Override
public void configureViewResolvers (ViewResolverRegistry registry) {
}
}
| true
|
1ffee95802648955f94a1e3d9b0426deea4de303
|
Java
|
glenert41/SkyStone
|
/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ShieldsAutonomous.java
|
UTF-8
| 7,929
| 2.40625
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
/*
Copyright (c) 2016 Robert Atkinson
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) provided that
the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of Robert Atkinson nor the names of his contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESSFOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
// This OpMode is just Shields messing around with holonomic drive and functions
// The OpMode utilizes the BACONbot hardware definition defined in HardwareBACONbot
// =================================
// TO DO:
// - refine movement with gyros
// =================================
@Autonomous(name = "Shields and Arleth: Autonomous", group = "Shields")
@Disabled
public class ShieldsAutonomous extends LinearOpMode {
/* Declare OpMode members. */
HardwareBACONbot robot = new HardwareBACONbot(); // Use a BACONbot's hardware
private ElapsedTime runtime = new ElapsedTime();
int robotHeading = 0; // Gyro integrated heading
int targetHeading = 0;
int headingError = 0;
double rScale = 0.5;
@Override
public void runOpMode() throws InterruptedException {
// Initialize the hardware variables.
// The init() method of the hardware class does all the work here
robot.init(hardwareMap);
// start calibrating the gyro.
telemetry.addData(">", "Gyro Calibrating. Do Not move!");
telemetry.update();
/*robot.gyro1.calibrate();
// make sure the gyro is calibrated.
while (robot.gyro1.isCalibrating()) {
Thread.sleep(50);
idle();
}
*/
telemetry.addData(">", "Gyro Calibrated. Press Start.");
telemetry.update();
// Send telemetry message to signify robot waiting;
//telemetry.addData(">", "Greetings, human.");
//telemetry.update();
// Wait for the game to start (driver presses PLAY)
waitForStart();
// == My fancy Autonomous code ==
// put the sensor up
//robot.opticalServo.setPosition(0);
// go toward the wall until you see the wall
headingPowerTime(225, 0.4, 4, 0.02);
// put the sensor down
//robot.opticalServo.setPosition(.53);
//sleep(200);
// strafe to the white line
headingPowerTime(180, 0.4, 4, 0.04);
// == End fancy autonomous code ==
/*
// do a little dance
headingPowerTime(0, 1, 1, 0);
// make a little love
headingPowerTime(45, 1, 1, 0);
// get down tonight
headingPowerTime(90, 1, 1, 0);
// get down get down
headingPowerTime(135, 1, 1, 0);
// do a little dance
headingPowerTime(180, 1, 1, 0);
// make a little love
headingPowerTime(225, 1, 1, 0);
// get down tonight
headingPowerTime(270, 1, 1, 0);
// get down get down
headingPowerTime(315, 1, 1, 0);
*/
/*
// testing out servo positions
if (gamepad1.x)
robot.opticalServo.setPosition(0);
if (gamepad1.y)
robot.opticalServo.setPosition(.33);
if (gamepad1.b)
robot.opticalServo.setPosition(.66);
if (gamepad1.a)
robot.opticalServo.setPosition(1);
while (opModeIsActive()) {
telemetry.addData("Raw", robot.odsSensor1.getRawLightDetected());
telemetry.addData("Normal", robot.odsSensor1.getLightDetected());
telemetry.update();
idle(); // Always call idle() at the bottom of your while(opModeIsActive()) loop
}
*/
}
public void goForward() {
robot.frontLeftMotor.setPower(-.5);
robot.frontRightMotor.setPower(.5);
robot.backLeftMotor.setPower(-.5);
robot.backRightMotor.setPower(.5);
}
public void wheelsOff() {
robot.frontLeftMotor.setPower(0);
robot.frontRightMotor.setPower(0);
robot.backLeftMotor.setPower(0);
robot.backRightMotor.setPower(0);
}
public void headingPowerTime(int heading, double power, int time, double lightVal) {
double headingRads = Math.toRadians(heading);
double x = power*Math.cos(headingRads);
double y = power*Math.sin(headingRads);
//robotHeading = robot.gyro1.getHeading();
headingError = robotHeading - targetHeading;
double r = (headingError - 180)/180*rScale;
// ensure minimal power to move robot
if ((r < .07) && (r > 0)) {
r = .07;
} else if ((r > -.07) && (r < 0)) {
r = -.07;
}
telemetry.addData("error:>", r);
telemetry.addData("r:>", r);
telemetry.update();
//double r = 0;
setWheelPower(x, y, r);
runtime.reset();
// get stuck in a while loop for the proper amount of time
while (opModeIsActive() && (runtime.seconds() < time)) {
if(lightVal > 0) {
//double light = robot.OpticalDistanceSensor.getLightDetected();
//telemetry.addData("light", light);
telemetry.update();
// if (light > lightVal)
break;
}
}
wheelsOff();
}
public void setWheelPower(double x, double y, double r) {
// calculate the power for each wheel (math from here: https://www.vexforum.com/index.php/12370-holonomic-drives-2-0-a-video-tutorial-by-cody/0)
double frontLeft = -y - x + r;
double frontRight = +y - x + r;
double backLeft = -y + x + r;
double backRight = +y + x + r;
// Normalize the values so none exceeds +/- 1.0
double max = Math.max(Math.max(Math.abs(frontLeft), Math.abs(frontRight)), Math.max(Math.abs(frontRight), Math.abs(frontRight)));
if (max > 1.0) {
frontLeft = frontLeft / max;
frontRight = frontRight / max;
backLeft = backLeft / max;
backRight = backRight / max;
}
// Set power on each wheel
robot.frontLeftMotor.setPower(frontLeft);
robot.frontRightMotor.setPower(frontRight);
robot.backLeftMotor.setPower(backLeft);
robot.backRightMotor.setPower(backRight);
}
}
| true
|
282e802019bdc53ff78590fd9e9a43136ab651d3
|
Java
|
Sonichka1311/Yandex-Tracker-Bot
|
/task-03-telegram-random-coffee/src/main/java/ru/hse/cs/java2020/task03/StateGetCommentsByPage.java
|
UTF-8
| 934
| 2.34375
| 2
|
[] |
no_license
|
package ru.hse.cs.java2020.task03;
import java.util.Objects;
public class StateGetCommentsByPage extends StateImpl {
StateGetCommentsByPage(Long userId, Bot bot) {
super(userId, bot);
}
@Override
public void action(String message) {
String token = getDatabase().getToken(getUserId());
String task = getDatabase().getTask(getUserId());
String companyId = getDatabase().getCompanyId(getUserId());
TrackerClient client = new TrackerClient(token, companyId);
int start = Integer.parseInt(message);
int num = getDatabase().getCount(getUserId());
String comments = client.getComments(task, start, start + num);
getDatabase().updatePage(getUserId(), start + num);
getDatabase().updateUserState(getUserId(), "waitNextComment");
getBot().sendMessage(getUser(), Objects.requireNonNullElse(comments, Constants.NOT_FOUND_COM));
}
}
| true
|
42004f3073da8b19a79f11581103756e0fa5f6a7
|
Java
|
seemethere/DeathEssentials
|
/src/com/github/seemethere/DeathEssentials/ModularPlugin.java
|
UTF-8
| 2,782
| 2.40625
| 2
|
[] |
no_license
|
package com.github.seemethere.DeathEssentials;
import com.github.seemethere.DeathEssentials.modules.*;
import com.github.seemethere.DeathEssentials.utils.configuration.ConfigManager;
import com.github.seemethere.DeathEssentials.utils.module.ModuleBase;
import com.github.seemethere.DeathEssentials.utils.module.ModuleDependencies;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Map;
import java.util.logging.Logger;
/**
* @author seemethere
*/
public class ModularPlugin extends JavaPlugin {
private static final double version = 1.0;
private ModuleManager moduleManager;
private Logger logger;
public void onEnable() {
this.saveDefaultConfig();
logger = this.getLogger();
new ModuleDependencies(this);
moduleManager = new ModuleManager(this);
setModuleList();
// Initial plug of modules
for (String s : moduleManager.getModuleList().keySet()) {
if (moduleManager.getInitialStatus().containsKey(s) &&
moduleManager.getInitialStatus().get(s)) {
moduleManager.plugModule(s);
}
}
//Enable InternalCommands
moduleManager.plugModule("InternalCommands");
logger.info("DeathEssentials has been enabled");
}
public void onDisable() {
// Unplugging of modules for safe exit
for (String s : moduleManager.getModuleList().keySet()) {
ModuleBase module = moduleManager.findModule(s);
if (moduleManager.isEnabled(module)) {
moduleManager.unplugModule(s, true);
}
}
logger.info("DeathEssentials has been disabled");
}
protected void setModuleList() {
addModule(new InternalCommands());
addModule(new TestModule());
addModule(new DeathCharge());
addModule(new DeathBan());
addModule(new KDR());
}
/**
* For public use, allows a developer to add a module directly from the ModularPlugin base
*
* @param module Module to be added
*/
public void addModule(ModuleBase module) {
moduleManager.addModule(module);
}
/**
* @return ModuleManager
*/
public ModuleManager getModuleManager() {
return moduleManager;
}
/**
* @return List of modules with classes
*/
public Map<String, ModuleBase> getModuleList() {
return moduleManager.getModuleList();
}
public double getVersion() {
return version;
}
public ConfigManager getModuleConfigManager(ModuleBase module) {
return this.getModuleManager().getModuleConfigManager(module);
}
public ModuleBase findModule(String name) {
return this.getModuleManager().findModule(name);
}
}
| true
|
cfde65792e661ceef5cbe26b21892b795dade224
|
Java
|
gabrielaionita/java-marathon
|
/JAVABasic/src/edu/tema/acasa18/Problema46.java
|
UTF-8
| 1,149
| 3.765625
| 4
|
[] |
no_license
|
/*** Tema pentru acas
* Problema 4.6: Afiseaza rezultatul operatiunii
* in urma introducerii operatorului si a doua numere
* @since 18july2020
* @author Ionita Gabriela
*/
package edu.tema.acasa18;
import java.util.Scanner;
public class Problema46 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter operator (+, -, * or /):");
char opIndex = scanner.next().charAt(0);
System.out.print("Enter number1:");
int number1 = scanner.nextInt();
System.out.print("Enter number2:");
int number2 = scanner.nextInt();
switch (opIndex) {
case '+':
System.out.println(number1 + number2);
break;
case '-':
System.out.println(number1 - number2);
break;
case '*':
System.out.println(number1 * number2);
break;
case '/':
System.out.println(number1 / number2);
break;
default:
System.out.println("Wrong operator!");
}
}
}
| true
|
18b5841b15eb3df3e5be715ca8bdfb2c8e2b4607
|
Java
|
mayanmohamed/news-task
|
/src/main/java/com/example/demo/entity/News.java
|
UTF-8
| 650
| 1.929688
| 2
|
[] |
no_license
|
package com.example.demo.entity;
import java.util.Arrays;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Entity
@Table(name = "news")
public class News {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String title;
@Column
private String description;
@Column
@Lob
private byte[] image;
}
| true
|
4c15a7d429c82741b4b9434d301c47505da1415a
|
Java
|
cdbhimani/joeydevolopmenttesting
|
/libgdxCommon/src/com/emptyPockets/network/kryonetImpl/KryonetGameClient.java
|
UTF-8
| 928
| 2.640625
| 3
|
[] |
no_license
|
package com.emptyPockets.network.kryonetImpl;
import java.io.IOException;
import com.emptyPockets.network.framework.GameClient;
import com.esotericsoftware.kryonet.Client;
public class KryonetGameClient extends GameClient {
Client client;
KryonetListener listener;
public KryonetGameClient() {
init();
}
public void init() {
client = new Client();
listener = new KryonetListener();
listener.setName("client");
client.addListener(listener);
}
@Override
public void startConnection() throws IOException{
client.start();
client.connect(connectTimeout, host, tcpPort, udpPort);
}
@Override
public void stopConnection() {
client.stop();
}
@Override
public void sendTCP(Object object) {
client.sendTCP(object);
}
@Override
public void sendUDP(Object object) {
client.sendUDP(object);
}
public Client getClient() {
return client;
}
}
| true
|
d52bad2f171e71cb4b1f2542c729eae2a56e71f7
|
Java
|
detelinradev/TelerikPreparationFinal
|
/src/CalculateFAct.java
|
UTF-8
| 573
| 3.15625
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class CalculateFAct {
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
double numberOne = scann.nextDouble();
double numberTwo = scann.nextDouble();
double sumOne = 1;
double sumTotal = 1;
for (int i = 1; i <= numberOne ; i++) {
sumOne = 1;
for (int j = i; j > 0 ; j--) {
sumOne *= j;
}
sumTotal += sumOne/Math.pow(numberTwo,i);
}
System.out.printf("%.5f",sumTotal);
}
}
| true
|
9dae68fa572270f273237eac539659c821a7df98
|
Java
|
agustinmadina/GlobantEvents
|
/Events/app/src/main/java/com/globant/events/adapters/EventsListViewHolderClient.java
|
UTF-8
| 729
| 1.898438
| 2
|
[] |
no_license
|
package com.globant.events.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.View;
import com.globant.events.activities.EventDetailClientActivity;
import com.globant.eventscorelib.baseActivities.BasePagerActivity;
import com.globant.eventscorelib.baseAdapters.BaseEventsListViewHolder;
public class EventsListViewHolderClient extends BaseEventsListViewHolder{
@Override
protected Class<? extends BasePagerActivity> getActivityClass() {
return EventDetailClientActivity.class;
}
public EventsListViewHolderClient(View itemView, Context context, Fragment fragment) {
super(itemView, context, fragment);
}
}
| true
|
c09846a9e5d9956c23549b00661fb767bbd071e9
|
Java
|
ArtemZaikovsky/Back
|
/src/main/java/com/trade_accounting/services/impl/CorrectionProductServiceImpl.java
|
UTF-8
| 2,305
| 2.21875
| 2
|
[] |
no_license
|
package com.trade_accounting.services.impl;
import com.trade_accounting.models.CorrectionProduct;
import com.trade_accounting.models.Product;
import com.trade_accounting.models.dto.CorrectionProductDto;
import com.trade_accounting.repositories.CorrectionProductRepository;
import com.trade_accounting.repositories.ProductRepository;
import com.trade_accounting.services.interfaces.CorrectionProductService;
import com.trade_accounting.utils.mapper.CorrectionProductMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@Transactional
@RequiredArgsConstructor
public class CorrectionProductServiceImpl implements CorrectionProductService {
private final CorrectionProductRepository correctionProductRepository;
private final ProductRepository productRepository;
private final CorrectionProductMapper correctionProductMapper;
@Override
public List<CorrectionProductDto> getAll() {
return correctionProductRepository.findAll().stream()
.map(correctionProductMapper::toDto)
.collect(Collectors.toList());
}
@Override
public CorrectionProductDto getById(Long id) {
Optional<CorrectionProduct> correctionProduct = correctionProductRepository.findById(id);
return correctionProductMapper.toDto(correctionProduct.orElse(new CorrectionProduct()));
}
@Override
public CorrectionProductDto create(CorrectionProductDto dto) {
return saveOrUpdate(dto);
}
@Override
public CorrectionProductDto update(CorrectionProductDto dto) {
return saveOrUpdate(dto);
}
@Override
public void deleteById(Long id) {
correctionProductRepository.deleteById(id);
}
private CorrectionProductDto saveOrUpdate(CorrectionProductDto dto) {
Optional<Product> product = productRepository.findById(dto.getProductId());
CorrectionProduct correctionProduct = correctionProductMapper.toModel(dto);
correctionProduct.setProduct(product.orElse(null));
return correctionProductMapper.toDto(correctionProductRepository.save(correctionProduct));
}
}
| true
|
8d034063dd8e80a72070ede48cc8e39fa6f8671d
|
Java
|
Vastra-Gotalandsregionen/oppna-program-rp-pdl
|
/pdl/composites/svc/src/main/java/se/vgregion/service/pdl/Report.java
|
UTF-8
| 16,469
| 1.585938
| 2
|
[] |
no_license
|
package se.vgregion.service.pdl;
import org.apache.cxf.binding.soap.SoapFault;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.riv.ehr.blocking.accesscontrol.checkblocks.v2.rivtabp21.CheckBlocksResponderInterface;
import se.riv.ehr.blocking.accesscontrol.checkblocksresponder.v2.CheckBlocksRequestType;
import se.riv.ehr.blocking.accesscontrol.checkblocksresponder.v2.CheckBlocksResponseType;
import se.riv.ehr.patientconsent.accesscontrol.checkconsent.v1.rivtabp21.CheckConsentResponderInterface;
import se.riv.ehr.patientconsent.accesscontrol.checkconsentresponder.v1.CheckConsentRequestType;
import se.riv.ehr.patientconsent.accesscontrol.checkconsentresponder.v1.CheckConsentResponseType;
import se.riv.ehr.patientconsent.querying.getconsentsforpatient.v1.rivtabp21.GetConsentsForPatientResponderInterface;
import se.riv.ehr.patientconsent.querying.getconsentsforpatientresponder.v1.GetConsentsForPatientRequestType;
import se.riv.ehr.patientconsent.querying.getconsentsforpatientresponder.v1.GetConsentsForPatientResponseType;
import se.riv.ehr.patientrelationship.accesscontrol.checkpatientrelation.v1.rivtabp21.CheckPatientRelationResponderInterface;
import se.riv.ehr.patientrelationship.accesscontrol.checkpatientrelationresponder.v1.CheckPatientRelationRequestType;
import se.riv.ehr.patientrelationship.accesscontrol.checkpatientrelationresponder.v1.CheckPatientRelationResponseType;
import se.vgregion.domain.assignment.Assignment;
import se.vgregion.domain.decorators.WithBlock;
import se.vgregion.domain.decorators.WithInfoType;
import se.vgregion.domain.decorators.WithOutcome;
import se.vgregion.domain.pdl.*;
import se.vgregion.domain.systems.CareSystem;
import se.vgregion.events.context.Patient;
import se.vgregion.domain.pdl.PdlContext;
import javax.xml.ws.WebServiceException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class Report {
private static final Logger LOGGER = LoggerFactory.getLogger(Report.class);
private Report() {
// Utility class, no constructor!
}
static PdlReport generateReport(
final String servicesHsaId,
final PdlContext ctx,
final Patient patient,
final List<WithInfoType<CareSystem>> careSystems,
final CheckBlocksResponderInterface checkBlocks,
final GetConsentsForPatientResponderInterface getConsentsForPatient,
final CheckPatientRelationResponderInterface checkRelationship,
final ExecutorService executorService,
final Assignment currentAssignment
) {
// Start multiple requests
Future<WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>>> blocksFuture =
blocks(servicesHsaId, ctx, patient, careSystems, checkBlocks, executorService);
Future<WithOutcome<CheckedConsent>> consentFuture;
// TODO as soon as the deprecated method which sends null as currentAssigment this should be cleaned up.
// TODO I.e. currentAssigment is the only assignment to be used.
Assignment legacyCodeAssignment = currentAssignment != null ? currentAssignment : ctx.currentAssignment;
if (legacyCodeAssignment.isOtherProviders()) {
consentFuture =
consent(
servicesHsaId,
ctx,
patient.patientId,
getConsentsForPatient,
executorService
);
} else {
// Return dummy false value. This will not be used since the assignment is only within same care giver.
consentFuture = consentNotNeeded(executorService);
}
Future<WithOutcome<Boolean>> relationshipFuture =
relationship(servicesHsaId, ctx, patient.patientId, checkRelationship, executorService);
// Aggreagate results
WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>> checkedSystems =
blocksWithFallback(blocksFuture, careSystems, patient.patientId);
WithOutcome<CheckedConsent> checkedConsent =
consentWithFallback(consentFuture, patient.patientId);
WithOutcome<Boolean> hasRelationship;
// TODO This if-else should also be removed.
if (currentAssignment != null) {
boolean hasAnyRelationship = hasAnyPatientInfoInCurrentAssignmentUnit(careSystems, currentAssignment);
if (hasAnyRelationship) {
hasRelationship = WithOutcome.success(hasAnyRelationship);
} else {
hasRelationship = relationshipWithFallback(relationshipFuture, patient.patientId);
}
} else {
hasRelationship = relationshipWithFallback(relationshipFuture, patient.patientId);
}
return new PdlReport(checkedSystems, checkedConsent, hasRelationship);
}
private static boolean hasAnyPatientInfoInCurrentAssignmentUnit(List<WithInfoType<CareSystem>> careSystems, Assignment currentAssignment) {
boolean match = false;
outer:
for (WithInfoType<CareSystem> foundSystemsWithPatientInfo : careSystems) {
String currentHsaIdForUnitWithPatientInfo = foundSystemsWithPatientInfo.value.careUnitHsaId;
if (currentHsaIdForUnitWithPatientInfo.equals(currentAssignment.careUnitHsaId)) {
match = true;
break outer;
}
}
return match;
}
private static WithOutcome<Boolean> relationshipWithFallback(Future<WithOutcome<Boolean>> relationshipFuture, String patientId) {
WithOutcome<Boolean> hasRelationship = WithOutcome.clientError(true);
try {
hasRelationship = relationshipFuture.get();
} catch (InterruptedException e) {
LOGGER.error("Failed to fetch relationship for patientId {} during report generation. Using fallback response.", patientId, e);
} catch (ExecutionException e) {
LOGGER.error("Failed to fetch relationship for patientId {} during report generation. Using fallback response.", patientId, e);
} catch (WebServiceException e) {
LOGGER.error("Failed to fetch relationship for patientId {} during report generation. Using fallback response.", patientId, e);
hasRelationship = WithOutcome.commFailure(true);
} catch (SoapFault e) {
LOGGER.error("Failed to fetch relationship for patientId {} during report generation. Using fallback response.", patientId, e);
hasRelationship = WithOutcome.commFailure(true);
}
return hasRelationship;
}
private static WithOutcome<CheckedConsent> consentWithFallback(Future<WithOutcome<CheckedConsent>> consentFuture, String patientId) {
WithOutcome<CheckedConsent> checkedConsent = WithOutcome.clientError(
new CheckedConsent(PdlReport.ConsentType.Consent, true));
try {
checkedConsent = consentFuture.get();
} catch (InterruptedException e) {
LOGGER.error("Failed to fetch consent for patientId {} during report generation. Using fallback response.", patientId, e);
} catch (ExecutionException e) {
LOGGER.error("Failed to fetch consent for patientId {} during report generation. Using fallback response.", patientId, e);
} catch (WebServiceException e) {
LOGGER.error("Failed to fetch systems for patientId {} during report generation. Using fallback response.", patientId, e);
checkedConsent = WithOutcome.commFailure(
new CheckedConsent(PdlReport.ConsentType.Consent, true));
} catch (SoapFault e) {
LOGGER.error("Failed to fetch systems for patientId {} during report generation. Using fallback response.", patientId, e);
checkedConsent = WithOutcome.commFailure(
new CheckedConsent(PdlReport.ConsentType.Consent, true));
}
return checkedConsent;
}
private static WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>> blocksWithFallback(
Future<WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>>> blocksFuture,
List<WithInfoType<CareSystem>> careSystems, String patientId
) {
WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>> checkedBlocks =
WithOutcome.clientError(mapCareSystemsFallback(careSystems));
try {
checkedBlocks = blocksFuture.get();
} catch (InterruptedException e) {
LOGGER.error("Failed to fetch systems for patientId {} during report generation. Using fallback response.", patientId, e);
} catch (ExecutionException e) {
LOGGER.error("Failed to fetch systems for patientId {} during report generation. Using fallback response.", patientId, e);
} catch (WebServiceException e) {
LOGGER.error("Failed to fetch systems for patientId {} during report generation. Using fallback response.", patientId, e);
checkedBlocks = WithOutcome.commFailure(mapCareSystemsFallback(careSystems));
} catch (SoapFault e) {
LOGGER.error("Failed to fetch systems for patientId {} during report generation. Using fallback response.", patientId, e);
checkedBlocks = WithOutcome.commFailure(mapCareSystemsFallback(careSystems));
}
return checkedBlocks;
}
/**
* <p>Maps List<WithInfoType<CareSystem>> to List<WithInfoType<WithBlock<CareSystem>>>.</p>
* <p>None of the mapped care systems will have a block.</p>
*
* @param careSystems Care systems to map
* @return
*/
private static ArrayList<WithInfoType<WithBlock<CareSystem>>> mapCareSystemsFallback(
List<WithInfoType<CareSystem>> careSystems
) {
ArrayList<WithInfoType<WithBlock<CareSystem>>> fallbackSystems = new ArrayList<WithInfoType<WithBlock<CareSystem>>>();
for (WithInfoType<CareSystem> cs : careSystems) {
WithBlock<CareSystem> unblockedSystem = WithBlock.unblocked(cs.value);
WithInfoType<WithBlock<CareSystem>> infotypeWithFallbackBlock = cs.mapValue(unblockedSystem);
fallbackSystems.add(infotypeWithFallbackBlock);
}
return fallbackSystems;
}
static Future<WithOutcome<Boolean>> relationship(
final String servicesHsaId,
final PdlContext ctx,
final String patientId,
final CheckPatientRelationResponderInterface checkRelationship,
ExecutorService executorService
) {
Callable<WithOutcome<Boolean>> relationshipAsync = new Callable<WithOutcome<Boolean>>() {
public WithOutcome<Boolean> call() throws Exception {
return checkRelationship(servicesHsaId, ctx, patientId, checkRelationship);
}
};
return executorService.submit(relationshipAsync);
}
static Future<WithOutcome<CheckedConsent>> consent(
final String servicesHsaId,
final PdlContext ctx,
final String patientId,
final GetConsentsForPatientResponderInterface getConsentsForPatient,
ExecutorService executorService
) {
Callable<WithOutcome<CheckedConsent>> consentAsync = new Callable<WithOutcome<CheckedConsent>>() {
public WithOutcome<CheckedConsent> call() throws Exception {
return careProviderHasPatientConsent(servicesHsaId, ctx, patientId, getConsentsForPatient);
}
};
return executorService.submit(consentAsync);
}
// Sorry for all the brackets...
// This is a list of Care systems, each belonging to a specific information decorator.
// The response is from an external system. It can fail with fallback or succeed.
// This is all executed async.
static Future<WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>>> blocks(
final String servicesHsaId, final PdlContext ctx,
final Patient patient,
final List<WithInfoType<CareSystem>> careSystems,
final CheckBlocksResponderInterface checkBlocks,
final ExecutorService executorService
) {
Callable<WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>>> blocksAsync =
new Callable<WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>>>() {
public WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>> call() throws Exception {
return checkBlocks(servicesHsaId, ctx, patient, careSystems, checkBlocks);
}
};
return executorService.submit(blocksAsync);
}
static WithOutcome<Boolean> checkRelationship(
String regionalSecurityServicesHsaId,
PdlContext ctx,
String patientId,
CheckPatientRelationResponderInterface checkRelationship
) {
CheckPatientRelationRequestType request = Relationship.checkRelationshipRequest(ctx, patientId);
CheckPatientRelationResponseType relationshipResponse =
checkRelationship.checkPatientRelation(regionalSecurityServicesHsaId, request);
boolean relation = relationshipResponse.getCheckResultType().isHasPatientrelation();
return Relationship.decideOutcome(relationshipResponse.getCheckResultType().getResult(), relation);
}
static WithOutcome<ArrayList<WithInfoType<WithBlock<CareSystem>>>> checkBlocks(
String regionalSecurityServicesHsaId,
PdlContext ctx,
Patient patient,
List<WithInfoType<CareSystem>> careSystems,
CheckBlocksResponderInterface checkBlocks
) {
CheckBlocksRequestType request = Blocking.checkBlocksRequest(ctx, patient, careSystems);
CheckBlocksResponseType blockResponse =
checkBlocks.checkBlocks(regionalSecurityServicesHsaId, request);
ArrayList<WithInfoType<WithBlock<CareSystem>>> decoratedSystems = Blocking.decorateCareSystems(careSystems, blockResponse);
return Blocking.decideOutcome(blockResponse.getCheckBlocksResultType().getResult(), decoratedSystems);
}
static WithOutcome<CheckedConsent> checkConsent(
String regionalSecurityServicesHsaId,
PdlContext ctx,
String patientId,
CheckConsentResponderInterface checkConsent
) {
CheckConsentRequestType request = Consent.checkConsentRequest(ctx, patientId);
CheckConsentResponseType consentResponse =
checkConsent.checkConsent(regionalSecurityServicesHsaId, request);
CheckedConsent consent = Consent.asCheckedConsent(consentResponse);
return Consent.decideOutcome(consentResponse.getCheckResultType().getResult(), consent);
}
static WithOutcome<CheckedConsent> careProviderHasPatientConsent(
String regionalSecurityServicesHsaId,
PdlContext ctx,
String patientId,
GetConsentsForPatientResponderInterface getConsentsForPatient
) {
GetConsentsForPatientRequestType request = Consent.getConsentsForPatientRequest(ctx, patientId);
GetConsentsForPatientResponseType getConsentsForPatientResponse = getConsentsForPatient.getConsentsForPatient(
regionalSecurityServicesHsaId, request);
CheckedConsent consent = Consent.asCheckedConsent(getConsentsForPatientResponse);
return Consent.decideOutcome(getConsentsForPatientResponse.getGetConsentsResultType().getResult(), consent);
}
private static Future<WithOutcome<CheckedConsent>> consentNotNeeded(ExecutorService executorService) {
Future<WithOutcome<CheckedConsent>> consentFuture;
Callable<WithOutcome<CheckedConsent>> consentCallable =
new Callable<WithOutcome<CheckedConsent>>() {
public WithOutcome<CheckedConsent> call() {
return WithOutcome.success(new CheckedConsent(PdlReport.ConsentType.Consent, false));
}
};
consentFuture = executorService.submit(consentCallable);
return consentFuture;
}
}
| true
|
08276603e7f41e8a5c0467bfc95951203550ff3a
|
Java
|
robertcduvall/vooga-cps108-fall2010
|
/src/vooga/games/tictactoe/states/TheirTurnState.java
|
UTF-8
| 2,117
| 3.171875
| 3
|
[] |
no_license
|
package vooga.games.tictactoe.states;
import java.awt.Graphics2D;
import vooga.engine.core.Game;
import vooga.engine.core.PlayField;
import vooga.engine.networking.client.ClientConnection;
import vooga.engine.resource.Resources;
import vooga.engine.state.GameState;
/**
* GameState for when the player is waiting for the other player to play.
*
* @author Cue, Kolodziejzyk, Townsend
* @version 1.0
*/
public class TheirTurnState extends GameState{
private Game game;
private ClientConnection connection;
private PlayField field;
private PlayState playState;
private int checkDelay = 1;
/**
* Constructor for the GameState shown when it's the other player's turn.
*
* @param game Game to be able to switch GameStates
* @param connection ClientConnection to get the latest message from the socket
* @param field PlayField for TheirTurnState to render
* @param playState PlayState to switch to and pass the message whenever it gets a non "theirTurn" String from the socket
* @author Cue, Kolodziejzyk, Townsend
* @version 1.0
*/
public TheirTurnState(Game game, ClientConnection connection, PlayField field, PlayState playState){
this.game = game;
this.connection = connection;
this.field = field;
this.playState = playState;
}
/**
* If it receives a message from the socket that is not "theirTurn", then switch to the PlayState and tell the PlayState what the message was.
* checkDelay is a way around a rendering issue since render is called after update and thus would never be called if I block the main thread
* with the connection.getData() call.
* @author Cue, Kolodziejzyk, Townsend
* @version 1.0
*/
@Override
public void update(long t) {
if(checkDelay == 0){
String status = connection.getData();
if(!status.equals(Resources.getString("theirTurnString"))){
checkDelay = 1;
playState.setMessage(status);
game.getGameStateManager().switchTo(playState);
}
}
else{
checkDelay--;
}
}
@Override
public void render(Graphics2D g) {
super.render(g);
field.render(g);
}
@Override
public void initialize() {
}
}
| true
|
3ea08f606e2363bc4acca453f4741ab8ee83ba04
|
Java
|
EHassumer/CustomerDemo
|
/demo/src/main/java/com/edanur/demo/controller/AddressController.java
|
UTF-8
| 2,266
| 2.265625
| 2
|
[] |
no_license
|
package com.edanur.demo.controller;
import com.edanur.demo.web.dtomodel.AddressDto;
import com.edanur.demo.web.request.AddressRequest;
import com.edanur.demo.service.AddressService;
import com.edanur.demo.web.response.AddressResponse;
import com.edanur.demo.web.response.CustomerResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javassist.NotFoundException;
import lombok.RequiredArgsConstructor;
import org.dozer.DozerBeanMapper;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/address")
@Api(value = "Address Api documentation")
@RequiredArgsConstructor
public class AddressController {
private final AddressService addressService;
private final DozerBeanMapper mapper;
@GetMapping
@ApiOperation(value = "All addresses getting method")
public List<AddressResponse> getAllAddresses() {
return (addressService.getAllAddresses())
.stream()
.map(address -> mapper.map(address, AddressResponse.class))
.collect(Collectors.toList());
}
@GetMapping("/{addressId}")
@ApiOperation(value = "Getting a address with id")
public AddressResponse getAddress(@PathVariable int addressId){
return mapper.map(addressService.getAddressById(addressId),AddressResponse.class);
}
@PostMapping
@ApiOperation(value = "New Address creating method")
public AddressResponse createAddress(@RequestBody AddressRequest addressRequest){
return mapper.map(addressService.createAddress(addressRequest),AddressResponse.class);
}
@DeleteMapping("/{addressId}")
@ApiOperation(value = "Address deleting method")
public void deleteAddress(@PathVariable("addressId") int addressId) {
addressService.deleteAddress(addressId);
}
@PutMapping("/{addressId}")
@ApiOperation(value = "Address updating method")
public void updateAddress(@PathVariable("addressId") int addressId,
@RequestBody AddressRequest addressRequest){
addressService.updateAddress(addressId, addressRequest);
}
}
| true
|
68f0940b10edf76d2f46d2bd8cf29d940b03dc6e
|
Java
|
150719873/zhdt
|
/project-pipe-parent/module-parent/core-module-parent/pipe-core/src/main/java/com/dotop/pipe/core/vo/patrol/PatrolTaskTimerVo.java
|
UTF-8
| 1,601
| 1.945313
| 2
|
[] |
no_license
|
package com.dotop.pipe.core.vo.patrol;
import com.dotop.pipe.core.enums.CycleTemplateEnum;
import com.dotop.smartwater.dependence.core.common.pipe.BasePipeVo;
import com.dotop.smartwater.project.module.core.auth.vo.UserVo;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
import java.util.List;
@Data
@EqualsAndHashCode(callSuper = false)
public class PatrolTaskTimerVo extends BasePipeVo {
/**
* 定时任务id
*/
private String patrolTaskTimerId;
/**
* 绑定的路线id
*/
private String patrolRouteId;
/**
* 绑定的路线
*/
private PatrolRouteVo patrolRoute;
/**
* 处理人的id集合
*/
private List<String> handlerUserIds;
/**
* 处理人的集合(key:id,value:name)
*/
private List<UserVo> handlerUserMap;
/**
* 用于查询时间,初始时间
*/
private Date startDate;
/**
* 用于查询时间,结束时间
*/
private Date endDate;
/**
* 定时任务起始日期
*/
private Date basicTime;
/**
* 最后执行日期
*/
private Date lastTime;
/**
* 期限(天)
*/
private Integer limit;
/**
* 周期(天)
*/
private Integer cycle;
/**
* 发起间隔
*/
private CycleTemplateEnum cycleTemplate;
/**
* 已执行次数
*/
private Integer runTimes;
/**
* 状态(0:执行,1:不执行)
*/
private Integer status;
/**
* 限制执行次数
*/
private Integer limitTimes;
}
| true
|
072745f447a8938949477283aa688b1a05af4f49
|
Java
|
Jack-Iacono/Software-Dev-1
|
/Shipping.java
|
UTF-8
| 584
| 3.46875
| 3
|
[] |
no_license
|
package lab;
import java.util.Scanner;
public class Shipping {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please Enter Package Weight: ");
double weight = scan.nextDouble();
if(weight <= 2) {
System.out.print("Cost: $2.50");
}else if(weight <= 4) {
System.out.print("Cost: $4.50");
}else if(weight <= 10) {
System.out.print("Cost: $7.50");
}else if(weight <= 20) {
System.out.print("Cost: $10.50");
}else {
System.out.print("Package Cannot Be Shipped");
}
}
}
| true
|
c28300bc6014002258a99a3ca65a988a5c3b6604
|
Java
|
britobluis/programacion2
|
/TP Diagramas/clase030418_finalNov14/src/clase030418_finalnov14/Clase030418_finalNov14.java
|
UTF-8
| 2,568
| 3.140625
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clase030418_finalnov14;
import java.util.Date;
import java.text.*;
import javax.swing.JOptionPane;
/**
*
* @author Luis Brito
*/
public class Clase030418_finalNov14 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Creacion de Tarjeta de credito
Date fechaTarjeta1 = new Date();
//Dar mejor formato a fecha
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Tarjeta_de_Credito tarjeta1 = new Tarjeta_de_Credito(fechaTarjeta1, 35000);
System.out.println("El numero de la tarjeta es: $" + tarjeta1.getLimite() + " y fue creada el: " + sdf.format(tarjeta1.getFecha_Ingreso()));
Cliente cliente1 = new Cliente(1234567, "Pepe", "Perez", 1234567891011L);
//Agrega una tarjeta de credito a cliente1
cliente1.setCredit_Car(tarjeta1);
System.out.println("El cliente: " + cliente1.getNombre() + " " + cliente1.getApellido() + " DNI: " + cliente1.getDni() + " CUIT: " + cliente1.getCuit()
+ "\nTiene una tarjeta de credito con un limite de: $" + cliente1.getCredit_Car().getLimite()
+ " y fue creada el: " + sdf.format(cliente1.getCredit_Car().getFecha_Ingreso()));
//Crea un empleado
Date fechaIngresoEmpleado1 = new Date();
Empleado empleado1 = new Empleado(fechaIngresoEmpleado1, 55555, 31548969, "Ramon", "Rodriguez", 789456123789L);
//Crea un factura
Date fechaVenta1 = new Date();
Factura facturaVenta1 = new Factura(empleado1, cliente1, 777, fechaVenta1, 25000);
JOptionPane.showMessageDialog(null, "Factura Nro: " + facturaVenta1.getNro_Factura() + " Fecha: " + sdf.format(facturaVenta1.getFecha())
+ "\nVendedor: " + facturaVenta1.getEmp().getNombre() + " " + facturaVenta1.getEmp().getApellido() + " Legajo: " + facturaVenta1.getEmp().getNro_Legajo()
+ "\nCliente: " + facturaVenta1.getClie().getNombre() + " " + facturaVenta1.getClie().getApellido() + " DNI: " + facturaVenta1.getClie().getDni()
+ "\nLimite Tarjeta de Credito: $" + facturaVenta1.getClie().getCredit_Car().getLimite()
+ "\nMonto a pagar: $" + facturaVenta1.getMonto() + "\nPAGO ACEPTADO.");
}
}
| true
|
5ae0ea1b8cf949e46a38ef7a395171f12f8574e9
|
Java
|
OFactory/SchokoFactory
|
/src/de/OFactory/SchokoFactory/game/Map.java
|
ISO-8859-1
| 10,976
| 2.9375
| 3
|
[] |
no_license
|
package de.OFactory.SchokoFactory.game;
import java.util.ArrayList;
import org.newdawn.slick.GameContainer;
import de.OFactory.SchokoFactory.game.patterns.Wiese;
import de.OFactory.SchokoFactory.main.MainState;
import de.OFactory.SchokoFactory.main.Updateable;
public class Map extends ArrayList<Pattern> implements Updateable{
private static final long serialVersionUID = 1L;
private int height;
private int width;
public Pattern hoveredpattern; //Gehoverter Pattern
public Pattern clicked; //Geklickter Pattern
public Pattern selected_pattern = null; // ausgewhltes Pattern
//TODO Info ADDEN
public Map(){
super();
}
public void update(GameContainer gc) {
if(clicked != null){ // Clicked Pattern
if(MainState.curpatternstate == null){ // Kein Gebude ausgewhlt: nur Auswahlmglichkeit
if(clicked instanceof Wiese) {
selected_pattern = null; // keine Auswahl beim Klicken auf leeres Feld
} else {
selected_pattern = clicked; // Gebude auswhlen
MainState.ip.switchTab(0); // Tab wechseln
}
} else {
if(clicked instanceof Wiese){ //Feld "leer" ( = Wiese)
if(MainState.curpatternstate != PatternState.WIESE) {
if (!(MainState.curpatternstate == PatternState.GIEER && MainState.p.getMoney() < 200)){
set(clicked.getId(), Pattern.getInstance(this, clicked.getX(), clicked.getY(), MainState.curpatternstate, clicked.getId(), clicked.getXCoordinate(), clicked.getYCoordinate()));
}
MainState.curpatternstate = null;
}
} else { //Feld hat ein Gebude
if(MainState.curpatternstate == PatternState.WIESE) //Gebude entfernen (-> Wiese)
set(clicked.getId(), new Wiese(clicked.getX(), clicked.getY(), clicked.getId(), clicked.getXCoordinate(), clicked.getYCoordinate()));
else // Keine Wiese: Gebude Auswhlen
selected_pattern = clicked;
}
}
}
for(Pattern p : this) //jedes Pattern zeichnen
if(p != null)
p.update(gc);
// if(gc.getInput().isKeyPressed(Input.KEY_S)){
// saveMap();
// }
}
/** Erstellt ein Feld (=Liste) von Patterns aus einer Angebebenen Breite und Hhe
* mit folgenedem Schema:
*
* h = 3 | w = 3
* 0
* 1 2
* 3 4 5
* 6 7
* 8
*
* @param int pattern_width | Breite des Feldes
* @param int pattern_height | Hhe des Feldes
* @return Map ps | Das Feld bestehend aus Pattern
*/
public static Map generateMap(int pattern_width, int pattern_height) {
int i = 0;
Map ps = new Map();
ps.setHeight(pattern_height);
ps.setWidth(pattern_width);
int grid_width = 0; // Anzahl Spalten in nter Reihe
int xcoor = 1;
int ycoor = 1;
for(int y = 0; y < (pattern_width+1)*2-1; y++){ // fr jede Reihe
if(y >= pattern_width+1){ // nte Reihe erreicht(max width)
grid_width--;
xcoor = pattern_width;// muss bei bugfix(pattern_width ist immer 1 grer) gendert werden
ycoor = y - pattern_height+1; //spter nur noch +1
} else {
grid_width = y;
xcoor = y;
ycoor = 1;
}
for(int x = 0; x < grid_width; x++){ // fr jede Spalte
Wiese w = new Wiese( (int) ( x*MainState.TEXTURE_WIDTH * MainState.curpatternscale +//Normal Placement
( ((pattern_width+1)-grid_width)*MainState.TEXTURE_WIDTH * MainState.curpatternscale ) / 2 - //Verschiebung durch Anzahl Patterns in Reihe
(pattern_width+1)*MainState.TEXTURE_WIDTH*MainState.curpatternscale / 3),
(int) ( y*MainState.TEXTURE_HEIGHT * MainState.curpatternscale - //Normal Placement
(pattern_height+1)*MainState.TEXTURE_HEIGHT * MainState.curpatternscale / 1.5),
i, xcoor, ycoor ); // i = ID
ps.add(w);
if (y >= pattern_width+1) {
xcoor--;
ycoor++;
} else {
xcoor--;
ycoor++;
}
i++;
}
}
return ps;
}
/**
* Restrukturiert
*
* @param curpatternscale Skalierung
*/
public void restructureMap(float curpatternscale){
int grid_width = 0; // Anzahl Spalten in nter Reihe
int i = 0;
for(int y = 0; y < this.getWidth()*2-1; y++){ // fr jede Reihe
if(y >= this.getHeight()){ // nte Reihe erreicht(max width)
grid_width--;
} else {
grid_width = y;
}
for(int x = 0; x < grid_width; x++){ // fr jede Spalte
this.get(i).setX( (int) ( x*MainState.TEXTURE_WIDTH * curpatternscale +//Normal Placement
( (this.getWidth()-grid_width)*MainState.TEXTURE_WIDTH * curpatternscale ) / 2 - //Verschiebung durch Anzahl Patterns in Reihe
this.getWidth()*MainState.TEXTURE_WIDTH*curpatternscale / 3));
this.get(i).setY((int) ( y*MainState.TEXTURE_HEIGHT * curpatternscale - //Normal Placement
this.getHeight()*MainState.TEXTURE_HEIGHT * curpatternscale / 1.5));
i++;
}
}
}
/**
* Zoomt eine Map an die eine bestimmte Stelle (zx,zy) heran bzw. heraus.
* Hierbei kommt es darauf an, ob currpatternscale grer oder kleiner als die vorhergegangene Skalierung ist,
* und ob die Map herangezoomt bzw. herausgezoomt werden soll.
* Hierbei bewegen sich alle Pattern gleichmig um die Zoomstelle herum,
* hnlich wie die Pixel bei der Zoom-Funktion von Bildern.
*
* @param curpatternscale Skalierung
* @param zx X-Position des Zoom-Punktes
* @param zy Y-Position des Zoom-Punktes
*/
public void zoomMap(double in_scale, int zx, int zy){
double scale = -in_scale;
for(Pattern p: this){
int rel_x = zx - p.getX();
int rel_y = zy - p.getY();
p.setX(p.getX() + (int) Math.round(rel_x*scale));
p.setY(p.getY() + (int) Math.round(rel_y*scale));
}
}
/** Strukturiert ein Feld mit bergabe eines Arrays aus PatternStates
* mit folgendem Format: (siehe auch generateMap(int, int))
*
* h = 3 | w = 3
* 0
* 1 2
* 3 4 5
* 6 7
* 8
*
* @param ArrayList<PatternState> ps | Liste von PatternStates fr die Map
* @return Map m | Das Feld bestehend aus Pattern
*/
public static Map structureMap(ArrayList<PatternState> ps) {
int i = 0;
int pattern_width = (int) Math.sqrt(ps.size()) + 1;
int pattern_height = (int) Math.sqrt(ps.size()) + 1;
Map m = new Map();
m.setWidth(pattern_width - 1);
m.setHeight(pattern_height - 1);
int xcoor = 1;
int ycoor = 1;
int grid_width = 0; // Anzahl Spalten in nter Reihe
for(int y = 0; y < pattern_width*2-1; y++){ // fr jede Reihe
if(y >= pattern_width){ // nte Reihe erreicht(max width)
grid_width--;
xcoor = pattern_width-1;
ycoor = y - pattern_height+2;
} else {
grid_width = y;
xcoor = y;
ycoor = 1;
}
for(int x = 0; x < grid_width; x++){ // fr jede Spalte
int px = (int) ( x*MainState.TEXTURE_WIDTH * MainState.curpatternscale +//Normal Placement
( (pattern_width-grid_width)*MainState.TEXTURE_WIDTH * MainState.curpatternscale ) / 2 - //Verschiebung durch Anzahl Patterns in Reihe
pattern_width*MainState.TEXTURE_WIDTH*MainState.curpatternscale / 3);
int py = (int) ( y*MainState.TEXTURE_HEIGHT * MainState.curpatternscale - //Normal Placement
pattern_height*MainState.TEXTURE_HEIGHT * MainState.curpatternscale / 1.5);
Pattern p = null;
PatternState state = ps.get(i);
p = Pattern.getInstance(m, px, py, state, i, xcoor, ycoor);
//TODO Alle anderen PatternStates adden! Allgemeinde Methode
m.add(p);
i++;
if (y >= pattern_width) {
xcoor--;
ycoor++;
} else {
xcoor--;
ycoor++;
}
}
}
return m;
}
// /** Gibt den Speicherstring zurck.
// *
// * @return Str sb = der Sepicherstring. Format (WIP)
// */
// public String getSaveString(){
// StringBuilder sb = new StringBuilder("");
// //TODO ordentlich encrypten
// sb.append(name + " " /*+ lastedit + " " + height + " " + width + " "*/);
//
// for(Pattern p : this){
// //sb.append(Long.toBinaryString(p.getPatternState().getId()) + " "); Binary could be an Option #SOVIELEMGLICHKEITEN
// sb.append(p.getPatternState().getId() + " ");
// }
//
// return sb.toString();
// }
// public void saveMap(){
// saveMap(Map.SAVE_PATH_DIR + "/" + name + ".sf");
// }
// /** Speichert die Map im angebenem Dateipfad
// * in Form des mapstring-Formats(siehe getSaveString())
// *
// * @param String path | Dateipfad
// * @return Map m | Die ausgelesene Karte(Speicherstand)
// */
// public void saveMap(String path){
//
// System.out.println("Saving Map \"" + name + "\" to \"" + path + "\"...");
//
// File f = new File(path);
//
// try {
//
// FileWriter fw = new FileWriter(f);
// fw.write(this.getSaveString());
// fw.close();
// System.out.println("Succesfully saved Map \"" + name + "\"!");
//
// } catch (IOException e) {
// System.err.println("ERROR <003>: Datei \"" + path + "\" konnte nicht gefunden werden!");
// e.printStackTrace();
// }
// }
public String toString(){
return "Map(size= " + this.getWidth() + "*" + this.getHeight() + ")"; //Bsp. Map[name=test; ArrayList[Pattern....]]
}
// STATIC
// /** Liest eine Karte(Speicherstand) aus einem angebebenem String
// *
// * @param String mapstring | Der String der Map
// * @return Map m | Die ausgelesene Karte(Speicherstand)
// * @return null, wenn der MapString inkorrekt ist!
// */
// public static Map readMap(String mapstring){
// String name = "";
// ArrayList<PatternState> ps = new ArrayList<PatternState>();
//
// String[] mapstrings = mapstring.split(" ");
//
// for(String s : mapstrings){
// if( GameUtils.isNumeric(s) ){
// ps.add(PatternState.getById(Long.parseLong(s)));
//
// } else {
// name = s;
// }
// }
//
// Map m = Map.structureMap(ps); //Strukturieren
// m.setName(name);
//
//
// return m;
// }
// /** Liest eine Karte(Speicherstand) aus einer angebebenen Datei heraus
// *
// * @param path | Der Dateipfad der Datei
// * @return Map map | Die ausgelesene Karte(Speicherstand)
// * @return null, wenn die Datei inkorrekt ist!
// */
// public static Map readSavedMap(String path){
// File f = new File(path);
// System.out.println("Reading " + path + " ...");
// String mapstring = null;
//
// try {
//
// BufferedReader br = new BufferedReader(new FileReader(f));
// mapstring = br.readLine();
//
// br.close();
//
// } catch (IOException e) {
// System.err.println("ERROR <003>: Datei \"" + path + "\" konnte nicht gefunden werden!");
// e.printStackTrace();
// }
//
//
//
// return readMap(mapstring);
// }
// Getter und Setter
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
}
| true
|
e72220c370cfab8f8c3da3fcf309968d985f6a29
|
Java
|
aiscy/botrino
|
/command/src/main/java/botrino/command/CommandEventProcessor.java
|
UTF-8
| 4,153
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
/*
* This file is part of the Botrino project and is licensed under the MIT license.
*
* Copyright (c) 2020 Alexandre Miranda
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package botrino.command;
import botrino.api.config.object.I18nConfig;
import botrino.command.config.CommandConfig;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.User;
import reactor.core.publisher.Mono;
import java.util.Locale;
/**
* Allows to perform some preliminary processing on the message create events received from the command service
* subscription. This includes filtering events early, and determining the prefix and the locale adapted to the event.
*/
public interface CommandEventProcessor {
/**
* A {@link CommandEventProcessor} that only filters bot accounts and that always uses the default prefix and
* locale.
*/
CommandEventProcessor NO_OP = new CommandEventProcessor() {
@Override
public String toString() {
return "CommandEventProcessor.NO_OP";
}
};
/**
* Allows to filter {@link MessageCreateEvent} instances to prevent the execution of commands in some arbitrary
* situations. If the filter doesn't pass, the event is effectively dropped. The filter is applied before any
* processing on the event is performed (tokenization, localization, privilege/scope checks...). By default, the
* filter is set to drop events from bot accounts and webhooks, and allow everything else.
*
* @param event the event to filter
* @return a {@link Mono} emitting {@code true} if the event should be accepted, and either {@code false} or empty
* if the event should be dropped. If an error occurs, it will be logged then the event will be dropped.
*/
default Mono<Boolean> filter(MessageCreateEvent event) {
return Mono.just(!event.getMessage().getAuthor().map(User::isBot).orElse(true));
}
/**
* Determines the prefix to use in order for the given event to be recognized as a command. By default, it completes
* empty which indicates to use the default prefix as defined by {@link CommandConfig#prefix()}.
*
* @param event the event to find the prefix for
* @return a {@link Mono} emitting the prefix appropriate for the event. Empty will use the default prefix. If an
* error occurs, it will be logged then the event will be dropped.
*/
default Mono<String> prefixForEvent(MessageCreateEvent event) {
return Mono.empty();
}
/**
* Determines the locale to use for interactions following the given event. By default, it completes empty which
* indicates to use the default locale as defined by {@link I18nConfig#defaultLocale()}.
*
* @param event the event to find the locale for
* @return a {@link Mono} emitting the locale appropriate for the event. Empty will use the default locale. If an
* error occurs, it will be logged then the event will be dropped.
*/
default Mono<Locale> localeForEvent(MessageCreateEvent event) {
return Mono.empty();
}
}
| true
|
a5d996803943ba966af0d60d16833774037a0d06
|
Java
|
zhudaihao/SafeLogin-master
|
/app/src/main/java/com/ks/safe/login/lockpattern/PatternLockActivity.java
|
UTF-8
| 3,757
| 2.28125
| 2
|
[] |
no_license
|
package com.ks.safe.login.lockpattern;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;
import com.ks.safe.login.R;
import com.ks.safe.login.lockpattern.view.PatternLockView;
import com.ks.safe.login.lockpattern.view.PatternViewLintener;
/**
* 图案解锁
* Created by sgffsg on 17/4/24.
*/
public class PatternLockActivity extends AppCompatActivity implements Runnable {
private PatternLockView patternLockView;
private TextView tvTip;
private String password;
private String type;
private SPUtils spUtils;
private int num = 1;
private int maxNum = 4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pattern_lock);
patternLockView = (PatternLockView) findViewById(R.id.patternlockview);
tvTip = (TextView) findViewById(R.id.tv_tip);
spUtils = new SPUtils(this, "patternPSW");
type = getIntent().getStringExtra("type");
if ("open".equals(type)) {
String psw = spUtils.getString("password");
if (!TextUtils.isEmpty(psw) && psw.length() > 3) {
patternLockView.setPassword(psw);
} else {
patternLockView.setIsSetting(true);
}
} else {
patternLockView.setIsSetting(true);
}
tvTip.setText("请输入手势");
patternLockView.setPatternViewListener(new PatternViewLintener() {
@Override
public void onSuccess() {
if (num <= maxNum) {
onBackPressed();
}
}
@Override
public void onSet(String psw) {
if (!TextUtils.isEmpty(psw)) {
if (TextUtils.isEmpty(password)) {
password = psw;
tvTip.setText("再次输入手势");
} else {
if (password.equals(psw)) {
tvTip.setText("设置成功");
spUtils.put("password", password);
onBackPressed();
} else {
password = "";
tvTip.setText("两次手势不一致");
}
}
}
}
@Override
public void onError() {
if (num < maxNum) {
tvTip.setText("手势密码错误,还可以输入" + (maxNum - num) + "次");
num++;
} else {
tvTip.setText("锁定30秒");
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// tvTip.setText("请输入手势");
// num = 1;
// }
// }, 30000);
//
}
}
});
}
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
@Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("type", type);
setResult(RESULT_OK, intent);
finish();
}
int timer = 30;
@Override
public void run() {
if (num >= maxNum) {
tvTip.setText("锁定" + timer + "秒");
timer--;
} else {
timer = 30;
}
}
}
| true
|
12677b6819ec9c2c336c785fe002edc8c238a00e
|
Java
|
emoalb/JAVADB
|
/_03_introduction_to_hibernate_skeleton/src/main/java/RemoveTowns/RemoveTowns.java
|
UTF-8
| 1,954
| 3.046875
| 3
|
[] |
no_license
|
package RemoveTowns;
import entities.Town;
import interfaces.Executable;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import java.util.Scanner;
public class RemoveTowns implements Executable {
private final String getTownQuery = "FROM Town WHERE name = :name";
private final String deleteAddressesQuery = "DELETE Address WHERE town.id= :id";
private final String deleteTownsQuery = "DELETE Town WHERE id= :id";
private EntityManager entityManager;
private Scanner console;
public RemoveTowns(EntityManager entityManager, Scanner console) {
this.entityManager = entityManager;
this.console = console;
}
@Override
public void execute() {
String name = this.console.nextLine();
this.entityManager.getTransaction().begin();
try {
Town town = entityManager.createQuery(this.getTownQuery, Town.class).setParameter("name", name).getSingleResult();
this.entityManager.getTransaction().commit();
this.entityManager.getTransaction().begin();
int deleteAddressCount = this.entityManager.createQuery(this.deleteAddressesQuery).setParameter("id", town.getId()).executeUpdate();
this.entityManager.getTransaction().commit();
this.entityManager.getTransaction().begin();
int deleteTownCount = this.entityManager.createQuery(this.deleteTownsQuery).setParameter("id", town.getId()).executeUpdate();
this.entityManager.getTransaction().commit();
String address = deleteAddressCount == 1 ? "address" : "addresses";
System.out.printf("%d %s in %s deleted", deleteAddressCount, address, town.getName()).println();
} catch (NoResultException e) {
System.out.println("No such town was found!");
this.entityManager.getTransaction().commit();
}
}
}
| true
|
0c81468e2efe2e2119c69b6617d009b8d0592261
|
Java
|
ikluev/bindingTest
|
/com/test/mopub_ios_sdk/MPAdView.java
|
UTF-8
| 3,907
| 1.546875
| 2
|
[] |
no_license
|
package com.test.mopub_ios_sdk;
import com.intel.inde.moe.natj.general.NatJ;
import com.intel.inde.moe.natj.general.Pointer;
import com.intel.inde.moe.natj.general.ann.ByValue;
import com.intel.inde.moe.natj.general.ann.Generated;
import com.intel.inde.moe.natj.general.ann.Library;
import com.intel.inde.moe.natj.general.ann.Mapped;
import com.intel.inde.moe.natj.general.ann.MappedReturn;
import com.intel.inde.moe.natj.general.ann.NInt;
import com.intel.inde.moe.natj.general.ann.Owned;
import com.intel.inde.moe.natj.general.ann.Runtime;
import com.intel.inde.moe.natj.objc.ObjCRuntime;
import com.intel.inde.moe.natj.objc.ann.ObjCClassBinding;
import com.intel.inde.moe.natj.objc.ann.Selector;
import com.intel.inde.moe.natj.objc.map.ObjCObjectMapper;
import com.test.mopub_ios_sdk.protocol.MPAdViewDelegate;
import ios.coregraphics.struct.CGRect;
import ios.coregraphics.struct.CGSize;
import ios.corelocation.CLLocation;
import ios.foundation.NSCoder;
import ios.uikit.UIView;
@Generated
@Library("mopub_ios_sdk")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class MPAdView extends UIView {
static {
NatJ.register();
}
@Generated
protected MPAdView(Pointer peer) {
super(peer);
}
@Generated
@Selector("adContentViewSize")
@ByValue
public native CGSize adContentViewSize();
@Generated
@Selector("adUnitId")
public native String adUnitId();
@Generated
@Owned
@Selector("alloc")
public static native MPAdView alloc();
@Generated
@Selector("allowedNativeAdsOrientation")
public native int allowedNativeAdsOrientation();
@Generated
@Selector("delegate")
@MappedReturn(ObjCObjectMapper.class)
public native MPAdViewDelegate delegate();
@Generated
@Selector("forceRefreshAd")
public native void forceRefreshAd();
@Generated
@Selector("init")
public native MPAdView init();
@Generated
@Selector("initWithAdUnitId:size:")
public native MPAdView initWithAdUnitIdSize(String adUnitId,
@ByValue CGSize size);
@Generated
@Selector("initWithCoder:")
public native MPAdView initWithCoder(NSCoder aDecoder);
@Generated
@Selector("initWithFrame:")
public native MPAdView initWithFrame(@ByValue CGRect frame);
@Generated
@Selector("isTesting")
public native boolean isTesting();
@Generated
@Selector("keywords")
public native String keywords();
@Generated
@Selector("loadAd")
public native void loadAd();
@Generated
@Selector("location")
public native CLLocation location();
@Generated
@Selector("lockNativeAdsToOrientation:")
public native void lockNativeAdsToOrientation(int orientation);
@Generated
@Selector("rotateToOrientation:")
public native void rotateToOrientation(@NInt long newOrientation);
@Generated
@Selector("setAdUnitId:")
public native void setAdUnitId(String value);
@Generated
@Selector("setDelegate:")
public native void setDelegate_unsafe(
@Mapped(ObjCObjectMapper.class) MPAdViewDelegate value);
@Generated
public void setDelegate(
@Mapped(ObjCObjectMapper.class) MPAdViewDelegate value) {
Object __old = delegate();
if (value != null) {
com.intel.inde.moe.natj.objc.ObjCRuntime.associateObjCObject(this,
value);
}
setDelegate_unsafe(value);
if (__old != null) {
com.intel.inde.moe.natj.objc.ObjCRuntime.dissociateObjCObject(this,
__old);
}
}
@Generated
@Selector("setKeywords:")
public native void setKeywords(String value);
@Generated
@Selector("setLocation:")
public native void setLocation(CLLocation value);
@Generated
@Selector("setTesting:")
public native void setTesting(boolean value);
@Generated
@Selector("startAutomaticallyRefreshingContents")
public native void startAutomaticallyRefreshingContents();
@Generated
@Selector("stopAutomaticallyRefreshingContents")
public native void stopAutomaticallyRefreshingContents();
@Generated
@Selector("unlockNativeAdsOrientation")
public native void unlockNativeAdsOrientation();
}
| true
|
8d9ed0d248b773e6a3c56c7b44588aa423465a01
|
Java
|
srinivasp94/certification
|
/PegasysHMIS/app/src/main/java/com/example/pegasys/pegasyshmis/model/Records.java
|
UTF-8
| 578
| 2.109375
| 2
|
[] |
no_license
|
package com.example.pegasys.pegasyshmis.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* Created by pegasys on 5/28/2018.
*/
public class Records {
@SerializedName("filename")
@Expose
public String filename;
@SerializedName("filepath")
@Expose
public String filepath;
@Override
public String toString() {
return new ToStringBuilder(this).append("filename", filename).append("filepath", filepath).toString();
}
}
| true
|
787580d7b66c39b7cd853ccc4645431f9ca9a2e8
|
Java
|
AAFC-BICoE/object-store-api
|
/src/main/java/ca/gc/aafc/objectstore/api/service/ObjectOrphanRemovalService.java
|
UTF-8
| 3,730
| 2.390625
| 2
|
[
"MIT"
] |
permissive
|
package ca.gc.aafc.objectstore.api.service;
import ca.gc.aafc.dina.jpa.BaseDAO;
import ca.gc.aafc.objectstore.api.OrphanRemovalConfiguration;
import ca.gc.aafc.objectstore.api.entities.Derivative;
import ca.gc.aafc.objectstore.api.entities.ObjectStoreMetadata;
import ca.gc.aafc.objectstore.api.entities.ObjectUpload;
import ca.gc.aafc.objectstore.api.minio.MinioFileService;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.List;
@Service
@Log4j2
public class ObjectOrphanRemovalService {
private static final int MAX_ORPHAN_QUERY_LIMIT = 1000;
private final ObjectUploadService objectUploadService;
private final MinioFileService fileService;
private final BaseDAO baseDAO;
private final OrphanRemovalConfiguration.OrphanRemovalExpirationSetting expiration;
public ObjectOrphanRemovalService(
ObjectUploadService objectUploadService,
MinioFileService fileService,
BaseDAO baseDAO,
OrphanRemovalConfiguration orphanRemovalConfiguration
) {
this.objectUploadService = objectUploadService;
this.fileService = fileService;
this.baseDAO = baseDAO;
this.expiration = orphanRemovalConfiguration.getExpiration();
}
// Default cron expression '-' as default value will disable execution
@Scheduled(cron = "${orphan-removal.cron.expression:-}")
@Transactional
public void removeObjectOrphans() {
List<ObjectUpload> orphans = findOrphans();
orphans.forEach(objectUpload -> {
if (isExpired(objectUpload)) {
deleteUpload(objectUpload);
deleteMinioFile(objectUpload);
}
});
}
/**
* Returns all Object Uploads that have no matching file identifiers associated with Derivatives or
* ObjectStoreMetadata. ObjectUpload.fileIdentifier NOT IN Derivatives.fileIdentifier AND
* ObjectStoreMetadata.fileIdentifier.
*
* @return all Object Uploads that have no matching file identifiers associated with Derivatives or
* ObjectStoreMetadata.
*/
private List<ObjectUpload> findOrphans() {
String sql =
"SELECT ou " +
"FROM " + ObjectUpload.class.getCanonicalName() + " ou " +
"LEFT JOIN " + ObjectStoreMetadata.class.getCanonicalName() + " m ON ou.fileIdentifier = m.fileIdentifier " +
"LEFT JOIN " + Derivative.class.getCanonicalName() + " d ON ou.fileIdentifier = d.fileIdentifier " +
"WHERE m.fileIdentifier IS NULL AND d.fileIdentifier IS NULL";
return baseDAO.resultListFromQuery(
ObjectUpload.class,
sql,
0,
MAX_ORPHAN_QUERY_LIMIT,
null);
}
private boolean isExpired(ObjectUpload upload) {
LocalDateTime uploadDate = upload.getCreatedOn().toLocalDateTime();
LocalDateTime expiration;
if (this.expiration == null || this.expiration.getObjectMaxAge() == null) {
expiration = uploadDate.plusWeeks(1);
} else {
expiration = uploadDate.plusSeconds(this.expiration.getObjectMaxAge().getSeconds());
}
return LocalDateTime.now().isAfter(expiration);
}
private void deleteUpload(ObjectUpload objectUpload) {
objectUploadService.delete(objectUpload);
log.info("object upload with file identifier: "
+ objectUpload.getFileIdentifier().toString() + " has been removed");
}
@SneakyThrows
private void deleteMinioFile(ObjectUpload objectUpload) {
String fileName = objectUpload.getCompleteFileName();
fileService.removeFile(
objectUpload.getBucket(),
fileName,
objectUpload.getIsDerivative());
log.info(fileName + " removed from minio");
}
}
| true
|
3e648dd677e85d7d4dd88e7fb094a3a2a6bf3ae6
|
Java
|
gabrielfelipeoliveira/Transpetweb
|
/Transpetweb/src/main/java/modelo/dao/veiculo/VeiculoDAOSGDBImpl.java
|
UTF-8
| 1,473
| 2.359375
| 2
|
[] |
no_license
|
package modelo.dao.veiculo;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import modelo.dao.GenericoJPADAO;
import modelo.entidade.usuario.motorista.Motorista;
import modelo.entidade.veiculo.Veiculo;
import modelo.factory.conexao.ConexaoFactory;
public class VeiculoDAOSGDBImpl extends GenericoJPADAO{
public VeiculoDAOSGDBImpl(Class<Veiculo> classe) {
super(classe);
}
ConexaoFactory fabrica = new ConexaoFactory();
public List<Veiculo> listarAnimalPorIdMotorista(Motorista motorista) {
Session sessao = null;
List<Veiculo> veiculos = null;
try {
sessao = fabrica.getConexao().openSession();
sessao.beginTransaction();
CriteriaBuilder construtor = sessao.getCriteriaBuilder();
CriteriaQuery<Veiculo> criteria = construtor.createQuery(Veiculo.class);
Root<Veiculo> raiz = criteria.from(Veiculo.class);
criteria.where(construtor.equal(raiz.get("motoristaVeiculo"), motorista.getIdUsuario()));
criteria.select(raiz);
veiculos = sessao.createQuery(criteria).getResultList();
sessao.getTransaction().commit();
} catch (Exception sqlException) {
sqlException.printStackTrace();
if (sessao.getTransaction() != null) {
sessao.getTransaction().rollback();
}
} finally {
if (sessao != null) {
sessao.close();
}
}
return veiculos;
}
}
| true
|
b805a767bd14a236ba4531e71eef8d54a91ec7e4
|
Java
|
Yuzunyannn/ElementalSorcery
|
/src/main/java/yuzunyannn/elementalsorcery/elf/edifice/EFloorPostOffice.java
|
UTF-8
| 4,262
| 2.109375
| 2
|
[] |
no_license
|
package yuzunyannn.elementalsorcery.elf.edifice;
import java.util.List;
import java.util.Random;
import net.minecraft.block.BlockLeaves;
import net.minecraft.block.BlockStainedGlass;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import yuzunyannn.elementalsorcery.api.ESObjects;
import yuzunyannn.elementalsorcery.elf.pro.ElfProfession;
import yuzunyannn.elementalsorcery.entity.elf.EntityElfBase;
import yuzunyannn.elementalsorcery.tile.TileElfTreeCore;
public class EFloorPostOffice extends ElfEdificeFloor {
@Override
public NBTTagCompound createBuildData(IBuilder builder, Random rand) {
return new NBTTagCompound();
}
@Override
public int getFloorHeight(IBuilder builder) {
return 4;
}
@Override
public int getInvestWeight() {
return 50;
}
@Override
public int getMaxCountInTree(TileElfTreeCore core) {
return 1;
}
@Override
public void build(IBuilder builder) {
BlockPos pos = builder.getFloorBasicPos();
int treeSize = builder.getEdificeSize();
BuilderHelper helper = new BuilderHelper(builder);
int high = this.getFloorHeight(builder);
// 地毯
helper.genCarpet(EnumDyeColor.GREEN);
IBlockState PLANK = helper.blockPlank();
IBlockState GLASS = Blocks.STAINED_GLASS.getDefaultState().withProperty(BlockStainedGlass.COLOR,
EnumDyeColor.GRAY);
{
// 中心台子
int size = 4;
for (int y = 0; y < 3; y++) {
for (int i = -size + 1; i < size; i++) {
int n = GenElfEdifice.getFakeCircleLen(size, i, 2);
IBlockState state = PLANK;
if (y == 1) {
if (Math.abs(i) <= 1) {
if (i == 0) continue;
else state = GLASS;
}
} else if (y == 2) {
if (i % 2 != 0) state = PLANK;
else state = GLASS;
}
builder.setBlockState(pos.add(i, y, n), state);
builder.setBlockState(pos.add(i, y, -n), state);
builder.setBlockState(pos.add(n, y, i), state);
builder.setBlockState(pos.add(-n, y, i), state);
}
}
// 吊灯
int n = GenElfEdifice.getFakeCircleLen(size, 0, 2);
helper.genLamp(pos.add(n, high - 1, 0), 0);
helper.genLamp(pos.add(-n, high - 1, 0), 0);
helper.genLamp(pos.add(0, high - 1, n), 0);
helper.genLamp(pos.add(0, high - 1, -n), 0);
}
// 后面一排树叶
{
IBlockState LEAF = ESObjects.BLOCKS.ELF_LEAF.getDefaultState().withProperty(BlockLeaves.DECAYABLE, false);
IBlockState GLOWSTONE = Blocks.GLOWSTONE.getDefaultState();
int size = treeSize;
for (int y = 0; y < 1; y++) {
for (int i = -size + 1; i < size; i++) {
int n = GenElfEdifice.getFakeCircleLen(size, i, 2) - 1;
IBlockState state = LEAF;
int test = Math.abs(i);
if (test == size - 1 || test == 0) state = GLOWSTONE;
builder.setBlockState(pos.add(i, y, n), state);
builder.setBlockState(pos.add(i, y, -n), state);
builder.setBlockState(pos.add(n, y, i), state);
builder.setBlockState(pos.add(-n, y, i), state);
}
}
}
}
@Override
public void surprise(IBuilder builder, Random rand) {
}
@Override
public void spawn(IBuilder builder) {
BuilderHelper helper = new BuilderHelper(builder);
TileElfTreeCore core = helper.treeCore();
if (core == null) return;
// 接待员
List<EntityElfBase> elfs = EFloorHall.getFloorElf(builder, ElfProfession.POST_RECEPTIONIST);
if (elfs.size() < 4) {
BlockPos pos = builder.getFloorBasicPos();
int size = 4;
for (int y = 0; y < 3; y++) {
int n = GenElfEdifice.getFakeCircleLen(size, 0, 2) + 1;
EFloorHall.trySpawnElfAt(builder, ElfProfession.POST_RECEPTIONIST, pos.add(0, y, n));
EFloorHall.trySpawnElfAt(builder, ElfProfession.POST_RECEPTIONIST, pos.add(0, y, -n));
EFloorHall.trySpawnElfAt(builder, ElfProfession.POST_RECEPTIONIST, pos.add(n, y, 0));
EFloorHall.trySpawnElfAt(builder, ElfProfession.POST_RECEPTIONIST, pos.add(-n, y, 0));
}
}
World world = core.getWorld();
this.trySpawnQuest(builder, 24000 * 2 + world.rand.nextInt(24000 * 2));
}
}
| true
|
80a35b60bc62fda9e79b8e9cd228ee8aed885212
|
Java
|
malvers/RandomInfectionSimulation
|
/src/MyCombinationsWithRepeats.java
|
UTF-8
| 977
| 3.21875
| 3
|
[] |
no_license
|
public class MyCombinationsWithRepeats {
private static String[] allCombis;
static String[] get(final int positions, final int numLetters) {
int numberCombis = 0;
while (true) {
String str = Integer.toString(numberCombis, numLetters);
if (str.length() > positions) {
break;
}
numberCombis++;
}
allCombis = new String[numberCombis];
numberCombis = 0;
while (true) {
String str = Integer.toString(numberCombis, numLetters);
if (str.length() < positions) {
while (str.length() < positions) str = "0" + str;
}
if (str.length() > positions) {
break;
}
allCombis[numberCombis] = str;
numberCombis++;
}
return allCombis;
}
/// main for testing
public static void main(String[] args) {
get(6, 3);
}
}
| true
|
b7f10c109578d9faa84abb6d6421f2fd041e268f
|
Java
|
sekinecoulibaly/wackend
|
/wackend/src/main/java/com/yopyop/wackend/controller/ErlController.java
|
UTF-8
| 2,394
| 1.992188
| 2
|
[] |
no_license
|
package com.yopyop.wackend.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
import javax.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yopyop.wackend.service.*;
import com.yopyop.wackend.controller.GreetingException;
import com.yopyop.wackend.dto.ErlDTO;
import com.yopyop.wackend.dto.SubscriptionDTO;
@RestController
public class ErlController {
Logger logger = LoggerFactory.getLogger("ErlController");
@Autowired
ErlService erlService;
@RequestMapping(value="/erl/{cid}", method = RequestMethod.GET)
public ResponseEntity<ErlDTO> getById(@PathVariable String cid) throws Exception {
return new ResponseEntity<ErlDTO>(erlService.findByCid(cid),HttpStatus.OK);
}
@RequestMapping(value="/erl", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public List<ErlDTO> getAll() throws Exception {
return erlService.findAll();
}
@RequestMapping(value="/erl", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public ErlDTO add(@RequestBody ErlDTO erl) throws Exception {
return erlService.add(erl);
}
@RequestMapping(value="/erl/{cid}", method = RequestMethod.DELETE)
public ResponseEntity<ErlDTO> deleteByCid(@PathVariable String cid) throws Exception {
erlService.deleteByCid(cid);
return new ResponseEntity<ErlDTO>((ErlDTO)null,HttpStatus.OK);
}
@ExceptionHandler(GreetingException.class)
public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex) {
ErrorResponse error = new ErrorResponse();
error.setErrorCode(HttpStatus.PRECONDITION_FAILED.value());
error.setMessage(ex.getMessage());
return new ResponseEntity<ErrorResponse>(error, HttpStatus.PRECONDITION_FAILED);
}
}
| true
|
921b336ed8a9c0276f1182925326b96003dff55d
|
Java
|
paultuckey/urlrewritefilter
|
/src/test/java/org/tuckey/web/filters/urlrewrite/test/UrlRewriteTestCase.java
|
UTF-8
| 19,214
| 1.835938
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
/**
* Copyright (c) 2005-2023, Paul Tuckey
* All rights reserved.
* ====================================================================
* Licensed under the BSD License. Text as follows.
* <p>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* <p>
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* - Neither the name tuckey.org nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
* <p>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
package org.tuckey.web.filters.urlrewrite.test;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletConnection;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpUpgradeHandler;
import jakarta.servlet.http.Part;
import junit.framework.TestCase;
import org.tuckey.web.filters.urlrewrite.Conf;
import org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl;
import org.tuckey.web.filters.urlrewrite.Rule;
import org.tuckey.web.filters.urlrewrite.UrlRewriter;
import org.tuckey.web.filters.urlrewrite.utils.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* The idea for UrlRewriteTestCase is that users can extend it to create their own
* simple unit tests instead of having to manually setup a mock request and the filter.
* <p/>
* note, Ideally this would be in a separate urlrewrite-test.jar but that
* seems a little over the top for one class.
*/
public class UrlRewriteTestCase extends TestCase {
Conf conf;
UrlRewriter urlRewriter;
public void loadConf(URL confFileUrl) {
Log.setLevel("SYSOUT:DEBUG");
conf = new Conf(confFileUrl);
assertTrue("Conf should load without errors", conf.isOk());
urlRewriter = new UrlRewriter(conf);
}
public Rule getRule(String ruleName) {
List rules = urlRewriter.getConf().getRules();
Rule rule = null;
if (rules != null) {
for (int i = 0; i < rules.size(); i++) {
Rule loopRule = (Rule) rules.get(i);
if (ruleName.equalsIgnoreCase(loopRule.getName())) {
rule = loopRule;
}
}
}
if (rule == null) {
assertTrue("Rule by the name " + ruleName + " does not exist", false);
}
return rule;
}
/**
* Checks to see if the specified rule name matches the url specified.
*
* @param ruleName - the name of the rule
* @param requestUrl - the url to check
*/
public void assertRuleMatches(String ruleName, String requestUrl) {
Rule rule = getRule(ruleName);
MockResponse response = new MockResponse();
MockRequest request = new MockRequest(requestUrl);
NormalRewrittenUrl rewrittenUrl = null;
try {
rewrittenUrl = (NormalRewrittenUrl) rule.matches(request.getRequestURI(), request, response);
} catch (IOException e) {
assertNull("IOException during rule matching " + e.toString(), e);
} catch (ServletException e) {
assertNull("ServletException during rule matching " + e.toString(), e);
} catch (InvocationTargetException e) {
assertNull("InvocationTargetException during rule matching " + e.toString(), e);
}
assertNotNull("Rule " + ruleName + " does not match", rewrittenUrl);
}
public void assertRuleDoesNotMatches(String ruleName, String requestUrl) {
Rule rule = getRule(ruleName);
MockResponse response = new MockResponse();
MockRequest request = new MockRequest(requestUrl);
NormalRewrittenUrl rewrittenUrl = null;
try {
rewrittenUrl = (NormalRewrittenUrl) rule.matches(request.getRequestURI(), request, response);
} catch (IOException e) {
assertNull("IOException during rule matching " + e.toString(), e);
} catch (ServletException e) {
assertNull("ServletException during rule matching " + e.toString(), e);
} catch (InvocationTargetException e) {
assertNull("InvocationTargetException during rule matching " + e.toString(), e);
}
assertNull("Rule " + ruleName + " match", rewrittenUrl);
}
/**
* An empty method so that Junit doesn't complain when running tests.
*/
public void testUrlRerwriteTestCase() {
// do nothing
}
}
class MockRequest implements HttpServletRequest {
private String requestURI;
private int serverPort = 80;
private String queryString;
private String method = "GET";
private Hashtable headers = new Hashtable();
private Hashtable attrs = new Hashtable();
private Hashtable parameters = new Hashtable();
private String authType;
private int contentLength;
private String contentType;
private String contextPath = "";
private Cookie[] cookies;
private int cookieCounter;
private String pathInfo;
private String pathTranslated;
private String protocol;
private String remoteAddr;
private String remoteHost;
private String remoteUser;
private String requestedSessionId;
private String requestUrl;
private String serverName;
private String servletPath;
private String scheme;
private int localPort = 0;
public MockRequest() {
}
public MockRequest(String requestURI) {
this.requestURI = contextPath + requestURI;
this.requestUrl = requestURI;
this.servletPath = requestURI;
}
public void setRequestURI(String requestURI) {
this.requestURI = requestURI;
}
public String getAuthType() {
return authType;
}
public void setAuthType(String s) {
authType = s;
}
public Cookie[] getCookies() {
return cookies;
}
public long getDateHeader(String s) {
return 0;
}
public String getHeader(String s) {
if (s == null) {
return null;
}
return (String) headers.get(s);
}
public Enumeration getHeaders(String s) {
return headers.elements();
}
public Enumeration getHeaderNames() {
return headers.keys();
}
public int getIntHeader(String s) {
return 0;
}
public String getMethod() {
return method;
}
public String getPathInfo() {
return pathInfo;
}
public String getPathTranslated() {
return pathTranslated;
}
public String getContextPath() {
return contextPath;
}
public String getQueryString() {
return queryString;
}
public String getRemoteUser() {
return remoteUser;
}
private ArrayList roles = new ArrayList();
public boolean isUserInRole(String s) {
return roles.contains(s);
}
public void addRole(String s) {
roles.add(s);
}
public void removeRole(String s) {
roles.remove(s);
}
public Principal getUserPrincipal() {
return null;
}
public String getRequestedSessionId() {
return requestedSessionId;
}
public String getRequestURI() {
return requestURI;
}
public StringBuffer getRequestURL() {
if (requestUrl == null) return null;
return new StringBuffer(requestUrl);
}
public String getServletPath() {
return servletPath;
}
public HttpSession getSession(boolean b) {
return null;
}
public void setSessionNew(boolean b) {
}
public HttpSession getSession() {
return null;
}
@Override
public String changeSessionId() {
return null;
}
public boolean isRequestedSessionIdValid() {
return false;
}
public boolean isRequestedSessionIdFromCookie() {
return false;
}
public boolean isRequestedSessionIdFromURL() {
return false;
}
@Override
public boolean authenticate(HttpServletResponse httpServletResponse) throws IOException, ServletException {
return false;
}
@Override
public void login(String s, String s1) throws ServletException {
}
@Override
public void logout() throws ServletException {
}
@Override
public Collection<Part> getParts() throws IOException, ServletException {
return null;
}
@Override
public Part getPart(String s) throws IOException, ServletException {
return null;
}
@Override
public <T extends HttpUpgradeHandler> T upgrade(Class<T> aClass) throws IOException, ServletException {
return null;
}
/**
* @deprecated
*/
public boolean isRequestedSessionIdFromUrl() {
return false;
}
public Object getAttribute(String s) {
return attrs.get(s);
}
public Enumeration getAttributeNames() {
return null;
}
public String getCharacterEncoding() {
return characterEncoding;
}
String characterEncoding;
public void setCharacterEncoding(String s) throws UnsupportedEncodingException {
characterEncoding = s;
}
public int getContentLength() {
return contentLength;
}
@Override
public long getContentLengthLong() {
return 0;
}
public String getContentType() {
return contentType;
}
public ServletInputStream getInputStream() throws IOException {
return null;
}
public String getParameter(String s) {
return (String) parameters.get(s);
}
public Enumeration getParameterNames() {
return null;
}
public String[] getParameterValues(String s) {
return new String[0];
}
public Map getParameterMap() {
return null;
}
public String getProtocol() {
return protocol;
}
public String getScheme() {
return scheme;
}
public String getServerName() {
return serverName;
}
public int getServerPort() {
return serverPort;
}
public BufferedReader getReader() throws IOException {
return null;
}
public String getRemoteAddr() {
return remoteAddr;
}
public String getRemoteHost() {
return remoteHost;
}
public void setAttribute(String s, Object o) {
attrs.put(s, o);
}
public void removeAttribute(String s) {
attrs.remove(s);
}
public Locale getLocale() {
return null;
}
public Enumeration getLocales() {
return null;
}
public boolean isSecure() {
return false;
}
public RequestDispatcher getRequestDispatcher(String s) {
return null;
}
/**
* @deprecated
*/
public String getRealPath(String s) {
return null;
}
public int getRemotePort() {
return 0;
}
public String getLocalName() {
return null;
}
public String getLocalAddr() {
return null;
}
public int getLocalPort() {
return localPort;
}
@Override
public ServletContext getServletContext() {
return null;
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
return null;
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
return null;
}
@Override
public boolean isAsyncStarted() {
return false;
}
@Override
public boolean isAsyncSupported() {
return false;
}
@Override
public AsyncContext getAsyncContext() {
return null;
}
@Override
public DispatcherType getDispatcherType() {
return null;
}
@Override
public String getRequestId() {
return null;
}
@Override
public String getProtocolRequestId() {
return null;
}
@Override
public ServletConnection getServletConnection() {
return null;
}
public void setServerPort(int i) {
serverPort = i;
}
public void setQueryString(String s) {
queryString = s;
}
public void setMethod(String s) {
method = s;
}
public void setHeader(String name, String value) {
headers.put(name, value);
}
public void setContentLength(int i) {
contentLength = i;
}
public void setContentType(String s) {
contentType = s;
}
public void setContextPath(String s) {
contextPath = s;
}
public void addCookie(Cookie c) {
if (cookies == null) cookies = new Cookie[100];
cookies[cookieCounter++] = c;
}
public void addParameter(String s, String s1) {
parameters.put(s, s1);
}
public void setPathInfo(String s) {
pathInfo = s;
}
public void setPathTranslated(String s) {
pathTranslated = s;
}
public void setProtocol(String s) {
protocol = s;
}
public void setRemoteAddr(String s) {
remoteAddr = s;
}
public void setRemoteHost(String s) {
remoteHost = s;
}
public void setRemoteUser(String s) {
remoteUser = s;
}
public void setRequestedSessionId(String s) {
requestedSessionId = s;
}
public void setRequestURL(String s) {
requestUrl = s;
}
public void setServerName(String s) {
serverName = s;
}
public void setScheme(String s) {
scheme = s;
}
public void addHeader(String s, String s1) {
headers.put(s, s1);
}
public void setLocalPort(int localPort) {
this.localPort = localPort;
}
}
class MockResponse implements HttpServletResponse {
private Hashtable responseHeaders = new Hashtable();
private int status = 200;
private String redirectedUrl;
private List cookies = new ArrayList();
private Locale locale;
public void addCookie(Cookie cookie) {
cookies.add(cookie);
}
public boolean containsHeader(String s) {
return false;
}
public String encodeURL(String s) {
if (s == null) return null;
if (s.indexOf("http:") == 0) return s;
if (s.contains("?")) {
return s.substring(0, s.indexOf("?")) + ";mockencoded=test" + s.substring(s.indexOf("?"), s.length());
} else {
return s.concat(";mockencoded=test");
}
}
public String encodeRedirectURL(String s) {
return encodeURL(s);
}
/**
* @deprecated
*/
public String encodeUrl(String s) {
return encodeURL(s);
}
/**
* @deprecated
*/
public String encodeRedirectUrl(String s) {
return encodeURL(s);
}
public void sendError(int i, String s) throws IOException {
}
public void sendError(int i) throws IOException {
}
public void sendRedirect(String s) throws IOException {
redirectedUrl = s;
}
public void setDateHeader(String s, long l) {
responseHeaders.put(s, l + "");
}
public void addDateHeader(String s, long l) {
responseHeaders.put(s, l + "");
}
public void setHeader(String s, String s1) {
responseHeaders.put(s, s1);
}
public void addHeader(String s, String s1) {
responseHeaders.put(s, s1);
}
public void setIntHeader(String s, int i) {
responseHeaders.put(s, i + "");
}
public void addIntHeader(String s, int i) {
responseHeaders.put(s, i + "");
}
public void setStatus(int i) {
status = i;
}
/**
* @deprecated
*/
public void setStatus(int i, String s) {
}
public String getCharacterEncoding() {
return null;
}
public String getContentType() {
return null;
}
public ServletOutputStream getOutputStream() throws IOException {
return null;
}
public PrintWriter getWriter() throws IOException {
return null;
}
public void setCharacterEncoding(String s) {
}
public void setContentLength(int i) {
}
@Override
public void setContentLengthLong(long l) {
}
public void setContentType(String s) {
}
public void setBufferSize(int i) {
}
public int getBufferSize() {
return 0;
}
public void flushBuffer() throws IOException {
}
public void resetBuffer() {
}
public boolean isCommitted() {
return false;
}
public void reset() {
}
public void setLocale(Locale l) {
locale = l;
}
public Locale getLocale() {
return locale;
}
public String getHeader(String s) {
return (String) responseHeaders.get(s);
}
@Override
public Collection<String> getHeaders(String s) {
return null;
}
@Override
public Collection<String> getHeaderNames() {
return null;
}
public int getStatus() {
return status;
}
public String getRedirectedUrl() {
return redirectedUrl;
}
public List getCookies() {
return cookies;
}
}
| true
|
45f1075203cd12c54998c8b6b6638c373cb560a4
|
Java
|
GabrielTavares99/your-travel-app
|
/app/src/main/java/com/ueuo/gabrieltavares/main/ItemPacoteDetalhe.java
|
UTF-8
| 1,434
| 2.140625
| 2
|
[
"MIT"
] |
permissive
|
package com.ueuo.gabrieltavares.main;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import com.ueuo.gabrieltavares.main.model.Pacote;
import com.ueuo.gabrieltavares.main.util.MoedaUtil;
import com.ueuo.gabrieltavares.main.util.ResourceUtil;
import com.ueuo.gabrieltavares.your_travel_app.R;
import java.io.Serializable;
public class ItemPacoteDetalhe extends AppCompatActivity {
TextView lbl_local, lbl_preco, lbl_descrição;
ImageView img_local;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_pacote_detalhe);
Bundle bundle = getIntent().getExtras();
Pacote pacote = (Pacote) bundle.getSerializable("pacote");
lbl_local = findViewById(R.id.item_pacote_detalhe_local);
lbl_local.setText(pacote.getLocal());
lbl_preco = findViewById(R.id.item_pacote_detalhe_preco);
lbl_preco.setText(MoedaUtil.getPrecoFormatadoEmReal(pacote.getPreco()));
lbl_descrição = findViewById(R.id.item_pacote_detalhe_descricao);
lbl_descrição.setText(pacote.getDescrição());
img_local = findViewById(R.id.item_pacote_detalhe_imagem);
img_local.setImageDrawable(ResourceUtil.getDrawableImage(getApplicationContext(), pacote.getImagem()));
}
}
| true
|
848a4385457b4a01dee217868fd3879696543fcf
|
Java
|
whaleal/icefrog
|
/icefrog-collections/src/main/java/com/whaleal/icefrog/collections/SortedMapDifference.java
|
UTF-8
| 504
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.whaleal.icefrog.collections;
import java.util.SortedMap;
/**
* An object representing the differences between two sorted MapUtil.
*/
public interface SortedMapDifference<K extends Object, V extends Object>
extends MapDifference<K, V> {
@Override
SortedMap<K, V> entriesOnlyOnLeft();
@Override
SortedMap<K, V> entriesOnlyOnRight();
@Override
SortedMap<K, V> entriesInCommon();
@Override
SortedMap<K, ValueDifference<V>> entriesDiffering();
}
| true
|
6486f9578a2072aa27a16db81f42629d069c04b8
|
Java
|
emailandxu/DBMSR
|
/src/buffer/Block.java
|
GB18030
| 5,416
| 2.71875
| 3
|
[] |
no_license
|
/*
* Created on 2005-1-24
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package buffer;
import java.util.Date;
import diskaccess.DiskManagement;
/**
* @author zh
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public abstract class Block {
public static final int META_BLOCK = 1;
public static final int SCHEMA_BLOCK = 2;
public static final int INDEX_BLOCK = 3;
public static final int DATA_BLOCK = 4;
public static final int INDEX_INFO_BLOCK = 5;
/**
*
*/
private byte[] data;
/**
* ָÿĵַصhashmap
*/
private IDEntry idEntry;
/**
* ǷĹ,жǷҪдļ
* data[]privateDataBlockֻµsetXXX
* MetaBlock,SchemaBlock,IndexBlockУʹʼߣ
* ЧʿǣڲҪݽṹֻдشʱʹdata飬˲Ϊprivate
*/
protected boolean modified = false;
Block(byte[] buffer, IDEntry id) {
data = buffer;
idEntry = id;
}
/**
* ÿʹǰҪʼ,Ϊֹγʼ,ж
* meta, index, indexinfo, schemaджȷ
* data븲
* @return
*/
protected boolean initialized() {
return data == null;
}
/**
* ͷſռ䣬бҪʱ仯Ŀд
* @param disk
*/
protected abstract void releaseMemory(DiskManagement disk);
/**
* д
* Ӧü̳и÷
* @return
*/
void writeBlock(DiskManagement disk) {
disk.writeToDisk(
idEntry.getFileID(),
idEntry.getBlockID(),
data);
data = null;
}
/**
* Ϊʡڴ,Ҫʱ,ڶ֮,Ϊnull
* @param dt
*/
void setData(byte[] dt) {
data = dt;
}
/**
* ֻreloadõ
* @return
*/
byte[] getData() {
return data;
}
/**
* @return Returns the idEntry.
*/
IDEntry getIdEntry() {
return idEntry;
}
/**
* ºΪȡֶ
* @param offset data[]еʼλ
* @param value
*/
// byte
protected void setByte(int offset, byte value) {
data[offset] = value;
}
protected byte getByte(int offset) {
return data[offset];
}
// short
protected void setShort(int offset, short value) {
data[offset] = (byte)(value >> 8);
data[offset+1] = (byte)(value >> 0);
}
protected short getShort(int offset) {
return (short)((data[offset] << 8) |
(data[offset+1] & 0xff));
}
// int
protected void setInt(int offset, int value) {
data[offset] = (byte)(value >> 24);
data[offset+1] = (byte)(value >> 16);
data[offset+2] = (byte)(value >> 8);
data[offset+3] = (byte)(value >> 0);
}
protected int getInt(int offset) {
return (int)(((data[offset] & 0xff) << 24) |
((data[offset+1] & 0xff) << 16) |
((data[offset+2] & 0xff) << 8) |
((data[offset+3] & 0xff) << 0));
}
// long
protected void setLong(int offset, long value) {
data[offset] = (byte)(value >> 56);
data[offset+1] = (byte)(value >> 48);
data[offset+2] = (byte)(value >> 40);
data[offset+3] = (byte)(value >> 32);
data[offset+4] = (byte)(value >> 24);
data[offset+5] = (byte)(value >> 16);
data[offset+6] = (byte)(value >> 8);
data[offset+7] = (byte)(value >> 0);
}
protected long getLong(int offset) {
return ((((long)data[offset] & 0xff) << 56) |
(((long)data[offset+1] & 0xff) << 48) |
(((long)data[offset+2] & 0xff) << 40) |
(((long)data[offset+3] & 0xff) << 32) |
(((long)data[offset+4] & 0xff) << 24) |
(((long)data[offset+5] & 0xff) << 16) |
(((long)data[offset+6] & 0xff) << 8) |
(((long)data[offset+7] & 0xff) << 0));
}
// char
protected void setChar(int offset, char value) {
data[offset] = (byte)(value >> 8);
data[offset+1] = (byte)(value >> 0);
}
protected char getChar(int offset) {
return (char)((data[offset] << 8) |
(data[offset+1] & 0xff));
}
// boolean
protected void setBoolean(int offset, boolean value) {
data[offset] = value ? (byte)1 : (byte)0;
}
protected boolean getBoolean(int offset) {
return data[offset] == 1 ?
true : false;
}
// double
protected void setDouble(int offset, double value) {
setLong(offset, Double.doubleToRawLongBits(value));
}
protected double getDouble(int offset) {
return Double.longBitsToDouble(getLong(offset));
}
// time
protected void setTime(int offset, Date value) {
setLong( offset, value.getTime());
}
protected Date getTime(int offset) {
return new Date(getLong(offset));
}
// string
protected void setString(int offset, String value, int maxLength) {
char[] chr = value.toCharArray();
int i = 0;
for ( ; i < chr.length && i < maxLength; i++) {
setChar(offset, chr[i]);
offset += 2;
}
if (i<maxLength)
for ( ; i < maxLength ; i++) {
setChar(offset, (char)0);
offset += 2;
}
}
protected String getString(int offset, int maxLength) {
char[] chr = new char[maxLength];
int i = 0;
for ( ; i < maxLength; i++) {
chr[i] = getChar(offset);
if (chr[i] == 0) break;
offset += 2;
}
return new String(chr,0,i);
}
}
| true
|
12af7b2fa33cd8d6f8c09998119403cc5ce77e86
|
Java
|
bilbo3000/coding
|
/lintcode/implement_queue_by_two_stacks.java
|
UTF-8
| 1,017
| 3.734375
| 4
|
[] |
no_license
|
public class Solution {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public Solution() {
// do initialization if necessary
stack1 = new Stack<>();
stack2 = new Stack<>();
}
// O(1)
public void push(int element) {
// write your code here
stack1.push(element);
}
// O(n)
public int pop() {
// write your code here
while (stack1.size() != 0) {
stack2.push(stack1.pop());
}
int result = stack2.pop();
while (stack2.size() != 0) {
stack1.push(stack2.pop());
}
return result;
}
// O(n)
public int top() {
// write your code here
while (stack1.size() != 0) {
stack2.push(stack1.pop());
}
int result = stack2.peek();
while (stack2.size() != 0) {
stack1.push(stack2.pop());
}
return result;
}
}
| true
|
348951ff6f5123870b3d5e3b7e067e978c81d431
|
Java
|
Nursultan1/2lesson5.2
|
/src/com/company/HomeWorkA/Uploader.java
|
UTF-8
| 642
| 2.765625
| 3
|
[] |
no_license
|
package com.company.HomeWorkA;
import java.util.concurrent.CountDownLatch;
public class Uploader extends Thread{
private CountDownLatch countDownLatch;
private int sizeOfFile=500;
private int speedOfDownload=20;
public Uploader (CountDownLatch countDownLatch){
this.countDownLatch=countDownLatch;
}
@Override
public void run(){
try{
for (int i = 0; i < 15; i++) {
System.out.println("-");
sleep(50);
}
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true
|
335579f519c4aa5d3cb899643c7ff8b6c532b04f
|
Java
|
AndreiKviatkouski/VideoCrawlerVK
|
/src/main/java/by/AndreiKviatkouski/action/DownloaderManagerAction.java
|
UTF-8
| 851
| 2.40625
| 2
|
[] |
no_license
|
package by.AndreiKviatkouski.action;
import by.AndreiKviatkouski.entyties.Video;
import by.AndreiKviatkouski.service.DownloadService;
import lombok.Data;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Data
public class DownloaderManagerAction {
private List<Video> finishList;
ExecutorService executor = Executors.newFixedThreadPool(4);
public void startTreads() {
for (Video video : finishList) {
DownloadService downloader = new DownloadService();
Thread thread = new Thread(downloader);
downloader.setUrl(video.getDownloadLink());
downloader.setFileName("src\\main\\java\\by\\AndreiKviatkouski\\video2\\" + video.getName());
executor.execute(thread);
}
executor.shutdown();
}
}
| true
|
32810bc35297a092734dd25efc731e5bea933213
|
Java
|
melodyshu/design
|
/src/main/java/com/example/design/build/BMWModel.java
|
UTF-8
| 542
| 2.84375
| 3
|
[] |
no_license
|
package com.example.design.build;
public class BMWModel extends CarModel {
@Override
protected void start() {
System.out.println("宝马跑起来是这个样子的...");
}
@Override
protected void stop() {
System.out.println("宝马这样停车...");
}
@Override
protected void alarm() {
System.out.println("宝马的喇叭声音是这个样子的...");
}
@Override
protected void engineBoom() {
System.out.println("宝马的引擎是这个声音...");
}
}
| true
|
53e178d92102dbfe9250f39407400c04e783f309
|
Java
|
basiljude/financial_management
|
/src/main/java/com/byta/lenus/domain/PatientPaiment.java
|
UTF-8
| 5,484
| 2.0625
| 2
|
[] |
no_license
|
package com.byta.lenus.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A PatientPaiment.
*/
@Entity
@Table(name = "patient_paiment")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class PatientPaiment implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "jhi_date")
private LocalDate date;
@Column(name = "amound")
private Double amound;
@Column(name = "description")
private String description;
@OneToOne
@JoinColumn(unique = true)
private CashDesk encounder;
@OneToMany(mappedBy = "patientPaiment")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Encounder> encounders = new HashSet<>();
@OneToMany(mappedBy = "patientPaiment")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Type> types = new HashSet<>();
@OneToMany(mappedBy = "patientPaiment")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Invoice> invoices = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getDate() {
return date;
}
public PatientPaiment date(LocalDate date) {
this.date = date;
return this;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Double getAmound() {
return amound;
}
public PatientPaiment amound(Double amound) {
this.amound = amound;
return this;
}
public void setAmound(Double amound) {
this.amound = amound;
}
public String getDescription() {
return description;
}
public PatientPaiment description(String description) {
this.description = description;
return this;
}
public void setDescription(String description) {
this.description = description;
}
public CashDesk getEncounder() {
return encounder;
}
public PatientPaiment encounder(CashDesk cashDesk) {
this.encounder = cashDesk;
return this;
}
public void setEncounder(CashDesk cashDesk) {
this.encounder = cashDesk;
}
public Set<Encounder> getEncounders() {
return encounders;
}
public PatientPaiment encounders(Set<Encounder> encounders) {
this.encounders = encounders;
return this;
}
public PatientPaiment addEncounder(Encounder encounder) {
this.encounders.add(encounder);
encounder.setPatientPaiment(this);
return this;
}
public PatientPaiment removeEncounder(Encounder encounder) {
this.encounders.remove(encounder);
encounder.setPatientPaiment(null);
return this;
}
public void setEncounders(Set<Encounder> encounders) {
this.encounders = encounders;
}
public Set<Type> getTypes() {
return types;
}
public PatientPaiment types(Set<Type> types) {
this.types = types;
return this;
}
public PatientPaiment addType(Type type) {
this.types.add(type);
type.setPatientPaiment(this);
return this;
}
public PatientPaiment removeType(Type type) {
this.types.remove(type);
type.setPatientPaiment(null);
return this;
}
public void setTypes(Set<Type> types) {
this.types = types;
}
public Set<Invoice> getInvoices() {
return invoices;
}
public PatientPaiment invoices(Set<Invoice> invoices) {
this.invoices = invoices;
return this;
}
public PatientPaiment addInvoice(Invoice invoice) {
this.invoices.add(invoice);
invoice.setPatientPaiment(this);
return this;
}
public PatientPaiment removeInvoice(Invoice invoice) {
this.invoices.remove(invoice);
invoice.setPatientPaiment(null);
return this;
}
public void setInvoices(Set<Invoice> invoices) {
this.invoices = invoices;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientPaiment patientPaiment = (PatientPaiment) o;
if (patientPaiment.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), patientPaiment.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "PatientPaiment{" +
"id=" + getId() +
", date='" + getDate() + "'" +
", amound='" + getAmound() + "'" +
", description='" + getDescription() + "'" +
"}";
}
}
| true
|
8c13348dc246ae9e873c54390fabf5dddf820d7d
|
Java
|
mp06111998/java-coding-college
|
/Java2/Vaje2.java
|
UTF-8
| 1,895
| 3.375
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ponavljanje;
/**
*
* @author Marcel
*/
public class Vaje2 {
public static void main(String[] args) {
System.out.println(" n n! Stirling(n) napaka (%)");
System.out.println("--------------------------------------------------------------");
for (int i = 1; i <= 100; i++) {
double napaka = (fakultetaD(i) - stirlingD(i)) / (double) fakultetaD(i) * 100;
System.out.printf("%3d%21.9E%21.9E%16.7f\n",i,fakultetaD(i),stirlingD(i),napaka);
}
}
public static double fakultetaD(int n){
double rezultat = 1;
for (int i = 2; i <= n; i++) {
rezultat = rezultat * i;
}
return rezultat;
}
public static double stirlingD(int n){
return Math.sqrt(2*Math.PI*n)*Math.pow((n/Math.E),n);
}
/*public static void main(String[] args) {
System.out.println(" n n! Stirling(n) napaka (%)");
System.out.println("--------------------------------------------------------------");
for (int i = 1; i <= 20; i++) {
double napaka = (fakultetaL(i) - stirlingL(i)) / (double) fakultetaL(i) * 100;
System.out.printf("%3d%21d%21d%16.7f\n",i,fakultetaL(i),stirlingL(i),napaka);
}
}
public static long fakultetaL(int n){
long rezultat = 1;
for (int i = 2; i <= n; i++) {
rezultat = rezultat * i;
}
return rezultat;
}
public static long stirlingL(int n){
return Math.round(Math.sqrt(2*Math.PI*n)*Math.pow((n/Math.E),n));
}*/
}
| true
|
8382a6086eaf09781a92f88dc6a20e7d26a514b8
|
Java
|
EnigmaBridge/ejbca
|
/modules/externalra/src/org/ejbca/extra/db/RevocationRequest.java
|
UTF-8
| 7,123
| 2.203125
| 2
|
[] |
no_license
|
/*************************************************************************
* *
* EJBCA Community: The OpenSource Certificate Authority *
* *
* This software is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.ejbca.extra.db;
import java.math.BigInteger;
/**
* Request to use to revoke a generate certificate. Contains the IssuerDN, certificate SN and
* revocation reason (One of the RevocationRequest.REVOKATION_REASON_ constants).
* Optionally you can request revocation of the user in EJBCA, so the user can not get a new
* certificate, when revoking the user, all the users certificates are revoked. This is requested by
* setting the parameter revokeuser to true. You can also optionally request revocation of all the users
* certificates, but without revoking the user itself, do this by setting revokall to true.
*
* REVOKATION_REASON_REMOVEFROMCRL can be used to "unrevoke" a certificate that was previously revoked
* with reason REVOKATION_REASON_CERTIFICATEHOLD
*
* Parameters inherited from the base class ExtRARequest is ignored.
*
* @author philip
* $Id$
*/
public class RevocationRequest extends ExtRARequest {
public static final float LATEST_VERSION = (float) 3.0;
static final int CLASS_TYPE = 8;
// Public Constants.
/**
* Constant specifying type of revocation
*/
public static final int REVOKATION_REASON_UNSPECIFIED = 0;
public static final int REVOKATION_REASON_KEYCOMPROMISE = 1;
public static final int REVOKATION_REASON_CACOMPROMISE = 2;
public static final int REVOKATION_REASON_AFFILIATIONCHANGED = 3;
public static final int REVOKATION_REASON_SUPERSEDED = 4;
public static final int REVOKATION_REASON_CESSATIONOFOPERATION = 5;
public static final int REVOKATION_REASON_CERTIFICATEHOLD = 6;
/** REVOKATION_REASON_REMOVEFROMCRL can be used to "unrevoke" a certificate that was previously revoked with reason REVOKATION_REASON_CERTIFICATEHOLD */
public static final int REVOKATION_REASON_REMOVEFROMCRL = 8;
public static final int REVOKATION_REASON_PRIVILEGESWITHDRAWN = 9;
public static final int REVOKATION_REASON_AACOMPROMISE = 10;
// Field constants
private static final String REVOKATIONREASON = "REVOCATIONREASON";
private static final String ISSUERDN = "ISSUERDN";
private static final String CERTIFICATESN = "CERTIFICATESN";
private static final String USERNAME = "USERNAME";
/** If all the users certificates should be revoked */
private static final String REVOKEALL = "REVOKEALL";
/** If the user should be revoked as well, and not only the certificates */
private static final String REVOKEUSER = "REVOKEUSER";
private static final long serialVersionUID = 1L;
/**
* Constructor revoking a specific certificate.
*/
public RevocationRequest(long requestId, String issuerdn, BigInteger certificatesn, int revocationReason){
data.put(REQUESTID, Long.valueOf(requestId));
data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE));
data.put(VERSION, Float.valueOf(LATEST_VERSION));
data.put(ISSUERDN, issuerdn);
data.put(CERTIFICATESN, certificatesn);
data.put(USERNAME, "");
data.put(REVOKATIONREASON, Integer.valueOf(revocationReason));
data.put(REVOKEALL, Boolean.FALSE);
data.put(REVOKEUSER, Boolean.FALSE);
}
/**
* Constructor revoking a specific certificate, or optionally all certificates of the user owning this certificate, and optionally the user as well
*/
public RevocationRequest(long requestId, String issuerdn, BigInteger certificatesn, int revocationReason, boolean revokeuser, boolean revokeall){
data.put(REQUESTID, Long.valueOf(requestId));
data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE));
data.put(VERSION, Float.valueOf(LATEST_VERSION));
data.put(ISSUERDN, issuerdn);
data.put(CERTIFICATESN, certificatesn);
data.put(USERNAME, "");
data.put(REVOKATIONREASON, Integer.valueOf(revocationReason));
data.put(REVOKEALL, Boolean.valueOf(revokeall));
data.put(REVOKEUSER, Boolean.valueOf(revokeuser));
}
/**
* Constructor revoking all of a users certificates, and optionally the user as well
*/
public RevocationRequest(long requestId, String username, int revocationReason, boolean revokeuser){
data.put(REQUESTID, Long.valueOf(requestId));
data.put(CLASSTYPE, Integer.valueOf(CLASS_TYPE));
data.put(VERSION, Float.valueOf(LATEST_VERSION));
data.put(ISSUERDN, "");
data.put(CERTIFICATESN, new BigInteger("-1"));
data.put(USERNAME, username);
data.put(REVOKATIONREASON, Integer.valueOf(revocationReason));
data.put(REVOKEALL, Boolean.TRUE);
data.put(REVOKEUSER, Boolean.valueOf(revokeuser));
}
/**
* Constructor used when laoded from a persisted state
*/
public RevocationRequest(){}
public float getLatestVersion() {
return LATEST_VERSION;
}
/**
* Returns the issuer DN of the certificate which keystore should be recreated
*/
public String getIssuerDN(){
return (String) data.get(ISSUERDN);
}
/**
* Returns the Certificate Serialnumber of the certificate which keystore should be recreated
*/
public BigInteger getCertificateSN(){
return (BigInteger) data.get(CERTIFICATESN);
}
/**
* Returns the revokation reason. One of the REVOKATION_REASON_ constants.
*/
public int getRevocationReason(){
return ((Integer) data.get(REVOKATIONREASON)).intValue();
}
/**
* Returns the true is the all the users certificate should be revoked, false if only the given one.
*/
public boolean getRevokeAll(){
return ((Boolean) data.get(REVOKEALL)).booleanValue();
}
/**
* Returns the true is the user should be revoked, false if only the certificates.
*/
public boolean getRevokeUser(){
return ((Boolean) data.get(REVOKEUSER)).booleanValue();
}
public void upgrade() {
if(Float.compare(LATEST_VERSION, getVersion()) != 0) {
if(data.get(REVOKEALL) == null) {
data.put(REVOKEALL, Boolean.FALSE);
}
if(data.get(REVOKEUSER) == null) {
data.put(REVOKEUSER, Boolean.FALSE);
}
if(data.get(USERNAME) == null) {
data.put(USERNAME, "");
}
data.put(VERSION, Float.valueOf(LATEST_VERSION));
}
}
}
| true
|
80be5c0ff557eba3b96041f1d8f38949ca5950cd
|
Java
|
p78o233/wx_plaform_self
|
/suport/src/main/java/com/example/suport/service/impl/wx/WxUserManageServiceImpl.java
|
UTF-8
| 13,680
| 2
| 2
|
[] |
no_license
|
package com.example.suport.service.impl.wx;/*
* @author p78o2
* @date 2019/9/26
*/
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.api.entity.po.WxUserInfo;
import com.example.api.entity.po.WxUserTag;
import com.example.api.entity.vo.GetUserInfoListVo;
import com.example.api.entity.vo.UserGetVo;
import com.example.api.entity.vo.UserTagVo;
import com.example.suport.mapper.wx.WxUserManageMapper;
import com.example.suport.service.wx.WxInitService;
import com.example.suport.service.wx.WxUserManageService;
import com.example.suport.url.WxHttpRequest;
import com.example.suport.utils.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class WxUserManageServiceImpl implements WxUserManageService {
@Value("${isSaveDb}")
private boolean isSaveDb;
@Autowired
private WxInitService wxInitService;
@Autowired
private WxUserManageMapper wxUserManageMapper;
@Override
public List<String> getUserOpenIds(String wxAppId, String next_openid) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
String resultStr = WxHttpRequest.getUserGet(accessToken, next_openid);
JSONObject resultJson = JSON.parseObject(resultStr);
// openid列表
List<String> openIdList = new ArrayList<String>();
// 返回值的data字段
String resultData = resultJson.getString("data");
JSONObject resultDataObj = JSON.parseObject(resultData);
JSONArray jsonArray = (JSONArray) resultDataObj.get("openid");
openIdList.addAll((List<String>) JSONArray.parseArray(jsonArray.toString(), String.class));
//
if (isSaveDb) {
//调用获取查看用户详细功能,并保存
if (openIdList.size() < 100) {
List<WxUserInfo> userInfos = new ArrayList<>();
userInfos = getUserInfoBatchget(wxAppId, openIdList);
// 批量插入,重复数据先删除再插入
wxUserManageMapper.insertUserInfotList(userInfos);
} else {
// 切割完成之后的新list
List<List<String>> newList = new ArrayList<List<String>>();
ToolsUtils toolsUtils = new ToolsUtils();
newList = toolsUtils.splitList(openIdList, 100);
for (int i = 0; i < newList.size(); i++) {
List<WxUserInfo> userInfos = new ArrayList<>();
userInfos = getUserInfoBatchget(wxAppId, newList.get(i));
// 批量插入,重复数据先删除再插入
wxUserManageMapper.insertUserInfotList(userInfos);
}
}
}
return openIdList;
} else {
return null;
}
}
@Override
public WxUserInfo getUserInfo(String wxAppId, String openId, String lang) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
String resultStr = WxHttpRequest.getUserInfo(accessToken, openId, lang);
WxUserInfo wxUserInfo = new WxUserInfo();
// fastjson字符串转成对象
wxUserInfo = JSON.parseObject(resultStr, WxUserInfo.class);
return wxUserInfo;
} else {
return null;
}
}
@Override
public List<WxUserInfo> getUserInfoBatchget(String wxAppId, List<String> list) {
// 最多请求100个人
if (list.size() < 100) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
// 用户详细信息列表
List<WxUserInfo> userInfos = new ArrayList<>();
if (accessToken != null) {
List<GetUserInfoListVo> guiList = new ArrayList<GetUserInfoListVo>();
for (String item : list) {
GetUserInfoListVo gui = new GetUserInfoListVo();
gui.setOpenid(item);
gui.setLang("zh_CN");
guiList.add(gui);
}
JSONArray arrayList = JSONArray.parseArray(JSONObject.toJSONString(guiList));
JSONObject jsonObject = new JSONObject();
jsonObject.put("user_list", arrayList);
// 网络请求
String resultStr = WxHttpRequest.getUserInfoBatchge(accessToken, jsonObject.toJSONString());
JSONObject resultJson = JSON.parseObject(resultStr);
String resultData = resultJson.getString("user_info_list");
JSONArray resultDataObj = JSON.parseArray(resultData);
// fastjson Array 转成List<Object>
userInfos.addAll((List<WxUserInfo>) JSONArray.parseArray(resultDataObj.toString(), WxUserInfo.class));
for (WxUserInfo userInfo : userInfos) {
userInfo.setWxAppId(wxAppId);
userInfo.setCreateTime(new Date());
}
return userInfos;
} else {
return null;
}
}
return null;
}
@Override
public List<WxUserTag> getUserTag(String wxAppId) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
String resultStr = WxHttpRequest.getTag(accessToken);
JSONObject resultObj = JSON.parseObject(resultStr);
JSONArray jsonArray = (JSONArray) resultObj.get("tags");
List<WxUserTag> userTags = new ArrayList<WxUserTag>();
userTags.addAll((List<WxUserTag>) JSONArray.parseArray(jsonArray.toString(), WxUserTag.class));
for(int i=0;i<userTags.size();i++){
userTags.get(i).setWxAppId(wxAppId);
userTags.get(i).setCreateTime(new Date());
}
if (isSaveDb) {
// 保存进数据库
wxUserManageMapper.insertUserTagList(userTags);
}
return userTags;
}
return null;
}
@Override
public WxUserTag createUserTag(String wxAppId, String name) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
JSONObject sendObject = new JSONObject();
sendObject.put("tag", jsonObject);
String resultStr = WxHttpRequest.createTag(accessToken, sendObject.toJSONString());
JSONObject resultObj = JSON.parseObject(resultStr);
JSONObject tagJson = resultObj.getJSONObject("tag");
WxUserTag wxUserTag = new WxUserTag();
wxUserTag.setTagId(tagJson.getInteger("id"));
wxUserTag.setName(tagJson.getString("name"));
return wxUserTag;
}
return null;
}
@Override
public boolean editUserTag(String wxAppId, WxUserTag wxUserTag) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonObj = (JSONObject) JSONObject.toJSON(wxUserTag);
jsonObj.put("id", jsonObj.getInteger("tagId"));
JSONObject jsonSend = new JSONObject();
jsonSend.put("tag", jsonObj);
String resultStr = WxHttpRequest.editTag(accessToken, jsonSend.toJSONString());
JSONObject resultObj = JSON.parseObject(resultStr);
if (resultObj.getInteger("errcode") == 0) {
if (isSaveDb) {
WxUserTag wxUserTagUpdate = new WxUserTag();
wxUserTagUpdate.setTagId(jsonObj.getInteger("id"));
wxUserTagUpdate.setName(wxUserTag.getName());
wxUserTagUpdate.setWxAppId(wxAppId);
wxUserManageMapper.updateUserTag(wxUserTag);
}
return true;
} else {
return false;
}
}
return false;
}
@Override
public boolean deleteUserTag(String wxAppId, int id) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", id);
JSONObject jsonSend = new JSONObject();
jsonSend.put("tag", jsonObject);
String resultStr = WxHttpRequest.deleteTag(accessToken, jsonSend.toJSONString());
JSONObject resultObj = JSON.parseObject(resultStr);
if(resultObj.getInteger("errcode")==0) {
if(isSaveDb) {
wxUserManageMapper.deleteUserTag(id,wxAppId);
}
return true;
}else {
return false;
}
}
return false;
}
@Override
public String getTagUsers(String wxAppId, int tagId, String next_openid) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonSend = new JSONObject();
jsonSend.put("tagid",tagId);
jsonSend.put("next_openid",next_openid);
// 网络请求
String resultStr = WxHttpRequest.getTagUsers(accessToken,jsonSend.toJSONString());
return resultStr;
}
return null;
}
@Override
public boolean setTagsBatchtagging(String wxAppId, UserTagVo userTagVo) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonSend = (JSONObject)JSONObject.toJSON(userTagVo);
// 网络请求
String resultStr = WxHttpRequest.setTagsBatchtagging(accessToken,jsonSend.toJSONString());
JSONObject resultObj = JSON.parseObject(resultStr);
if(resultObj.getInteger("errcode")==0)
return true;
return false;
}
return false;
}
@Override
public boolean deleteTagsBatchtagging(String wxAppId, UserTagVo userTagVo) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonSend = (JSONObject)JSONObject.toJSON(userTagVo);
// 网络请求
String resultStr = WxHttpRequest.deleteTagsBatchtagging(accessToken,jsonSend.toJSONString());
JSONObject resultObj = JSON.parseObject(resultStr);
if(resultObj.getInteger("errcode")==0)
return true;
return false;
}
return false;
}
@Override
public String getUserTagList(String wxAppId, String openId) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonSend = new JSONObject();
jsonSend.put("openid", openId);
// 网络请求
String resultStr = WxHttpRequest.getUserTagList(accessToken, jsonSend.toJSONString());
return resultStr;
}
return null;
}
@Override
public String setUserRemark(String wxAppId, String openId, String remark) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonSend = new JSONObject();
jsonSend.put("openid", openId);
jsonSend.put("remark",remark);
// 网络请求
String resultStr = WxHttpRequest.setUserRemark(accessToken, jsonSend.toJSONString());
return resultStr;
}
return null;
}
@Override
public String getBlackList(String wxAppId, String begin_openid) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonSend = new JSONObject();
jsonSend.put("begin_openid", begin_openid);
// 网络请求
String resultStr = WxHttpRequest.getBlackList(accessToken, jsonSend.toJSONString());
return resultStr;
}
return null;
}
@Override
public String setBlackList(String wxAppId, List<String> openIds) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonSend = new JSONObject();
jsonSend.put("openid_list", openIds);
// 网络请求
String resultStr = WxHttpRequest.setBlackList(accessToken, jsonSend.toJSONString());
return resultStr;
}
return null;
}
@Override
public String deleteBlackList(String wxAppId, List<String> openIds) {
String accessToken = wxInitService.getAccessToken(wxAppId).getAccessToken();
if (accessToken != null) {
JSONObject jsonSend = new JSONObject();
jsonSend.put("openid_list", openIds);
// 网络请求
String resultStr = WxHttpRequest.deleteBlackList(accessToken, jsonSend.toJSONString());
return resultStr;
}
return null;
}
}
| true
|
c8f093f467634d03d09e1b6ca73f08a4cc91b164
|
Java
|
janck13/spring-boot-plus
|
/src/main/java/com/github/boot/framework/util/ConstUtils.java
|
UTF-8
| 952
| 1.773438
| 2
|
[] |
no_license
|
package com.github.boot.framework.util;
/**
* 常量工具类
* @author ChenJianhui
*/
public class ConstUtils {
public static final String SYSTEM_PROFILE_KEY = "xdiamond.project.profile";
/**
* 自动登录Token
*/
public static final String TOKEN_NAME = "TOKEN";
/**
* session中存放的请求标识的key值
*/
public static final String SESSION_API_REQUESTID = "sessionApiRequestId";
/**
* session中存放的User对象的key值
*/
public static final String SESSION_USER = "profile";//"sessionUser";
/**
* session中存放的用户权限的key值
*/
public static final String SESSION_USER_ALLOW_RIGHT = "allowRight";
/**
* 系统包含的所有的权限
*/
public static final String APP_ALL_RIGHT_MAP = "allRightsMap";
/**
* 系统没有权限控制的请求URL
*/
public static final String APP_ALLOW_URLS = "allowUrls";
public static final String SESSION_USER_ID = "sessionUserId";
}
| true
|
47d4ef35359319f1037a297a45dd56daff50e856
|
Java
|
boydos/license
|
/src/main/java/org/headsupdev/license/LicenseEncoder.java
|
UTF-8
| 3,026
| 2.3125
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2010-2011 Heads Up Development Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.headsupdev.license;
import org.headsupdev.license.exception.InvalidFormatException;
import java.security.*;
import java.io.*;
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;
/**
* TODO add a description
*
* @author Andrew Williams
* @version $Id: LicenseEncoder.java 76 2012-03-17 23:17:03Z handyande $
* @since 1.0
*/
public class LicenseEncoder
{
private Key priv, shared;
public LicenseEncoder()
{
}
public void setPrivateKey( Key key )
{
this.priv = key;
}
public void setSharedKey( Key key )
{
this.shared = key;
}
public String encodeLicense( License in )
throws NoSuchAlgorithmException, InvalidKeyException, InvalidFormatException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
in.getProperties().store( out, in.getLicenseTitle() );
}
catch ( IOException e )
{
throw new InvalidFormatException( e );
}
return encode( out.toByteArray() );
}
protected String encode( byte[] data )
throws NoSuchAlgorithmException, InvalidKeyException
{
if ( priv == null || shared == null )
{
throw new IllegalStateException( "Keys must be set before decoding the license" );
}
MessageDigest digester = MessageDigest.getInstance( "MD5" );
digester.update( data );
byte[] digest = digester.digest();
try
{
Cipher cipher = Cipher.getInstance( "RSA/ECB/PKCS1Padding" );
cipher.init( Cipher.ENCRYPT_MODE, priv );
byte[] signature = cipher.doFinal( digest );
byte[] decompressed = new byte[ data.length + signature.length + 2 ];
System.arraycopy( data, 0, decompressed, 0, data.length );
decompressed[ data.length ] = 0;
decompressed[ data.length + 1 ] = 0;
System.arraycopy( signature, 0, decompressed, data.length + 2, signature.length );
Cipher cipher2 = Cipher.getInstance( "DES/ECB/PKCS5Padding" );
cipher2.init( Cipher.ENCRYPT_MODE, shared );
byte[] out = cipher2.doFinal( decompressed );
return DatatypeConverter.printBase64Binary( out );
}
catch ( Exception e )
{
e.printStackTrace();
return "";
}
}
}
| true
|
b9f1470dca5dc57aa935ccc4f53cdea16e86f00e
|
Java
|
xiaolanyun/DevOps_AppiumParallelTest
|
/src/test/java/com/xiaolanyun/appium/DataTest/pages/Mart_SellerMyPage.java
|
UTF-8
| 1,297
| 1.835938
| 2
|
[] |
no_license
|
package com.xiaolanyun.appium.DataTest.pages;
import org.openqa.selenium.By;
/*
* @author 24075
* @classname:Mart_SellerMyPages
* @Description:卖家基本信息元素定义
*/
public class Mart_SellerMyPage {
//修改信息
public static final By MSMP_BUTTON_SELLERCHANGE = By.id("com.example.xiaolanyun.ldmart:id/btn_change");
//保存信息
public static final By MSMP_BUTTON_SELLERSAVE = By.id("com.example.xiaolanyun.ldmart:id/btn_save");
//姓名
public static final By MSMP_BUTTON_SELLERNAME = By.id("com.example.xiaolanyun.ldmart:id/seller_name");
//新密码
public static final By MSMP_BUTTON_SELLERPASSWORD1 = By.id("com.example.xiaolanyun.ldmart:id/seller_password1");
//确认密码
public static final By MSMP_BUTTON_SELLERPASSWORD2 = By.id("com.example.xiaolanyun.ldmart:id/seller_password2");
//电话
public static final By MSMP_BUTTON_SELLERPHONE = By.id("com.example.xiaolanyun.ldmart:id/seller_phone");
//地址
public static final By MSMP_BUTTON_SELLERADDRESS = By.id("com.example.xiaolanyun.ldmart:id/seller_address");
//提前触发保存信息告警弹框
//确定
public static final By MSMP_BUTTON_SELLERINFOALARMON = By.id("android:id/button1");
//取消
public static final By MSMP_BUTTON_SELLERINFOALARMOFF = By.id("android:id/button2");
}
| true
|
24fd520978e0079f122addd844c50f9db38ac7ed
|
Java
|
bob-walters/burlap
|
/src/main/java/burlap/mdp/auxiliary/StateMapping.java
|
UTF-8
| 302
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package burlap.mdp.auxiliary;
import burlap.mdp.core.state.State;
/**
* A state mapping interface that maps one state into another state. Can be useful if mapping one state from one domain into a different domain.
* @author James MacGlashan
*
*/
public interface StateMapping {
State mapState(State s);
}
| true
|
77a7455fedc670d6b73c7d74f8954f4ecca4ee9e
|
Java
|
Geczy/SAS2006
|
/Server/src/server/org/engine/character/combat/ranged/RangeCombat.java
|
UTF-8
| 3,364
| 2.4375
| 2
|
[] |
no_license
|
package server.org.engine.character.combat.ranged;
import server.org.engine.character.Client;
public class RangeCombat
{
public static int calculateRangeAttack( Client c )
{
int attackLevel = c.playerLevel[4];
attackLevel *= c.specAccuracy;
if( c.fullVoidRange() ) {
attackLevel += c.getLevelForXP( c.playerXP[c.playerRanged] ) * 0.1;
}
if( c.prayerActive[3] ) {
attackLevel *= 1.05;
} else if( c.prayerActive[11] ) {
attackLevel *= 1.10;
} else if( c.prayerActive[19] ) {
attackLevel *= 1.15;
}
if( c.fullVoidRange() && c.specAccuracy > 1.15 ) {
attackLevel *= 1.75;
}
return ( int )( attackLevel + c.playerBonus[4] * 1.95 );
}
public static int calculateRangeDefence( Client c )
{
int defenceLevel = c.playerLevel[1];
if( c.prayerActive[0] ) {
defenceLevel += c.getLevelForXP( c.playerXP[c.playerDefence] ) * 0.05;
} else if( c.prayerActive[5] ) {
defenceLevel += c.getLevelForXP( c.playerXP[c.playerDefence] ) * 0.1;
} else if( c.prayerActive[13] ) {
defenceLevel += c.getLevelForXP( c.playerXP[c.playerDefence] ) * 0.15;
} else if( c.prayerActive[24] ) {
defenceLevel += c.getLevelForXP( c.playerXP[c.playerDefence] ) * 0.2;
} else if( c.prayerActive[25] ) {
defenceLevel += c.getLevelForXP( c.playerXP[c.playerDefence] ) * 0.25;
}
return defenceLevel + c.playerBonus[9] + c.playerBonus[9] / 2;
}
public static int rangeMaxHit( Client c )
{
int rangeLevel = c.playerLevel[4];
double modifier = 1.0;
double wtf = c.specDamage;
int itemUsed = c.usingBow ? c.lastArrowUsed: c.lastWeaponUsed;
if( c.prayerActive[3] ) {
modifier += 0.05;
} else if( c.prayerActive[11] ) {
modifier += 0.10;
} else if( c.prayerActive[19] ) {
modifier += 0.15;
}
if( c.fullVoidRange() ) {
modifier += 0.20;
}
double c1 = modifier * rangeLevel;
int rangeStr = getRangeStr( c, itemUsed );
double max = ( c1 + 8 ) * ( rangeStr + 64 ) / 640;
if( wtf != 1 ) {
max *= wtf;
}
if( max < 1 ) {
max = 1;
}
return ( int )max;
}
public static int getRangeStr( Client c, int i )
{
if( i == 4214 ) {
return 70;
}
switch( i ) {
// bronze to rune bolts
case 877:
return 10;
case 9140:
return 46;
case 9141:
return 64;
case 9142:
case 9241:
case 9240:
return 82;
case 9143:
case 9243:
case 9242:
return 100;
case 9144:
case 9244:
case 9245:
return 115;
// bronze to dragon arrows
case 882:
return 7;
case 884:
return 10;
case 886:
return 16;
case 888:
return 22;
case 890:
return 31;
case 892:
case 4740:
return 49;
case 11212:
return 60;
// knifes
case 864:
return 3;
case 863:
return 4;
case 865:
return 7;
case 866:
return 10;
case 867:
return 14;
case 868:
return 24;
}
return 0;
}
public static int correctBowAndArrows( Client c )
{
switch( c.playerEquipment[c.playerWeapon] ) {
case 839:
case 841:
return 882;
case 843:
case 845:
return 884;
case 847:
case 849:
return 886;
case 851:
case 853:
return 888;
case 855:
case 857:
return 890;
case 859:
case 861:
return 892;
case 4734:
case 4935:
case 4936:
case 4937:
return 4740;
case 11235:
return 11212;
}
return - 1;
}
}
| true
|
1b9c6c333c4dd1839b3c46a57da77b6bdcd29387
|
Java
|
dddddttttt/androidsourcecodes
|
/是男人就下一百层/src/org/void1898/www/agilebuddy/Prefs.java
|
UTF-8
| 5,975
| 1.875
| 2
|
[] |
no_license
|
package org.void1898.www.agilebuddy;
import org.void1898.www.agilebuddy.util.ConstantInfo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
/**
*
* @author void1898@gmail.com
*
*/
public class Prefs extends Activity implements OnClickListener,
SeekBar.OnSeekBarChangeListener {
private SharedPreferences mBaseSettings;
private SharedPreferences mRankingSettings;
private EditText mUserNameEditText;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.options);
mBaseSettings = PreferenceManager.getDefaultSharedPreferences(this);
CheckBox vibrateCheckbox = (CheckBox) findViewById(R.id.options_vibrate_checkbox);
vibrateCheckbox.setChecked(mBaseSettings.getBoolean(
ConstantInfo.PREFERENCE_KEY_VIBRATE, true));
vibrateCheckbox
.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
mBaseSettings.edit().putBoolean(
ConstantInfo.PREFERENCE_KEY_VIBRATE, true)
.commit();
} else {
mBaseSettings.edit().putBoolean(
ConstantInfo.PREFERENCE_KEY_VIBRATE, false)
.commit();
}
}
});
CheckBox soundsCheckbox = (CheckBox) findViewById(R.id.options_sounds_checkbox);
soundsCheckbox.setChecked(mBaseSettings.getBoolean(
ConstantInfo.PREFERENCE_KEY_SOUNDS, true));
soundsCheckbox
.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
mBaseSettings.edit().putBoolean(
ConstantInfo.PREFERENCE_KEY_SOUNDS, true)
.commit();
} else {
mBaseSettings.edit().putBoolean(
ConstantInfo.PREFERENCE_KEY_SOUNDS, false)
.commit();
}
}
});
CheckBox showTipsCheckbox = (CheckBox) findViewById(R.id.options_showtips_checkbox);
showTipsCheckbox.setChecked(mBaseSettings.getBoolean(
ConstantInfo.PREFERENCE_KEY_SHOWTIPS, true));
showTipsCheckbox
.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
mBaseSettings.edit().putBoolean(
ConstantInfo.PREFERENCE_KEY_SHOWTIPS, true)
.commit();
} else {
mBaseSettings
.edit()
.putBoolean(
ConstantInfo.PREFERENCE_KEY_SHOWTIPS,
false).commit();
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.velocityController);
seekBar.setProgress(mBaseSettings.getInt(
ConstantInfo.PREFERENCE_KEY_POWER, 40));
seekBar.setOnSeekBarChangeListener(this);
mRankingSettings = getSharedPreferences(
ConstantInfo.PREFERENCE_RANKING_INFO, 0);
mUserNameEditText = (EditText) findViewById(R.id.options_username_edittext);
mUserNameEditText.setText(mRankingSettings.getString(
ConstantInfo.PREFERENCE_KEY_RANKING_NAME, ""));
TextView bestRecordTextView = (TextView) findViewById(R.id.options_best_record_textview);
bestRecordTextView.setText(""
+ bestRecordTextView.getText()
+ mRankingSettings.getInt(
ConstantInfo.PREFERENCE_KEY_RANKING_SCORE, 0));
Button okayButton = (Button) findViewById(R.id.options_okay_button);
okayButton.setOnClickListener(this);
Button uploadScoreButton = (Button) findViewById(R.id.options_upload_score_button);
uploadScoreButton.setOnClickListener(this);
Button tipsButton = (Button) findViewById(R.id.options_tips_button);
tipsButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String userName = null;
if (mUserNameEditText.getText() != null) {
userName = mUserNameEditText.getText().toString()
.replace("\n", " ").trim();
}
if (userName == null || "".equals(userName)) {
showToast(R.string.options_toast_username_null);
return;
} else if (userName.length() > 20) {
showToast(R.string.options_toast_username_too_long);
return;
}
mRankingSettings.edit().putString(
ConstantInfo.PREFERENCE_KEY_RANKING_NAME, userName).commit();
switch (v.getId()) {
case R.id.options_okay_button:
finish();
break;
case R.id.options_upload_score_button:
mRankingSettings.edit().putBoolean(
ConstantInfo.PREFERENCE_KEY_RANKING_FLAG,
!mRankingSettings.getBoolean(
ConstantInfo.PREFERENCE_KEY_RANKING_FLAG, false))
.commit();
break;
case R.id.options_tips_button:
Intent i = new Intent(this, TipsActivity.class);
startActivity(i);
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mBaseSettings.edit().putInt(ConstantInfo.PREFERENCE_KEY_POWER,
seekBar.getProgress()).commit();
}
private void showToast(int strId) {
Toast toast = Toast.makeText(this, strId, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 0, 220);
toast.show();
}
}
| true
|
c05e3f6b4af0f8da689441239108091fea22c948
|
Java
|
FedotovDV/2020-Maven
|
/src/test/java/ru/yandex/fed3375546/gomoku/impl/DefaultHumanTurnTest.java
|
UTF-8
| 1,167
| 2.421875
| 2
|
[] |
no_license
|
package ru.yandex.fed3375546.gomoku.impl;
import org.hamcrest.core.IsEqual;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import ru.yandex.fed3375546.gomoku.Cell;
import ru.yandex.fed3375546.gomoku.CellValue;
import ru.yandex.fed3375546.gomoku.GameTable;
import ru.yandex.fed3375546.gomoku.HumanTurn;
public class DefaultHumanTurnTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private HumanTurn humanTurn;
@Before
public void before() {
humanTurn = new DefaultHumanTurn();
}
@Test
public void testSetGameTableNotNull() {
thrown.expect(NullPointerException.class);
thrown.expectMessage(new IsEqual<String>("Game table can't be null"));
humanTurn.setGameTable(null);
}
@Test
public void testMakeTurn() {
GameTable gameTable = mock(GameTable.class);
humanTurn.setGameTable(gameTable);
Cell cell = humanTurn.makeTurn(0, 1);
assertEquals(0, cell.getRowIndex());
assertEquals(1, cell.getColIndex());
verify(gameTable).setValue(0, 1, CellValue.HUMAN);
}
}
| true
|
b581a26e6b3986dc2f471c34f5b95a57f517a3f6
|
Java
|
vschwartz-tgm/mobilelearning
|
/MobileLearning/app/src/main/java/com/example/neeraj/mobilelearning/HelpScreen.java
|
UTF-8
| 1,343
| 2.25
| 2
|
[] |
no_license
|
package com.example.neeraj.mobilelearning;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
/**
* Created by pzhanel on 09/01/2018.
* Das ist der Screen, der Auftaucht, wenn auf den "Hilfe" Button geclickt wird.
*/
public class HelpScreen extends AppCompatActivity {
ScrollView sv1, sv2, sv3, sv4;
TextView headline1, headline2, headline3, headline4, headline5, answ1, answ2, answ3, answ4, answ5;
Button buttonback; // Zurückbutton
/**
* Methode onCreate, wird beim Erstellen aufgerugen
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help_screen);
buttonback = (Button) findViewById(R.id.buttonback);
buttonback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HelpScreen.this, PlayActivity.class);
startActivity(intent);
}
});
}
/**
* Konstruktor
*/
public void init(){
}
}
| true
|
680a765c96a42901e43753a701fc8b114d7f1297
|
Java
|
EvanSnook/RoboSports-370
|
/RoboSport370/src/main/java/model/Librarian.java
|
UTF-8
| 3,523
| 2.796875
| 3
|
[] |
no_license
|
package model;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import model.enums.RobotType;
public class Librarian {
private List<RobotAI> robots;
public Librarian() {
robots = new ArrayList<>();
loadRobots();
}
/**
* Load the robots from the website
*/
private void loadRobots() {
// Grab the robots from gpu0.usask.ca
JSONArray array = getRobotList();
if (array == null) {
System.err.println("Couldn't get Robots from gpu0.usask.ca");
return;
}
// Loop through the list and add the robots to robots
for (Object robotJson : array) {
JSONObject curRobotJson = (JSONObject) ((JSONObject) robotJson).get("script");
RobotAI curRobot = RobotAI.getBuilder(true)
.get(getRobotType(curRobotJson))
.build(curRobotJson);
// Add the stats to the robot.
curRobot.setStats(getRobotStats(curRobotJson));
// Add other attributes
curRobot.setName((String) curRobotJson.get("name"));
curRobot.setTeam((String) curRobotJson.get("team"));
robots.add(curRobot);
}
}
private RobotType getRobotType(JSONObject robot) {
switch ((String) robot.get("class")) {
case "Scout":
return RobotType.SCOUT;
case "Sniper":
return RobotType.SNIPER;
case "Tank":
return RobotType.TANK;
default:
return null;
}
}
/**
* Get the stats from the specified {@code JSONObject} {@code Robot}
*
* @param robot the robot to get the stats of
* @return {@link Stats} for the specified {@code Robot}
*/
private Stats getRobotStats(JSONObject robot) {
Stats stats = new Stats();
stats.setWins((long) robot.get("wins"));
stats.setLosses((long) robot.get("losses"));
stats.setLived((long) robot.get("lived"));
stats.setDied((long) robot.get("died"));
stats.setExecutions((long) robot.get("executions"));
stats.setKilled((long) robot.get("killed"));
stats.setMoved((long) robot.get("moved"));
stats.setMatches((long) robot.get("matches"));
stats.setAbsorbed((long) robot.get("absorbed"));
return stats;
}
/**
* Get the list of all of the robots from the website
*
* @return the {@link JSONArray} of {@code Robot}s or {@code null} if an error occurred.
*/
private JSONArray getRobotList() {
JSONParser parser = new JSONParser();
String json = "";
try {
String host = "10.81.6.35";
Socket socket = new Socket(host, 20001);
OutputStream os = socket.getOutputStream();
os.write("{\"list-request\":{\"data\":\"full\"}}\n".getBytes());
os.flush();
InputStream is = socket.getInputStream();
int ch;
while ((ch = is.read()) != -1)
json += (char) ch;
socket.close();
return (JSONArray) parser.parse(json);
} catch (Exception ex) {
return null;
}
}
public List<RobotAI> getRobots() {
return robots;
}
}
| true
|