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
0e7e8ae81665725275c9da6e3d5672efb5727587
Java
UnstoppableN/Invasion-mod
/src/main/java/invmod/common/entity/PathNode.java
UTF-8
2,620
2.84375
3
[]
no_license
package invmod.common.entity; import invmod.common.util.IPosition; import net.minecraft.util.MathHelper; public class PathNode implements IPosition { public final int xCoord; public final int yCoord; public final int zCoord; public final PathAction action; private final int hash; public boolean isFirst; int index; float totalPathDistance; float distanceToNext; float distanceToTarget; private PathNode previous; public PathNode(int i, int j, int k) { this(i, j, k, PathAction.NONE); } public PathNode(int i, int j, int k, PathAction pathAction) { this.index = -1; this.isFirst = false; this.xCoord = i; this.yCoord = j; this.zCoord = k; this.action = pathAction; this.hash = makeHash(i, j, k, this.action); } public static int makeHash(int x, int y, int z, PathAction action) { return y & 0xFF | (x & 0xFF) << 8 | (z & 0xFF) << 16 | (action.ordinal() & 0xFF) << 24; } public float distanceTo(PathNode pathpoint) { float f = pathpoint.xCoord - this.xCoord; float f1 = pathpoint.yCoord - this.yCoord; float f2 = pathpoint.zCoord - this.zCoord; return MathHelper.sqrt_float(f * f + f1 * f1 + f2 * f2); } public float distanceTo(float x, float y, float z) { float f = x - this.xCoord; float f1 = y - this.yCoord; float f2 = z - this.zCoord; return MathHelper.sqrt_float(f * f + f1 * f1 + f2 * f2); } public boolean equals(Object obj) { if ((obj instanceof PathNode)) { PathNode node = (PathNode) obj; return (this.hash == node.hash) && (this.xCoord == node.xCoord) && (this.yCoord == node.yCoord) && (this.zCoord == node.zCoord) && (node.action == this.action); } return false; } public boolean equals(int x, int y, int z) { return (this.xCoord == x) && (this.yCoord == y) && (this.zCoord == z); } public int hashCode() { return this.hash; } public boolean isAssigned() { return this.index >= 0; } public int getXCoord() { return this.xCoord; } public int getYCoord() { return this.yCoord; } public int getZCoord() { return this.zCoord; } public String toString() { return this.xCoord + ", " + this.yCoord + ", " + this.zCoord + ", " + this.action; } public PathNode getPrevious() { return previous; } public void setPrevious(PathNode previous) { this.previous = previous; } }
true
937dbd7247ae66a6c2cd22f7c7afc14ba614f765
Java
gyongyiovics/piratesDB
/src/main/java/application/models/Ship.java
UTF-8
1,821
2.96875
3
[]
no_license
package application.models; import java.util.List; import java.util.Map; public class Ship { private int id; private String name; private int attackPower; private int state; //TODO: final fields and sql? private final String weapon = "CANNON"; private final int cannonDamage = 25; private Map<String, List<Pirate>> shipWithCrew; public Ship(int id, String name, int attackPower, int state) { this.id = id; this.name = name; this.attackPower = attackPower; this.state = state; } public Ship(String name, int attackPower, int state, Map<String, List<Pirate>> shipWithCrew) { this.name = name; this.attackPower = attackPower; this.state = state; this.shipWithCrew = shipWithCrew; } public int attack(Ship enemy) { enemy.setAttackPower(enemy.getAttackPower() - this.getCannonDamage()); return enemy.getAttackPower(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAttackPower() { return attackPower; } public void setAttackPower(int attackPower) { this.attackPower = attackPower; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String getWeapon() { return weapon; } public int getCannonDamage() { return cannonDamage; } public Map<String, List<Pirate>> getShipWithCrew() { return shipWithCrew; } public void setShipWithCrew(Map<String, List<Pirate>> shipWithCrew) { this.shipWithCrew = shipWithCrew; } }
true
2c48be15ce18c23df4ed5659c3bf55f40a42e872
Java
BaiMaGod/buwangjiServer
/src/com/ttxs/buwangji/bean/UserTask.java
UTF-8
2,558
2.171875
2
[]
no_license
/** * @author yc * @parameter */ package com.ttxs.buwangji.bean; /** * @author Administrator * */ public class UserTask { private String id; private int taskCount; private int finishCount; private int taskDays; private int finishDays; private int issueCount; private String updateTime; private String arg1; private String arg2; private String arg3; /** * @return the arg1 */ public String getArg1() { return arg1; } /** * @param arg1 the arg1 to set */ public void setArg1(String arg1) { this.arg1 = arg1; } /** * @return the arg2 */ public String getArg2() { return arg2; } /** * @param arg2 the arg2 to set */ public void setArg2(String arg2) { this.arg2 = arg2; } /** * @return the arg3 */ public String getArg3() { return arg3; } /** * @param arg3 the arg3 to set */ public void setArg3(String arg3) { this.arg3 = arg3; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the taskCount */ public int getTaskCount() { return taskCount; } /** * @param taskCount the taskCount to set */ public void setTaskCount(int taskCount) { this.taskCount = taskCount; } /** * @return the finishCount */ public int getFinishCount() { return finishCount; } /** * @param finishCount the finishCount to set */ public void setFinishCount(int finishCount) { this.finishCount = finishCount; } /** * @return the taskDays */ public int getTaskDays() { return taskDays; } /** * @param taskDays the taskDays to set */ public void setTaskDays(int taskDays) { this.taskDays = taskDays; } /** * @return the finishDays */ public int getFinishDays() { return finishDays; } /** * @param finishDays the finishDays to set */ public void setFinishDays(int finishDays) { this.finishDays = finishDays; } /** * @return the issueCount */ public int getIssueCount() { return issueCount; } /** * @param issueCount the issueCount to set */ public void setIssueCount(int issueCount) { this.issueCount = issueCount; } /** * @return the updateTime */ public String getUpdateTime() { return updateTime; } /** * @param updateTime the updateTime to set */ public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } }
true
79a76772cb6ea9e0c399673a88a4632a13c9ad15
Java
kmajetic/TinyLayerAroundGit
/src/tinylayeraroundgit/actions/GitGuiAction.java
UTF-8
1,427
1.859375
2
[]
no_license
package tinylayeraroundgit.actions; import java.util.List; import java.util.logging.Logger; import org.eclipse.core.internal.resources.Folder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import temp.TempDebug; import tinylayeraroundgit.git.Command; import tinylayeraroundgit.git.GitCommandExecutor; import tinylayeraroundgit.utils.GitProjectUtils; public class GitGuiAction extends AbstractActionDelegate { /** * Constructor for Action1. */ public GitGuiAction() { super(); } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { List<IProject> projects = getSelectedProjects(); if( projects == null || projects.size() == 0 ) { openInformationDialog( "Problem", "No selected project found" ); return; } for( IProject project : projects ) { Command gitCommand = new Command( "git gui" ); try { gitCommand.executeOn( project, true ); } catch ( InterruptedException e ) { e.printStackTrace(); } GitProjectUtils.refresh( project ); } } }
true
c209c8a83d186534d337163928c246422198ab3c
Java
zhmdlmag/OOP-Intranet
/WSP/src/Tester/TestClass.java
UTF-8
1,168
2.390625
2
[]
no_license
package Tester; import java.util.Collections; import java.util.Comparator; import Enums.Faculty; import Enums.PeriodOfStudy; import Enums.State; import Exceptions.InvalidMarkException; import Intranet.Course; import Intranet.DataBase; import Intranet.IOUtils; import Intranet.Student; import Intranet.TableBuilder; import Intranet.Transcript; import Intranet.User; public class TestClass { public static void main(String[] args) { TableBuilder.buildTable(TableBuilder.bookHeaders, DataBase.getInstance().getBooks(), "LALLA"); TableBuilder.buildTable(TableBuilder.courseHeaders, DataBase.getInstance().getCourses(), "LALLA"); Student student = new Student("Kambar", "Zhamauov", "kz", Faculty.FIT); Course course2 = new Course("ADS", "CSCI1222", 4, 7, Faculty.FIT); student.getTranscript().addCourse(course2, PeriodOfStudy.FIRST_FALL); Transcript transcript = student.getTranscript(); TableBuilder.buildTable(transcript.extractData(), "ASDAD"); TableBuilder.buildTable(TableBuilder.courseFileHeaders, course2.getCourseFiles(), "ASasdd"); // 5 -> Length - 5 = 0 // 6 -> Length - 6 = -1 // 7 -> Length - 7 = -2 // 8 -> Length - 8 = -3 } }
true
c321f438db7aae90605db175fe5b385df928cd14
Java
liebeDY/EZ_Kit
/project_EZ_Kit/EZ_Kit/src/main/java/com/project/ezkit/user/UserMapper.java
UTF-8
452
1.734375
2
[]
no_license
package com.project.ezkit.user; import java.util.Map; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper { void insertUser(User u); User selectUserById(String user_id); User selectUserByNick(String user_nick); void updateUser(User u); void updateUserRating(Map map); void updateUserPoint(User u); void deleteUser(String user_id); User userPasswordByEmail(Map map); }
true
e7b0956df5854cb88a4406a6672e1675b35ce812
Java
qweetar/travel_agency_task2
/src/main/java/ru/myfirstwebsite/dao/impl/CountryDaoImpl.java
UTF-8
2,398
2.515625
3
[]
no_license
package ru.myfirstwebsite.dao.impl; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import ru.myfirstwebsite.dao.CountryDao; import ru.myfirstwebsite.domain.Country; import java.util.List; @Repository @Transactional public class CountryDaoImpl implements CountryDao { @Autowired @Qualifier("sessionFactory") private SessionFactory sessionFactory; @Override public List<Country> findAll() { try (Session session = sessionFactory.openSession()){ return session.createQuery("select tu from Country tu", Country.class).getResultList(); } } @Override public Country getById(Integer id) { try (Session session = sessionFactory.openSession()) { return session.find(Country.class, id); } } @Override public void delete(Integer id) { try (Session session = sessionFactory.openSession()) { session.beginTransaction(); session.delete(getById(id)); session.getTransaction().commit(); session.close(); } } @Override public void save(Country entity) { try (Session session = sessionFactory.openSession()){ Transaction transaction = session.getTransaction(); transaction.begin(); session.save(entity); transaction.commit(); } } @Override public void update(Country entity) { try (Session session = sessionFactory.openSession()) { Transaction transaction = session.getTransaction(); transaction.begin(); session.saveOrUpdate(entity); transaction.commit(); } } @Override public Country findByCountryName(String countryName) { try (Session session = sessionFactory.openSession()) { Query<Country> query = session.createQuery("select tu from Country tu where tu.countryName = :countryName", Country.class); query.setParameter("countryName", countryName); return query.getSingleResult(); } } }
true
27f3ba796af40ec5adb62db3479da48b7645a852
Java
saymatrisha/OnlineDoctorAppointmentSite
/src/com/appoinment/DocUpdateServlet.java
UTF-8
2,847
2.25
2
[]
no_license
package com.appoinment; import java.io.IOException; import java.sql.PreparedStatement; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; public class DocUpdateServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Resource(name="connection") private DataSource ds; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession session = request.getSession(); //PrintWriter out = response.getWriter(); String docId = (String)session.getAttribute("doc_id"); // out.println(docId); String fname = request.getParameter("fname"); String lname= request.getParameter("lname"); String uname = request.getParameter("uname"); String email = request.getParameter("email"); String pass = request.getParameter("pass"); String repass = request.getParameter("rePass"); String degree = request.getParameter("degree"); String department = request.getParameter("department"); String con = request.getParameter("conno"); String gender = request.getParameter("gender"); try { PreparedStatement pSt = ds.getConnection().prepareStatement("update doctors_reg set firstname=?,lastname=?,email=?,password=?,retypepassword=?,degree=?,department=?,contactNo=?,gender=? where username=?"); pSt.setString(1, fname); pSt.setString(2, lname); pSt.setString(3, email); pSt.setString(4, pass); pSt.setString(5, repass); pSt.setString(6, degree); pSt.setString(7, department); pSt.setString(8, con); pSt.setString(9, gender); pSt.setString(10,uname ); int update = pSt.executeUpdate(); if(update > 0) { session.setAttribute("doc_id", docId); session.setAttribute("fname", fname); session.setAttribute("lname", lname); session.setAttribute("uname", uname); session.setAttribute("email", email); session.setAttribute("pass", pass); session.setAttribute("repass",repass); session.setAttribute("degree", degree); session.setAttribute("depart", department); session.setAttribute("conno", con); session.setAttribute("gender", gender); request.setAttribute("sumsg", "Data updated successfully"); request.getRequestDispatcher("DocHomePage.jsp").forward(request, response); } else { request.setAttribute("upmsg", "Something Mess"); request.getRequestDispatcher("DocUpdate.jsp").forward(request, response); } }catch(Exception ex) { ex.printStackTrace(); } } }
true
bd04647cac1fd7a4dc779acbe1c4f169db3d2a2c
Java
renansantosmendes/PhD_MOEAD_02
/src/main/java/Problems/DTLZ5.java
UTF-8
3,345
2.875
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 Problems; import Implementations.AbstractDoubleProblem; import Implementations.DoubleSolution; import java.util.ArrayList; import java.util.List; import org.uma.jmetal.util.JMetalException; /** * * @author renansantos */ public class DTLZ5 extends AbstractDoubleProblem { private Integer originalNumberOfObjectives; /** * Creates a default DTLZ5 problem (12 variables and 3 objectives) */ public DTLZ5() { this(12, 3); } /** * Creates a DTLZ5 problem instance * * @param numberOfVariables Number of variables * @param numberOfObjectives Number of objective functions */ public DTLZ5(Integer numberOfVariables, Integer numberOfObjectives) throws JMetalException { setNumberOfVariables(numberOfVariables); setNumberOfObjectives(numberOfObjectives); setOriginalNumberOfObjectives(numberOfObjectives); setNumberOfAggregatedObjectives(numberOfObjectives); setName("DTLZ5"); List<Double> lowerLimit = new ArrayList<>(getNumberOfVariables()); List<Double> upperLimit = new ArrayList<>(getNumberOfVariables()); for (int i = 0; i < getNumberOfVariables(); i++) { lowerLimit.add(0.0); upperLimit.add(1.0); } setLowerLimit(lowerLimit); setUpperLimit(upperLimit); } /** * Evaluate() method */ public void evaluate(DoubleSolution solution) { int numberOfVariables = getNumberOfVariables(); int numberOfObjectives = getOriginalNumberOfObjectives(); double[] theta = new double[numberOfObjectives - 1]; double g = 0.0; double[] f = new double[numberOfObjectives]; double[] x = new double[numberOfVariables]; int k = getNumberOfVariables() - getOriginalNumberOfObjectives() + 1; for (int i = 0; i < numberOfVariables; i++) { x[i] = solution.getVariableValue(i); } for (int i = numberOfVariables - k; i < numberOfVariables; i++) { g += (x[i] - 0.5) * (x[i] - 0.5); } double t = java.lang.Math.PI / (4.0 * (1.0 + g)); theta[0] = x[0] * java.lang.Math.PI / 2.0; for (int i = 1; i < (numberOfObjectives - 1); i++) { theta[i] = t * (1.0 + 2.0 * g * x[i]); } for (int i = 0; i < numberOfObjectives; i++) { f[i] = 1.0 + g; } for (int i = 0; i < numberOfObjectives; i++) { for (int j = 0; j < numberOfObjectives - (i + 1); j++) { f[i] *= java.lang.Math.cos(theta[j]); } if (i != 0) { int aux = numberOfObjectives - (i + 1); f[i] *= java.lang.Math.sin(theta[aux]); } } for (int i = 0; i < numberOfObjectives; i++) { solution.setObjective(i, f[i]); } //Renan added this part List<Double> objectivesList = new ArrayList<>(); for (int i = 0; i < numberOfObjectives; i++) { objectivesList.add(f[i]); } solution.setAttribute("RealObjectives", objectivesList); } }
true
a7f1c85b1030a647299bddf4be270521499410b8
Java
ReBicycle/Rebicycle_Ver1
/Rebicycle_Ver1/src/main/java/org/kosta/rebicycle/model/dao/BicycleDAOImpl3.java
UTF-8
1,062
2.1875
2
[]
no_license
package org.kosta.rebicycle.model.dao; import java.util.List; import javax.annotation.Resource; import org.kosta.rebicycle.model.vo.BicycleVO; import org.kosta.rebicycle.model.vo.CalendarVO; import org.kosta.rebicycle.model.vo.RentVO; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; @Repository public class BicycleDAOImpl3 implements BicycleDAO{ @Resource private SqlSessionTemplate template; public BicycleVO findBicycleByNo(int bicycleNo){ return template.selectOne("bicycle.findBicycleByNo",bicycleNo); } public List<BicycleVO> findBicycleList() { return template.selectList("bicycle.findBicycleList"); } public BicycleVO findBicycleDetailByNo(int no) { return template.selectOne("bicycle.findBicycleDetailByNo", no); } public List<CalendarVO> findPossibleDayByNo(int no){ return template.selectList("bicycle.findPossibleDayByNo", no); } //빌리기 public void rentRegister(RentVO rvo){ template.insert("bicycle.rentRegister",rvo); } }
true
2f5c76762758ab2d1152b7665275e7a5ff8dc43c
Java
wsongtiang/Process
/LogIn.java
UTF-8
9,824
2.34375
2
[]
no_license
package ui; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.font.TextAttribute; import java.util.Map; import javax.swing.*; import domain.*; import control.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class LogIn extends JFrame{ private String host = "jdbc:derby://localhost:1527/BusDB"; private String user = "nbuser"; private String password = "nbuser"; private String autable = "AUTHENTICATION"; private Connection conn; private PreparedStatement stmt; // private LoginDomain logindo; // private LoginControl logcon; private JLabel jlbuserid = new JLabel("UserID"); private JLabel jlbpassword = new JLabel("Password"); private JTextField jtfuserid = new JTextField (15); private JPasswordField jtfpassword = new JPasswordField(); private JButton jbtlogin = new JButton("LOGIN"); // private JLabel jlbforget = new JLabel("Forget Password?"); private JButton jbtforget = new JButton("Forget Password?"); private ImageIcon login = new ImageIcon(getClass().getResource("loginSmall.png")); private JLabel logo = new JLabel(login,SwingConstants.CENTER); private JPanel logoPanel = new JPanel(new FlowLayout()); public LogIn(){ // logcon = new LoginControl(); setLayout(new BorderLayout()); JPanel basic = new JPanel(); basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS)); add(basic); JPanel topPanel = new JPanel(new BorderLayout(0, 0)); topPanel.setMaximumSize(new Dimension(450, 0)); JLabel hint = new JLabel("Log In"); hint.setBorder(BorderFactory.createEmptyBorder(0, 25, 0, 0)); topPanel.add(hint); logoPanel.add(logo); JSeparator separator = new JSeparator(); separator.setForeground(Color.gray); topPanel.add(separator, BorderLayout.SOUTH); topPanel.add(logoPanel, BorderLayout.NORTH); basic.add(topPanel); JPanel jptop = new JPanel(new BorderLayout()); jptop.setBorder(BorderFactory.createEmptyBorder(15,25,15,25)); JPanel pane1 = new JPanel(); JPanel jpcenter = new JPanel(new GridLayout(4,2)); jpcenter.add(jlbuserid); jpcenter.add(jtfuserid); jpcenter.add(new JLabel("")); jpcenter.add(new JLabel("")); jpcenter.add(jlbpassword); jpcenter.add(jtfpassword); jpcenter.add(new JLabel("")); // jpcenter.add(jlbforget); // Font font = jlbforget.getFont(); jpcenter.add(jbtforget); Font font = jbtforget.getFont(); //button transparent jbtforget.setOpaque(false); jbtforget.setContentAreaFilled(false); jbtforget.setBorderPainted(false); Map attributes = font.getAttributes(); attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); jbtforget.setFont(font.deriveFont(attributes)); // jlbforget.setFont(font.deriveFont(attributes)); JPanel pane2 = new JPanel(); JPanel jpsouth = new JPanel(); jpsouth.add(jbtlogin); pane1.add(jpcenter); basic.add(jptop,BorderLayout.NORTH); jptop.add(pane1,BorderLayout.CENTER); pane2.add(jpsouth); jptop.add(pane2,BorderLayout.SOUTH); createConnection(); jbtlogin.addActionListener(new ButtonListener()); jbtforget.addActionListener(new ForgetListener()); setTitle("LogIn"); setSize(600,350); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public ResultSet selectRecord(String userid){ String queryStr = "SELECT * FROM "+ autable + " WHERE userid = ? "; ResultSet rs = null; try{ stmt = conn.prepareStatement(queryStr); stmt.setString(1, userid); rs = stmt.executeQuery(); }catch(SQLException ex){ JOptionPane.showMessageDialog(null,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); } return rs; } // private class ButtonListener implements ActionListener{ // public void actionPerformed(ActionEvent e){ // if(e.getSource() == jbtlogin){ // String userid = jtfuserid.getText(); // String password = jtfpassword.getText(); // // ResultSet rs // } // } // } private class ButtonListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if(e.getSource() == jbtlogin){ String enteredUsername = jtfuserid.getText(); String enteredPassword = jtfpassword.getText(); if(!enteredUsername.equals("") && !enteredPassword.equals("")){ ResultSet rs = selectRecord(enteredUsername); try{ if(rs.next()){ String username = rs.getString("userid"); String password = rs.getString("password"); String staffid = rs.getString("staffid"); if(username.compareTo(enteredUsername) == 0){ if(password.compareTo(enteredPassword) == 0){ if(staffid.charAt(0)=='M'){ JOptionPane.showMessageDialog(null, "Welcome,Manager!","Login Successful!",JOptionPane.INFORMATION_MESSAGE); new AdminLogin(); closeFrame(); } else if(staffid.charAt(0)=='S'){ JOptionPane.showMessageDialog(null, "Welcome,Staff!","Login Successful!",JOptionPane.INFORMATION_MESSAGE); new StaffLogin(); closeFrame(); } }else{ JOptionPane.showMessageDialog(null, "Invalid password.","Login Failed",JOptionPane.ERROR_MESSAGE); jtfuserid.setText(""); jtfpassword.setText(""); jtfuserid.requestFocusInWindow();} } }else{ JOptionPane.showMessageDialog(null, "Invalid username.","Login Failed",JOptionPane.ERROR_MESSAGE); jtfuserid.setText(""); jtfpassword.setText(""); jtfuserid.requestFocusInWindow();} }catch(SQLException ex){ } // if(validity){ // // // JOptionPane.showMessageDialog(null,"Congrats login successful!","Welcome",JOptionPane.INFORMATION_MESSAGE); // new StaffLogin(); //// closeFrame(); //// new Home(); //// currentUser = enteredUsername; //// Login loginReadStaff = loginControl.selectUser(enteredUsername); //// currentStaff = loginReadStaff.getStaffID(); // dispose(); // } // else{ // JOptionPane.showMessageDialog(null, "Invalid username or password.","Login Failed",JOptionPane.ERROR_MESSAGE); // jtfuserid.setText(""); // jtfpassword.setText(""); // jtfuserid.requestFocusInWindow(); // } } else{ JOptionPane.showMessageDialog(null,"Both username and password fields cannot be blank!","Attention",JOptionPane.WARNING_MESSAGE); // jtfUsername.requestFocusInWindow(); } } else{ //exit button // logcon.closeDB(); closeFrame(); System.exit(0); } } } public void closeFrame(){ this.dispose(); } private class ForgetListener implements ActionListener{ public void actionPerformed(ActionEvent e){ new ForgetPassword(); closeFrame(); } } private class WindowListener extends WindowAdapter{ public void windowClosing(WindowEvent e) { closeFrame(); } } private void createConnection(){ try{ conn = DriverManager.getConnection(host,user,password); } catch(SQLException ex){ JOptionPane.showMessageDialog(null,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE); } } public static void main(String [] args){ LogIn frame = new LogIn(); } }
true
7a4b5d5638807b39237eff4c209b01f47f1559fd
Java
nwoodthorpe/BusStop
/Android/app/src/main/java/com/nwoodthorpe/busstop/TutorialMenuListAdapter.java
UTF-8
2,454
2.296875
2
[]
no_license
package com.nwoodthorpe.busstop; /** * Created by Nathaniel on 3/23/2016. */ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.TextView; import java.sql.Time; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; /** * Created by Nathaniel on 12/13/2015. */ // Adapter that links our data to the ListView on Transactions Activity public class TutorialMenuListAdapter extends ArrayAdapter<FavRoute> { private ArrayList<FavRoute> list; int listLayoutXML = R.layout.menu_list_item; public TutorialMenuListAdapter(Context context, int textViewResourceId, ArrayList<FavRoute> list) { super(context, textViewResourceId, list); this.list = list; } @Override public int getCount() { return list==null?0:list.size(); } @Override public View getView(final int position, View convertView, ViewGroup parent) { final FavRoute user = list.get(position); View v = null; LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); int layout = listLayoutXML; v = vi.inflate(layout, parent, false); if (user != null) { TextView name = (TextView) v.findViewById(R.id.name); TextView time = (TextView) v.findViewById(R.id.time); Switch enabled = null; TextView smallName = (TextView)v.findViewById(R.id.smallName); if (name != null) { name.setText(user.name); } if (time != null) { int secondsETA = user.seconds; if(secondsETA < 10){ time.setText("Due!"); }else if(secondsETA < 60){ time.setText("Less than a minute!"); }else { time.setText((secondsETA / 60) + " minutes"); } } if(enabled != null){ enabled.setChecked(user.enabled==1); } if(smallName!=null){ smallName.setText(user.shortRoute); } } return v; } }
true
1eaedbfc55486b2fbe751f13da7eae04713e9785
Java
Goju-Ryu/xvm
/javatools/src/main/java/org/xvm/compiler/ast/CmpExpression.java
UTF-8
18,021
2.03125
2
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "CC-BY-4.0" ]
permissive
package org.xvm.compiler.ast; import org.xvm.asm.Argument; import org.xvm.asm.Constant; import org.xvm.asm.ConstantPool; import org.xvm.asm.ErrorListener; import org.xvm.asm.GenericTypeResolver; import org.xvm.asm.MethodStructure.Code; import org.xvm.asm.Op; import org.xvm.asm.OpCondJump; import org.xvm.asm.OpTest; import org.xvm.asm.constants.TypeConstant; import org.xvm.asm.op.Cmp; import org.xvm.asm.op.IsEq; import org.xvm.asm.op.IsGt; import org.xvm.asm.op.IsGte; import org.xvm.asm.op.IsLt; import org.xvm.asm.op.IsLte; import org.xvm.asm.op.IsNotEq; import org.xvm.asm.op.IsNotNull; import org.xvm.asm.op.IsNull; import org.xvm.asm.op.JumpEq; import org.xvm.asm.op.JumpGt; import org.xvm.asm.op.JumpGte; import org.xvm.asm.op.JumpLt; import org.xvm.asm.op.JumpLte; import org.xvm.asm.op.JumpNotEq; import org.xvm.asm.op.JumpNotNull; import org.xvm.asm.op.JumpNull; import org.xvm.asm.op.Label; import org.xvm.compiler.Compiler; import org.xvm.compiler.Token; import org.xvm.compiler.Token.Id; import org.xvm.compiler.ast.Context.Branch; import org.xvm.util.Severity; /** * Comparison binary expression. * * <ul> * <li><tt>COMP_EQ: "=="</tt> - </li> * <li><tt>COMP_NEQ: "!="</tt> - </li> * <li><tt>COMP_LT: "<"</tt> - </li> * <li><tt>COMP_GT: "><tt>"</tt> - </li> * <li><tt>COMP_LTEQ: "<="</tt> - </li> * <li><tt>COMP_GTEQ: ">="</tt> - </li> * <li><tt>COMP_ORD: "<=><tt>"</tt> - </li> * </ul> * * @see TypeConstant#supportsEquals * @see TypeConstant#supportsCompare * @see TypeConstant#callEquals * @see TypeConstant#callCompare */ public class CmpExpression extends BiExpression { // ----- constructors -------------------------------------------------------------------------- public CmpExpression(Expression expr1, Token operator, Expression expr2) { super(expr1, operator, expr2); switch (operator.getId()) { case COMP_EQ: case COMP_NEQ: case COMP_LT: case COMP_GT: case COMP_LTEQ: case COMP_GTEQ: case COMP_ORD: break; default: throw new IllegalArgumentException("operator: " + operator); } } // ----- accessors ----------------------------------------------------------------------------- /** * @return true iff the expression produces a Boolean value, or false iff the expression * produces an Ordered value */ public boolean producesBoolean() { return operator.getId() != Id.COMP_ORD; } /** * @return true iff the expression uses a type composition's equals() function, or false iff the * expression uses a type composition's compare() function */ public boolean usesEquals() { Id id = operator.getId(); return id == Id.COMP_EQ | id == Id.COMP_NEQ; } public boolean isAscending() { Id id = operator.getId(); return id == Id.COMP_LT | id == Id.COMP_LTEQ; } // ----- compilation --------------------------------------------------------------------------- @Override public TypeConstant getImplicitType(Context ctx) { return producesBoolean() ? pool().typeBoolean() : pool().typeOrdered(); } @Override protected Expression validate(Context ctx, TypeConstant typeRequired, ErrorListener errs) { ConstantPool pool = pool(); boolean fValid = true; boolean fEqual = usesEquals(); // attempt to guess the types that are being compared TypeConstant type1 = expr1.getImplicitType(ctx); // allow the second expression to resolve names based on the first value type's // contributions boolean fInfer = type1 != null; if (fInfer) { ctx = ctx.enterInferring(type1); } TypeConstant type2 = expr2.getImplicitType(ctx); if (fInfer) { ctx = ctx.exit(); } TypeConstant typeRequest = chooseCommonType(pool, fEqual, type1, type2); Expression expr1New = expr1.validate(ctx, typeRequest, errs); if (expr1New == null) { fValid = false; } else { expr1 = expr1New; type1 = expr1New.getType(); // if we weren't previously able to determine a "target" type to use, then try again now // that the first expression is validated if (typeRequest == null) { typeRequest = chooseCommonType(pool, fEqual, type1, type2); } } if (fInfer) { ctx = ctx.enterInferring(type1); } Expression expr2New = expr2.validate(ctx, typeRequest, errs); if (fInfer) { ctx = ctx.exit(); } if (expr2New == null) { fValid = false; } else { expr2 = expr2New; type2 = expr2New.getType(); if (fValid) { boolean fConst1 = expr1New.isConstant(); boolean fConst2 = expr2New.isConstant(); // make sure that we can compare the left value to the right value TypeConstant typeCommon = chooseCommonType(pool, fEqual, type1, fConst1, type2, fConst2, true); if (typeCommon == null) { // try to resolve the types using the current context GenericTypeResolver resolver = ctx.getFormalTypeResolver(); TypeConstant type1R = type1.resolveGenerics(pool, resolver); TypeConstant type2R = type2.resolveGenerics(pool, resolver); typeCommon = chooseCommonType(pool, fEqual, type1R, fConst1, type2R, fConst2, true); } if (typeCommon == null) { fValid = false; if (type1.equals(pool.typeNull())) { log(errs, Severity.ERROR, Compiler.EXPRESSION_NOT_NULLABLE, type2.getValueString()); } else if (type2.equals(pool.typeNull())) { log(errs, Severity.ERROR, Compiler.EXPRESSION_NOT_NULLABLE, type1.getValueString()); } else { log(errs, Severity.ERROR, Compiler.TYPES_NOT_COMPARABLE, type1.getValueString(), type2.getValueString()); } } else { m_typeCommon = typeCommon; } } } TypeConstant typeResult = getImplicitType(ctx); Constant constVal = null; if (fValid) { if (expr1New.isConstant() && expr2New.isConstant()) { try { constVal = expr1New.toConstant().apply(operator.getId(), expr2New.toConstant()); } catch (RuntimeException e) {} } else if (expr1New instanceof NameExpression && type2.equals(pool().typeNull())) { m_fArg2Null = true; fValid = checkNullComparison(ctx, (NameExpression) expr1New, errs); } else if (expr2New instanceof NameExpression && type1.equals(pool().typeNull())) { m_fArg1Null = true; fValid = checkNullComparison(ctx, (NameExpression) expr2New, errs); } } return finishValidation(ctx, typeRequired, typeResult, fValid ? TypeFit.Fit : TypeFit.NoFit, constVal, errs); } /** * Choose a common type for the specified types without checking for a required function. * * @param fEqual true if we need the equality comparison; false for ordering comparison * @param type1 the first type * @param type2 the second type * * @return the common type; null if there is no common type */ protected static TypeConstant chooseCommonType( ConstantPool pool, boolean fEqual, TypeConstant type1, TypeConstant type2) { return chooseCommonType(pool, fEqual, type1, false, type2, false, false); } /** * Choose a common type for the specified types. * * @param fEqual true if we need the equality comparison; false for ordering comparison * @param type1 the first type * @param fConst1 specifies if the first expression is a constant; used only if fCheck is true * @param type2 the second type * @param fConst2 specifies if the second expression is a constant; used only if fCheck is true * @param fCheck if true, ensure the common type has the required function * * @return the common type; null if there is no common type */ protected static TypeConstant chooseCommonType(ConstantPool pool, boolean fEqual, TypeConstant type1, boolean fConst1, TypeConstant type2, boolean fConst2, boolean fCheck) { if (type1 != null && type1.containsUnresolved() || type2 != null && type2.containsUnresolved()) { return null; } TypeConstant typeCommon = Op.selectCommonType(type1, type2, ErrorListener.BLACKHOLE); if (type1 == null || type2 == null) { return typeCommon; } if (typeCommon != null && fCheck) { if (fEqual ? typeCommon.supportsEquals (type1, fConst1) && typeCommon.supportsEquals (type2, fConst2) // Compare : typeCommon.supportsCompare(type1, fConst1) && typeCommon.supportsCompare(type2, fConst2)) { return typeCommon; } // the support check failed; go to the resolution logic typeCommon = null; } if (typeCommon == null) { // equality check for any Ref objects is allowed if (fEqual && type1.isA(pool.typeRef()) && type2.isA(pool.typeRef())) { return pool.typeRef(); } // try to resolve formal types boolean fFormal1 = type1.containsFormalType(true); boolean fFormal2 = type2.containsFormalType(true); if (fFormal1 ^ fFormal2) { if (fFormal1) { type1 = type1.resolveConstraints(); } if (fFormal2) { type2 = type2.resolveConstraints(); } // since it's guaranteed that neither type contains formal, we can recurse typeCommon = chooseCommonType(pool, fEqual, type1, fConst1, type2, fConst2, fCheck); } } return typeCommon; } private boolean checkNullComparison(Context ctx, NameExpression exprTarget, ErrorListener errs) { TypeConstant typeTarget = exprTarget.getType(); TypeConstant typeNull = pool().typeNull(); TypeConstant typeTrue = null; TypeConstant typeFalse = null; if (!typeTarget.isNullable() && !typeNull.isA(typeTarget.resolveConstraints())) { log(errs, Severity.ERROR, Compiler.EXPRESSION_NOT_NULLABLE, typeTarget.getValueString()); return false; } switch (operator.getId()) { case COMP_EQ: typeTrue = typeNull; typeFalse = typeTarget.removeNullable(); break; case COMP_NEQ: typeTrue = typeTarget.removeNullable(); typeFalse = typeNull; break; } exprTarget.narrowType(ctx, Branch.WhenTrue, typeTrue); exprTarget.narrowType(ctx, Branch.WhenFalse, typeFalse); return true; } @Override public void generateAssignment(Context ctx, Code code, Assignable LVal, ErrorListener errs) { if (LVal.isLocalArgument()) { // evaluate the sub-expressions Argument arg1 = expr1.generateArgument(ctx, code, true, true, errs); Argument arg2 = expr2.generateArgument(ctx, code, true, true, errs); Argument argResult = LVal.getLocalArgument(); OpTest op; // generate the op that combines the two sub-expressions switch (operator.getId()) { case COMP_EQ: op = m_fArg1Null ? new IsNull(arg2, argResult) : m_fArg2Null ? new IsNull(arg1, argResult) : new IsEq(arg1, arg2, argResult); break; case COMP_NEQ: op = m_fArg1Null ? new IsNotNull(arg2, argResult) : m_fArg2Null ? new IsNotNull(arg1, argResult) : new IsNotEq(arg1, arg2, argResult); break; case COMP_LT: op = new IsLt(arg1, arg2, argResult); break; case COMP_GT: op = new IsGt(arg1, arg2, argResult); break; case COMP_LTEQ: op = new IsLte(arg1, arg2, argResult); break; case COMP_GTEQ: op = new IsGte(arg1, arg2, argResult); break; case COMP_ORD: op = new Cmp(arg1, arg2, argResult); break; default: throw new IllegalStateException(); } op.setCommonType(m_typeCommon); code.add(op); return; } super.generateAssignment(ctx, code, LVal, errs); } @Override public void generateConditionalJump( Context ctx, Code code, Label label, boolean fWhenTrue, ErrorListener errs) { if (!isConstant() && producesBoolean()) { // evaluate the sub-expressions Argument arg1 = expr1.generateArgument(ctx, code, true, true, errs); Argument arg2 = expr2.generateArgument(ctx, code, true, true, errs); OpCondJump op; // generate the op that combines the two sub-expressions switch (operator.getId()) { case COMP_EQ: op = fWhenTrue ? (m_fArg1Null ? new JumpNull(arg2, label) : m_fArg2Null ? new JumpNull(arg1, label) : new JumpEq (arg1, arg2, label)) : (m_fArg1Null ? new JumpNotNull(arg2, label) : m_fArg2Null ? new JumpNotNull(arg1, label) : new JumpNotEq (arg1, arg2, label)); break; case COMP_NEQ: op = fWhenTrue ? (m_fArg1Null ? new JumpNotNull(arg2, label) : m_fArg2Null ? new JumpNotNull(arg1, label) : new JumpNotEq (arg1, arg2, label)) : (m_fArg1Null ? new JumpNull(arg2, label) : m_fArg2Null ? new JumpNull(arg1, label) : new JumpEq (arg1, arg2, label)); break; case COMP_LT: op = fWhenTrue ? new JumpLt(arg1, arg2, label) : new JumpGte(arg1, arg2, label); break; case COMP_GT: op = fWhenTrue ? new JumpGt(arg1, arg2, label) : new JumpLte(arg1, arg2, label); break; case COMP_LTEQ: op = fWhenTrue ? new JumpLte(arg1, arg2, label) : new JumpGt(arg1, arg2, label); break; case COMP_GTEQ: op = fWhenTrue ? new JumpGte(arg1, arg2, label) : new JumpLt(arg1, arg2, label); break; default: case COMP_ORD: throw new IllegalStateException(); } op.setCommonType(m_typeCommon); code.add(op); return; } super.generateConditionalJump(ctx, code, label, fWhenTrue, errs); } // ----- fields -------------------------------------------------------------------------------- /** * The common type used for the comparison. */ protected TypeConstant m_typeCommon; private transient boolean m_fArg1Null; // is the first arg equal to "Null" private transient boolean m_fArg2Null; // is the second arg equal to "Null" }
true
68cb5047ca044c94418768313b8c36b8e0e6db64
Java
guimattiello/CofreExemplo
/src/test/java/cucumbertests/CofreTest.java
UTF-8
646
1.703125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cucumbertests; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; import org.junit.Test; import static org.junit.Assert.*; import org.junit.runner.RunWith; /** * * @author guimat */ @RunWith(Cucumber.class) @CucumberOptions(plugin = {"pretty", "html:target/cucumber"}, features="src/test/resources/cucumbertests/") public class CofreTest { public CofreTest() { } @Test public void hello() { } }
true
0d924e24d8ce84517ef07a4664a1de6d73176505
Java
ShauryaS99/MDBInventory
/app/src/main/java/com/jackie/mdbinventory/Inventory.java
UTF-8
1,348
2.375
2
[]
no_license
package com.jackie.mdbinventory; import android.provider.BaseColumns; /** Represents the purchases made by MDB members. * @author: Jacqueline Zhang * @date: 03/05/2019 * */ public final class Inventory { private Inventory() {} public static class InventoryEntry implements BaseColumns { public static final String TABLE_NAME = "purchases"; public static final String COLUMN_MERCHANT_NAME = "merchant"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_DATE = "date"; public static final String COLUMN_DATE_LONG = "date_long"; public static final String COLUMN_COST = "cost"; public static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + InventoryEntry.TABLE_NAME + " (" + InventoryEntry._ID + " INTEGER PRIMARY KEY," + InventoryEntry.COLUMN_MERCHANT_NAME + " TEXT," + InventoryEntry.COLUMN_DESCRIPTION + " TEXT," + InventoryEntry.COLUMN_DATE + " TEXT," + InventoryEntry.COLUMN_DATE_LONG + " TEXT," + InventoryEntry.COLUMN_COST + " TEXT)"; public static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + InventoryEntry.TABLE_NAME; } }
true
fe6474789093adbaa37ed7c606f45c428ddf7411
Java
recnederland/winter2021turkish
/src/javaProgramlamayaGirisInheritance2/KrediUI.java
UTF-8
323
2.015625
2
[]
no_license
package javaProgramlamayaGirisInheritance2; public class KrediUI { // public void KrediHesapla(OgretmenKrediManager ogretmenKrediManager) { // ogretmenKrediManager.Hesapla(); // } Bunun yerine asagidaki kullanilabilir public void KrediHesapla(BaseKrediManager baseKrediManager) { baseKrediManager.Hesapla(); } }
true
b039714ecb2caf260a851fb68b4901492f84b922
Java
xiezhifeng/mysource
/jira-project/jira-components/jira-core/src/main/java/com/atlassian/jira/issue/issuetype/IssueTypeImpl.java
UTF-8
2,088
1.992188
2
[]
no_license
/* * Copyright (c) 2002-2004 * All rights reserved. */ package com.atlassian.jira.issue.issuetype; import com.atlassian.jira.avatar.Avatar; import com.atlassian.jira.avatar.AvatarManager; import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.jira.issue.IssueConstantImpl; import com.atlassian.jira.security.JiraAuthenticationContext; import com.atlassian.jira.util.BaseUrl; import com.atlassian.jira.web.action.admin.translation.TranslationManager; import org.ofbiz.core.entity.GenericValue; public class IssueTypeImpl extends IssueConstantImpl implements IssueType { public static final String AVATAR_FIELD = "avatar"; private final AvatarManager avatarManager; public IssueTypeImpl(GenericValue genericValue, TranslationManager translationManager, JiraAuthenticationContext authenticationContext, BaseUrl locator, AvatarManager avatarManager) { super(genericValue, translationManager, authenticationContext, locator); this.avatarManager = avatarManager; } public boolean isSubTask() { return ComponentAccessor.getSubTaskManager().isSubTaskIssueType(genericValue); } @Override public Avatar getAvatar() { final Long avatarId = getAvatarId(); return avatarId != null ? getAvatarOrDefault(avatarId) : null; } private Avatar getAvatarOrDefault(final Long avatarId) { Avatar assignedAvatar = avatarManager.getById(avatarId); if ( null==assignedAvatar ) { assignedAvatar = avatarManager.getById(avatarManager.getDefaultAvatarId(Avatar.Type.ISSUETYPE)); } return assignedAvatar; } public String getType() { if (isSubTask()) { return "Sub-Task"; } else { return "Standard"; } } public Long getAvatarId() { return genericValue.getLong(AVATAR_FIELD); } public void setAvatarId(final Long avatarId) { genericValue.set(AVATAR_FIELD, avatarId); } }
true
dfa362ec1711d13e0d3e50596ee7cbd26290c521
Java
SilverChu/LeetCode
/src/com/legend/easy/ExcelSheetColumnNumber.java
UTF-8
664
3.734375
4
[]
no_license
package com.legend.easy; /** * #171 Given a column title as appear in an Excel sheet, return its * corresponding column number. * <p> * For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 */ public class ExcelSheetColumnNumber { public int titleToNumber(String s) { int result = 0; for (int i = 0; i < s.length(); i++) { result = result * 26 + (s.charAt(i) - 'A' + 1); } return result; } public static void main(String[] args) { ExcelSheetColumnNumber escn = new ExcelSheetColumnNumber(); int result = escn.titleToNumber("BK"); System.out.println(result); } }
true
c9d11c306ba031259d933ebe2b2338efe3afc86d
Java
leochinaliu/flink-cdc-connectors
/flink-connector-mongodb-cdc/src/main/java/com/alibaba/ververica/cdc/connectors/mongodb/internal/MongoDBCSConnector.java
UTF-8
489
2.03125
2
[ "Apache-2.0" ]
permissive
package com.alibaba.ververica.cdc.connectors.mongodb.internal; import io.debezium.connector.mongodb.MongoDbConnector; import org.apache.kafka.connect.connector.Task; /** * A Kafka Connect source connector that creates {@link MongoDBCSConnectorTask tasks} that replicate the context of one or more * MongoDB replica sets. */ public class MongoDBCSConnector extends MongoDbConnector { @Override public Class<? extends Task> taskClass() { return MongoDBCSConnectorTask.class; } }
true
873d857213af015f418fc69cbfaab17cb644fdb7
Java
lnyhyzy/openapi-sdk-java
/src/main/java/com/xinrenxinshi/XrxsApprovalService.java
UTF-8
4,412
2.140625
2
[]
no_license
package com.xinrenxinshi; import com.xinrenxinshi.domain.approval.FlowType; import com.xinrenxinshi.domain.approval.ProcessFlowInfo; import com.xinrenxinshi.domain.approval.ProcessStepAndCopyInfo; import com.xinrenxinshi.exception.ApiException; import com.xinrenxinshi.openapi.XrxsOpenapiClient; import com.xinrenxinshi.request.ApprovalDetialRequest; import com.xinrenxinshi.request.ApprovalListRequest; import com.xinrenxinshi.request.ApprovalNodeInfoRequest; import com.xinrenxinshi.request.ApprovalTypeGetRequest; import com.xinrenxinshi.response.ApprovalDetialResponse; import com.xinrenxinshi.response.ApprovalListResponse; import com.xinrenxinshi.response.ApprovalNodeInfoResponse; import com.xinrenxinshi.response.ApprovalTypeGetResponse; import java.util.List; /** * 审批相关service * * @author: liuchenhui * @create: 2019-11-14 14:46 **/ public abstract class XrxsApprovalService { /** * 获取审批列表 * * @param access_token 授权token * @param pageNo 列表起始页 * @param pageSize 每页条数 * @param flowStatus 审批状态list * @param flowTypes 审批类型list * @param departmentIds 部门ids */ public static ApprovalListResponse getFlowList(String access_token, Integer pageNo, Integer pageSize, List<String> flowStatus, List<String> flowTypes, List<String> departmentIds) throws ApiException { ApprovalListRequest request = new ApprovalListRequest(access_token); request.setPageNo(pageNo); request.setPageSize(pageSize); request.setFlowStatus(flowStatus); request.setFlowTypes(flowTypes); request.setDepartmentIds(departmentIds); XrxsOpenapiClient openapiClient = XrxsOpenapiClient.getInstance(); ApprovalListResponse response = openapiClient.execute(request); if (response != null && response.getErrcode() == 0) { return response; } throw new ApiException(response.getErrcode(), response.getErrmsg()); } /** * 获取审批表单详情 * * @param access_token 授权token * @param processId 审批id */ public static ProcessFlowInfo getFlowDetail(String access_token, Integer processId) throws ApiException { ApprovalDetialRequest request = new ApprovalDetialRequest(access_token); request.setProcessId(processId); XrxsOpenapiClient openapiClient = XrxsOpenapiClient.getInstance(); ApprovalDetialResponse response = openapiClient.execute(request); if (response != null && response.getErrcode() == 0) { return response.getData(); } throw new ApiException(response.getErrcode(), response.getErrmsg()); } /** * 获取审批类型 * * @param access_token 授权token */ public static List<FlowType> getFLowTypes(String access_token) throws ApiException { ApprovalTypeGetRequest request = new ApprovalTypeGetRequest(access_token); XrxsOpenapiClient openapiClient = XrxsOpenapiClient.getInstance(); ApprovalTypeGetResponse response = openapiClient.execute(request); if (response != null && response.getErrcode() == 0) { return response.getData(); } throw new ApiException(response.getErrcode(), response.getErrmsg()); } /** * 获取审批节点信息 * * @param access_token 授权token * @param processId 审批id */ public static ProcessStepAndCopyInfo getNodeInfo(String access_token, Integer processId) throws ApiException { ApprovalNodeInfoRequest request = new ApprovalNodeInfoRequest(access_token); request.setProcessId(processId); XrxsOpenapiClient openapiClient = XrxsOpenapiClient.getInstance(); ApprovalNodeInfoResponse response = openapiClient.execute(request); if (response != null && response.getErrcode() == 0) { return response.getData(); } throw new ApiException(response.getErrcode(), response.getErrmsg()); } }
true
ca754b048377fb010682493c310548a90461258b
Java
yuanyixiong/esb
/uippush-client-api/src/main/java/com/sinoif/esb/query/model/dto/ApproveInfoDataDTO.java
UTF-8
1,887
2.0625
2
[]
no_license
package com.sinoif.esb.query.model.dto; import com.alibaba.fastjson.annotation.JSONField; import java.io.Serializable; /** * <p>待审核数据明细</p> * * @author chenxjuc * @date 2019/11/11 */ public class ApproveInfoDataDTO implements Serializable { @JSONField(name = "_id") private String id; /*** * 待审核数据 JSON格式 */ @JSONField(name = "data") private Object data; @JSONField(name = "_parent") private String parent; @JSONField(name = "_interface_id") private String interfaceId; @JSONField(name = "_topic") private String topic; @JSONField(name = "_approve_status") private String approveStatus; /** * 审核时间 */ @JSONField(name = "_approve_time", format = "yyyy-MM-dd HH:mm:ss") private String approveTime; public String getId() { return id; } public void setId(String id) { this.id = id; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public String getInterfaceId() { return interfaceId; } public void setInterfaceId(String interfaceId) { this.interfaceId = interfaceId; } public String getApproveStatus() { return approveStatus; } public void setApproveStatus(String approveStatus) { this.approveStatus = approveStatus; } public String getApproveTime() { return approveTime; } public void setApproveTime(String approveTime) { this.approveTime = approveTime; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } }
true
2a9b061928250674250569c71cadc864350d0d93
Java
AhmedMAghani/Wuzzuf-data-analysis-client
/src/main/java/service/WuzzufServiceImpl.java
UTF-8
558
2.34375
2
[]
no_license
package service; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.core.MediaType; @Consumes(MediaType.APPLICATION_JSON) public class WuzzufServiceImpl implements WuzzufService { private final Client restClient; public WuzzufServiceImpl(Client restClient) { this.restClient = restClient; } public String fetchWuzzufDataCount(String url) { return restClient .target(url) .request(MediaType.APPLICATION_JSON) .get(String.class); } }
true
7f204c0d8334d69d2edfc6f689281521f1cef26c
Java
pralabhkumar/TonY
/tony-core/src/main/java/com/linkedin/tony/models/JobEvent.java
UTF-8
1,041
2.453125
2
[ "BSD-2-Clause", "BSD-3-Clause", "Apache-2.0", "MIT" ]
permissive
/** * Copyright 2018 LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. * See LICENSE in the project root for license information. */ package com.linkedin.tony.models; import com.linkedin.tony.events.Event; import com.linkedin.tony.events.EventType; import java.util.Date; public class JobEvent { private EventType type; private Object event; private long timestamp; public EventType getType() { return type; } public Object getEvent() { return event; } public Date getTimestamp() { return new Date(timestamp); } public void setType(EventType type) { this.type = type; } public void setEvent(Object event) { this.event = event; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public static JobEvent convertEventToJobEvent(Event e) { JobEvent wrapper = new JobEvent(); wrapper.setType(e.getType()); wrapper.setEvent(e.getEvent()); wrapper.setTimestamp(e.getTimestamp()); return wrapper; } }
true
e3aad7837fb9d06979985d146471961628a9420d
Java
pptsagar279/smps
/app/src/main/java/com/example/spasbynituk/student.java
UTF-8
2,952
2.03125
2
[]
no_license
package com.example.spasbynituk; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.example.spasbynituk.databinding.ActivitySigninactivityBinding; import com.example.spasbynituk.databinding.ActivityStudentBinding; import com.example.spasbynituk.module.User; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.FirebaseDatabase; public class student extends AppCompatActivity { ActivityStudentBinding binding; FirebaseAuth mAuth; FirebaseDatabase database; ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityStudentBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); getSupportActionBar().hide(); mAuth = FirebaseAuth.getInstance(); database = FirebaseDatabase.getInstance(); progressDialog = new ProgressDialog(student.this); progressDialog.setTitle("Creating Account"); progressDialog.setTitle("we are creating your account"); binding.button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { progressDialog.show(); mAuth.createUserWithEmailAndPassword(binding.etEmail.getText().toString() , binding.etPassword.getText().toString()). addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressDialog.dismiss(); if (task.isSuccessful()){ User user = new User(binding.etUsername.getText().toString() , binding.etEmail.getText().toString() , binding.etPassword.getText().toString()); Toast.makeText(student.this, "User created Successfully", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(student.this,task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); } }); binding.etacccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(student.this , ssignin.class); startActivity(intent); } }); } }
true
9e7481fc2ba3c6e87207446008b2c18d050f54c3
Java
lukspv/MoradoresHome
/src/modelo/dao/ApartamentoDao.java
UTF-8
7,678
2.25
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package modelo.dao; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.awt.Desktop; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import modelo.conexao.FabricaConexao; import modelo.entidade.Apartamento; import modelo.entidade.Bloco; import modelo.entidade.Morador; /** * * @author lucas */ public class ApartamentoDao { private String Comando;//comando sql private PreparedStatement ps;//preparando o ambiente para o comando sql (intermediario) private ResultSet rs;// armazenar os dados do banco da aplicação (apenas nas consultas) private Connection Conecta; //metodos public void cadastrar(Apartamento apartamento) throws SQLException { Conecta = FabricaConexao.Conectar(); Comando = "insert into apartamento (apnumero,apandar,apdispo,apblid) values (?,?,?,?);"; ps = Conecta.prepareStatement(Comando); ps.setString(1, apartamento.getapnumero()); ps.setString(2, apartamento.getapandar()); ps.setString(3, apartamento.getdispo()); ps.setString(4, apartamento.getbloco().getblid()); ps.execute(); FabricaConexao.FecharConexao(); } public void alterar(Apartamento apartamento) throws SQLException { Conecta = FabricaConexao.Conectar(); Comando = "update apartamento set apandar = ?, apdispo = ?, apblid = ? where apnumero=?;"; ps = Conecta.prepareStatement(Comando); ps.setString(1, apartamento.getapandar()); ps.setString(2, apartamento.getdispo()); ps.setString(3, apartamento.getbloco().getblid()); ps.setString(4, apartamento.getapnumero()); ps.execute(); FabricaConexao.FecharConexao(); } public void excluir(String id) throws SQLException { Conecta = FabricaConexao.Conectar(); Comando = "delete from apartamento where apnumero=?"; ps = Conecta.prepareStatement(Comando); ps.setString(1, id); ps.execute(); FabricaConexao.FecharConexao(); } public List<Apartamento> listarTodos() throws SQLException { Conecta = FabricaConexao.Conectar(); Comando = "select * from apartamento join bloco on apblid=blid;"; ps = Conecta.prepareStatement(Comando); rs = ps.executeQuery(); List<Apartamento> lista = new ArrayList<>(); Apartamento apartamento = new Apartamento(); while (rs.next()) { apartamento.setapnumero(rs.getString("apnumero")); apartamento.setapandar(rs.getString("apandar")); apartamento.setdispo(rs.getString("apdispo")); Bloco bloco = new Bloco(); bloco.setblid(rs.getString("blid")); bloco.setblnumero(rs.getString("blnumero")); bloco.setblrua(rs.getString("blrua")); apartamento.setbloco(bloco); lista.add(apartamento); } FabricaConexao.FecharConexao(); //System.out.println("6"); return lista; } public List<Apartamento> listarTodos(String numero) throws SQLException { Conecta = FabricaConexao.Conectar(); Comando = "select * from apartamento join bloco on apblid=blid where" + " apnumero like ? limit 5;"; ps = Conecta.prepareStatement(Comando); ps.setString(1, numero + "%"); rs = ps.executeQuery(); List<Apartamento> lista = new ArrayList<>(); Apartamento apartamento = new Apartamento(); while (rs.next()) { apartamento.setapnumero(rs.getString("apnumero")); apartamento.setapandar(rs.getString("apandar")); apartamento.setdispo(rs.getString("apdispo")); Bloco bloco = new Bloco(); bloco.setblid(rs.getString("blid")); bloco.setblnumero(rs.getString("blnumero")); bloco.setblrua(rs.getString("blrua")); apartamento.setbloco(bloco); lista.add(apartamento); } FabricaConexao.FecharConexao(); return lista; } public Apartamento buscar(String numero) throws SQLException { Conecta = FabricaConexao.Conectar(); Comando = "select * from apartamento join Bloco on Apblid=Blid where apnumero = ? "; ps = Conecta.prepareStatement(Comando); ps.setString(1, numero); rs = ps.executeQuery(); Apartamento apartamento = apartamento = new Apartamento(); if (rs.next()) { apartamento.setapnumero(rs.getString("apnumero")); apartamento.setapandar(rs.getString("apandar")); apartamento.setdispo(rs.getString("apdispo")); Bloco bloco = new Bloco(); bloco.setblid(rs.getString("blid")); bloco.setblnumero(rs.getString("blnumero")); bloco.setblrua(rs.getString("blrua")); apartamento.setbloco(bloco); } FabricaConexao.FecharConexao(); return apartamento; } public void relatorio() throws FileNotFoundException, SQLException { Conecta = FabricaConexao.Conectar(); Comando = "select * from apartamento join bloco on apblid=blid;"; ps = Conecta.prepareStatement(Comando); rs = ps.executeQuery(); List<Apartamento> lista = new ArrayList<>(); while (rs.next()) { Apartamento apartamento = new Apartamento(); apartamento.setapnumero(rs.getString("apnumero")); apartamento.setapandar(rs.getString("apandar")); apartamento.setdispo(rs.getString("apdispo")); Bloco bloco = new Bloco(); bloco.setblid(rs.getString("blid")); bloco.setblnumero(rs.getString("blnumero")); bloco.setblrua(rs.getString("blrua")); apartamento.setbloco(bloco); lista.add(apartamento); } Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\lucas\\Downloads\\Apartamentos_Cadastrados.pdf")); document.open(); document.add(new Paragraph("Lista de Apartamentos Cadastrados\n\n")); for (Apartamento m : lista) { document.add(new Paragraph("\n" + "Apartamento: " + m.getapnumero() + "\n" + "Numero: " + m.getapandar() + "\n" + "Bloco: " + m.getbloco().getblid() + "\n" + "Disponibiliade: " + m.getdispo())); } document.add(new Paragraph("Sistema de Lucas Vieira")); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } document.close(); try { Desktop.getDesktop().open(new File("C:\\Users\\lucas\\Downloads\\Apartamentos_Cadastrados.pdf")); } catch (IOException ex) { Logger.getLogger(MoradorDao.class.getName()).log(Level.SEVERE, null, ex); } } }
true
271d8e30f7e0bce31733d5e0ce01113bf4121e5a
Java
Tylian/labelmaker
/src/main/java/net/tylian/labelmaker/common/labels/Label.java
UTF-8
5,496
2.28125
2
[]
no_license
package net.tylian.labelmaker.common.labels; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.tylian.labelmaker.common.Utils; import org.lwjgl.opengl.GL11; /** * Created by Tylian on 4/15/2017. */ public class Label { private Vec3d offset; private Vec3d rotation; private String text; private float scale = 1.0f; public Label(Vec3d offset, Vec3d rotation, String text) { this.offset = offset; this.text = text; this.rotation = rotation; } public Label(NBTTagCompound nbt) { this.deserializeNBT(nbt); } public Vec3d getParentPosition(World worldIn) { return Vec3d.ZERO; } public Vec3d getParentRotation(World worldIn) { return Vec3d.ZERO; } protected String getType() { return "label"; } public NBTTagCompound serializeNBT() { NBTTagCompound nbt = new NBTTagCompound(); nbt.setString("Type", this.getType()); nbt.setTag("Offset", Utils.nbtWriteVec3d(this.offset)); nbt.setTag("Rotation", Utils.nbtWriteVec3d(this.rotation)); nbt.setString("Text", this.text); nbt.setFloat("Scale", this.scale); return nbt; } public void deserializeNBT(NBTTagCompound nbt) { this.offset = Utils.nbtReadVec3d(nbt.getCompoundTag("Offset")); this.rotation = Utils.nbtReadVec3d(nbt.getCompoundTag("Rotation")); this.text = nbt.getString("Text"); this.scale = nbt.getFloat("Scale"); } @SideOnly(Side.CLIENT) public boolean shouldRender(World worldIn) { EntityPlayerSP player = Minecraft.getMinecraft().player; Vec3d pos = this.getParentPosition(worldIn).add(offset); return (player.getDistanceSq(pos.xCoord, pos.yCoord, pos.zCoord) < 4096.0d); } @SideOnly(Side.CLIENT) public void render(World worldIn, float partialTicks) { GlStateManager.pushMatrix(); GlStateManager.disableCull(); Vec3d rot = this.getParentRotation(worldIn).add(rotation); FontRenderer fontRenderer = Minecraft.getMinecraft().fontRendererObj; EntityPlayerSP player = Minecraft.getMinecraft().player; double x = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks; double y = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks; double z = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks; GlStateManager.translate(-x, -y, -z); int textWidth = fontRenderer.getStringWidth(text); Tessellator tessellator = Tessellator.getInstance(); VertexBuffer buffer = tessellator.getBuffer(); GlStateManager.depthMask(false); Vec3d pos = this.getParentPosition(worldIn).add(offset); GlStateManager.translate(pos.xCoord, pos.yCoord, pos.zCoord); GlStateManager.rotate((float)rot.xCoord * 360.0f, 1.0f, 0.0f, 0.0f); GlStateManager.rotate((float)rot.yCoord * 360.0f, 0.0f, 1.0f, 0.0f); GlStateManager.rotate((float)rot.zCoord * 360.0f, 0.0f, 0.0f, 1.0f); GlStateManager.glNormal3f(0.0F, 1.0F, 0.0F); GlStateManager.scale(-0.0625f * this.scale, -0.0625f * this.scale, 0.0625f * this.scale); // Center everything GlStateManager.translate(-textWidth / 2 - 1, -5.5f, -0.001f); GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); GlStateManager.disableTexture2D(); buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); buffer.pos(0.0f, 11.0f, 0.0f).color(0.0f, 0.0f, 0.0f, 1.0f).endVertex(); buffer.pos(0.0f, 0.0f, 0.0f).color(0.0f, 0.0f, 0.0f, 1.0f).endVertex(); buffer.pos(textWidth + 4.0f, 0.0f, 0.0f).color(0.0f, 0.0f, 0.0f, 1.0f).endVertex(); buffer.pos(textWidth + 4.0f, 11.0f, 0.0f).color(0.0f, 0.0f, 0.0f, 1.0f).endVertex(); tessellator.draw(); buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); buffer.pos(1.0f, 10.0f, 0.0f).color(1.0f, 1.0f, 1.0f, 1.0f).endVertex(); buffer.pos(1.0f, 1.0f, 0.0f).color(1.0f, 1.0f, 1.0f, 1.0f).endVertex(); buffer.pos(textWidth + 3.0f, 1.0f, 0.0f).color(1.0f, 1.0f, 1.0f, 1.0f).endVertex(); buffer.pos(textWidth + 3.0f, 10.0f, 0.0f).color(1.0f, 1.0f, 1.0f, 1.0f).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); GlStateManager.depthMask(true); fontRenderer.drawString(text, 2, 2, 0x000000); GlStateManager.enableCull(); GlStateManager.disableBlend(); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.popMatrix(); } }
true
17bf0b609ebad8db9e87356a9c80f3b1aed4d9bd
Java
peace710/AJLife
/ALifeRxJava/src/main/java/me/peace/rx/java/combining/CombinLatest.java
UTF-8
1,120
2.890625
3
[]
no_license
package me.peace.rx.java.combining; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.functions.BiFunction; import io.reactivex.rxjava3.functions.Consumer; import me.peace.rx.LogUtils; public class CombinLatest { private static final String TAG = "CombinLatest"; public static void main(String[] args) { CombinLatest combinLatest = new CombinLatest(); combinLatest.combinlatest(); } public void combinlatest(){ Observable<String> observable1 = Observable.just("8","100","10086"); Observable<String> observable2 = Observable.just("f"); Observable.combineLatest(observable1, observable2, new BiFunction<String, String, String>() { @Override public String apply(String t1, String t2) throws Throwable { return t1 + t2; } }).subscribe(new Consumer<String>() { @Override public void accept(String s) throws Throwable { LogUtils.d(TAG, "RxJava Observable Operator combinlatest: s = [" + s + "]"); } }); } }
true
c3f0ad5590e8438323a8f4a331072329f480d52e
Java
MrBlackk/fix-me
/broker/src/main/java/com/mrb/fixme/broker/handler/ResultTagValidator.java
UTF-8
891
2.34375
2
[]
no_license
package com.mrb.fixme.broker.handler; import com.mrb.fixme.core.Core; import com.mrb.fixme.core.FixTag; import com.mrb.fixme.core.Result; import com.mrb.fixme.core.exception.WrongFixTagException; import com.mrb.fixme.core.handler.BaseMessageHandler; import java.nio.channels.AsynchronousSocketChannel; public class ResultTagValidator extends BaseMessageHandler { @Override public void handle(AsynchronousSocketChannel clientChannel, String message) { final String result; try { result = Core.getFixValueByTag(message, FixTag.RESULT); } catch (WrongFixTagException ex) { System.out.println(ex.getMessage()); return; } if (Result.is(result)) { super.handle(clientChannel, message); } else { System.out.println("Wrong result type in message: " + message); } } }
true
1de4ad52be090e659b0e07ff0d53d53ba20b77a4
Java
nothize/COWARD
/src/main/java/coward/big2/card/Suit.java
UTF-8
105
1.640625
2
[]
no_license
package coward.big2.card; public enum Suit { SPADE__, // HEART__, // CLUB___, // DIAMOND, // ; }
true
4e66fcf751c32e3d225b264a2a950689940dbc9f
Java
LJIJCJ/Test
/src/com/homework/Super.java
GB18030
112
1.804688
2
[ "MIT" ]
permissive
package com.homework; public class Super { public Super() { System.out.println("ó๹"); } }
true
df39126aa1effe571b5ec4111f5c2f36e6693e10
Java
YuraLukyanov/versionsComparator
/src/main/java/yura/lukyanov/versionsComparator/hibernate/model/AttrObjectTypeID.java
UTF-8
937
2.125
2
[]
no_license
package yura.lukyanov.versionsComparator.hibernate.model; import javax.persistence.Embeddable; import javax.persistence.ManyToOne; /** * Created by yuriylukyanov on 3/25/15. */ @Embeddable public class AttrObjectTypeID implements java.io.Serializable { private ObjectType objectType; private Attribute attr; private AttributeSchema attributeSchema; @ManyToOne public ObjectType getObjectType() { return objectType; } public void setObjectType(ObjectType objectType) { this.objectType = objectType; } @ManyToOne public Attribute getAttr() { return attr; } public void setAttr(Attribute attr) { this.attr = attr; } @ManyToOne public AttributeSchema getAttributeSchema() { return attributeSchema; } public void setAttributeSchema(AttributeSchema attributeSchema) { this.attributeSchema = attributeSchema; } }
true
b72ec3d6e1b99bdda6a640d5259c850f25a1ddbf
Java
hyoGirl/companyCode
/Buiness-Log/src/main/java/com/business/log/service/UserService.java
UTF-8
450
1.859375
2
[]
no_license
package com.business.log.service; import com.business.log.pojo.User; import java.util.List; /** * @Auther: Administrator * @Date: 2018/8/2 0002 10:58 * @Description: */ public interface UserService { List<User> findAllUser(); User findUserById(long id); void deleteUserById(long id); boolean addUser(User user); boolean updateUser(User user); boolean deleteUserByID(long id); }
true
a5fe4e0db7b34a4b4bfdcc024020824e4d17c79b
Java
fankbulli/util-play
/src/dos/Demo1.java
UTF-8
341
1.882813
2
[]
no_license
package dos; import java.io.IOException; public class Demo1 { public static void main(String[] args) { try { Runtime.getRuntime ().exec ("ffmpeg -i C:\\Users\\zxd\\qq.mp4 -vframes 30 -y -f gif C:\\Users\\zxd\\a.gif "); } catch (IOException e) { e.printStackTrace (); } ; } }
true
c8ab4812f4f2395069fd06c4a9d0f88549914314
Java
avikabra/gradebook-final
/Gradebook.java
UTF-8
15,331
3.28125
3
[]
no_license
import java.util.Scanner; public class Gradebook { public static void main(String []args) { //variable declaration and initialization String classTemp; String creditsHolder; String creditsTemp; boolean classSizeReq = false; boolean classesReq = false; boolean userVibing = true; boolean hasClass = false; boolean percentDomain; int classSize = 0; int classCounter = 0; int userLargeReq = 0; int weight = 0; int switchIndex = 0; double classGradesTemp; double gradeTemp; double[] cg; String[] classSwitch; double[] gradeSwitch; int[] creditsSwitch; //user inputs classes, credits, and percent grades Scanner scan = new Scanner(System.in); System.out.println("Welcome to the Gradebook!"); while (!classSizeReq) { System.out.println("How many classes are you taking this year?"); classSize = Integer.parseInt(scan.nextLine()); if (classSize >= 1) { classSizeReq = true; } else System.out.println("Please choose a number greater than or equal to 1"); } String[] classes = new String[classSize]; double[] classGrades = new double[classSize]; int[] credits = new int[classSize]; for (int i = 0; i < classSize; i++) { System.out.println("Please input class #" + (i+1) + " that you are taking this year."); classes[i] = scan.nextLine(); if ((classes[i].toUpperCase().indexOf("AP ") != -1) || (classes[i].toUpperCase().indexOf("AT ") != -1)) { weight++; } System.out.println("How many credits is this class? Click return for 1 or type in a different number."); creditsHolder = scan.nextLine(); if (creditsHolder.equals("")) credits[i] = 1; else credits[i] = Integer.parseInt(creditsHolder); while (credits[i] <= 0) { System.out.println("Enter a credit value greater than 0."); credits[i] = Integer.parseInt(scan.nextLine()); } System.out.println("Enter your current PERCENT grade (out of 90) for " + classes[i] + ": "); classGrades[i] = Double.parseDouble(scan.nextLine()); while (classGrades[i] < 0 || classGrades[i] > 90) { System.out.println("Enter a percentage from 0 - 90."); classGrades[i] = Double.parseDouble(scan.nextLine()); } } //checkpoint #1, use only when testing code /* for (int i = 0; i < classes.length; i++) { System.out.print(classes[i] + " "); } System.out.println(); for (int i = 0; i < classGrades.length; i++) { System.out.print(classGrades[i] + " "); } System.out.println(); for (int i = 0; i < credits.length; i++) { System.out.print(credits[i] + " "); } System.out.println(); */ //loop until user is done manipulating their grades (hence the user is done vibing) while (userVibing) { System.out.println("Which of the following actions would you like to take?"); System.out.print("[1] Check Weighted GPA, [2] Check Unweighted GPA, [3] Add/Remove a Class, [4] Change Grade,"); System.out.println(" [5] Add Hypothetical Assignment, [6] Study Plan, [7] Exit"); userLargeReq = Integer.parseInt(scan.nextLine()); //runs methods based on user input if (userLargeReq == 1) { System.out.println("Your GPA is " + Math.floor(checkGPA(classGrades, credits, true, weight) * 100) / 100); } else if (userLargeReq == 2) { System.out.println("Your GPA is " + Math.floor(checkGPA(classGrades, credits, false, weight) * 100) / 100); } else if (userLargeReq == 3) { //adding/removing can't be done in a method, requires returning arrays of multiple types //method without using ArrayList System.out.println("What class would you like to add/remove?"); classTemp = scan.nextLine(); hasClass = false; for (int i = 0; i < classes.length; i++) { if (classTemp.toUpperCase().equals(classes[i].toUpperCase())) { hasClass = true; switchIndex = i; } } if (hasClass) { System.out.println("Removing class: " + classTemp + "..."); classSwitch = new String[classes.length-1]; gradeSwitch = new double[classes.length-1]; creditsSwitch = new int[classes.length-1]; if ((classTemp.toUpperCase().indexOf("AP ") != -1) || (classTemp.toUpperCase().indexOf("AT ") != -1)) { weight--; } for (int j = 0; j < classes.length; j++) { if (j < switchIndex) { classSwitch[j] = classes[j]; gradeSwitch[j] = classGrades[j]; creditsSwitch[j] = credits[j]; } else if (j > switchIndex) { classSwitch[j-1] = classes[j]; gradeSwitch[j-1] = classGrades[j]; creditsSwitch[j-1] = credits[j]; } } classes = classSwitch; classGrades = gradeSwitch; credits = creditsSwitch; System.out.println("Done"); } else { classSwitch = new String[classes.length+1]; gradeSwitch = new double[classes.length+1]; creditsSwitch = new int[classes.length+1]; if ((classTemp.toUpperCase().indexOf("AP ") != -1) || (classTemp.toUpperCase().indexOf("AT ") != -1)) { weight++; } System.out.println("How many credits is this class? Click return for 1 or type in a different number."); creditsTemp = scan.nextLine(); System.out.println("Enter your current PERCENT grade (out of 90) for " + classTemp + ": "); gradeTemp = Double.parseDouble(scan.nextLine()); for (int j = 0; j < classes.length; j++) { classSwitch[j] = classes[j]; gradeSwitch[j] = classGrades[j]; creditsSwitch[j] = credits[j]; } classSwitch[classes.length] = classTemp; gradeSwitch[classes.length] = gradeTemp; if (creditsTemp.equals("")) creditsSwitch[classes.length] = 1; else creditsSwitch[classes.length] = Integer.parseInt(creditsTemp); classes = classSwitch; classGrades = gradeSwitch; credits = creditsSwitch; System.out.println("Done!"); } } else if (userLargeReq == 4) { cg = changeGrade(classes, classGrades, scan); classGrades[(int)(cg[0])] = cg[1]; } else if (userLargeReq == 5) { classGrades = imagAssign(classes, classGrades, credits, weight, scan); } else if (userLargeReq == 6) { optimizeTime(classes, classGrades, credits, scan); } else if (userLargeReq == 7) { //option to break while loop System.out.println("Bye bye! Your grades will not be stored."); userVibing = false; } } } //method to check either the weighted or unweighted GPA //INPUTS: grades, credits, weighted/unweighted, # of weighted classes //OUTPUTS: double GPA public static double checkGPA(double[] grades, int[] credits, boolean weighted, int weight) { double sum = 0; double creditsSum = 0; for (int i = 0; i < grades.length; i++) { if (grades[i] >= 85) { sum += 4.5 * credits[i]; } else if (grades[i] >= 75) { sum += 4 * credits[i]; } else if (grades[i] >= 65) { sum += 3.5 * credits[i]; } else if (grades[i] >= 55) { sum += 3 * credits[i]; } else if (grades[i] >= 45) { sum += 2.5 * credits[i]; } else if (grades[i] >= 35) { sum += 2 * credits[i]; } else if (grades[i] >= 25) { sum += 1.5 * credits[i]; } else if (grades[i] >= 15) { sum += 1 * credits[i]; } creditsSum += credits[i]; } if (weighted) sum += (weight * 0.5); return (sum / creditsSum); } //method to change a grade of one class if a new assignment comes in or user made a mistake while inputting classes //INPUT: classes, grades, scanner //OUTPUT: double array, index 0 = index of class to be changed, index 1 = new grade for that class public static double[] changeGrade(String[] classes, double[] grades, Scanner scan) { double[] returnA = new double[2]; int userReq = 0; System.out.println("Which of the following class grades would you like to change?"); for (int i = 0; i < classes.length; i++) { System.out.println("[" + (i+1) + "] " + classes[i] + " - " + grades[i]); } userReq = Integer.parseInt(scan.nextLine()); while (userReq < 1 || userReq > classes.length) { System.out.println("Select one of the classes please."); userReq = Integer.parseInt(scan.nextLine()); } returnA[0] = userReq - 1; System.out.println("Enter the new grade:"); returnA[1] = Double.parseDouble(scan.nextLine()); System.out.println("Done!"); return returnA; } //method to add a hypothetical assignment with some percentage weight to the current percentage in any class //INPUTS: classes, grades, credits, # of weighted classes, scanner //OUTPUT: double array grades with new percentage replacing old or with no replacement public static double[] imagAssign(String[] classes, double[] grades, int[] credits, int weightGPA, Scanner scan) { int userReq = 0; double currentGrade; double weight = 0; String grade; String yn; double gradeD = 0; double finalPercent = 0; System.out.println("Which of the following class grades would you like to add an assignment to?"); for (int i = 0; i < classes.length; i++) { System.out.println("[" + (i+1) + "] " + classes[i] + " - " + grades[i]); } userReq = Integer.parseInt(scan.nextLine()); while (userReq < 1 || userReq > classes.length) { System.out.println("Select one of the classes please."); userReq = Integer.parseInt(scan.nextLine()); } System.out.println("How much weight does this new assignment have as a PERCENT?"); weight = Double.parseDouble(scan.nextLine()); while (weight < 0 || weight >= 100) { System.out.println("Input a number in between 0 and 100"); weight = Double.parseDouble(scan.nextLine()); } System.out.println("What letter grade would you assign for this hypothetical assignment?"); grade = scan.nextLine(); while (grade.length() > 2) { System.out.println("Please put an appropriate grade."); grade = scan.nextLine(); } if (grade.equals("A+")) { gradeD = 90; } else if (grade.equals("A")) { gradeD = 80; } else if (grade.equals("B+")) { gradeD = 70; } else if (grade.equals("B")) { gradeD = 60; } else if (grade.equals("C+")) { gradeD = 50; } else if (grade.equals("C")) { gradeD = 40; } else if (grade.equals("D+")) { gradeD = 30; } else if (grade.equals("D")) { gradeD = 20; } else { gradeD = 10; } finalPercent = (weight/100) * gradeD + (1-(weight)/100) * grades[userReq - 1]; currentGrade = grades[userReq - 1]; System.out.println("The hypothetical percent after adding this assignment is " + (Math.floor(finalPercent * 100) / 100) + "."); System.out.println("Your weighted GPA after adding this assignment is " + (Math.floor(checkGPA(grades, credits, true, weightGPA) * 100) / 100)); System.out.println("Would you like to replace this percent with your current percentage? (y/n)"); yn = scan.nextLine(); while (yn.length() > 1) { System.out.println("Please put an appropriate grade."); yn = scan.nextLine(); } if (yn.equals("y")) grades[userReq - 1] = finalPercent; return grades; } //method that gives user a study plan to dedicate time to classes in order to improve GPA //INPUTS: classes, grades, credits, scanner //OUTPUTS: None, everything printed out to user public static void optimizeTime(String[] classes, double[] grades, int[] credits, Scanner scan) { double freeTime = 0; double weightingSum = 0; double temp; double[] weightings = new double[classes.length]; //assigns a numerical value to how easy it would be to get a grade to the next level for (int i = 0; i < classes.length; i++) { temp = grades[i]; weightings[i] = (temp % 10 - 5); if (weightings[i] < 0) weightings[i] += 10; weightings[i] *= (10 * credits[i]); if ((classes[i].toUpperCase().indexOf("AP ") != -1) || (classes[i].toUpperCase().indexOf("AT ") != -1)) { weightings[i] += 10; } //System.out.println(weightings[i]); weightings[i] *= (-10 * Math.sqrt(1 - Math.pow((temp-90), 2)/8100) + 10); //System.out.println(weightings[i]); weightingSum += weightings[i]; } System.out.println("How much free time do you have to work with? (in hours)"); freeTime = Double.parseDouble(scan.nextLine()); for (int i = 0; i < weightings.length; i++) { if (weightingSum == 0) { weightings[i] = freeTime/classes.length; } else { weightings[i] /= weightingSum; } } // + Math.floor((freeTime * weightings[i]) * 100) / 100) for (int i = 0; i < classes.length; i++) { System.out.println("The recommended allocation of time is as follows:"); System.out.println("[" + i + "] " + classes[i] + " - " + (Math.floor((freeTime * weightings[i]) * 100) / 100) + " hours."); } } }
true
687b61e903fbc85dc1cbb5c952a90f694663bfc8
Java
ssunyoung/Capstone
/Capstone/src/main/java/com/ssun/everybook/HomeController.java
UTF-8
1,522
2.28125
2
[]
no_license
package com.ssun.everybook; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.ssun.everybook.domain.PageMaker; import com.ssun.everybook.domain.SearchCriteria; import com.ssun.everybook.service.BoardService; @Controller public class HomeController { @Inject private BoardService service; private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, @ModelAttribute("cri") SearchCriteria cri, Model model) throws Exception { logger.info("Welcome home! The client locale is {}.", locale); logger.info(cri.toString() + "cri.tostringggggggggggggggggggggggggggggggggggg"); Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); PageMaker pageMaker = new PageMaker(); pageMaker.setCri(cri); pageMaker.setTotalCount(service.listSearchCount(cri)); model.addAttribute("pageMaker", pageMaker); model.addAttribute("serverTime", formattedDate); return "home"; } }
true
0900cbfda85a1b74e70750f8c34aa51a64154c8f
Java
moutainhigh/cloudconfig
/kuangchi/java/com/kuangchi/sdd/visitorConsole/checkUserLogin/service/impl/CheckUserLoginServiceImpl.java
UTF-8
4,964
1.992188
2
[]
no_license
package com.kuangchi.sdd.visitorConsole.checkUserLogin.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.kuangchi.sdd.visitorConsole.checkUserLogin.dao.CheckUserLoginDao; import com.kuangchi.sdd.visitorConsole.checkUserLogin.service.CheckUserLoginService; @Service("checkUserLoginServiceImpl") public class CheckUserLoginServiceImpl implements CheckUserLoginService { @Resource(name = "checkUserLoginDaoImpl") private CheckUserLoginDao checkUserLogindao; @Override public boolean checkUserLogin(Map map) { return checkUserLogindao.checkUserLogin(map); } @Override public boolean ifBlackList(Map map) { return checkUserLogindao.ifBlackList(map); } @Override public List<Map> getRecordInfoByCardNum(Map map) { return checkUserLogindao.selectRecordInfoByCardnum(map); } @Override public boolean ifPassiveBook(Map map) { return checkUserLogindao.ifPassiveBook(map); } @Override public Map queryVisitorByNum(Map map) { Map visitRecordList=checkUserLogindao.queryVisitorByNum(map); Map m=new HashMap(); List<Map> followVisitorList=checkUserLogindao.queryBookingFollowVisitor(m); String fVisitNum=""; String fVisitorName=""; String fVisitorSex=""; String fPaperType=""; String fPaperNum=""; String fMobile=""; String fAddress=""; String fIdentifyPhoto=""; String fCatchPhoto=""; for(Map fv:followVisitorList){ fVisitNum+=fv.get("fVisitNum")+"|"; fVisitorName+=fv.get("fVisitorName")+"|"; fVisitorSex+=fv.get("fVisitorSex")+"|"; fPaperType+=fv.get("fPaperType")+"|"; fPaperNum+=fv.get("fPaperNum")+"|"; fMobile+=fv.get("fMobile")+"|"; fAddress+=fv.get("fAddress")+"|"; fIdentifyPhoto+=fv.get("fIdentifyPhoto")+"|"; fCatchPhoto+=fv.get("fCatchPhoto")+"|"; } if(m!=null){ m.put("fVisitNum", "".equals(fVisitNum) ? "":fVisitNum.substring(0, fVisitNum.length()-1)); m.put("fVisitorName", "".equals(fVisitorName) ? "":fVisitorName.substring(0, fVisitorName.length()-1)); m.put("fVisitorSex", "".equals(fVisitorSex) ? "":fVisitorSex.substring(0, fVisitorSex.length()-1)); m.put("fPaperNum", "".equals(fPaperNum) ? "":fPaperNum.substring(0, fPaperNum.length()-1)); m.put("fPaperType", "".equals(fPaperType) ? "":fPaperType.substring(0, fPaperType.length()-1)); m.put("fMobile", "".equals(fMobile) ? "":fMobile.substring(0, fMobile.length()-1)); m.put("fAddress", "".equals(fAddress) ? "":fAddress.substring(0, fAddress.length()-1)); m.put("fIdentifyPhoto", "".equals(fIdentifyPhoto) ? "":fIdentifyPhoto.substring(0, fIdentifyPhoto.length()-1)); m.put("fCatchPhoto", "".equals(fCatchPhoto) ? "":fCatchPhoto.substring(0, fCatchPhoto.length()-1)); } return visitRecordList; } @Override public Map queryBookingVisitor(Map map) { if(!"".equals(map.get("mPaperNum"))&&map.get("mPaperNum")!=null&&!"".equals(map.get("mMobile"))&&map.get("mMobile")!=null){ map.put("mMobile", ""); } Map mainVisitor=checkUserLogindao.queryBookingVisitor(map); List<Map> followVisitorList=checkUserLogindao.queryBookingFollowVisitor(mainVisitor); String fVisitNum=""; String fVisitorName=""; String fVisitorSex=""; String fPaperType=""; String fPaperNum=""; String fMobile=""; String fAddress=""; String fIdentifyPhoto=""; String fCatchPhoto=""; for(Map m:followVisitorList){ fVisitNum+=m.get("fVisitNum")+"|"; fVisitorName+=m.get("fVisitorName")+"|"; fVisitorSex+=m.get("fVisitorSex")+"|"; fPaperType+=m.get("fPaperType")+"|"; fPaperNum+=m.get("fPaperNum")+"|"; fMobile+=m.get("fMobile")+"|"; fAddress+=m.get("fAddress")+"|"; fIdentifyPhoto+=m.get("fIdentifyPhoto")+"|"; fCatchPhoto+=m.get("fCatchPhoto")+"|"; } if(mainVisitor!=null){ mainVisitor.put("fVisitNum", "".equals(fVisitNum) ? "":fVisitNum.substring(0, fVisitNum.length()-1)); mainVisitor.put("fVisitorName", "".equals(fVisitorName) ? "":fVisitorName.substring(0, fVisitorName.length()-1)); mainVisitor.put("fVisitorSex", "".equals(fVisitorSex) ? "":fVisitorSex.substring(0, fVisitorSex.length()-1)); mainVisitor.put("fPaperNum", "".equals(fPaperNum) ? "":fPaperNum.substring(0, fPaperNum.length()-1)); mainVisitor.put("fPaperType", "".equals(fPaperType) ? "":fPaperType.substring(0, fPaperType.length()-1)); mainVisitor.put("fMobile", "".equals(fMobile) ? "":fMobile.substring(0, fMobile.length()-1)); mainVisitor.put("fAddress", "".equals(fAddress) ? "":fAddress.substring(0, fAddress.length()-1)); mainVisitor.put("fIdentifyPhoto", "".equals(fIdentifyPhoto) ? "":fIdentifyPhoto.substring(0, fIdentifyPhoto.length()-1)); mainVisitor.put("fCatchPhoto", "".equals(fCatchPhoto) ? "":fCatchPhoto.substring(0, fCatchPhoto.length()-1)); } return mainVisitor; } }
true
b5bf2ac58fedd79e9071342bd2c3c42e0a24a364
Java
Black-Garlic/sandaerosrc
/src/main/java/com/sangdaero/walab/user/domain/repository/UserRepository.java
UTF-8
1,336
1.859375
2
[]
no_license
package com.sangdaero.walab.user.domain.repository; import com.sangdaero.walab.common.entity.User; import com.sangdaero.walab.user.application.dto.SimpleUser; import com.sangdaero.walab.user.application.dto.VolunteerRanking; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface UserRepository extends JpaRepository<User, Long> { List<SimpleUser> findAllByOrderByName(); // List<SimpleUser> findTop5ByOrderByVolunteerTimeDesc(); List<User> findTop5ByOrderByVolunteerTimeDesc(); List<SimpleUser> findAllByUserTypeOrderByName(byte userType); User findBySocialId(String socialId); Page<User> findAllByNameContaining(String name, Pageable pageable); Page<User> findAllByNicknameContaining(String nickname, Pageable pageable); List<User> findAllByNameContaining(String keyword); @EntityGraph(attributePaths = { "userInterestList", "fundraising" }) Optional<User> getById(Long userId); boolean existsByPhone(String phone); User findByPhone(String phone); User findByNickname(String nickname); boolean existsByNickname(String nickname); }
true
81310e4b79077fbf879e0937a015ec413eff37ab
Java
Kyoo32/NEXT2015-2
/java/java0710/src/Manager.java
UTF-8
257
2.578125
3
[]
no_license
public class Manager extends Employee { public String department; public int i = 20; public Manager(String name){ super(name); //System.out.println("Manager()"); } public String getDetail(){ return super.getDetail() + department ; } }
true
d719fbda45fb92237b3e237dfa9886413125d011
Java
swapnilKurve20/SpringBoot-JPA-Demo
/demo/src/main/java/com/example/demo/rest/PostController.java
UTF-8
3,111
2.265625
2
[]
no_license
package com.example.demo.rest; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.example.demo.model.Posts; import com.example.demo.model.Tags; import com.example.demo.model.UserProfiles; import com.example.demo.pojo.PostDetails; import com.example.demo.pojo.PostDetails.TagsDetails; import com.example.demo.repo.IPostRepo; import com.example.demo.repo.ITagsRepo; import com.example.demo.repo.IUserProfiles; @RestController @RequestMapping("/post") public class PostController { @Autowired IUserProfiles userProfileRepo; @Autowired IPostRepo postRepo; @Autowired ITagsRepo tagRepo; @PostMapping("/{userProfileId}") public String addPost(@PathVariable(value = "userProfileId") String id, @RequestBody PostDetails post) throws Exception { Optional<UserProfiles> optional = userProfileRepo.findById(Long.parseLong(id)); UserProfiles up = optional.get(); Posts p = null; if (up.getId() != null) { p = new Posts(post.getTitle(), post.getDescription()); p.setUserProfile(up); Set<Tags> tags = new HashSet<>(); for (TagsDetails s : post.getTags()) { Tags tag = tagRepo.getTagByName(s.getName()); if (tag == null) { tag = new Tags(); tag.setId(s.getId()); tag.setName(s.getName()); tag.getPosts().add(p); tags.add(tag); } else { tag = tagRepo.getOne(tag.getId()); tag.getPosts().add(p); tags.add(tag); } } p.getTags().addAll(tags); p = postRepo.save(p); } if (p == null) throw new Exception("Invalid post"); else return String.valueOf(p.getId()); } @GetMapping("/{userProfileId}/getAllPosts") public List<PostDetails> getAllPosts(@PathVariable(value = "userProfileId") String id) { List<PostDetails> posts = new ArrayList<>(); Set<TagsDetails> tags = new HashSet<>(); for (Posts p : postRepo.findByUserProfile(Long.parseLong(id))) { tags.clear(); for (Tags t : p.getTags()) { tags.add(new TagsDetails(t.getId(), t.getName())); } posts.add(new PostDetails(p.getTitle(), p.getDescription(), tags)); } return posts; } @DeleteMapping("/{userProfileId}/removePostById") public void removePostById(@PathVariable(value = "userProfileId") String userProfileId, @RequestParam(value = "postId") String id) { Optional<Posts> posts = postRepo.findById(Long.parseLong(id)); if (posts.isPresent() && (posts.get().getUserProfile().getId() == Long.parseLong(userProfileId))) { postRepo.deleteById(Long.parseLong(id)); } } }
true
2e3b95a5633437e0e5f0ef998781a83aec248d81
Java
SMARTRACTECHNOLOGY/smartcosmos-edge-things
/src/test/java/net/smartcosmos/edge/things/service/metadata/DeleteMetadataRestServiceDefaultTest.java
UTF-8
3,269
2.0625
2
[ "Apache-2.0" ]
permissive
package net.smartcosmos.edge.things.service.metadata; import org.junit.*; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import net.smartcosmos.edge.things.ThingEdgeService; import net.smartcosmos.security.user.SmartCosmosUser; import net.smartcosmos.test.config.RetryTestConfig; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.validateMockitoUsage; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static net.smartcosmos.test.util.TestUtil.unwrapAndVerify; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @SpringApplicationConfiguration(classes = { ThingEdgeService.class, RetryTestConfig.class }) @ActiveProfiles("test") public class DeleteMetadataRestServiceDefaultTest { /* * TODO: 07/11/16 Update test after upgrading to Spring Boot 1.4 * * The currently used version of Spring Boot requires unwrapping the bean to verify @Retryable methods when mock() is used to create the mocked * bean. Otherwise a UnfinishedVerificationException would be thrown. * * Once Spring Boot is upgraded and @MockBean replaced mock(), unwrapAndVerify() can be replaced by Mockito.verify() again. * * (see https://github.com/spring-projects/spring-boot/issues/6828) */ // @MockBean // requires at least Spring Boot 1.4.0-RELEASE @Autowired private DeleteMetadataRestService service; final ResponseEntity expectedResponse = ResponseEntity.status(HttpStatus.I_AM_A_TEAPOT) .build(); @Before public void setUp() { initMocks(this); when(service.delete(anyString(), anyString(), any(SmartCosmosUser.class))) .thenThrow(new RuntimeException("Remote Exception 1")) .thenThrow(new RuntimeException("Remote Exception 2")) .thenReturn(expectedResponse); } @After public void tearDown() { validateMockitoUsage(); reset(service); } @Test public void thatApplicationContextLoads() { assertNotNull(service); } @Test public void thatDeleteMetadataRetries() { final String ownerType = "someOwnerType"; final String ownerUrn = "someOwnerUrn"; final SmartCosmosUser user = mock(SmartCosmosUser.class); ResponseEntity response = service.delete(ownerType, ownerUrn, user); assertEquals(expectedResponse, response); unwrapAndVerify(service, times(3)).delete(eq(ownerType), eq(ownerUrn), eq(user)); verifyNoMoreInteractions(service); } }
true
3f384f1ba8e9bac6a9e71878a6a3cc3c009b72fd
Java
Vyacheslav-Lapin/spring-fundamwntals5
/src/main/java/ru/vlapin/courses/spring/springfundamentals5/Country.java
UTF-8
663
2.296875
2
[]
no_license
package ru.vlapin.courses.spring.springfundamentals5; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Builder.Default; import lombok.Data; import lombok.experimental.FieldDefaults; import lombok.experimental.FieldNameConstants; import ru.vlapin.courses.spring.springfundamentals5.dao.Identifiable; import static lombok.AccessLevel.PRIVATE; @Data @Builder @AllArgsConstructor @FieldNameConstants @FieldDefaults(level = PRIVATE) public class Country implements Identifiable<Integer> { Integer id; String name; String groupName; public Country(String name, String groupName) { this.name = name; this.groupName = groupName; } }
true
1c05c234a00c10b4a7707a1d9df13669500889f8
Java
JaneMoskalenko/CourseProjectApp
/app/src/main/java/com/example/admin/courseproject/View/activity/TranslateActivity.java
UTF-8
2,109
2.140625
2
[]
no_license
package com.example.admin.courseproject.View.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.admin.courseproject.Presenter.services.speechkit.SpeechHelper; import com.example.admin.courseproject.Presenter.services.translate.TranslateCallback; import com.example.admin.courseproject.Presenter.services.translate.TranslateService; import com.example.admin.courseproject.R; import ru.yandex.speechkit.SpeechKit; import ru.yandex.speechkit.VocalizerListener; public class TranslateActivity extends Activity implements TranslateCallback{ private static final String TAG = TranslateService.class.getSimpleName(); TextView tv_translate; Button btn_play; private TranslateService mTranslateService; private SpeechHelper vocalizer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_translate); mTranslateService = new TranslateService(this); btn_play = (Button) findViewById(R.id.btn_play); tv_translate = (TextView) findViewById(R.id.tv_translate); Intent intent = getIntent(); String description = intent.getStringExtra("description"); mTranslateService.execute(description); vocalizer = new SpeechHelper(TranslateActivity.this); btn_play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text = tv_translate.getText().toString(); vocalizer.spechExecute(text); } }); } @Override public void onGetTranslateResponse(String result) { tv_translate.setText(result); } @Override public void onGetTranslateResponseException(String resultMessage) { Toast.makeText(this, resultMessage, Toast.LENGTH_SHORT).show(); } }
true
d4e896197d3b2ca5d02e4453cd5f721fec3795bc
Java
Nacho-Fili/Learning-to-read-sheet-music
/src/main/java/com/learningsheetmusic/app/repository/UserRepository.java
UTF-8
501
2.03125
2
[]
no_license
package com.learningsheetmusic.app.repository; import com.learningsheetmusic.app.entity.MyUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface UserRepository extends JpaRepository<MyUser, Long> { Optional<MyUser> findByUsername(String username); boolean existsByUsername(String username); List<MyUser> getAllByCreatedBy(String createdBy); }
true
3b6fc125bfa850cb90259148c0994c135457d135
Java
liestory/spring-tablegame
/table-game-auth-api/src/main/java/ru/tablegame/auth/resource/AuthResource.java
UTF-8
1,231
1.851563
2
[]
no_license
package ru.tablegame.auth.resource; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import reactor.core.publisher.Mono; import ru.tablegame.auth.resource.dto.ResponseError; import ru.tablegame.auth.resource.dto.user.AuthUserDto; import ru.tablegame.auth.resource.dto.user.TokenDto; /** * @author nemykin 19.03.2021 */ @RequestMapping("/api/auth") @Api(value = "контроллер для аутентификации") public interface AuthResource { @PostMapping @ApiOperation(value = "Создание токена") @ApiResponses(value = { @ApiResponse(code = 200, message = "токен юзера", response = TokenDto.class), @ApiResponse(code = 400, message = "Непредвиденная ошибка", response = ResponseError.class), }) Mono<ResponseEntity<TokenDto>> createToken(@RequestBody AuthUserDto authUserDto); }
true
e58594813788ca39bd06e11d9d4865986eb26dc6
Java
KevinHuangpf/CodeExams
/src/Main25.java
UTF-8
737
3.265625
3
[]
no_license
import java.util.Scanner; public class Main25 { public static void main(String args[]){ //输入 Scanner scanner = new Scanner(System.in); String[] string = scanner.nextLine().split(";"); System.out.print(compareStrings(string[0],string[1])); } public static boolean compareStrings(String A, String B) { //数字0到字母 int[] index = new int[80]; for (int i = 0; i < A.length(); i++) { index[A.charAt(i) - '0']++; } for (int i = 0; i < B.length(); i++) { index[B.charAt(i) - '0']--; if(index[B.charAt(i) - '0'] < 0){ return false; } } return true; } }
true
54dc366bdc702ae91954824a24ba5d4894016876
Java
janainamilitao/hackathon
/src/main/java/com/marketpay/hackathon/controller/UsuarioController.java
UTF-8
1,064
2.21875
2
[]
no_license
package com.marketpay.hackathon.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.marketpay.hackathon.model.Usuario; import com.marketpay.hackathon.model.dto.UsuarioDTO; import com.marketpay.hackathon.service.UsuarioService; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping("/usuarios") public class UsuarioController { @Autowired private UsuarioService usuarioService; private static final String APPLICATION_JSON = "application/json"; @ApiOperation(value = "Criação de usuário", response = UsuarioDTO.class) @RequestMapping(value = "/criarUsuario", method= RequestMethod.POST, produces = APPLICATION_JSON ) public Usuario criarUsuario(@RequestBody UsuarioDTO usuarioDTO) { return usuarioService.criarUsuario(usuarioDTO); } }
true
ab08dfdb4fe70222a3d0f087c91406ca559586d8
Java
AlexanderNesterovich/tat_lab_training
/FourthWeek/GmailTests/src/main/java/step/GmailSteps.java
UTF-8
1,939
2.578125
3
[]
no_license
package step; import beans.Letter; import beans.User; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import page_object.LoginPage; import page_object.MainPage; /** * Created by Aliaksandr_Nestsiarovich on 5/25/2016. */ public class GmailSteps { private static final Logger LOG = LoggerFactory.getLogger(GmailSteps.class); private WebDriver driver; private LoginPage loginPage; private MainPage mainPage; public GmailSteps(WebDriver driver) { this.driver = driver; } public void login(User firstUser) { LOG.trace("Login as {}.", firstUser); loginPage.setUserName(firstUser.getUserName()); loginPage.clickNext(); loginPage.uncheckStayLogged(); loginPage.setPasswordField(firstUser.getPassword()); mainPage = loginPage.clickSignIn(); } public void logout() { LOG.trace("Logout."); mainPage.clickLogout(); } public void openLoginPage() { LOG.debug("Open Login Page."); loginPage = new LoginPage(driver); loginPage.openPage(); } public void sendLetter(Letter letter) { LOG.debug("Send letter {}.", letter); mainPage.clickCompose(); mainPage.setTo(letter.getTo().getUserName()); mainPage.setSubject(letter.getSubject()); mainPage.setMessage(letter.getBody()); mainPage.clickSend(); } public void moveToSpam(Letter letter) { LOG.debug("Move letter to spam {}.", letter); mainPage.checkLetter(letter.getSubject(), letter.getBody(), letter.getFrom().getUserName()); mainPage.markAsSpam(); } public boolean isLetterInSpam(Letter letter) { LOG.debug("Check if letter in spam {}.", letter); mainPage.openSpamFolder(); return mainPage.isLetterPresent(letter.getFrom().getUserName(), letter.getSubject(), letter.getBody()); } }
true
3949568ace5a78e03668907d0049069d47e12f77
Java
Araksya-Hambaryan/ITC-9
/Anush_Ghazaryan/Homeworks/Selenium/selenium-project-example/src/test/java/selenium/testcases/DoSomeThingWithCookiesIT.java
UTF-8
2,009
2.453125
2
[]
no_license
package selenium.testcases; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assume.assumeFalse; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.support.PageFactory; import selenium.SeleniumTestWrapper; import selenium.pageobjects.StartPage; import selenium.utils.browser.Cookies; public class DoSomeThingWithCookiesIT extends SeleniumTestWrapper { StartPage startPage = PageFactory.initElements(getDriver(), StartPage.class); Cookies cookies = new Cookies(getDriver()); @Before public void setup() { startPage.open(); } @Test public void checkSomeValueFromCertainCookie() { assertThat(cookies.getValueOfCookieNamed("logged_in"), is("no")); } @Test public void addCustomCookie() { // skip if browser is phantomjs assumeFalse(testConfig.getBrowser().equals("phantomjs")); cookies.addCookie("myTestCookie", "added by selenium","github.com", "/", cookies.getValideExpireDate()); // check if custom cookie has been added successfully assertThat(cookies.getValueOfCookieNamed("myTestCookie"), is("added by selenium")); } @Test public void deleteCertainCookie() { // check if cookie exists initially assertThat(cookies.isCookiePresent("logged_in"), is(true)); // delete certain cookie cookies.deleteCookieNamed("logged_in"); // check if cookie was deleted successfully assertThat(cookies.isCookiePresent("logged_in"), is(false)); } @Test public void deleteAllCookies() { // check if number of localStorage is greater than 0 assertThat(cookies.getAllCookies().size(), greaterThan(0)); // delete all localStorage cookies.deleteAllCookies(); // check if number of localStorage is 0 assertThat(cookies.getAllCookies().size(), is(0)); } }
true
54ae981d48817f62bbaf8b1283de2d8d8349fe21
Java
Sicelo24/Client-Server
/src/eventregistration/Event.java
UTF-8
5,077
3.09375
3
[]
no_license
/** * Event.java * This class creates and stores the attendee details in a Derby database * @author Sicelo Zitha (216140943) * Date: 28 September 2020 */ package eventregistration; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JOptionPane; public class Event { static final String DATABASE_URL = "jdbc:derby://localhost:1527/Sunshine"; private final String username = "Administrator"; private final String password = "Password"; private String studentNumber; private String firstName; private String lastName; private String programme; private String hasResources; // Constructors public Event(String studentNumber) { this.studentNumber = studentNumber; } public Event(String studentNumber, String firstName, String lastName, String programme, String hasResources) { this.studentNumber = studentNumber; this.firstName = firstName; this.lastName = lastName; this.programme = programme; this.hasResources = hasResources; } // Getters public String getStudentNumber() { return studentNumber; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getProgramme() { return programme; } public String getHasResources() { return hasResources; } public boolean isUniqueStudentNumber() { Connection connection = null; PreparedStatement statement = null; String sql = "SELECT StudentNumber FROM Event WHERE StudentNumber = ?"; ResultSet resultSet = null; boolean unique = true; try { connection = DriverManager.getConnection(DATABASE_URL, "Administrator", "Password"); statement = connection.prepareStatement(sql); statement.setString(1, studentNumber); resultSet = statement.executeQuery(); if (resultSet.next()) { unique = false; // duplicate student number found } } catch(SQLException sqlException) { JOptionPane.showMessageDialog(null, "Error: " + sqlException); } finally { // Method 1 try { if (resultSet != null) resultSet.close(); } catch(Exception exception){ JOptionPane.showMessageDialog(null, exception.getMessage(), "Warning", JOptionPane.ERROR_MESSAGE); } try { if (statement != null) statement.close(); } catch(Exception exception){ JOptionPane.showMessageDialog(null, exception.getMessage(), "Warning", JOptionPane.ERROR_MESSAGE); } try { if (connection != null) connection.close(); } catch(Exception exception){ JOptionPane.showMessageDialog(null, exception.getMessage(), "Warning", JOptionPane.ERROR_MESSAGE); } } return unique; } public void save() { Connection connection = null; // manage connections Statement statement = null; // query statement int ok; try { connection = DriverManager.getConnection(DATABASE_URL, "Administrator", "Password"); statement = connection.createStatement(); ok = statement.executeUpdate("INSERT INTO Event VALUES('" + studentNumber + "', '" + firstName + "', '" + lastName + "', '" + programme + "', '" + hasResources + "')"); if (ok > 0) { JOptionPane.showMessageDialog(null, "Success! The information has been updated."); } else { JOptionPane.showMessageDialog(null, "Error: Could not update information."); } } catch(SQLException sqlException) { JOptionPane.showMessageDialog(null, "Error: Could not update. " + sqlException); } finally { // Method 1 try { if (statement != null) statement.close(); } catch(Exception exception){ JOptionPane.showMessageDialog(null, exception.getMessage(), "Warning", JOptionPane.ERROR_MESSAGE); } try { if (connection != null) connection.close(); } catch(Exception exception){ JOptionPane.showMessageDialog(null, exception.getMessage(), "Warning", JOptionPane.ERROR_MESSAGE); } } } }
true
9f83bf00e7ad83878b243b1b4a05e94881407264
Java
iryndin/misc
/expreval/src/test/java/net/iryndin/expreval/StringTokenEmitterTest.java
UTF-8
1,096
2.90625
3
[]
no_license
package net.iryndin.expreval; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * @author iryndin * @since 06/04/17 */ public class StringTokenEmitterTest { @Test public void testParseExpression() { List<String> list = StringTokenEmitter.parseExpression(" 1 + 2* 5* 6* 7*8 *9+ \t5*6*\t7*8+6+7+8*7"); assertEquals(Arrays.asList("1", "+", "2", "*", "5", "*", "6", "*", "7", "*", "8", "*", "9", "+", "5", "*", "6", "*", "7", "*", "8", "+", "6", "+", "7", "+", "8", "*", "7"), list); assertEquals(Arrays.asList("1", "*"), StringTokenEmitter.parseExpression("1 * ")); } @Test public void testStringTokenEmitter() throws EvalException { StringTokenEmitter ste = new StringTokenEmitter("1+2"); assertEquals(Token.createNumber(1), ste.emit()); assertEquals(Token.createAddOperation(), ste.emit()); assertEquals(Token.createNumber(2), ste.emit()); assertNull(ste.emit()); } }
true
0812c9942562f756177dc04ae956d9149413b44e
Java
pccr10001/BLEOperator
/src/adapter/BLENotificationServiceAdapter.java
UTF-8
2,874
2.4375
2
[]
no_license
package adapter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tinyb.BluetoothGattCharacteristic; import tinyb.BluetoothGattService; import java.util.LinkedList; import java.util.List; /** * Created by IDIC on 2017/1/4. */ public abstract class BLENotificationServiceAdapter<ResultType> { private static final Logger logger = LogManager.getLogger(BLENotificationServiceAdapter.class); private boolean isRunning; private BluetoothGattService service; private List<BLEServiceCallback<ResultType>> callbacks = new LinkedList<>(); protected BLEInstance instance; protected BLEServiceCallback<byte[]> innerNotification; public BLENotificationServiceAdapter(BluetoothGattService service) { this.service = service; this.instance = BLEInstance.getInstance(); } protected boolean init(Callback callback) { callback.operate(); return true; } protected BluetoothGattCharacteristic getNotificationCharacteristic() { //return the characteristic you want to notify here. return null; } public final void run(BLEServiceCallback<ResultType> callback) { try { isRunning = true; registerListener(callback); init(this::start); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); isRunning = false; } } private boolean start() { innerNotification = data -> { for (BLEServiceCallback<ResultType> callback : callbacks) callback.supply(convert(data)); }; instance.notifyCharacteristic(service.getDevice().getAddress(), getNotificationCharacteristic(), innerNotification); return true; } public ResultType convert(byte[] bytes) { //convert data here. return null; } public boolean stop() { if (innerNotification != null) { BluetoothGattCharacteristic characteristic = getNotificationCharacteristic(); instance.disableNotifyCharacteristic(service.getDevice().getAddress(), characteristic, innerNotification); logger.debug("Disable notification : " + characteristic.getUUID()); isRunning = false; return true; } return false; } protected final BluetoothGattService getService() { return service; } public final synchronized boolean registerListener(BLEServiceCallback<ResultType> callback) { return this.callbacks.add(callback); } public final synchronized boolean removeListener(BLEServiceCallback<ResultType> callback) { return this.callbacks.remove(callback); } public boolean isRunning() { return isRunning; } protected interface Callback { void operate(); } }
true
c5e152a9e2367f6a9650d68a4892da3a1cdf92a0
Java
doricke/RepairShop
/j/Java_BlastParserOffset/Hit.java
UTF-8
24,101
1.992188
2
[]
no_license
// import OutputTools; // import SeqTools; // import Sequence; /* Author:: Darrell O. Ricke, Ph.D. (mailto: d_ricke@yahoo.com) Copyright:: Copyright (c) 2002 Darrell O. Ricke, Ph.D., Paragon Software License:: GNU GPL license (http://www.gnu.org/licenses/gpl.html) Contact:: Paragon Software, 1314 Viking Blvd., Cedar, MN 55011 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /******************************************************************************/ public class Hit extends Object { /******************************************************************************/ private int alignment_length = 0; // alignment length private String description = ""; // FASTA header line private String error = ""; // error message private String expect = ""; // Expect private int identities = 0; // identities private int length = 0; // query sequence length private int percent = 0; // percent private String query_alignment = ""; // query alignment sequence private int query_end = 0; // query end private int query_frame = 0; // query frame private String query_name = ""; // query name private int query_start = 0; // query start private char query_strand = '+'; // query strand private String score = ""; // Score private String target_alignment = ""; // target alignment sequence private int target_end = 0; // target end private int target_frame = 0; // target frame private int target_length = 0; // target length private String target_name = ""; // target name private int target_start = 0; // target start private char target_strand = '+'; // target strand private String program_name = ""; // program name private int q_factor = 3; // query amino acid numbering system private int t_factor = 3; // target amino acid numbering system /******************************************************************************/ // Constructor Hit public Hit () { initialize (); } // constructor Hit /******************************************************************************/ // Initialize class variables. public void initialize () { alignment_length = 0; description = ""; error = ""; expect = ""; identities = 0; length = 0; percent = 0; query_alignment = ""; query_end = 0; query_frame = 0; query_name = ""; query_start = 0; query_strand = '+'; score = ""; target_alignment = ""; target_end = 0; target_frame = 0; target_length = 0; target_name = ""; target_start = 0; target_strand = '+'; program_name = ""; q_factor = 3; t_factor = 3; } // method initialize /******************************************************************************/ public int getAlignmentLength () { return alignment_length; } // method getAlignmentLength /******************************************************************************/ public String getDescription () { return description; } // method getDescription /******************************************************************************/ public String getError () { return error; } // method getError /******************************************************************************/ public String getExpect () { return expect; } // method getExpect /******************************************************************************/ public int getIdentities () { return identities; } // method getIdentities /******************************************************************************/ public int getLength () { return length; } // method getLength /******************************************************************************/ public int getPercent () { return percent; } // method getPercent /******************************************************************************/ public String getQueryAlignment () { return query_alignment; } // method getQueryAlignment /******************************************************************************/ public int getQueryEnd () { return query_end; } // method getQueryEnd /******************************************************************************/ public int getQueryFrame () { return query_frame; } // method getQueryFrame /******************************************************************************/ public String getQueryName () { return query_name; } // method getQueryName /******************************************************************************/ public int getQueryStart () { return query_start; } // method getQueryStart /******************************************************************************/ public char getQueryStrand () { return query_strand; } // method getQueryStrand /******************************************************************************/ public String getScore () { return score; } // method getScore /******************************************************************************/ public String getTargetAlignment () { return target_alignment; } // method getTargetAlignment /******************************************************************************/ public int getTargetEnd () { return target_end; } // method getTargetEnd /******************************************************************************/ public int getTargetFrame () { return target_frame; } // method getTargetFrame /******************************************************************************/ public int getTargetLength () { return target_length; } // method getTargetLength /******************************************************************************/ public String getTargetName () { return target_name; } // method getTargetName /******************************************************************************/ public int getTargetStart () { return target_start; } // method getTargetStart /******************************************************************************/ public char getTargetStrand () { return target_strand; } // method getTargetStrand /******************************************************************************/ public void setAlignmentLength ( int value ) { alignment_length = value; } // method setAlignmentLength /******************************************************************************/ public void setDescription ( String value ) { description = value; // Extract the target name from the description line. int index = value.indexOf ( ' ' ); // Check for no target name. if ( value.length () < 2 ) return; if ( index == -1 ) target_name = value.substring ( 1 ); else target_name = value.substring ( 1, index ); } // method setDescription /******************************************************************************/ public void setError ( String value ) { error = value; } // method setError /******************************************************************************/ public void setExpect ( String value ) { expect = value; } // method setExpect /******************************************************************************/ public void setIdentities ( int value ) { identities = value; } // method setIdentities /******************************************************************************/ public void setLength ( int value ) { length = value; } // method setLength /******************************************************************************/ public void setPercent ( int value ) { percent = value; } // method setPercent /******************************************************************************/ public void setProgramName ( String value ) { program_name = value; // System.out.println ( "Program name = " + program_name ); // Set the numbering system factors. if ( program_name.equals ( "BLASTN" ) == true ) { q_factor = 1; t_factor = 1; return; } // if // Set the numbering system factors. if ( program_name.equals ( "BLASTP" ) == true ) { q_factor = 1; t_factor = 1; return; } // if // Set the numbering system factors. if ( program_name.equals ( "BLASTX" ) == true ) { q_factor = 3; t_factor = 1; return; } // if // Set the numbering system factors. if ( program_name.equals ( "TBLASTN" ) == true ) { q_factor = 1; t_factor = 3; return; } // if // Set the numbering system factors. if ( program_name.equals ( "TBLASTX" ) == true ) { q_factor = 3; t_factor = 3; return; } // if System.out.println ( "Unknown BLAST program name: '" + program_name + "'" ); } // method setProgramName /******************************************************************************/ public void setQueryAlignment ( String value ) { query_alignment = value; } // method setQueryAlignment /******************************************************************************/ public void setQueryEnd ( int value ) { query_end = value; // System.out.println ( "Hit.setQueryEnd to " + value ); } // method setQueryEnd /******************************************************************************/ public void setQueryFrame ( int value ) { query_frame = value; // Check for complement strand. if ( value < 0 ) query_strand = '-'; } // method setQueryFrame /******************************************************************************/ public void setQueryName ( String value ) { query_name = value; } // method setQueryName /******************************************************************************/ public void setQueryStart ( int value ) { query_start = value; // System.out.println ( "Hit.setQueryStart to " + value ); } // method setQueryStart /******************************************************************************/ public void setQueryStrand ( char value ) { query_strand = value; } // method setQueryStrand /******************************************************************************/ public void setScore ( String value ) { score = value; } // method setScore /******************************************************************************/ public void setTargetAlignment ( String value ) { target_alignment = value; } // method setTargetAlignment /******************************************************************************/ public void setTargetEnd ( int value ) { target_end = value; } // method setTargetEnd /******************************************************************************/ public void setTargetFrame ( int value ) { target_frame = value; // Check for complement strand. if ( value < 0 ) target_strand = '-'; } // method setTargetFrame /******************************************************************************/ public void setTargetLength ( int value ) { target_length = value; } // method setTargetLength /******************************************************************************/ public void setTargetName ( String value ) { target_name = value; } // method setTargetName /******************************************************************************/ public void setTargetStart ( int value ) { target_start = value; } // method setTargetStart /******************************************************************************/ public void setTargetStrand ( char value ) { target_strand = value; } // method setTargetStrand /******************************************************************************/ // This method trims one amino acid from the begining of the query alignment. public void advanceQuery () { // Check for a gap character. if ( query_alignment.charAt ( 0 ) != '-' ) { // Check which strand the query alignment is from. if ( query_strand == '+' ) query_start += q_factor; else query_end -= q_factor; } // if // Shorten the query alignment. query_alignment = query_alignment.substring ( 1 ); } // method advanceQuery /******************************************************************************/ // This method trims one amino acid from the beginning of the target alignment. public void advanceTarget () { // Check for a gap character. if ( target_alignment.charAt ( 0 ) != '-' ) { // Check which strand the query alignment is from. if ( target_strand == '+' ) target_start += t_factor; else target_end -= t_factor; } // if // Shorten the query alignment. target_alignment = target_alignment.substring ( 1 ); } // method advanceTarget /******************************************************************************/ public void shortenQuery () { // System.out.println ( "shortenQuery: query = [" + query_start + " to " + query_end + " ]" ); // Check for a gap character. if ( query_alignment.charAt ( query_alignment.length () - 1 ) != '-' ) { // Check which strand the query alignment is from. if ( query_strand == '+' ) query_end -= q_factor; else query_start += q_factor; } // if // Shorten the query alignment. query_alignment = query_alignment.substring ( 0, query_alignment.length () - 1 ); } // method shortenQuery /******************************************************************************/ public void shortenTarget () { // Check for a gap character. if ( target_alignment.charAt ( target_alignment.length () - 1 ) != '-' ) { // Check which strand the target alignment is from. if ( target_strand == '+' ) target_end -= t_factor; else target_start += t_factor; } // if // Shorten the target alignment. target_alignment = target_alignment.substring ( 0, target_alignment.length () - 1 ); } // method shortenTarget /******************************************************************************/ private void trimMismatchEnd () { int align_end = query_alignment.length () - 1; while ( ( align_end > 0 ) && ( query_alignment.charAt ( align_end ) != target_alignment.charAt ( align_end ) ) ) { shortenQuery (); shortenTarget (); align_end = query_alignment.length () - 1; } // while } // method trimMismatchEnd /******************************************************************************/ private void trimMismatchStart () { while ( ( query_alignment.length () > 0 ) && ( ( query_alignment.charAt ( 0 ) != target_alignment.charAt ( 0 ) ) || ( query_alignment.charAt ( 0 ) == '*' ) ) ) { advanceQuery (); advanceTarget (); } // while } // method trimMismatchStart /******************************************************************************/ public void retotal () { identities = 0; // number of identities int aa_count = 0; // query amino acids // Traverse the alignment. for ( int i = 0; i < query_alignment.length (); i++ ) { // Check for an amino acid at this position. // if ( Sequence.isAA ( query_alignment.charAt ( i ) ) == true )a char q = query_alignment.charAt ( i ); if ( ( ( q >= 'a' ) && ( q <= 'z' ) ) || ( ( q >= 'A' ) && ( q <= 'Z' ) ) ) { aa_count++; // Check for identity amino acids. if ( q == target_alignment.charAt ( i ) ) identities++; } // if } // for // Reset the length of the alignment. alignment_length = query_alignment.length (); // Recompute the percent identity of the alignment. if ( aa_count > 0 ) percent = ( identities * 100 ) / aa_count; } // method retotal /******************************************************************************/ public void trimAAEnds () { // System.out.println ( "trimAAEnds: query = " + query_alignment ); // System.out.println ( "trimAAEnds: target = " + target_alignment ); // System.out.println (); // Trim the alignment end until the amino acids are identical. trimMismatchEnd (); // Check if the end of the alignment needs to be trimmed. int count = 0; int count2 = 0; while ( ( count < 3 ) && ( query_alignment.length () > 6 ) ) { int end = query_alignment.length () - 1; int start = end - 5; count = SeqTools.countIdentities ( query_alignment .substring ( start, end ), target_alignment.substring ( start, end ) ); count2 = SeqTools.countIdentities ( query_alignment .substring ( end-2, end ), target_alignment.substring ( end-2, end ) ); if ( ( count < 3 ) || ( count2 < 1 ) ) { // Shorten the alignment. shortenQuery (); shortenTarget (); trimMismatchEnd (); } // if } // while // Check if the begining of the alignment needs to be trimmed. trimMismatchStart (); count = 0; while ( ( count < 3 ) && ( query_alignment.length () > 6 ) ) { count = SeqTools.countIdentities ( query_alignment .substring ( 1, 6 ), target_alignment.substring ( 1, 6 ) ); count2 = SeqTools.countIdentities ( query_alignment .substring ( 1, 3 ), target_alignment.substring ( 1, 3 ) ); if ( ( count < 3 ) || ( count2 < 1 ) ) { // Shorten the alignment. advanceQuery (); advanceTarget (); trimMismatchStart (); } // if } // while // Retotal the number of identities, percent, etc. retotal (); // System.out.println ( "trimAAEnds: (end) query = " + query_alignment ); // System.out.println ( "trimAAEnds: (end) target = " + target_alignment ); // System.out.println (); } // method trimAAEnds /******************************************************************************/ // This method returns a copy of this hit. public Hit copyOf () { Hit copy = new Hit (); copy.setAlignmentLength ( alignment_length ); copy.setDescription ( description ); copy.setError ( error ); copy.setExpect ( expect ); copy.setIdentities ( identities ); copy.setLength ( length ); copy.setPercent ( percent ); copy.setQueryAlignment ( query_alignment ); copy.setQueryEnd ( query_end ); copy.setQueryFrame ( query_frame ); copy.setQueryName ( query_name ); copy.setQueryStart ( query_start ); copy.setQueryStrand ( query_strand ); copy.setScore ( score ); copy.setTargetAlignment ( target_alignment ); copy.setTargetEnd ( target_end ); copy.setTargetFrame ( target_frame ); copy.setTargetLength ( target_length ); copy.setTargetName ( target_name ); copy.setTargetStart ( target_start ); copy.setTargetStrand ( target_strand ); copy.setProgramName ( program_name ); return copy; } // method copyOf /******************************************************************************/ public void printHit () { System.out.println (); System.out.println ( "Hit:" ); OutputTools.write ( "alignment length", alignment_length ); OutputTools.write ( "description", description ); OutputTools.write ( "error", error ); OutputTools.write ( "expect", expect ); OutputTools.write ( "identities", identities ); OutputTools.write ( "length", length ); OutputTools.write ( "percent", percent ); OutputTools.write ( "query end", query_end ); OutputTools.write ( "query frame", query_frame ); OutputTools.write ( "query start", query_start ); OutputTools.write ( "query strand", query_strand ); OutputTools.write ( "score", score ); OutputTools.write ( "target end", target_end ); OutputTools.write ( "target frame", target_frame ); OutputTools.write ( "target_length", target_length ); OutputTools.write ( "target_name", target_name ); OutputTools.write ( "target_start", target_start ); OutputTools.write ( "target_strand", target_strand ); OutputTools.write ( "query alignment ", query_alignment ); OutputTools.write ( "target alignment", target_alignment ); } // method printHit /******************************************************************************/ private String getAccession () { int index = description.indexOf ( ' ' ); int tab_index = description.indexOf ( '\t' ); if ( ( tab_index > 0 ) && ( tab_index < index ) ) index = tab_index; if ( index > 0 ) return description.substring ( 1, index ); return "-"; } // method getAccession /******************************************************************************/ public String toResult ( String database_name ) { return toResult ( database_name, 0 ); } // method toResult /******************************************************************************/ public String toResult ( String database_name, int start_offset ) { StringBuffer result = new StringBuffer ( 4096 ); result.append ( query_name ); // query name result.append ( "\t" ); result.append ( query_start + start_offset ); // query start result.append ( "\t" ); result.append ( query_end + start_offset ); // query end result.append ( "\t" ); result.append ( query_strand ); // query strand result.append ( "\t" ); result.append ( target_strand ); // target strand result.append ( "\t" ); result.append ( identities ); // identities result.append ( "\t" ); result.append ( score ); // score result.append ( "\t" ); result.append ( expect ); // expect result.append ( "\t" ); result.append ( alignment_length ); // hit length result.append ( "\t" ); result.append ( percent ); // percent result.append ( "\t" ); result.append ( "similarity" ); // seq_type result.append ( "\t" ); result.append ( program_name ); // program name result.append ( "\t" ); result.append ( database_name ); // database name result.append ( "\t" ); result.append ( getAccession () ); // accession result.append ( "\t" ); result.append ( target_start ); // target start result.append ( "\t" ); result.append ( target_end ); // target end result.append ( "\t" ); result.append ( description ); // description result.append ( "\t" ); result.append ( query_alignment ); // query alignment result.append ( "\t" ); result.append ( target_alignment ); // target alignment return result.toString (); } // method toString /******************************************************************************/ } // class Hit
true
86f58b43b6fea5603a2f41750f1160c2812bf278
Java
tkonieczek/pol72
/src/main/java/dzien4/MinMax.java
UTF-8
399
3.25
3
[]
no_license
package dzien4; public class MinMax<T extends Comparable> { private T first; private T second; public MinMax(T first, T second) { this.first = first; this.second = second; } public T getMin() { return (first.compareTo(second) < 0 ? first : second); } public T getMax() { return (first.compareTo(second) > 0 ? second : first); } }
true
e93e6ac177321d6143809cfc89b523e9d8a634f4
Java
kapild/algorithms-design-and-analysis
/programming-practice/src/main/java/challenges/leetcode/StrobogrammaticNumberII.java
UTF-8
3,039
3.453125
3
[]
no_license
package challenges.leetcode; import static com.google.common.truth.Truth.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import challenges.AbstractCustomTestRunner; /** * 247. Strobogrammatic Number II * * A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). * * Find all strobogrammatic numbers that are of length = n. * * For example, Given n = 2, return ["11","69","88","96"]. * * @author Hxkandwal */ public class StrobogrammaticNumberII extends AbstractCustomTestRunner { private static StrobogrammaticNumberII _instance = new StrobogrammaticNumberII(); public List<String> findStrobogrammaticCleaner(int n) { return dfs (n, n); } // working our way outwards. Post order stitching. backtracking. private List<String> dfs (int len, int n) { if (len == 0) return Arrays.asList (""); if (len == 1) return Arrays.asList ("0", "1", "8"); List<String> ans = new ArrayList<>(); for (String num : dfs (len - 2, n)) { if (len != n) ans.add ("0" + num + "0"); ans.add ("6" + num + "9"); ans.add ("9" + num + "6"); ans.add ("8" + num + "8"); ans.add ("1" + num + "1"); } return ans; } public List<String> _findStrobogrammatic(int n) { List<String> ans = new ArrayList<> (); dfs (ans, "", n, 0); return ans; } private void dfs (List<String> ans, String build, int n, int index) { if (build.length () == n) ans.add (build); else { if (build.length () + 2 <= n) { dfs (ans, build.substring (0, index) + '6' + "" + '9' + build.substring (index), n, index + 1); dfs (ans, build.substring (0, index) + '9' + "" + '6' + build.substring (index), n, index + 1); if (build.length() > 0) dfs (ans, build.substring (0, index) + '0' + "" + '0' + build.substring (index), n, index + 1); dfs (ans, build.substring (0, index) + '1' + "" + '1' + build.substring (index), n, index + 1); dfs (ans, build.substring (0, index) + '8' + "" + '8' + build.substring (index), n, index + 1); } else { dfs (ans, build.substring (0, index) + '0' + build.substring (index), n, index + 1); dfs (ans, build.substring (0, index) + '1' + build.substring (index), n, index + 1); dfs (ans, build.substring (0, index) + '8' + build.substring (index), n, index + 1); } } } // driver method public static void main(String[] args) { _instance.runTest(2, Arrays.asList("69", "96", "11", "88")); } @SuppressWarnings("unchecked") public void runTest(final int n, final List<String> expectedOutput) { List<Object> answers = runAll(getClass(), new Object[] { n }); for (Object answer : answers) assertThat((List<String>) answer).isEqualTo(expectedOutput); System.out.println("ok!"); } }
true
6554d1bb3596912a534019d99acc901c6a9432d8
Java
andrewctran/subduction
/library/src/main/java/com/nextdoor/library/STFAnnotator.java
UTF-8
3,149
2.4375
2
[]
no_license
package com.nextdoor.library; import android.content.Context; import android.content.ContextWrapper; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.os.Environment; import android.view.View; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * Image handling for the bug/feedback reporter. */ public class STFAnnotator { public static final String STF_FILENAME = "stf_screenshot.jpg"; public static final String STF_DIR = "stfImages"; /** * Takes a screenshot of the current display. * @param rootView The root of the app's view hierarchy. * @return Screenshot in Bitmap format */ public static Bitmap takeScreenshot(View rootView) { rootView.setDrawingCacheEnabled(true); rootView.buildDrawingCache(true); return Bitmap.createBitmap(rootView.getDrawingCache()); } /** * Grabs the latest screenshot from disk. * @return Screenshot in Bitmap format */ public static Bitmap getScreenshot(String path) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 1; File screenshotFile = new File(path); Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(new FileInputStream(screenshotFile)); } catch (FileNotFoundException e) { } return bitmap; } /** * Saves the screenshot to disk, overriding any existing screenshot. * @param screenshot * @return The image path to the screenshot on disk. */ public static String saveScreenshot(Context context, Bitmap screenshot) { ContextWrapper cw = new ContextWrapper(context.getApplicationContext()); File directory = cw.getDir(STF_DIR, Context.MODE_PRIVATE); File imagePath = new File(directory, STF_FILENAME); FileOutputStream fos = null; try { fos = new FileOutputStream(imagePath); screenshot.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); } catch (Exception e) { e.printStackTrace(); } return imagePath.getAbsolutePath(); } public static void deleteScreenshot() { String imagePath = STFSession.imagePath; File imageFile = new File(imagePath); if (imageFile.exists()) { imageFile.delete(); } } /** * Overlay user annotations on the screenshot. * @param screenshot * @param annotation * @return The composite bitmap combining both screenshot and annotations. */ public static Bitmap mergeAnnotation(Bitmap screenshot, Bitmap annotation) { Bitmap overlay = Bitmap.createBitmap(screenshot.getWidth(), screenshot.getHeight(), screenshot.getConfig()); Canvas canvas = new Canvas(overlay); canvas.drawBitmap(screenshot, new Matrix(), null); canvas.drawBitmap(annotation, 0, 0, null); return overlay; } }
true
edf39e49f5379ce2afd59432557cff8944e34721
Java
yeonseo/AndroidWebAppEdu
/201908_JAVA_Study/chpter02/src/chpter02/BitOperator.java
UTF-8
368
3.03125
3
[]
no_license
package chpter02; public class BitOperator { public static void main(String[] args) { int x=0x0fff; int y=0xfff0; System.out.printf("%x ",(x&y)); System.out.printf("%x ",(x|y)); System.out.printf("%x ",(x^y)); System.out.printf("%x ",~x); System.out.printf("%x ",(x<<4)); System.out.printf("%x ",(x>>4)); System.out.printf("%x ",(-1>>>4)); } }
true
7ca8cb18c876c1420027e0e03f53e54125517c7a
Java
VoxelIndustry/AshRunica
/src/main/java/net/vi/ashrunica/common/gui/GuiHandler.java
UTF-8
1,632
2.203125
2
[ "Apache-2.0" ]
permissive
package net.vi.ashrunica.common.gui; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; import net.vi.ashrunica.client.gui.GuiRuneDesigner; import net.vi.ashrunica.client.gui.GuiRuneSynthetizer; import net.vi.ashrunica.common.tile.TileRuneDesigner; import net.vi.ashrunica.common.tile.TileRuneSynthetizer; import net.voxelindustry.brokkgui.wrapper.impl.BrokkGuiManager; import net.voxelindustry.steamlayer.container.IContainerProvider; import javax.annotation.Nullable; public class GuiHandler implements IGuiHandler { @Nullable @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { TileEntity tile = world.getTileEntity(new BlockPos(x, y, z)); if (tile instanceof IContainerProvider) return ((IContainerProvider) tile).createContainer(player); return null; } @Nullable @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { TileEntity tile = world.getTileEntity(new BlockPos(x, y, z)); switch (GuiType.values()[ID]) { case RUNE_DESIGNER: return BrokkGuiManager.getBrokkGuiContainer(new GuiRuneDesigner((TileRuneDesigner) tile)); case RUNE_SYNTHETIZER: return BrokkGuiManager.getBrokkGuiContainer(new GuiRuneSynthetizer((TileRuneSynthetizer) tile)); } return null; } }
true
518b9645d5410acb5c9713a67b30337dcb9e5dda
Java
krenog/muf
/src/main/java/com/krenog/myf/user/security/jwt/JwtConfig.java
UTF-8
1,653
2.015625
2
[]
no_license
package com.krenog.myf.user.security.jwt; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class JwtConfig { @Value("${security.jwt.token.header-string}") private String header; @Value("${security.jwt.token.expire-length}") private long expiration; @Value("${security.jwt.token.secret-key}") private String secret; @Value("${security.jwt.claim.userAuthorities}") private String userAuthoritiesClaimKey; @Value("${security.jwt.claim.userId}") private String userIdClaimKey; @Value("${security.jwt.audience}") private String appName; String getUserAuthoritiesClaimKey() { return userAuthoritiesClaimKey; } public void setUserAuthoritiesClaimKey(String userAuthoritiesClaimKey) { this.userAuthoritiesClaimKey = userAuthoritiesClaimKey; } String getUserIdClaimKey() { return userIdClaimKey; } public void setUserIdClaimKey(String userIdClaimKey) { this.userIdClaimKey = userIdClaimKey; } String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } String getHeader() { return header; } public void setHeader(String header) { this.header = header; } long getExpiration() { return expiration; } public void setExpiration(long expiration) { this.expiration = expiration; } String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } }
true
048064f964942d45aadd5cfea798a1b62b61b544
Java
dovakinlink/Netty-Dovakin-PushService
/src/main/java/org/dovakin/push/core/annotations/RequestController.java
UTF-8
547
2.109375
2
[ "Apache-2.0" ]
permissive
package org.dovakin.push.core.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by liuhuanchao on 2017/8/1. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface RequestController { @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface RequestMapping{ String value(); RequestMethod method() default RequestMethod.GET; } }
true
65f8f3015adb83f1f0e289d7f05b159d0b100418
Java
fatiilluch/TP2019
/src/test/java/domain/PrendasSuperponiblesTest.java
UTF-8
4,200
2.28125
2
[]
no_license
package domain; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import domain.events.Protocolo; import domain.repositorio.RepositorioMolde; public class PrendasSuperponiblesTest { Categoria superior = Categoria.Superior; Categoria inferior = Categoria.Inferior; Categoria calzado = Categoria.Calzado; Categoria accesorio = Categoria.Accesorio; Molde molde1; RepositorioMolde repoMolde = RepositorioMolde.getInstance(); private TipoDePrenda camisa; private TipoDePrenda remera; private TipoDePrenda campera; private TipoDePrenda pantalon; private TipoDePrenda zapatos; private TipoDePrenda reloj; private Protocolo informal = Protocolo.Informal; private Prenda camisaMangaLarga; private Prenda remeraEnV; private Prenda camperaGrande; private Prenda pantalonDeTraje; private Prenda zapatosFormales; private Prenda relojSwatch; private Imagen avatar1; private Imagen avatar2; private Imagen avatar3; private Imagen avatar4; private Imagen avatar5; private Imagen avatar6; private Guardarropa formal1; private Usuario maria; private EstadoUsuario premium; @Before public void init() { this.premium = new UsuarioPremium(); molde1 = new Molde(); Sensibilidad sensibilidad = new Sensibilidad(0.0, 0.0); this.maria = new Usuario("Meri", "123", sensibilidad, "Maria", "Grillo"); maria.setEstado(premium); this.formal1 = new Guardarropa(); this.avatar1 = new Imagen("imagenes\\prenda.jpg"); this.avatar2 = new Imagen("imagenes\\img2.png"); this.avatar3 = new Imagen("imagenes\\img3.png"); this.avatar4 = new Imagen("imagenes\\img4.png"); this.avatar5 = new Imagen("imagenes\\img5.png"); this.avatar6 = new Imagen("imagenes\\img6.png"); this.camisa = new TipoDePrenda("camisa", superior, 1); this.remera = new TipoDePrenda("remera", superior, 1); this.campera = new TipoDePrenda("campera", superior, 2); this.pantalon = new TipoDePrenda("pantalon", inferior,0); this.zapatos = new TipoDePrenda("zapatos", calzado,0); this.reloj = new TipoDePrenda("reloj", accesorio,0); molde1.agregarTipoDePrenda(remera); molde1.agregarTipoDePrenda(pantalon); repoMolde.agregarMolde(molde1); this.camisaMangaLarga = new Prenda(camisa, Tela.ALGODON, Color.ROSA, Protocolo.Informal,avatar2); this.camperaGrande = new Prenda(campera, Tela.SEDA, Color.NEGRO, Protocolo.Informal,avatar1); this.remeraEnV = new Prenda(remera, Tela.LANA,Color.BLANCO,Protocolo.Informal,avatar3); this.pantalonDeTraje = new Prenda(pantalon, Tela.LANA, Color.VERDE, Protocolo.Informal,avatar4); this.zapatosFormales = new Prenda(zapatos, Tela.CHAROL, Color.AZUL, Protocolo.Informal,avatar5); this.relojSwatch = new Prenda(reloj, Tela.METAL, Color.NEGRO, Protocolo.Informal,avatar6); formal1.agregarPrenda(camisaMangaLarga); formal1.agregarPrenda(camperaGrande); formal1.agregarPrenda(remeraEnV); formal1.agregarPrenda(pantalonDeTraje); formal1.agregarPrenda(zapatosFormales); formal1.agregarPrenda(relojSwatch); } @Test public void TestPrendasSuperponibles() { maria.agregarGuardarropa(formal1); // Assert.assertEquals(1,maria.pedirAtuendoAGuardarropa(formal1, informal)); } @Test public void filtrarPorCategoriaSegunTest() { int cantidasDePrendas = formal1.filtrarPorCategoria(superior).size(); Assert.assertEquals(3,cantidasDePrendas); } @Test public void indiceAleatorioTest() { int indice = formal1.indiceAleatorio(superior); Assert.assertTrue(indice >= 0); } @Test public void indiceAleatorioSegunElNivelTest() { List<Prenda> prendasLimitadas = formal1.getPrendas(); int indice = formal1.indiceAleatorioSegunElNivel(prendasLimitadas, 0); System.out.println(indice); Assert.assertTrue(indice >= 0); } }
true
5d519ce313581c2f90da8c982faa48149b6a09d6
Java
gd123yjy/OracleHomework
/src/main/java/cn/yjy/repository/imp/EnrollRepositoryImp.java
UTF-8
617
1.976563
2
[]
no_license
package cn.yjy.repository.imp; import cn.yjy.repository.EnrollRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; /** * Created by yjy on 17-1-4. */ @Repository public class EnrollRepositoryImp implements EnrollRepository { @Autowired private JdbcTemplate jdbcTemplate; @Override public void autoEnroll() { jdbcTemplate.execute("call AUTO_PROC()"); } @Override public void clearStatus() { jdbcTemplate.execute("call CLEAR_STATUS()"); } }
true
cee6ee46399a8ea5b59dac12b6f76762972e41b1
Java
Wazzap007/SeleniumPractice
/src/WebDriver/WebDriverManager.java
UTF-8
2,124
2.515625
3
[]
no_license
package WebDriver; import com.beust.jcommander.internal.Nullable; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.session.FirefoxFilter; public class WebDriverManager { public static ChromeDriver chromeDriverInit(String url, @Nullable ChromeOptions options){ System.setProperty("webdriver.chrome.driver","libs\\chromedriver.exe"); ChromeDriver driver; // TODO: надо проверить, что будет, если просто передать null if (options != null) { driver = new ChromeDriver(options); } else { driver = new ChromeDriver(); } if (!url.equals("")){ driver.get(url); } return driver; } public static FirefoxDriver firefoxDriverInit(String url, @Nullable FirefoxOptions options){ System.setProperty("webdriver.gecko.driver","libs\\geckodriver.exe"); FirefoxDriver driver; // TODO: надо проверить, что будет, если просто передать null if (options != null) { driver = new FirefoxDriver(options); } else { driver = new FirefoxDriver(); } if (!url.equals("")){ driver.get(url); } return driver; } public static void endProgram(RemoteWebDriver driver) { ChromeDriver chd = (ChromeDriver) driver; if (!driver.equals(null)) { // использую этот метод, т.к. он закрывает все вкладки, в отличие от close driver.quit(); } // завершаю выполнение программы, чтобы не происходило ошибок с обращением к несуществующей сессии (костыль) //System.exit(0); } }
true
2258d7bb11eee1072ab5d5e64cfdca01bcc6891b
Java
padob/pBlog
/src/main/java/pl/karolcz/pBlog/vote/VoteController.java
UTF-8
994
2.25
2
[ "MIT" ]
permissive
package pl.karolcz.pBlog.vote; import org.springframework.web.bind.annotation.*; import pl.karolcz.pBlog.comment.CommentService; import pl.karolcz.pBlog.common.web.Token; import pl.karolcz.pBlog.post.PostService; @RestController @RequestMapping(value = "/vote") class VoteController { private PostService postService; private CommentService commentService; public VoteController(PostService postService, CommentService commentService) { this.postService = postService; this.commentService = commentService; } @GetMapping("/post/{postId}") public int voteOnPost(@RequestHeader("Authorization") String token, @PathVariable String postId) { return postService.vote(Token.getIdFromToken(token), postId); } @GetMapping("/comment/{commentId}") public int voteOnComment(@RequestHeader("Authorization") String token, @PathVariable String commentId) { return commentService.vote(Token.getIdFromToken(token), commentId); } }
true
a9d5b424954b1d7d847f4782a7d888fd2607f813
Java
kong0836/dashboard
/dashboard-consumer/src/main/java/com/dashboard/mq/listener/MqListener.java
UTF-8
921
2.078125
2
[]
no_license
package com.dashboard.mq.listener; import com.dashboard.mq.QueueConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Component; /** * @author konglinghui * @description TODO * @date 2020/3/15 9:06 **/ @Component public class MqListener { private static final Logger LOGGER = LoggerFactory.getLogger(MqListener.class); @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @SendTo("SQueue") @JmsListener(destination = QueueConstants.TEST_QUEUE) public String handleMessage(String name) { LOGGER.info("接受mq消息:{}", name); return "接受mq消息:" + name; } }
true
4beadfa4324a2c9b41ebee48f8456c13d42a226b
Java
g6nfm/NFM-G6-REPO-MAIN
/xtGraphics.java
UTF-8
216,089
1.640625
2
[]
no_license
import java.applet.Applet; import java.applet.AudioClip; import java.awt.*; import java.awt.image.*; import java.io.*; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.awt.Graphics2D; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ThreadLocalRandom; import java.util.Timer; import java.util.TimerTask; import java.text.DecimalFormat; public class xtGraphics extends Panel implements Runnable { /** * */ private static final long serialVersionUID = -6463312620664057856L; /** * starting colors for the special screen in the credits */ public int credColors[] = { 25, 50, 100 }; /** * test image for the network load feature */ public Image aimLogo; public Graphics2D rd; public Medium m; public ImageObserver ob; public Applet app; public int fase; public int oldfase; public int starcnt; public int unlocked; public int lockcnt; public int opselect; public boolean shaded; public int flipo; public boolean nextc; public int gatey; public int looped; public int sc[]; public int invisible; public int nplayers; /** * x position of the cars at theh start of a race */ public int xstart[] = { 350, -350, 350, -350, 350, -350, 0 }; /** * z position of the cars at theh start of a race */ public int zstart[] = { -1540, -1540, -780, -780, 0, 0, 760 }; /* * hm... it would be interesting if there was a ystart... * int ystart[] = { * 250, 350, 450, 550, 650, 750, 850 * }; */ public float proba[] = { 0.6F, 0.7F, 0.4F, 0.3F, 0.8F, 0, 0.3F, 0.3F, 0.3F, 0.1F, 0.1F, 0.5F, 0, 0 }; public float dishandle[] = { 0.65F, 0.6F, 0.85F, 0.65F, 0.75F, 0.85F, 0.8F, 0.9F, 0.5F, 0.6F, 0.95F, 0.4F, 0.87F, 0.42F }; public float outdam[] = { 0.67F, 0.85F, 0.45F, 0.5F, 0.55F, 0.6F, 0.75F, 0.80F, 0.89F, 0.90F, 0.79F, 0.95F, 0.77F, 1.0F }; public boolean holdit; public int holdcnt; public boolean winner; public boolean setnumber; public int flexpix[]; public int smokey[]; public Image fleximg; public int flatrstart; public Thread runner; public int runtyp; public Image carsbg; public Image inst1; public Image inst2; public Image inst4; public Image inst6; public Image inst8; public Image instback; public Image kaff; public Image odmg; public Image overlay; public Image overlaystatus; public Image hunting; public Image opwr; public Image opos; public Image owas; public Image olap; public Image oyourwasted; public Image oyoulost; public Image oyouwon; public Image oyouwastedem; public Image ogameh; public Image oloadingmusic; public Image oflaot; public Image powerbar; public Image damagebar; public Image wastedtext; public Image postext; public Image kph; public Image laptext; public Image timetext; public Image dmg; public Image pwr; public Image pos; public Image was; public Image lap; public Image landrover; public Image br; public Image select; public Image loadingmusic; public Image yourwasted; public Image youlost; public Image youwon; public Image youwastedem; public Image gameh; public Image congrd; public Image gameov; public Image carstarter; public Image carstreetelites; public Image carfuriousfour; public Image statbostart; public Image statbose; public Image statboff; public Image statbstart; public Image statbse; public Image statbff; public Image brse; public Image pgate; public Image statb; public Image statbo; public Image mdness; public Image paused; public Image radicalplay; public Image logocars; public Image logomadnes; public Image logomadbg; public Image lotus; public Image byrd; public Image opback; public Image nfmcoms; public Image opti; public Image bgmain; public Image splash; public Image rpro; public Image nfmcom; public Image flaot; public Image fixhoop; public Image sarrow; public Image stunts; public Image racing; public Image wasting; public Image plus; public Image space; public Image arrows; public Image chil; public Image ory; public Image kz; public Image kx; public Image kv; public Image kp; public Image km; public Image kn; public Image kenter; public Image nfm; public Image trackbg[][]; public Image toyota; public Image dude[]; public Image dudeb[]; public int duds; public int dudo; public Image next[]; public Image back[]; public Image nextse; public Image backse; public Image nextstart; public Image backstart; public Image contin[]; public Image ostar[]; public Image star[]; public int pcontin; public int pnext; public int pback; public int pstar; public Image orank[]; public Image rank[]; public Image ocntdn[]; public Image cntdn[]; public int gocnt; public AudioClip engs[][]; public boolean pengs[]; public int enginsignature[] = { 0, 1, 2, 1, 0, 3, 2, 2, 1, 0, 3, 4, 1, 4 }; public AudioClip air[]; public boolean aird; public boolean grrd; public AudioClip crash[]; public AudioClip lowcrash[]; public AudioClip tires; public AudioClip checkpoint; public AudioClip carfixed; public AudioClip powerup; public AudioClip three; public AudioClip two; public AudioClip one; public AudioClip go; public AudioClip wastd; public AudioClip firewasted; public boolean pwastd; public AudioClip skid[]; public AudioClip dustskid[]; public boolean mutes; public RadicalMod mainmenu; public RadicalMod cars; public RadicalMod stracks[]; public RadicalMidi mtracks[]; public boolean isMidi[]; public boolean loadedt[]; public int lastload; public boolean mutem; public boolean sunny; public boolean macn; public boolean arrace; public int ana; public int cntan; public int cntovn; public boolean flk; public int tcnt; public boolean tflk; public String say; public String say2; public boolean wasay; public int clear; public int posit; public int wasted; public int laps; public int dested[]; public String names[] = { "Solstice", "Venomous", "Explorer", "Posiedon", "Vigero", "Diablo", //STARTER "Swiftslide", "Razorback", "Vulcan", "Iron Bull", "Amethyst", "Rampage", "Apollo", //BIG 3 "Khaos" //FINAL BOSS //"Poseidon", "Venomous", "The Wanderer", "Maniac", "Bluebird", "Scorpion", "Zorgaro", //"Havoc", "Velocity", "Diesel King", "Slipstream", "Rampage", "Angelus", "Dr. Monstaa" }; public String specialty[] = { "", "", "", " ", " ", " ", "[ Street Elites ]", "[ Street Elites ]", "[ Street Elites ]", "[ Leader of the Street Elites ]", "[ Furious Four ]", "[ Furious Four ]", "[ Furious Four ] ", "[ Leader of the Furious Four ]" }; public String creators[] = { "Reed", "GX", "G6", "GX", "KRC", "Chaotic", "Tunari", "Reed", "Reed", "Harmless", "Harmless", "G6", "ACVoong", "G6" }; public int currentRotation = -2; public int nameOfNewVariable; public int dmcnt; public boolean dmflk; public int pwcnt; public boolean pwflk; public String adj[][] = { { "Cool", "Okay", "Nice" }, { "Crazy", "Gnarly", "Insane" }, { "Incredible", "Ripping", "Radical" }, { "What do you even call that!?", "You are clinically insane...", "Can I get your autograph?" }, { "surf style", "off the lip", "bounce back" } }; public String exlm[] = { "!", "!!", "!!!" }; public String loop; public String spin; public String asay; public int auscnt; public boolean aflk; public int sndsize[] = { 106, 76, 56, 116, 92, 208, 70, 80, 152, 102, 27, 65, 52, 30, 151, 129, 70, 70, 100, 139, 200, 120, 100, 70 }; public Image hello; public Image sign; public Image loadbar; public int kbload; public int dnload; public float shload; public int radpx; public int pin; public int bgmy[] = { 0, 500 }; public int trkx[] = { 0, 900 }; float statrate[] = { 1.0F, 1.0F, 1.0F, 1.0F, 1.0F, 1.0F }; public int trkl; public int trklim; public float hipno[] = { 1.0F, 1.0F, 3F, 1.0F, 1.2F, 1.0F, 1.7F, 1.0F, 1.0F, 8F, 1.5F, 2.0F, 1.2F, 10F, 1.8F, 1.4F, 2.0F, 2.0F, 2.0F, 2.0F, 2.0F, 2.0F, 2.0F, 2.0F, 2.0F }; public int flkat; public int movly; public int xdu; public int ydu; public int gxdu; public int gydu; public int pgatx[] = { 146, 175, 215, 267, 334, 401, 452, 493, 521 }; public int pgaty[] = { 168, 188, 201, 212, 219, 214, 203, 189, 171 }; public int pgady[]; public boolean pgas[]; public int lxm; public int lym; public int pwait; public int stopcnt; public int cntwis; public int crshturn; public int bfcrash; public int bfskid; public boolean crashup; public boolean skidup; public int skflg; public int dskflg; public int flatr; public int flyr; public int flyrdest; public int flang; public int flangados; public float blackn; public float blacknados; /**Filter images * @param img Image to filter * @param type Integer of what filter to apply * * @author Kaffeinated */ public void filterImage(Image img, int type) { BufferedImage buff_img = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D rd_sep = buff_img.createGraphics(); rd_sep.drawImage(img, 0, 0, null); rd_sep.dispose(); // now buff_img = BufferedImage img if (type == 0) { //////// grayscale BufferedImage gray = new BufferedImage(buff_img.getWidth(), buff_img.getHeight(), BufferedImage.TYPE_INT_ARGB); ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); op.filter(buff_img, gray); rd.drawImage(gray, 0, 0, null); } if (type == 1) { ///////// sepia tone BufferedImage sepia = new BufferedImage(buff_img.getWidth(), buff_img.getHeight(), BufferedImage.TYPE_INT_ARGB); int sepiaDepth = 20; int w = buff_img.getWidth(); int h = buff_img.getHeight(); int[] pixels = new int[w * h * 4]; buff_img.getRaster().getPixels(0, 0, w, h, pixels); for (int x = 0; x < buff_img.getWidth(); x++) { for (int y = 0; y < buff_img.getHeight(); y++) { int rgb = buff_img.getRGB(x, y); Color color = new Color(rgb, true); int r = color.getRed(); int g = color.getGreen(); int b = color.getBlue(); int gry = (r + g + b) / 3; r = g = b = gry; r = r + (sepiaDepth * 2); g = g + sepiaDepth; if (r > 255) { r = 255; } if (g > 255) { g = 255; } if (b > 255) { b = 255; } b -= 20; if (b < 0) { b = 0; } if (b > 255) { b = 255; } color = new Color(r, g, b, color.getAlpha()); sepia.setRGB(x, y, color.getRGB()); } } rd.drawImage(sepia, 0, 0, null); } if (type == 2) { /////////// inverts colors BufferedImage invert = new BufferedImage(buff_img.getWidth(), buff_img.getHeight(), BufferedImage.TYPE_INT_ARGB); int w = buff_img.getWidth(); int h = buff_img.getHeight(); int[] pixels = new int[w * h * 4]; buff_img.getRaster().getPixels(0, 0, w, h, pixels); for (int x = 0; x < buff_img.getWidth(); x++) { for (int y = 0; y < buff_img.getHeight(); y++) { int rgb = buff_img.getRGB(x, y); Color color = new Color(rgb, true); int r = color.getRed(); int g = color.getGreen(); int b = color.getBlue(); r = 255 - r; g = 255 - g; b = 255 - b; if (r > 255) { r = 255; } if (r < 0) { r = 0; } if (g > 255) { g = 255; } if (g < 0) { g = 0; } if (b > 255) { b = 255; } if (b < 0) { b = 0; } color = new Color(r, g, b, color.getAlpha()); invert.setRGB(x, y, color.getRGB()); } } rd.drawImage(invert, 0, 0, null); } if (type == 3) { /////// alternate invert BufferedImage altinvert = new BufferedImage(buff_img.getWidth(), buff_img.getHeight(), BufferedImage.TYPE_INT_ARGB); int w = buff_img.getWidth(); int h = buff_img.getHeight(); int[] pixels = new int[w * h * 4]; buff_img.getRaster().getPixels(0, 0, w, h, pixels); for (int x = 0; x < buff_img.getWidth(); x++) { for (int y = 0; y < buff_img.getHeight(); y++) { int rgb = buff_img.getRGB(x, y); Color color = new Color(rgb, true); int r = color.getRed(); int g = color.getGreen(); int b = color.getBlue(); r = m.csky[0] - r; g = m.csky[1] - g; b = m.csky[2] - b; if (r > 255) { r = 255; } if (r < 0) { r = 0; } if (g > 255) { g = 255; } if (g < 0) { g = 0; } if (b > 255) { b = 255; } if (b < 0) { b = 0; } color = new Color(r, g, b, color.getAlpha()); altinvert.setRGB(x, y, color.getRGB()); } } rd.drawImage(altinvert, 0, 0, null); } if (type == 4) { /////// washout type filter BufferedImage washout = new BufferedImage(buff_img.getWidth(), buff_img.getHeight(), BufferedImage.TYPE_INT_ARGB); int w = buff_img.getWidth(); int h = buff_img.getHeight(); int[] pixels = new int[w * h * 4]; buff_img.getRaster().getPixels(0, 0, w, h, pixels); for (int x = 0; x < buff_img.getWidth(); x++) { for (int y = 0; y < buff_img.getHeight(); y++) { int rgb = buff_img.getRGB(x, y); Color color = new Color(rgb, true); int r = color.getRed(); int g = color.getGreen(); int b = color.getBlue(); int nr = r / 2; int ng = g / 2; r = nr + r; g = ng + g; b = b + (b / 2); if (r > 255) { r = 255; } if (r < 0) { r = 0; } if (g > 255) { g = 255; } if (g < 0) { g = 0; } if (b > 255) { b = 255; } if (b < 0) { b = 0; } color = new Color(r, g, b, color.getAlpha()); washout.setRGB(x, y, color.getRGB()); } } rd.drawImage(washout, 0, 0, null); } } /**Special color effect in credits * @param image the image * @return image the same image but filtered with color * * @author Kaffeinated */ public Image credsnap(Image image) { int i = 350; // image.getHeight(ob); int j = image.getWidth(ob); int ai[] = new int[j * i]; if (credColors[0] < 200) { credColors[0] += 5; } else { do { credColors[0] -= 5; } while (credColors[0] > 25); } if (credColors[1] < 100) { credColors[1] += 5; } else { do { credColors[1] -= 10; } while (credColors[1] > 50); } if (credColors[2] < 30) { credColors[2] += 5; } else { do { credColors[2] -= 5; } while (credColors[2] > 100); } PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, j, i, ai, 0, j); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } for (int k = 0; k < j * i; k++) { Color color = new Color(ai[k]); int l = (int) (color.getRed() * (credColors[0] / 100F)); if (l > 225) { l = 225; } if (l < 0) { l = 0; } int i1 = (int) (color.getGreen() * (credColors[1] / 100F)); if (i1 > 225) { i1 = 225; } if (i1 < 0) { i1 = 0; } int j1 = (int) (color.getBlue() * (credColors[2] / 100F)); if (j1 > 225) { j1 = 225; } if (j1 < 0) { j1 = 0; } Color color2 = new Color(l, i1, j1, 50); /// last is alpha ai[k] = color2.getRGB(); } Image image1 = createImage(new MemoryImageSource(j, i, ai, 0, j)); return image1; } public int colorinvert(int r, int g, int b) { int hex = (0xff << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); int neg = 0xFFFFFF - hex; return neg; } /** * drawcs for images * @param img image to draw * @param y y value * @author Kaffeinated */ public void paintcs(Image img, int y) { rd.drawImage(img, (img.getWidth(null) / 2) - 900, y, null); } /** * draw text over conto * @param text text to draw * @param contos conto to overlay * @author Rafa * @author Kaffeinated */ public void drawOver(String text, ContO contos) { int x = m.cx + (int) ((contos.x - m.x - m.cx)); int y = m.cy + (int) ((contos.y - m.y - m.cy)); int z = m.cz + (int) ((contos.z - m.z - m.cz)); x = Utility.rotSingle(x, z, m.cx, m.cz, m.xz, RadicalMath.sin(m.xz), RadicalMath.cos(m.xz))[0]; y = Utility.rotSingle(y, z, m.cy, m.cz, m.zy, RadicalMath.sin(m.zy), RadicalMath.cos(m.zy))[0]; z = Utility.rotSingle(y, z, m.cy, m.cz, m.zy, RadicalMath.sin(m.zy), RadicalMath.cos(m.zy))[1]; final int xScreenCoor = Utility.xs(x, z); final int yScreenCoor = Utility.cYs(y, z); rd.drawString("" + text, xScreenCoor, yScreenCoor); } public void carspergame(int stage) { if( stage == 9 || stage == 12 || stage == 15 || stage == 18 || stage == 21) { nplayers = 2; setnumber = true; } else { fase = 2; } if(!setnumber) { nplayers = 7; setnumber = true; } else { fase = 2; } } public boolean over(Image image, int i, int j, int k, int l) { int i1 = image.getHeight(ob); int j1 = image.getWidth(ob); return i > k - 5 && i < k + j1 + 5 && j > l - 5 && j < l + i1 + 5; } public void cantgo(Control control) { pnext = 0; trackbg(false); rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(476, "This stage will be unlocked when stage " + unlocked + " is complete!", 255, 255, 255, 3); int i = 0; do { rd.drawImage(pgate, 212 + i * 30, 190, null); } while (++i < 9); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); if (aflk) { drawcs(250, "[ Stage " + (unlocked + 1) + " Locked ]", 182, 0, 0, 3); aflk = false; } else { drawcs(250, "[ Stage " + (unlocked + 1) + " Locked ]", 255, 0, 0, 3); aflk = true; } rd.drawImage(select, 273, 45, null); rd.drawImage(br, 0, 0, null); rd.drawImage(back[pback], 50, 350, null); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(496, "You can also use Keyboard Arrows and Enter to navigate.", 255, 255, 255, 3); lockcnt--; if (lockcnt == 0 || control.enter || control.handb || control.left) { control.left = false; control.handb = false; control.enter = false; fase = 1; } } public void loadingstage(int i) { trackbg(true); rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(200, "Loading Stage " + i + ", please wait...", 182, 0, 0, 3); rd.drawImage(select, 273, 45, null); if (i <= 12) { rd.drawImage(brse, 0, 0, null); } if (i >= 13 && i != 25) { rd.drawImage(br, 0, 0, null); } rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(496, "You can also use Keyboard Arrows and Enter to navigate.", 255, 255, 255, 3); app.repaint(); } public void inst(Control control) { if (flipo == 0) { flipo = 1; bgmy[0] = 0; bgmy[1] = 500; } if (flipo == 2) { flipo = 3; dudo = 200; } if (flipo == 4) { flipo = 5; dudo = 250; } if (flipo == 6) { flipo = 7; dudo = 200; } if (flipo == 8) { flipo = 9; dudo = 250; } if (flipo == 10) { flipo = 11; dudo = 200; } if (flipo == 12) { flipo = 13; dudo = 200; } if (flipo == 14) { flipo = 15; dudo = 100; } int i = 0; rd.drawImage(instback, 0, 0, null); if (aflk) { aflk = false; } else { aflk = true; } if (flipo != 1) { if (dudo > 0) { if (aflk) { if (Math.random() > Math.random()) { duds = (int) (Math.random() * 3D); } else { duds = (int) (Math.random() * 2D); } } dudo--; } else { duds = 0; } rd.drawImage(dude[duds], 145, -10, null); rd.drawImage(oflaot, 242, 17, null); } rd.setColor(new Color(0, 0, 0)); rd.setFont(new Font("SansSerif", 1, 13)); if (flipo == 3 || flipo == 5) { if (flipo == 3) { rd.drawString("Hello! Welcome to G6's world of total madness!!", 312, 42); rd.drawString("In NFM G6 there are two ways that you can win a race.", 312, 82); rd.drawString("One is by racing and finishing in first place, the other is by", 312, 102); rd.drawString("wasting and destroying all of your opponents in the stage!", 312, 122); } else { rd.setColor(new Color(100, 100, 100)); rd.drawString("While racing, you will need to focus on going fast and going through", 312, 42); rd.drawString("all the checkpoints in the stage. To complete a lap, you must not", 312, 62); rd.drawString(" miss a checkpoint. As well, try to keep your power bar full at all ", 312, 82); rd.drawString("times. While wasting, you will just need to worry about hunting other", 312, 102); rd.drawString("cars down and smashing them to peices and setting them ablaze!", 312, 122); rd.setColor(new Color(182, 0, 0)); } rd.drawImage(inst2, 0, 0, null); } if (flipo == 7 || flipo == 9) { if (flipo == 7) { rd.drawString("Whether you are racing or wasting the other cars you will need", 312, 42); rd.drawString("to power up your car.", 312, 62); rd.drawString("=> More 'Power' makes your car become faster and stronger!", 312, 82); rd.drawString("To power up your car (and keep it powered up) you will need to", 312, 102); rd.drawString("perform stunts!", 312, 122); } else { rd.drawString("The better the stunt the more power you get!", 312, 42); rd.setColor(new Color(100, 100, 100)); rd.drawString("Forward looping pushes your car forwards in the air and helps", 312, 62); rd.drawString("when racing. Backward looping pushes your car upwards giving it", 312, 82); rd.drawString("more hang time in the air making it easier to control its landing.", 312, 102); rd.drawString("Left and right rolls shift your car in the air left and right slightly.", 312, 122); rd.setColor(new Color(182, 0, 0)); } rd.drawImage(inst4, 0, 0, null); } if (flipo == 11 || flipo == 13) { if (flipo == 11) { rd.drawString("When wasting cars, to help you find the other cars in the stage,", 312, 42); rd.drawString("press [ A ] to toggle the guidance arrow from pointing to the track", 312, 62); rd.drawString("to pointing to the cars.", 312, 82); rd.drawString("When your car is damaged. You fix it (and reset its 'Damage') by", 312, 102); rd.drawString("jumping through the electrified hoop.", 312, 122); } else { rd.setColor(new Color(100, 100, 100)); rd.drawString("You will find that in some stages it's easier to waste the other cars", 312, 42); rd.drawString("and in some others it's easier to race and finish in first place.", 312, 62); rd.drawString("It is up to you to decide when to waste and when to race.", 312, 82); rd.drawString("And remember, 'Power' is an important factor in the game. You", 312, 102); rd.drawString("will need it whether you are racing or wasting!", 312, 122); rd.setColor(new Color(182, 0, 0)); } rd.drawImage(inst8, 0, 0, null); } if (flipo == 15) { rd.drawImage(inst8, 0, 0, null); rd.drawString("There is a total of 25 stages!", 312, 42); rd.drawString("Every two stages completed a new car will be unlocked!", 312, 62); rd.drawString("I am Coach Insano by the way.", 312, 102); rd.drawString("I am your coach and narrator in this game! Good Luck!", 312, 122); } if (flipo == 1) { rd.drawImage(inst1, 0, 0, null); } if (flipo >= 1 && flipo <= 13) { rd.drawImage(next[pnext], 820, 90, null); } if (flipo >= 3 && flipo <= 15) { rd.drawImage(back[pback], 20, 90, null); } if (flipo == 15) { rd.drawImage(contin[pcontin], 750, 440, null); } if (control.enter || control.right) { if (flipo >= 1 && flipo <= 13) { flipo++; } if (control.enter && flipo == 15) { flipo = 0; fase = oldfase; rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); } control.enter = false; control.right = false; } if (control.left) { if (flipo >= 3 && flipo <= 15) { flipo -= 3; } control.left = false; } } public void fleximage(Image image, int i, int j) { if (i == 0) { PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, 900, 500, flexpix, 0, 900); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } } int k = 0; int l = 0; int i1 = 0; int j1 = 0; int k1 = (int) (Math.random() * 128D); int l1 = (int) (5D + Math.random() * 15D); int i2 = 0; do { Color color = new Color(flexpix[i2]); int j2 = 0; int k2 = 0; int l2 = 0; if (k == 0) { j2 = color.getRed(); l = j2; k2 = color.getGreen(); i1 = k2; l2 = color.getBlue(); j1 = l2; } else { j2 = (int) ((color.getRed() + l * 0.38F * i) / (1.0F + 0.38F * i)); l = j2; k2 = (int) ((color.getGreen() + i1 * 0.38F * i) / (1.0F + 0.38F * i)); i1 = k2; l2 = (int) ((color.getBlue() + j1 * 0.38F * i) / (1.0F + 0.38F * i)); j1 = l2; } if (++k == 900) { k = 0; } int i3 = (j2 * 17 + k2 + l2 + k1) / 22; int j3 = (k2 * 17 + j2 + l2 + k1) / 22; int k3 = (l2 * 17 + j2 + k2 + k1) / 22; if (j == 17) { i3 = (j2 * 17 + k2 + l2 + k1) / 22; j3 = (k2 * 17 + j2 + l2 + k1) / 21; k3 = (l2 * 17 + j2 + k2 + k1) / 20; } if (--l1 == 0) { k1 = (int) (Math.random() * 128D); l1 = (int) (5D + Math.random() * 15D); } Color color1 = new Color(i3, j3, k3); flexpix[i2] = color1.getRGB(); } while (++i2 < 0x6ddd0); fleximg = createImage(new MemoryImageSource(900, 500, flexpix, 0, 900)); rd.drawImage(fleximg, 0, 0, null); } public void arrow(int i, int j, CheckPoints checkpoints, ContO conto[], Control control, boolean flag) { //comeback int ai[] = new int[7]; int ai1[] = new int[7]; int ai2[] = new int[7]; /** * x resolution divided by two converted to hex * http://www.binaryhexconverter.com/decimal-to-hex-converter */ char c = '\u01C2'; byte byte0 = -90; /** * x resolution plus 30 converted to hex? * http://www.binaryhexconverter.com/decimal-to-hex-converter */ char c1 = '\u02BC'; //2BC int k = 0; do { ai1[k] = byte0; } while (++k < 7); // 7 ai[0] = c; ai2[0] = c1 + 110; ai[1] = c - 35; ai2[1] = c1 + 50; ai[2] = c - 15; ai2[2] = c1 + 50; ai[3] = c - 15; ai2[3] = c1 - 50; ai[4] = c + 15; ai2[4] = c1 - 50; ai[5] = c + 15; ai2[5] = c1 + 50; ai[6] = c + 35; ai2[6] = c1 + 50; k = 0; int l = 0; if (!flag) { char c2 = '\0'; if (checkpoints.x[i] - checkpoints.opx[0] >= 0) { c2 = '\264'; } k = (int) (90 + c2 + Math.atan( (double) (checkpoints.z[i] - checkpoints.opz[0]) / (double) (checkpoints.x[i] - checkpoints.opx[0])) / 0.017453292519943295D); } else { int k1 = -1; boolean flag1 = false; int l2 = 1; do { if ((Utility.py(checkpoints.opx[0] / 100, checkpoints.opx[l2] / 100, checkpoints.opz[0] / 100, checkpoints.opz[l2] / 100) < k1 || k1 == -1) && (!flag1 || checkpoints.onscreen[l2] != 0) && checkpoints.dested[l2] == 0) { l = l2; k1 = Utility.py(checkpoints.opx[0] / 100, checkpoints.opx[l2] / 100, checkpoints.opz[0] / 100, checkpoints.opz[l2] / 100); if (checkpoints.onscreen[l2] != 0) { flag1 = true; } } } while (++l2 < nplayers); l2 = 0; if (checkpoints.opx[l] - checkpoints.opx[0] >= 0) { l2 = 180; } k = (int) (90 + l2 + Math.atan((double) (checkpoints.opz[l] - checkpoints.opz[0]) / (double) (checkpoints.opx[l] - checkpoints.opx[0])) / 0.017453292519943295D); rd.drawImage(hunting, 0, 0, null); rd.setFont(new Font("Adventure", 1, 15)); FontHandler.fMetrics = rd.getFontMetrics(); rd.setColor(new Color(255, 255, 255)); drawcs(16, names[sc[l]], 255, 255, 255, 0); //PRESS A rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); /* * example use of drawOver */ //drawOver(names[sc[l]], conto[l]); } for (k += m.xz; k < 0; k += 360) { } for (; k > 180; k -= 360) { } if (!flag) { if (k > 130) { k = 130; } if (k < -130) { k = -130; } } else { if (k > 100) { k = 100; } if (k < -100) { k = -100; } } if (Math.abs(ana - k) < 180) { if (Math.abs(ana - k) < 10) { ana = k; } else if (ana < k) { ana += 10; } else { ana -= 10; } } else { if (k < 0) { ana += 15; if (ana > 180) { ana -= 360; } } if (k > 0) { ana -= 15; if (ana < -180) { ana += 360; } } } Utility.rot(ai, ai2, c, c1, ana, 7); k = Math.abs(ana); if (!flag) { if (k > 7 || j > 0 || j == -2 || cntan != 0) { int i1 = 0; do { ai[i1] = Utility.cXs(ai[i1], ai2[i1]); ai1[i1] = Utility.cYs(ai1[i1], ai2[i1]); } while (++i1 < 7); i1 = (int) (255F + 255F * (m.snap[0] / 100F)); if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } int l1 = (int) (120F + 120F * (m.snap[1] / 100F)); if (l1 > 255) { l1 = 255; } if (l1 < 0) { l1 = 0; } int j2 = 0; if (j <= 0) { if (k <= 45 && j != -2 && cntan == 0) { i1 = (i1 * k + m.csky[0] * (45 - k)) / 45; l1 = (l1 * k + m.csky[1] * (45 - k)) / 45; j2 = (j2 * k + m.csky[2] * (45 - k)) / 45; } if (k >= 90) { int i3 = (int) (255F + 255F * (m.snap[0] / 100F)); if (i3 > 255) { i3 = 255; } if (i3 < 0) { i3 = 0; } i1 = (i1 * (140 - k) + i3 * (k - 90)) / 50; if (i1 > 255) { i1 = 255; } } } else if (flk) { i1 = (int) (255F + 255F * (m.snap[0] / 100F)); if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } flk = false; } else { i1 = (int) (117F + 117F * (m.snap[0] / 100F)); if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } l1 = (int) (0F + 0F * (m.snap[1] / 100F)); if (l1 > 255) { l1 = 255; } if (l1 < 0) { l1 = 0; } flk = true; } rd.setColor(new Color(200, 0, 0)); rd.fillPolygon(ai, ai1, 7); i1 = (int) (255F + 255F * (m.snap[0] / 100F)); if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } l1 = (int) (128F + 128F * (m.snap[1] / 100F)); if (l1 > 255) { l1 = 255; } if (l1 < 0) { l1 = 0; } j2 = 0; if (j <= 0) { if (k <= 45 && j != -2 && cntan == 0) { i1 = (i1 * k + m.csky[0] * (45 - k)) / 45; l1 = (l1 * k + m.csky[1] * (45 - k)) / 45; j2 = (j2 * k + m.csky[2] * (45 - k)) / 45; } } else if (flk) { i1 = (int) (255F + 255F * (m.snap[0] / 100F)); if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } l1 = 0; } rd.setColor(new Color(0, 0, 0)); rd.drawPolygon(ai, ai1, 7); } } else { int j1 = 0; do { ai[j1] = Utility.cXs(ai[j1], ai2[j1]); ai1[j1] = Utility.cYs(ai1[j1], ai2[j1]); } while (++j1 < 7); rd.setColor(new Color(conto[l].p[0].c[0],conto[l].p[0].c[1],conto[l].p[0].c[2])); rd.fillPolygon(ai, ai1, 7); j1 = (int) (120F + 120F * (m.snap[0] / 100F)); if (j1 > 255) { j1 = 255; } if (j1 < 0) { j1 = 0; } int i2 = (int) (114F + 114F * (m.snap[1] / 100F)); if (i2 > 255) { i2 = 255; } if (i2 < 0) { i2 = 0; } int k2 = (int) (255F + 255F * (m.snap[2] / 100F)); if (k2 > 255) { k2 = 255; } if (k2 < 0) { k2 = 0; } rd.setColor(new Color(0, 0, 0)); rd.drawPolygon(ai, ai1, 7); } } public void levelhigh(int i, int j, int k, int l, int i1) { rd.drawImage(gameh, 352, 15, null); byte byte0 = 16; ///////////// change this to 1 to relock the game char c = '0'; char c1 = '`'; if (l < 50) { if (aflk) { byte0 = 106; c = '\260'; c1 = '\377'; aflk = false; } else { aflk = true; } } if (i != 0) { if (k == 0) { drawcs(60, "You Wasted 'em!", byte0, c, c1, 0); } else if (k == 1) { drawcs(60, "Photo Finish!", byte0, c, c1, 0); } else { drawcs(60, "Photo Finish! So close!", byte0, c, c1, 0); } } else if (j == 229) { drawcs(60, "Wasted!", byte0, c, c1, 0); } else if (i1 > 2) { drawcs(60, "Stunts!", byte0, c, c1, 0); } else { drawcs(60, "Best Stunt!", byte0, c, c1, 0); } drawcs(420, "Press [ Enter ] to continue", 0, 0, 0, 0); } public void playsounds(Madness madness, Control control, int i) { if (fase == 0 && starcnt < 35 && cntwis != 8 && !mutes) { boolean flag = control.up && madness.speed > 0.0F || control.down && madness.speed < 10F; boolean flag1 = madness.skid == 1 && control.handb || Math.abs(madness.scz[0] - (madness.scz[1] + madness.scz[0] + madness.scz[2] + madness.scz[3]) / 4F) > 1.0F || Math.abs(madness.scx[0] - (madness.scx[1] + madness.scx[0] + madness.scx[2] + madness.scx[3]) / 4F) > 1.0F; boolean flag2 = false; if (control.up && madness.speed < 10F) { flag1 = true; flag = true; flag2 = true; } if (flag && madness.mtouch) { if (!madness.capsized) { if (!flag1) { if (madness.power != 98F) { if (Math.abs(madness.speed) > 0.0F && Math.abs(madness.speed) <= Madness.swits[madness.cn][0]) { int j = (int) ((3F * Math.abs(madness.speed)) / Madness.swits[madness.cn][0]); if (j == 2) { if (pwait == 0) { j = 0; } else { pwait--; } } else { pwait = 7; } sparkeng(j); } if (Math.abs(madness.speed) > Madness.swits[madness.cn][0] && Math.abs(madness.speed) <= Madness.swits[madness.cn][1]) { int k = (int) ((3F * (Math.abs(madness.speed) - Madness.swits[madness.cn][0])) / (Madness.swits[madness.cn][1] - Madness.swits[madness.cn][0])); if (k == 2) { if (pwait == 0) { k = 0; } else { pwait--; } } else { pwait = 7; } sparkeng(k); } if (Math.abs(madness.speed) > Madness.swits[madness.cn][1] && Math.abs(madness.speed) <= Madness.swits[madness.cn][2]) { int l = (int) ((3F * (Math.abs(madness.speed) - Madness.swits[madness.cn][1])) / (Madness.swits[madness.cn][2] - Madness.swits[madness.cn][1])); sparkeng(l); } } else { byte byte0 = 2; if (pwait == 0) { if (Math.abs(madness.speed) > Madness.swits[madness.cn][1]) { byte0 = 3; } } else { pwait--; } sparkeng(byte0); } } else { sparkeng(-1); if (flag2) { if (stopcnt <= 0) { air[5].loop(); stopcnt = 10; } } else if (stopcnt <= -2) { air[2 + (int) (m.random() * 3F)].loop(); stopcnt = 7; } } } else { sparkeng(3); } grrd = false; aird = false; } else { pwait = 15; if (!madness.mtouch && !grrd && m.random() > 0.00000000000002D) { air[(int) (m.random() * 4F)].loop(); stopcnt = 5; grrd = true; } if (!madness.wtouch && !aird) { stopairs(); air[(int) (m.random() * 4F)].loop(); stopcnt = 10; aird = true; } sparkeng(-1); } if (madness.cntdest != 0 && cntwis < 7) { if (!pwastd) { wastd.loop(); pwastd = true; } } else { if (pwastd) { wastd.stop(); pwastd = false; } if (cntwis == 7 && !mutes) { firewasted.play(); } } } else { sparkeng(-2); if (pwastd) { wastd.stop(); pwastd = false; } } if (stopcnt != -20) { if (stopcnt == 1) { stopairs(); } stopcnt--; } if (bfcrash != 0) { bfcrash--; } if (bfskid != 0) { bfskid--; } if (madness.newcar) { cntwis = 0; } if (fase == 0 || fase == 6 || fase == -1 || fase == -2 || fase == -3 || fase == -4 || fase == -5) { if (mutes != Control.mutes) { mutes = Control.mutes; } if (Control.mutem != mutem) { mutem = Control.mutem; if (mutem) { if (loadedt[i - 1]) { if(isMidi[i - 1]) { mtracks[i - 1].setPaused(true); } else { stracks[i - 1].stop(); } } } else if (loadedt[i - 1]) { System.out.println("We've reached an unmute check..."); if(isMidi[i - 1]) { System.out.println("Unmute check > play midi..."); mtracks[i - 1].resume(); } else { System.out.println("Unmute check > play mod..."); stracks[i - 1].resume(); } } } } if (madness.cntdest != 0 && cntwis < 7) { if (madness.dest) { cntwis++; } } else { if (madness.cntdest == 0) { cntwis = 0; } if (cntwis == 7) { cntwis = 8; } } } public void crash(float f, int i) { if (bfcrash == 0) { if (i == 0) { if (Math.abs(f) > 25F && Math.abs(f) < 170F) { if (!mutes) { lowcrash[crshturn].play(); } bfcrash = 2; } if (Math.abs(f) >= 170F) { if (!mutes) { crash[crshturn].play(); } bfcrash = 2; } if (Math.abs(f) > 25F) { if (crashup) { crshturn--; } else { crshturn++; } if (crshturn == -1) { crshturn = 2; } if (crshturn == 3) { crshturn = 0; } } } if (i == -1) { if (Math.abs(f) > 25F && Math.abs(f) < 170F) { if (!mutes) { lowcrash[2].play(); } bfcrash = 2; } if (Math.abs(f) > 170F) { if (!mutes) { crash[2].play(); } bfcrash = 2; } } if (i == 1) { if (!mutes) { tires.play(); } bfcrash = 3; } } } public void replyn() { if (aflk) { drawcs(30, "Replay > ", 0, 0, 0, 0); aflk = false; } else { drawcs(30, "Replay >>", 0, 128, 255, 0); aflk = true; } } private Image pressed(Image image) { int i = image.getHeight(ob); int j = image.getWidth(ob); int ai[] = new int[j * i]; PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, j, i, ai, 0, j); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } for (int k = 0; k < j * i; k++) { if (ai[k] != ai[j * i - 1]) { ai[k] = 0xff000000; } } Image image1 = createImage(new MemoryImageSource(j, i, ai, 0, j)); return image1; } private Image dodgen(Image image) { int i = image.getHeight(ob); int j = image.getWidth(ob); int ai[] = new int[j * i]; PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, j, i, ai, 0, j); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } for (int k = 0; k < j * i; k++) { Color color = new Color(ai[k]); int l = color.getRed() * 3 + 90; if (l > 255) { l = 255; } if (l < 0) { l = 0; } int i1 = color.getGreen() * 3 + 90; if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } int j1 = color.getBlue() * 3 + 90; if (j1 > 255) { j1 = 255; } if (j1 < 0) { j1 = 0; } Color color1 = new Color(l, i1, j1); ai[k] = color1.getRGB(); } Image image1 = createImage(new MemoryImageSource(j, i, ai, 0, j)); return image1; } private void smokeypix(byte abyte0[], MediaTracker mediatracker, Toolkit toolkit) { Image image = toolkit.createImage(abyte0); mediatracker.addImage(image, 0); try { mediatracker.waitForID(0); } catch (Exception _ex) { } PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, 466, 202, smokey, 0, 466); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } } public void stoploading() { loading(); app.repaint(); runner.stop(); runner = null; runtyp = 0; } public void nofocus() { rd.setColor(new Color(255, 255, 255)); rd.setFont(new Font("Adventure", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(14, ">> Game lost its focus. Click screen with mouse to continue. <<", 100, 100, 100, 3); drawcs(495, ">> Game lost its focus. Click screen with mouse to continue. <<", 100, 100, 100, 3); } public boolean overon(int i, int j, int k, int l, int i1, int j1) { return i1 > i && i1 < i + k && j1 > j && j1 < j + l; } public void pauseimage(Image image) { PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, 900, 500, flexpix, 0, 900); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } int i = 0; int j = 0; int k = 0; int l = 0; int i1 = 0; do { Color color = new Color(flexpix[i1]); int j1 = 0; if (l == 0) { j1 = (color.getRed() + color.getGreen() + color.getBlue()) / 3; k = j1; } else { j1 = (color.getRed() + color.getGreen() + color.getBlue() + k * 30) / 33; k = j1; } if (++l == 900) { l = 0; } if (i1 > 900 * (65 + j) + 331 && j < 188) { //(i1 > 900 * (//8 (Y START VALUE) + j) + //331 (MIDPOINT) && j < 188) int k1 = (j1 + 20) / 3; //RGB int l1 = (j1 + 20) / 3; int i2 = (j1 + 20) / 3; if (++i == 237) { j++; i = 0; } Color color2 = new Color(k1, l1, i2); flexpix[i1] = color2.getRGB(); } else { Color color1 = new Color(j1, j1, j1); flexpix[i1] = color1.getRGB(); } } while (++i1 < 0x6ddd0); fleximg = createImage(new MemoryImageSource(900, 500, flexpix, 0, 900)); rd.drawImage(fleximg, 0, 0, null); m.flex = 0; } public void loadmusic(int i, int j) { hipnoload(i, false); app.setCursor(new Cursor(3)); app.repaint(); boolean flag = false; if (i == unlocked && (i == 1 || i == 2 || i == 3 || i == 4 || i == 7 || i == 8 || i == 9 || i == 10 || i == 12 || i == 13 || i == 16)) { flag = true; } if (flag) { runtyp = i; runner = new Thread(this); runner.start(); } if(!loadedt[i - 1]) { System.out.println("Loading music..."); File f = new File("data/music/stage" + i + ".mid"); File f2 = new File("data/music/stage" + i + ".mp3"); File f3 = new File("data/music/stage" + i + ".ogg"); // this also serves as a check so radicalmidi doesn't throw an error if (f.exists()) { System.out.println("Initializing midi..."); isMidi[i - 1] = true; mtracks[i - 1] = new RadicalMidi("data/music/stage" + i + ".mid"); System.out.println("Loading midi..."); mtracks[i - 1].load(); loadedt[i - 1] = true; } else if (f2.exists()) { System.out.println("Initializing mp3..."); isMidi[i - 1] = true; mtracks[i - 1] = new RadicalMidi("data/music/stage" + i + ".mp3"); System.out.println("Loading mp3..."); mtracks[i - 1].load(); loadedt[i - 1] = true; } else if (f3.exists()) { System.out.println("Initializing/loading ogg..."); isMidi[i - 1] = true; mtracks[i - 1] = new RadicalMidi("data/music/stage" + i + ".ogg"); loadedt[i - 1] = true; } else { System.out.println("Initializing mod..."); isMidi[i - 1] = false; stracks[i - 1] = new RadicalMod("data/music/stage" + i + ".radq", app); if(stracks[i - 1].loaded == 1) { loadedt[i - 1] = true; } } } if (!isMidi[i - 1]) { System.out.println("Loading mod..."); if (i == 1) { stracks[0].loadMod(160, 7200, 125, sunny, macn); } if (i == 2) { stracks[1].loadMod(260, 8000, 125, sunny, macn); } if (i == 3) { stracks[2].loadMod(270, 8000, 125, sunny, macn); } if (i == 4) { stracks[3].loadMod(190, 8000, 125, sunny, macn); } if (i == 5) { stracks[4].loadMod(370, 8000, 125, sunny, macn); } if (i == 6) { stracks[5].loadMod(220, 8000, 125, sunny, macn); } if (i == 7) { stracks[6].loadMod(300, 8000, 125, sunny, macn); } if (i == 8) { stracks[7].loadMod(200, 8000, 125, sunny, macn); } if (i == 9) { stracks[8].loadMod(400, 7800, 125, sunny, macn); } if (i == 10) { stracks[9].loadMod(400, 7700, 125, sunny, macn); } if (i == 11) { stracks[10].loadMod(370, 7900, 125, sunny, macn); } if (i == 12) { stracks[11].loadMod(290, 7900, 125, sunny, macn); } if (i == 13) { stracks[12].loadMod(222, 7600, 125, sunny, macn); } if (i == 14) { stracks[13].loadMod(230, 8000, 125, sunny, macn); } if (i == 15) { stracks[14].loadMod(220, 8000, 125, sunny, macn); } if (i == 16) { stracks[15].loadMod(261, 8000, 125, sunny, macn); } if (i == 17) { stracks[16].loadMod(400, 7600, 125, sunny, macn); } if (i == 18) { stracks[17].loadMod(400, 7600, 125, sunny, macn); } if (i == 19) { stracks[18].loadMod(400, 7600, 125, sunny, macn); } if (i == 20) { stracks[19].loadMod(400, 7600, 125, sunny, macn); } if (i == 21) { stracks[20].loadMod(400, 7600, 125, sunny, macn); } if (i == 22) { stracks[21].loadMod(400, 7600, 125, sunny, macn); } if (i == 23) { stracks[22].loadMod(400, 7600, 125, sunny, macn); } if (i == 24) { stracks[23].loadMod(400, 7600, 125, sunny, macn); } if (i == 25) { stracks[24].loadMod(400, 7600, 125, sunny, macn); } } if (flag) { runner.stop(); runner = null; runtyp = 0; } System.gc(); lastload = i - 1; if (j == 0) { if (loadedt[i - 1]) { if (isMidi[i - 1]) { System.out.println("Playing midi..."); mtracks[i - 1].play(); } else { System.out.println("Playing mod..."); stracks[i - 1].play(); } } app.setCursor(new Cursor(0)); fase = 6; } else { fase = 176; } pcontin = 0; mutem = false; mutes = false; } /**Loads images from images.radq * * @author Omar Wally */ public void loadimages() { Toolkit toolkit = Toolkit.getDefaultToolkit(); MediaTracker mediatracker = new MediaTracker(app); dnload += 12; int howManyImages = 0; try { URL url = new URL(app.getCodeBase(), "data/images.radq"); ZipInputStream zipinputstream = new ZipInputStream(url.openStream()); for (ZipEntry zipentry = zipinputstream.getNextEntry(); zipentry != null; zipentry = zipinputstream .getNextEntry()) { int i = (int) zipentry.getSize(); String s = zipentry.getName(); byte abyte0[] = new byte[i]; int j = 0; int k; for (; i > 0; i -= k) { k = zipinputstream.read(abyte0, j, i); j += k; } if ("kaff.jpg".equals(s)) { kaff = loadimage(abyte0, mediatracker, toolkit); } if ("cars.png".equals(s)) { carsbg = loadimage(abyte0, mediatracker, toolkit); } if ("carstarter.png".equals(s)) { carstarter = loadimage(abyte0, mediatracker, toolkit); } if ("carstreetelites.png".equals(s)) { carstreetelites = loadimage(abyte0, mediatracker, toolkit); } if ("carfuriousfour.png".equals(s)) { carfuriousfour = loadimage(abyte0, mediatracker, toolkit); } if ("statbostart.gif".equals(s)) { statbostart = loadimage(abyte0, mediatracker, toolkit); } if ("statbose.gif".equals(s)) { statbose = loadimage(abyte0, mediatracker, toolkit); } if ("statboff.gif".equals(s)) { statboff = loadimage(abyte0, mediatracker, toolkit); } if ("statbstart.gif".equals(s)) { statbstart = loadimage(abyte0, mediatracker, toolkit); } if ("statbse.gif".equals(s)) { statbse = loadimage(abyte0, mediatracker, toolkit); } if ("statbff.gif".equals(s)) { statbff = loadimage(abyte0, mediatracker, toolkit); } if ("smokey.gif".equals(s)) { smokeypix(abyte0, mediatracker, toolkit); } if ("1.gif".equals(s)) { orank[0] = loadimage(abyte0, mediatracker, toolkit); } if ("gameh.gif".equals(s)) { ogameh = loadimage(abyte0, mediatracker, toolkit); } if ("gameov.gif".equals(s)) { gameov = loadimage(abyte0, mediatracker, toolkit); } if ("landrover.png".equals(s)) { landrover = loadimage(abyte0, mediatracker, toolkit); } if ("lap.gif".equals(s)) { olap = loadimage(abyte0, mediatracker, toolkit); } if ("paused.gif".equals(s)) { paused = loadimage(abyte0, mediatracker, toolkit); } if ("select.gif".equals(s)) { select = loadimage(abyte0, mediatracker, toolkit); } if ("yourwasted.gif".equals(s)) { oyourwasted = loadimage(abyte0, mediatracker, toolkit); } if ("youwastedem.gif".equals(s)) { oyouwastedem = loadimage(abyte0, mediatracker, toolkit); } if ("d1.gif".equals(s)) { dude[0] = loadimage(abyte0, mediatracker, toolkit); } if ("d2.gif".equals(s)) { dude[1] = loadimage(abyte0, mediatracker, toolkit); } if ("d3.gif".equals(s)) { dude[2] = loadimage(abyte0, mediatracker, toolkit); } if ("float.gif".equals(s)) { oflaot = loadimage(abyte0, mediatracker, toolkit); } if ("1c.gif".equals(s)) { ocntdn[1] = loadimage(abyte0, mediatracker, toolkit); } if ("2c.gif".equals(s)) { ocntdn[2] = loadimage(abyte0, mediatracker, toolkit); } if ("3c.gif".equals(s)) { ocntdn[3] = loadimage(abyte0, mediatracker, toolkit); } if ("2.gif".equals(s)) { orank[1] = loadimage(abyte0, mediatracker, toolkit); } if ("3.gif".equals(s)) { orank[2] = loadimage(abyte0, mediatracker, toolkit); } if ("4.gif".equals(s)) { orank[3] = loadimage(abyte0, mediatracker, toolkit); } if ("5.gif".equals(s)) { orank[4] = loadimage(abyte0, mediatracker, toolkit); } if ("6.gif".equals(s)) { orank[5] = loadimage(abyte0, mediatracker, toolkit); } if ("7.gif".equals(s)) { orank[6] = loadimage(abyte0, mediatracker, toolkit); } if ("bgmain.png".equals(s)) { bgmain = loadimage(abyte0, mediatracker, toolkit); } if ("br.png".equals(s)) { br = loadimage(abyte0, mediatracker, toolkit); } if ("brse.png".equals(s)) { brse = loadimage(abyte0, mediatracker, toolkit); } if ("loadingmusic.gif".equals(s)) { oloadingmusic = loadimage(abyte0, mediatracker, toolkit); } if ("radicalplay.gif".equals(s)) { radicalplay = loadimage(abyte0, mediatracker, toolkit); } if ("back.gif".equals(s)) { back[0] = loadimage(abyte0, mediatracker, toolkit); back[1] = bressed(back[0]); } if ("backstarter.gif".equals(s)) { backstart = loadimage(abyte0, mediatracker, toolkit); } if ("backse.gif".equals(s)) { backse = loadimage(abyte0, mediatracker, toolkit); } if ("continue2.gif".equals(s)) { contin[0] = loadimage(abyte0, mediatracker, toolkit); contin[1] = bressed(contin[0]); } if ("next.gif".equals(s)) { next[0] = loadimage(abyte0, mediatracker, toolkit); next[1] = bressed(next[0]); } if ("nextstarter.gif".equals(s)) { nextstart = loadimage(abyte0, mediatracker, toolkit); } if ("nextse.gif".equals(s)) { nextse = loadimage(abyte0, mediatracker, toolkit); } if ("pgate.gif".equals(s)) { pgate = loadimage(abyte0, mediatracker, toolkit); } if ("rpro.gif".equals(s)) { rpro = loadimage(abyte0, mediatracker, toolkit); } if ("track1.jpg".equals(s)) { trackbg[0][0] = loadimage(abyte0, mediatracker, toolkit); trackbg[1][0] = dodgen(trackbg[0][0]); } if ("splash.png".equals(s)) { splash = loadimage(abyte0, mediatracker, toolkit); } if ("track2.jpg".equals(s)) { trackbg[0][1] = loadimage(abyte0, mediatracker, toolkit); trackbg[1][1] = dodgen(trackbg[0][1]); } if ("toyota.png".equals(s)) { toyota = loadimage(abyte0, mediatracker, toolkit); } if ("youlost.gif".equals(s)) { oyoulost = loadimage(abyte0, mediatracker, toolkit); } if ("youwon.gif".equals(s)) { oyouwon = loadimage(abyte0, mediatracker, toolkit); } if ("0c.gif".equals(s)) { ocntdn[0] = loadimage(abyte0, mediatracker, toolkit); } if ("damage.gif".equals(s)) { odmg = loadimage(abyte0, mediatracker, toolkit); } if ("power.gif".equals(s)) { opwr = loadimage(abyte0, mediatracker, toolkit); } if ("position.gif".equals(s)) { opos = loadimage(abyte0, mediatracker, toolkit); } if ("wasted.gif".equals(s)) { owas = loadimage(abyte0, mediatracker, toolkit); } if ("wastedtext.png".equals(s)) { wastedtext = loadimage(abyte0, mediatracker, toolkit); } if ("laptext.png".equals(s)) { laptext = loadimage(abyte0, mediatracker, toolkit); } if ("postext.png".equals(s)) { postext = loadimage(abyte0, mediatracker, toolkit); } if ("timetext.png".equals(s)) { timetext = loadimage(abyte0, mediatracker, toolkit); } if ("kph.png".equals(s)) { kph = loadimage(abyte0, mediatracker, toolkit); } if ("powerbar.png".equals(s)) { powerbar = loadimage(abyte0, mediatracker, toolkit); } if ("damagebar.png".equals(s)) { damagebar = loadimage(abyte0, mediatracker, toolkit); } if ("start1.gif".equals(s)) { ostar[0] = loadimage(abyte0, mediatracker, toolkit); } if ("start2.gif".equals(s)) { ostar[1] = loadimage(abyte0, mediatracker, toolkit); star[2] = pressed(ostar[1]); } if ("congrad.gif".equals(s)) { congrd = loadimage(abyte0, mediatracker, toolkit); } if ("madness.gif".equals(s)) { mdness = loadimage(abyte0, mediatracker, toolkit); } if ("fixhoop.gif".equals(s)) { fixhoop = loadimage(abyte0, mediatracker, toolkit); } if ("arrow.gif".equals(s)) { sarrow = loadimage(abyte0, mediatracker, toolkit); } if ("stunts.gif".equals(s)) { stunts = loadimage(abyte0, mediatracker, toolkit); } if ("racing.gif".equals(s)) { racing = loadimage(abyte0, mediatracker, toolkit); } if ("wasting.gif".equals(s)) { wasting = loadimage(abyte0, mediatracker, toolkit); } if ("plus.gif".equals(s)) { plus = loadimage(abyte0, mediatracker, toolkit); } if ("space.gif".equals(s)) { space = loadimage(abyte0, mediatracker, toolkit); } if ("arrows.gif".equals(s)) { arrows = loadimage(abyte0, mediatracker, toolkit); } if ("chil.gif".equals(s)) { chil = loadimage(abyte0, mediatracker, toolkit); } if ("ory.gif".equals(s)) { ory = loadimage(abyte0, mediatracker, toolkit); } if ("overlay.png".equals(s)) { overlay = loadimage(abyte0, mediatracker, toolkit); } if ("overlaystatus.png".equals(s)) { overlaystatus = loadimage(abyte0, mediatracker, toolkit); } if ("hunting.png".equals(s)) { hunting = loadimage(abyte0, mediatracker, toolkit); } if ("inst1.png".equals(s)) { inst1 = loadimage(abyte0, mediatracker, toolkit); } if ("inst2.png".equals(s)) { inst2 = loadimage(abyte0, mediatracker, toolkit); } if ("inst4.png".equals(s)) { inst4 = loadimage(abyte0, mediatracker, toolkit); } if ("inst6.png".equals(s)) { inst6 = loadimage(abyte0, mediatracker, toolkit); } if ("inst8.png".equals(s)) { inst8 = loadimage(abyte0, mediatracker, toolkit); } if ("instback.png".equals(s)) { instback = loadimage(abyte0, mediatracker, toolkit); } if ("kz.gif".equals(s)) { kz = loadimage(abyte0, mediatracker, toolkit); } if ("kx.gif".equals(s)) { kx = loadimage(abyte0, mediatracker, toolkit); } if ("kv.gif".equals(s)) { kv = loadimage(abyte0, mediatracker, toolkit); } if ("kp.gif".equals(s)) { kp = loadimage(abyte0, mediatracker, toolkit); } if ("km.gif".equals(s)) { km = loadimage(abyte0, mediatracker, toolkit); } if ("kn.gif".equals(s)) { kn = loadimage(abyte0, mediatracker, toolkit); } if ("kenter.gif".equals(s)) { kenter = loadimage(abyte0, mediatracker, toolkit); } if ("nfm.gif".equals(s)) { nfm = loadimage(abyte0, mediatracker, toolkit); } if ("options.gif".equals(s)) { opti = loadimage(abyte0, mediatracker, toolkit); } if ("opback.gif".equals(s)) { opback = loadimage(abyte0, mediatracker, toolkit); } if ("logocars.gif".equals(s)) { logocars = loadimage(abyte0, mediatracker, toolkit); } if ("logomadmess.gif".equals(s)) { logomadnes = loadimage(abyte0, mediatracker, toolkit); } if ("logomadbg.gif".equals(s)) { logomadbg = loadimage(abyte0, mediatracker, toolkit); } if ("lotus.png".equals(s)) { lotus = loadimage(abyte0, mediatracker, toolkit); } if ("byrd.gif".equals(s)) { byrd = loadimage(abyte0, mediatracker, toolkit); } if ("nfmcoms.gif".equals(s)) { nfmcoms = loadimage(abyte0, mediatracker, toolkit); } if ("nfmcom.gif".equals(s)) { nfmcom = loadimage(abyte0, mediatracker, toolkit); } howManyImages++; dnload += 3; } zipinputstream.close(); System.out.println("Images loaded: " + howManyImages); } catch (IOException e) { System.out.println("Error Reading Images: " + e); e.printStackTrace(); } System.gc(); } /**Loads images from the web * * @author Kaffeinated */ public void loadnetworkimages() { Utility.startTimer(); dnload += 12; try { aimLogo = Utility.webGet("http://i59.servimg.com/u/f59/14/03/33/42/logo10.png"); ///aim games logo /// URL goes here // dnload += 3; } catch (Exception exception) { System.out.println("Error Loading Network Images: " + exception); } System.gc(); Utility.stopTimer(); } public void pausedgame(int i, Control control, Record record) { rd.drawImage(fleximg, 0, 0, null); if (control.up) { opselect--; if (opselect == -1) { opselect = 3; } control.up = false; } if (control.down) { opselect++; if (opselect == 4) { opselect = 0; } control.down = false; } if (opselect == 0) { rd.setColor(new Color(255, 167, 51)); rd.fillRoundRect(349, 100, 195, 28, 7, 24); //x,y,xlen,ylen,linesize,cornersize if (shaded) { rd.setColor(new Color(225, 200, 255)); } else { rd.setColor(new Color(182, 0, 0)); } rd.drawRoundRect(349, 100, 195, 28, 7, 24); } if (opselect == 1) { rd.setColor(new Color(255, 167, 51)); rd.fillRoundRect(387, 132, 118, 28, 7, 24); if (shaded) { rd.setColor(new Color(225, 200, 255)); } else { rd.setColor(new Color(182, 0, 0)); } rd.drawRoundRect(387, 132, 118, 28, 7, 24); } if (opselect == 2) { rd.setColor(new Color(255, 167, 51)); rd.fillRoundRect(349, 168, 195, 28, 7, 24); if (shaded) { rd.setColor(new Color(225, 200, 255)); } else { rd.setColor(new Color(182, 0, 0)); } rd.drawRoundRect(349, 168, 195, 28, 7, 24); } if (opselect == 3) { rd.setColor(new Color(255, 167, 51)); rd.fillRoundRect(395, 201, 107, 28, 7, 24); if (shaded) { rd.setColor(new Color(225, 200, 255)); } else { rd.setColor(new Color(182, 0, 0)); } rd.drawRoundRect(395, 201, 107, 28, 7, 24); } rd.drawImage(paused, 331, 65, null); if (control.enter || control.handb) { if (opselect == 0) { if (loadedt[i - 1] && !mutem) { if(isMidi[i - 1]) { System.out.println("Unmute check > play midi..."); mtracks[i - 1].resume(); } else { System.out.println("Unmute check > play mod..."); stracks[i - 1].resume(); } } fase = 0; } if (opselect == 1) { if (record.caught >= 300) { if (loadedt[i - 1] && !mutem) { if(isMidi[i - 1]) { System.out.println("Unmute check > play midi..."); mtracks[i - 1].resume(); } else { System.out.println("Unmute check > play mod..."); stracks[i - 1].resume(); } } fase = -1; } else { fase = -8; } } if (opselect == 2) { if (loadedt[i - 1]) { if(isMidi[i - 1]) { mtracks[i - 1].setPaused(true); } else { stracks[i - 1].stop(); } } oldfase = -7; fase = 11; } if (opselect == 3) { if (loadedt[i - 1]) { if(isMidi[i - 1]) { mtracks[i - 1].setPaused(true); } else { stracks[i - 1].stop(); } } fase = 10; opselect = 0; } control.enter = false; control.handb = false; } } public void credits(Control control) { if (flipo == 0) { firewasted.play(); flipo = 1; bgmy[0] = 0; bgmy[1] = 500; } if (flipo >= 1 && flipo <= 100) { rad(flipo, 0); flipo++; if (flipo == 100) { flipo = 1; } } if (flipo == 101) { int i = 0; do { rd.drawImage(bgmain, 0, bgmy[i], null); bgmy[i] -= 10; if (bgmy[i] <= -500) { bgmy[i] = 500; } } while (++i < 2); rd.drawImage(mdness, 218, 7, null); rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(65, "At Radicalplay.com", 0, 0, 0, 3); drawcs(100, "Cartoon 3D Engine, Game Programming, 3D Models, Graphics and Sound Effects", 0, 0, 0, 3); drawcs(120, "Everything By Omar Waly", 70, 70, 70, 3); rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(180, "Thanks for Game Testing", 0, 0, 0, 3); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(200, "Soufy H Abutaleb, Sherif Abouzeid,", 90, 90, 90, 3); drawcs(215, "Kareem Mansour, Youssef Wahby,", 90, 90, 90, 3); drawcs(230, "Taymour Farid, Mahmoud Waly", 90, 90, 90, 3); drawcs(245, "and Mahmoud Ezzeldin (Turbo)", 90, 90, 90, 3); rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(340, "Music was obtained from the ModArchive.org", 0, 0, 0, 3); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(360, "All tracks where remixed to fit game by Omar Waly", 90, 90, 90, 3); drawcs(380, "For more details about the music: http://www.radicalplay.com/madcars/music.html", 90, 90, 90, 3); } if (flipo == 102) { int i = 0; do { rd.drawImage(bgmain, 0, bgmy[i], null); bgmy[i] -= 10; if (bgmy[i] <= -500) { bgmy[i] = 500; } } while (++i < 2); rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); ////////////////////////////////////////////////////////////////////// drawcs(100, "These files have been edited and enhanced by Kaffeinated", 0, 0, 0, 3); drawcs(180, "Thanks for help and suggestions goes to", 0, 0, 0, 3); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(200, "Chaotic for help with NFMM graphics", 90, 90, 90, 3); drawcs(215, "DragShot for his opponent status and desktop hack", 90, 90, 90, 3); drawcs(230, "Ten Graves, Phyrexian, and Hyde233 for bug fixes", 90, 90, 90, 3); ////////////////////////////////////////////////////////////////////// rd.setColor(new Color(0, 0, 0)); rd.fillRect(0, 347, 900, 500); rd.drawImage(kaff, 0, 347, null); } if (flipo == 103) { int j = 0; do { rd.drawImage(bgmain, 0, bgmy[j], null); bgmy[j] -= 16; if (bgmy[j] <= -500) { bgmy[j] = 500; } } while (++j < 2); rd.drawImage(nfmcom, 125, 170, null); } if (flipo == 102) { rd.drawImage(next[pnext], 600, 10, null); } else { rd.drawImage(next[pnext], 600, 370, null); } if (control.enter || control.handb || control.right) { if (flipo >= 1 && flipo <= 100) { flipo = 101; app.setCursor(new Cursor(0)); } else { flipo++; } if (flipo == 104) { flipo = 0; fase = 10; } control.enter = false; control.handb = false; control.right = false; } } public void stat(Madness madness[], CheckPoints checkpoints, Control control, ContO conto[], boolean flag) { if (holdit) { holdcnt++; if (m.flex != 0) { m.flex = 0; } if (control.enter || holdcnt > 250) { fase = -2; control.enter = false; } } else { if (holdcnt != 0) { holdcnt = 0; } if (control.enter) { if (loadedt[checkpoints.stage - 1]) { if(isMidi[checkpoints.stage - 1]) { mtracks[checkpoints.stage - 1].setPaused(true); } else { stracks[checkpoints.stage - 1].stop(); } } fase = -6; control.enter = false; } } if (fase != -2) { holdit = false; if (checkpoints.wasted == nplayers - 1) { if (m.flex != 2) { rd.setColor(new Color(m.csky[0], m.csky[1], m.csky[2])); rd.fillRect(341, 70, youwastedem.getWidth(ob), youwastedem.getHeight(ob)); rd.setColor(new Color(m.cfade[0], m.cfade[1], m.cfade[2])); rd.drawRect(341, 70, youwastedem.getWidth(ob), youwastedem.getHeight(ob)); } rd.drawImage(youwastedem, 341, 70, null); if (aflk) { drawcs(120, "You Won, all cars have been wasted!", 180, 0, 0, 0); drawcs(140, "You have mastered this stage!", 180, 0, 0, 0); drawcs(420, "Press [ Enter ] to continue", 180, 0, 0, 0); aflk = false; } else { drawcs(120, "You Won, all cars have been wasted!", 230, 0, 0, 0); drawcs(140, "You have mastered this stage!", 230, 0, 0, 0); drawcs(420, "Press [ Enter ] to continue", 230, 0, 0, 0); aflk = true; } checkpoints.haltall = true; holdit = true; winner = true; } if (!holdit && madness[0].dest && cntwis == 8) { if (m.flex != 2) { rd.setColor(new Color(m.csky[0], m.csky[1], m.csky[2])); rd.fillRect(347, 70, yourwasted.getWidth(ob), yourwasted.getHeight(ob)); rd.setColor(new Color(m.cfade[0], m.cfade[1], m.cfade[2])); rd.drawRect(347, 70, yourwasted.getWidth(ob), yourwasted.getHeight(ob)); } rd.drawImage(yourwasted, 347, 70, null); drawcs(420, "Press [ Enter ] to continue", 0, 0, 0, 0); holdit = true; winner = false; } if (!holdit) { int i = 0; do { if (checkpoints.clear[i] == checkpoints.nlaps * checkpoints.nsp && checkpoints.pos[i] == 0) { if (i == 0) { if (m.flex != 2) { rd.setColor(new Color(m.csky[0], m.csky[1], m.csky[2])); rd.fillRect(383, 70, youwon.getWidth(ob), youwon.getHeight(ob)); rd.setColor(new Color(m.cfade[0], m.cfade[1], m.cfade[2])); rd.drawRect(383, 70, youwon.getWidth(ob), youwon.getHeight(ob)); } rd.drawImage(youwon, 383, 70, null); if (aflk) { drawcs(120, "You finished first, nice job!", 180, 0, 0, 0); drawcs(140, "You have mastered this stage!", 180, 0, 0, 0); drawcs(420, "Press [ Enter ] to continue", 180, 0, 0, 0); aflk = false; } else { drawcs(120, "You finished first, nice job!", 230, 0, 0, 0); drawcs(140, "You have mastered this stage!", 230, 0, 0, 0); drawcs(420, "Press [ Enter ] to continue", 230, 0, 0, 0); aflk = true; } winner = true; } else { if (m.flex != 2) { rd.setColor(new Color(m.csky[0], m.csky[1], m.csky[2])); rd.fillRect(386, 70, youlost.getWidth(ob), youlost.getHeight(ob)); rd.setColor(new Color(m.cfade[0], m.cfade[1], m.cfade[2])); rd.drawRect(386, 70, youlost.getWidth(ob), youlost.getHeight(ob)); } rd.drawImage(youlost, 386, 70, null); if (aflk) { drawcs(120, "" + names[sc[i]] + " finished first, race over!", 180, 0, 0, 0); drawcs(140, "Better luck next time, maybe take a break and try again?", 180, 0, 0, 0); aflk = false; } else { drawcs(120, "" + names[sc[i]] + " finished first, race over!", 230, 0, 0, 0); drawcs(140, "Better luck next time, maybe take a break and try again?", 230, 0, 0, 0); aflk = true; } winner = false; } drawcs(420, "Press [ Enter ] to continue", 0, 0, 0, 0); checkpoints.haltall = true; holdit = true; } } while (++i < nplayers); } if (flag) { if (checkpoints.stage != 110 && arrace != control.arrace) { arrace = control.arrace; if (arrace) { wasay = true; say = ">> Arrow now pointing at Cars <<"; tcnt = -5; } if (!arrace) { wasay = false; say = ">> Arrow now pointing at Track <<"; tcnt = -5; cntan = 20; } } if(!control.toggle){ rd.drawImage(overlay, 0, 0, null); } if(starcnt > 0) { rd.setColor(new Color(255, 255, 255)); rd.setFont(new Font("Adventure", 1, 35)); FontHandler.fMetrics = rd.getFontMetrics(); rd.drawString("Loading Opponent Status...",220, 482); } if (!holdit && fase != -6 && starcnt == 0) { int num_cars = nplayers; for (int array_one = 0; array_one < num_cars; array_one++) { boolean flag_status = false; for (int array_two = 0; array_two < num_cars; array_two++) { if (checkpoints.pos[array_two] == array_one && checkpoints.dested[array_two] == 0 && !flag_status) { int y_value = 32; // use to move status up or down int x_value = 105; // use to move status left or right rd.setFont(new Font("Adventure", 1, 15)); FontHandler.fMetrics = rd.getFontMetrics(); rd.setColor(new Color(255, 255, 255)); if (array_one == 0) rd.drawString("1st",21 + x_value * array_one, 490); if (array_one == 1) rd.drawString("2nd",21 + x_value * array_one, 490); if (array_one == 2) rd.drawString("3rd",21 + x_value * array_one, 490); if (array_one >= 3) rd.drawString((array_one + 1)+"th", 21 + x_value * array_one, 490); rd.setColor(new Color(255, 255, 255)); rd.drawString(names[sc[array_two]], 29 + x_value * array_one, 472); if (madness[0].im == array_two){ int red = (int) (159.0F + (159.0F * ((float) m.snap[0] / 100.0F))); if (red > 255) red = 255; if (red < 0) red = 0; int green = (int) (207.0F + (207.0F * ((float) m.snap[1] / 100.0F))); if (green > 255) green = 255; if (green < 0) green = 0; int blue = (int) (255.0F + (255.0F * ((float) m.snap[2] / 100.0F))); if (blue > 255) blue = 255; if (blue < 0) blue = 0; rd.setColor(new Color(182, 0, 0)); rd.drawRect(19 + x_value * array_one, 456, 105, 35); //rd.drawRect(531 1 less + x_value, 58 1 less + y_value + 30 * array_one, 114, 25); } if(arrace) { int dmg = (int)(60F * ((float)madness[array_two].hitmag / (float)madness[array_two].maxmag[sc[array_two]])); int red = 244; int green = 244; int blue = 11; if(dmg > 20) green = (int)(244F - 233F * ((float)(dmg - 20) / 40F)); red = (int)((float)red + (float)red * ((float)m.snap[0] / 100F)); if(dmg > 60) dmg = 60; if(red > 255) red = 255; if(red < 0) red = 0; green = (int)((float)green + (float)green * ((float)m.snap[1] / 100F)); if(green > 255) green = 255; if(green < 0) green = 0; blue = (int)((float)blue + (float)blue * ((float)m.snap[2] / 100F)); if(blue > 255) blue = 255; if(blue < 0) blue = 0; rd.setColor(new Color(red, green, blue)); rd.fillRect(49 + x_value * array_one, 480, dmg, 5); rd.setColor(new Color(0, 0, 0)); rd.drawRect(49 + x_value * array_one, 480, 60, 5); } else { //comeback float power = madness[array_two].power; int red = 128; if (power == 98F) { red = 64; } int green = (int) (190D + power * 0.37D); int blue = 244; if (auscnt < 45 && aflk) { red = 128; green = 244; blue = 244; } red = (int) (red + red * (m.snap[0] / 100F)); if (red > 255) { red = 255; } if (red < 0) { red = 0; } green = (int) (green + green * (m.snap[1] / 100F)); if (green > 255) { green = 255; } if (green < 0) { green = 0; } blue = (int) (blue + blue * (m.snap[2] / 100F)); if (blue > 255) { blue = 255; } if (blue < 0) { blue = 0; } rd.setColor(new Color(red, green, blue)); //rd.fillRect(565 + x_value, 75 + y_value + 30 * array_one, (int)((power / 98F) * 60F), 5); rd.fillRect(49 + x_value * array_one, 480,(int)((power / 98F) * 60F), 5); rd.setColor(new Color(0, 0, 0)); rd.drawRect(49 + x_value * array_one, 480, 60, 5); } flag_status = true; } } } rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); rd.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); arrow(madness[0].point, madness[0].missedcp, checkpoints, conto, control, arrace); rd.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); if (!arrace && auscnt == 45 && madness[0].capcnt == 0) { if (madness[0].missedcp > 0) { if (madness[0].missedcp > 15 && madness[0].missedcp < 50) { if (flk) { drawcs(70, "Checkpoint Missed!", 255, 0, 0, 0); } else { drawcs(70, "Checkpoint Missed!", 210, 0, 0, 2); } } madness[0].missedcp++; if (madness[0].missedcp == 70) { madness[0].missedcp = -2; } } else if (madness[0].mtouch && cntovn < 70) { if (Math.abs(ana) > 100) { cntan++; } else if (cntan != 0) { cntan--; } if (cntan > 40) { cntovn++; cntan = 40; if (flk) { drawcs(90, "Wrong Way!", 255, 0, 0, 0); flk = false; } else { drawcs(90, "Wrong Way!", 210, 0, 0, 2); flk = true; } } } } } if (m.flex != 2 || m.flex == 2) { //ONSCREEN rd.setColor(new Color(m.csky[0], m.csky[1], m.csky[2])); //ORANGE COLOR rd.setColor(new Color(182, 0, 0)); rd.setFont(new Font("Adventure", 1, 15)); //GUI TEXT rd.drawImage(laptext, 14, 21, null); rd.drawImage(wastedtext, 108, 21, null); //TURN WHITE rd.setColor(new Color(255, 255, 255)); //GUI TEXT rd.drawImage(damagebar, 677, 21, null); rd.drawImage(powerbar, 677, 47, null); //LAPS rd.drawString(" " + (madness[0].nlaps + 1) + " / " + checkpoints.nlaps + "", 56, 40); rd.drawString(" " + checkpoints.wasted + " / " + (nplayers - 1), 181, 40); //CHANGE SIZE rd.setColor(new Color(182, 0, 0)); rd.setFont(new Font("Adventure", 1, 18)); //POSITION rd.drawImage(postext, 36, 50, null); //CHANGE WHITE rd.setColor(new Color(255, 255, 255)); String suffix = ""; int position = checkpoints.pos[0] + 1; if((position - 1) % 10 == 0 && position != 11) { suffix = "st"; } if((position - 2) % 10 == 0 && position != 12) { suffix = "nd"; } if((position - 3) % 10 == 0 && position != 13) { suffix = "rd"; } if(position % 10 == 0 || position % 10 >= 4 || position == 11 || position == 12 || position == 13) { suffix = "th"; } //CHANGE SIZE rd.setFont(new Font("Adventure", 1, 30)); FontHandler.fMetrics = rd.getFontMetrics(); rd.drawString("" + position + suffix + "", 150, 76); //CHANGE BACK} rd.setFont(new Font("Adventure", 1, 22)); FontHandler.fMetrics = rd.getFontMetrics(); rd.setColor(new Color(182, 0, 0)); rd.drawImage(timetext, 27, 414, null); rd.drawImage(kph, 790, 468, null); rd.drawString("", 660,438); //the timer if(!checkpoints.haltall && starcnt == 0) { time++; } int speed =(int) madness[0].speed ; int millis = time * 1000 / 21; String timer = this.getTime(millis); rd.setColor(new Color(255, 255, 255)); rd.drawString(timer, 94, 434); rd.drawString("" + speed, 847, 489); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); } m.flex++; } else { if (posit != checkpoints.pos[madness[0].im]) { rd.drawImage(rank[checkpoints.pos[madness[0].im]], 110, 28, null); posit = checkpoints.pos[madness[0].im]; } if (wasted != checkpoints.wasted) { rd.setColor(new Color(m.csky[0], m.csky[1], m.csky[2])); rd.fillRect(150, 8, 30, 10); rd.setColor(new Color(255, 74, 86)); rd.drawString("" + checkpoints.wasted + " / 6", 150, 18); wasted = checkpoints.wasted; } if (laps != madness[0].nlaps) { rd.setColor(new Color(m.csky[0], m.csky[1], m.csky[2])); rd.fillRect(51, 8, 40, 10); rd.setColor(new Color(134, 33, 207)); rd.drawString("" + (madness[0].nlaps + 1) + " / " + checkpoints.nlaps + "", 51, 18); laps = madness[0].nlaps; } } drawstat(Madness.maxmag[madness[0].cn], madness[0].hitmag, madness[0].newcar, madness[0].power); } if (!holdit) { if (starcnt != 0 && starcnt <= 35) { if (starcnt == 35 && !mutes) { three.play(); } if (starcnt == 24) { gocnt = 2; if (!mutes) { two.play(); } } if (starcnt == 13) { gocnt = 1; if (!mutes) { one.play(); } } if (starcnt == 2) { gocnt = 0; if (!mutes) { go.play(); } } duds = 0; if (starcnt <= 37 && starcnt > 32) { duds = 1; } if (starcnt <= 26 && starcnt > 21) { duds = 1; } if (starcnt <= 15 && starcnt > 10) { duds = 1; } if (starcnt <= 4) { duds = 2; m.flex = 0; } if (dudo != -1) { rd.drawImage(dudeb[duds], dudo, 0, null); } if (gocnt != 0) { rd.drawImage(cntdn[gocnt], 320, 50, null); } else { rd.drawImage(cntdn[gocnt], 298, 50, null); } } if (looped != 0 && madness[0].loop == 2) { looped = 0; } if (madness[0].power < 45F) { if (tcnt == 30 && auscnt == 45 && madness[0].mtouch && madness[0].capcnt == 0) { if (looped != 2) { if (pwcnt < 70 || pwcnt < 160 && looped != 0) { if (pwflk) { drawcs(110, "Power low, perform stunt!", 255, 227, 156, 0); pwflk = false; } else { drawcs(110, "Power low, perform stunt!", 255, 192, 33 ,0); pwflk = true; } } } else if (pwcnt < 250) { if (pwflk) { drawcs(105, "> > Press Enter for GAME INSTRUCTIONS! < <", 255, 192, 33, 0); drawcs(120, "To learn how to preform STUNTS!", 255, 192, 33 ,0); pwflk = false; } else { drawcs(105, "> > Press Enter for GAME INSTRUCTIONS! < <", 255, 227, 156, 0); drawcs(120, "To learn how to preform STUNTS!", 255, 227, 156, 0); pwflk = true; } } pwcnt++; if (pwcnt == 300) { pwcnt = 0; if (looped != 0) { looped++; if (looped == 3) { looped = 1; } } } } } else if (pwcnt != 0) { pwcnt = 0; } if (madness[0].capcnt == 0) { if (tcnt < 30) { if (tflk) { if (!wasay) { drawcs(125, say, 230, 0, 0, 0); } else { drawcs(125, say, 230, 0, 0, 0); } tflk = false; } else { if (!wasay) { drawcs(125, say, 255, 180, 0, 0); } else { drawcs(125, say, 255, 180, 0, 0); } tflk = true; } tcnt++; } else if (wasay) { wasay = false; } if (auscnt < 45) { if (aflk) { drawcs(105, asay, 230, 0, 0, 0); aflk = false; } else { drawcs(105, asay, 255, 180, 0, 0); aflk = true; } auscnt++; } if(arrace) { rd.setFont(new Font("Adventure", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(433,">> Car Status now showing Enemy Damage <<", 230, 0, 0, 0); } else { rd.setFont(new Font("Adventure", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(433,">> Car Status now showing Power <<", 230, 0, 0, 0); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); } } else if (tflk) { drawcs(125, "Bad Landing!", 255, 180, 0, 0); tflk = false; } else { drawcs(125, "Bad Landing!", 255, 180, 0, 0); tflk = true; } if (madness[0].trcnt == 10) { loop = ""; spin = ""; asay = ""; int j; for (j = 0; madness[0].travzy > 225; j++) { madness[0].travzy -= 360; } while (madness[0].travzy < -225) { madness[0].travzy += 360; j--; } if (j == 1) { loop = "Frontflip"; } if (j == 2) { loop = "Double Frontflip"; } if (j == 3) { loop = "Triple Frontflip"; } if (j >= 4) { loop = "Ultra Flip"; } if (j == -1) { loop = "Backflip"; } if (j == -2) { loop = "Double Backflip"; } if (j == -3) { loop = "Triple Backflip"; } if (j <= -4) { loop = "Mega Flip"; } if (j == 0) { if (madness[0].ftab && madness[0].btab) { loop = "Tabletop and reversed Tabletop"; } else if (madness[0].ftab || madness[0].btab) { loop = "Tabletop"; } } if (j > 0 && madness[0].btab) { loop = "Radical " + loop; } if (j < 0 && madness[0].ftab) { loop = "Radical " + loop; } if (!("").equals(loop)) { asay += " " + loop; } j = 0; for (madness[0].travxy = Math.abs(madness[0].travxy); madness[0].travxy > 270;) { madness[0].travxy -= 360; j++; } if (j == 0 && madness[0].rtab) { if (("").equals(loop)) { spin = "Tabletop"; } else { spin = "Flipside"; } } if (j == 1) { spin = "Rollspin"; } if (j == 2) { spin = "Double Rollspin"; } if (j == 3) { spin = "Triple Rollspin"; } if (j >= 4) { spin = "Super Rollspin"; } j = 0; boolean flag1 = false; for (madness[0].travxz = Math.abs(madness[0].travxz); madness[0].travxz > 90;) { madness[0].travxz -= 180; if ((j += 180) > 900) { j = 900; flag1 = true; } } if (j != 0) { if (("").equals(loop) && ("").equals(spin)) { asay += " " + j; if (flag1) { asay += " and beyond"; } } else { if (!("").equals(loop)) { if (("").equals(loop)) { asay += " " + spin; } else { asay += " with " + spin; } } asay += " by " + j; if (flag1) { asay += " and beyond"; } } } else if (!("").equals(spin)) { if (("").equals(loop)) { asay += " " + spin; } else { asay += " by " + spin; } } if (!("").equals(asay)) { auscnt -= 15; } if (!("").equals(loop)) { auscnt -= 25; } if (!("").equals(spin)) { auscnt -= 25; } if (j != 0) { auscnt -= 25; } if (auscnt < 45) { if (!mutes) { powerup.play(); } if (auscnt < -20) { auscnt = -20; } byte byte0 = 0; if (madness[0].powerup > 20F) { byte0 = 1; } if (madness[0].powerup > 40F) { byte0 = 2; } if (madness[0].powerup > 150F) { byte0 = 3; } if (madness[0].surfer) { asay = " " + adj[4][(int) (m.random() * 3F)] + asay; } if (byte0 != 3) { asay = adj[byte0][(int) (m.random() * 3F)] + asay + exlm[byte0]; } else { asay = adj[byte0][(int) (m.random() * 3F)]; } if (!wasay) { tcnt = auscnt; if (madness[0].power != 98F) { say = "Power Refilled " + (int) ((100F * madness[0].powerup) / 98F) + "%"; } else { say = "Power FULL"; } if (skidup) { skidup = false; } else { skidup = true; } } } } if (madness[0].newcar) { if (!wasay) { say = "Car Repaired"; tcnt = 0; } if (crashup) { crashup = false; } else { crashup = true; } } if (clear != madness[0].clear && madness[0].clear != 0) { if (!wasay) { say = "Checkpoint!"; tcnt = 15; } clear = madness[0].clear; if (!mutes) { checkpoint.play(); } cntovn = 0; if (cntan != 0) { cntan = 0; } } int k = 1; do { if (dested[k] != checkpoints.dested[k]) { dested[k] = checkpoints.dested[k]; if (dested[k] == 1) { wasay = true; say = "" + names[sc[k]] + " has been wasted!"; tcnt = -15; } if (dested[k] == 2) { wasay = true; say = "You wasted " + names[sc[k]] + "!"; tcnt = -15; } } } while (++k < nplayers); } } public void finish(CheckPoints checkpoints, ContO aconto[], Control control) { rd.drawImage(fleximg, 0, 0, null); if (winner) { if (checkpoints.stage == unlocked) { if (checkpoints.stage != 25) { rd.drawImage(congrd, 315, 30, null); drawcs(80, "Stage " + checkpoints.stage + " Completed!", 170, 170, 170, 3); } else { rd.drawImage(congrd, 315 + (int) (m.random() * 10F), 30, null); } byte byte0 = 0; int i = 0; pin = 60; if (checkpoints.stage == 3) { byte0 = 6; i = 265; pin = 0; sc[0] = 6; } if (checkpoints.stage == 6) { byte0 = 7; i = 240; pin = 0; sc[0] = 7; } if (checkpoints.stage == 9) { byte0 = 8; i = 290; pin = 0; sc[0] = 8; } if (checkpoints.stage == 12) { byte0 = 9; i = 226; pin = 0; sc[0] = 9; } if (checkpoints.stage == 15) { byte0 = 10; i = 200; pin = 0; sc[0] = 10; } if (checkpoints.stage == 18) { byte0 = 11; i = 200; pin = 0; sc[0] = 11; } if (checkpoints.stage == 21) { byte0 = 12; i = 270; pin = 0; sc[0] = 12; } if (checkpoints.stage == 24) { byte0 = 13; i = 290; pin = 0; sc[0] = 13; } if (checkpoints.stage != 25) { rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); if (aflk) { drawcs(120 + pin, "Stage " + (checkpoints.stage + 1) + " is now unlocked!", 182, 0, 0, 3); } else { drawcs(120 + pin, "Stage " + (checkpoints.stage + 1) + " is now unlocked!", 255, 255, 255, 3); } if (byte0 != 0) { if (aflk) { drawcs(140, "And:", 182, 0, 0, 3); } else { drawcs(140, "And:", 255, 0, 0, 3); } rd.setColor(new Color(255, 170, 0)); float f = (float) Math.random(); if (f < 0.69999999999999996D) { rd.drawRect(275, 170, 349, 126); } else { rd.fillRect(275, 170, 350, 127); } rd.setColor(new Color(255, 100, 0)); rd.fillRect(276, 170, 348, 4); rd.fillRect(276, 170, 4, 125); rd.fillRect(276, 292, 348, 4); rd.fillRect(624, 170, 4, 125); aconto[byte0].y = i; aconto[sc[0]].blackout = false; m.crs = true; m.x = -450; m.y = -260; m.z = -50; m.xz = 0; m.zy = 0; aconto[sc[0]].z = 1000; //zoom car aconto[sc[0]].y = 0 - aconto[sc[0]].grat;; //y positioning - IDK aconto[sc[0]].x = 0; //x positioning aconto[sc[0]].xz = -90; //normal spin //aconto[sc[0]].xy += 0; //barrel roll aconto[sc[0]].zy = 0; //backflips aconto[sc[0]].wzy -= 10; //wheels //custom spin, Thanks IP if (aconto[sc[0]].xy >= 90 || aconto[sc[0]].xy <= 0) { currentRotation *= -1; } aconto[sc[0]].xy += currentRotation; nameOfNewVariable = aconto[sc[0]].xy; m.ground = 2470; aconto[byte0].d(rd); String s = ""; if (byte0 == 13) { s = " "; } if (aflk) { drawcs(400, "" + names[byte0] + "" + s + " has been unlocked!", 182, 0, 0, 3); } else { drawcs(400, "" + names[byte0] + "" + s + " has been unlocked!", 255, 0, 0, 3); } pin = 180; } rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(140 + pin, "GAME SAVED", 182, 0, 0, 3); if (pin == 60) { pin = 30; } else { pin = 0; } } else { rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); if (aflk) { drawcs(90, "Woohoooo you finished the game!!!", 144, 167, 255, 3); } else { drawcs(90, "Woohoooo you finished the game!!!", 228, 240, 255, 3); } if (aflk) { drawcs(140, "Your Awesome!", 144, 167, 255, 3); } else { drawcs(142, "Your Awesome!", 228, 240, 255, 3); } if (aflk) { drawcs(190, "You're truly a RADICAL GAMER!", 144, 167, 255, 3); } else { drawcs(190, "You're truly a RADICAL GAMER!", 255, 100, 100, 3); } rd.setColor(new Color(0, 0, 0)); rd.fillRect(0, 205, 900, 62); rd.drawImage(radicalplay, radpx + (int) (8D * Math.random() - 4D), 205, null); if (radpx != 147) { radpx += 40; if (radpx > 900) { radpx = -453; } } if (flipo == 40) { radpx = 148; } flipo++; if (flipo == 70) { flipo = 0; } if (radpx == 147) { rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); if (aflk) { drawcs(259, "A Game by Radicalplay.com", 144, 167, 255, 3); } else { drawcs(259, "A Game by Radicalplay.com", 228, 240, 255, 3); } } if (aflk) { drawcs(300, "Now get up and dance!", 144, 167, 255, 3); } else { drawcs(300, "Now get up and dance!", 228, 240, 255, 3); } pin = 0; } if (aflk) { aflk = false; } else { aflk = true; } } else { pin = 30; rd.drawImage(congrd, 315, 87, null); drawcs(137, "Stage " + checkpoints.stage + " Completed!", 170, 170, 170, 3); drawcs(154, "" + checkpoints.name + "", 128, 128, 128, 3); } } else { pin = 30; rd.drawImage(gameov, 280, 117, null); drawcs(167, "Failed to Complete Stage " + checkpoints.stage + "!", 170, 170, 170, 3); drawcs(184, "" + checkpoints.name + "", 128, 128, 128, 3); } rd.drawImage(contin[pcontin], 405, 450 - pin, null); if (control.enter || control.handb) { fase = 10; if (loadedt[checkpoints.stage - 1]) { if(isMidi[checkpoints.stage - 1]) { mtracks[checkpoints.stage - 1].setPaused(true); } else { stracks[checkpoints.stage - 1].stop(); } } if (checkpoints.stage == unlocked && winner && unlocked != 25) { checkpoints.stage++; unlocked++; } flipo = 0; control.enter = false; control.handb = false; } } public void sortcars(int i) { if (i == 6) { sc[1] = 7; sc[2] = 7; sc[3] = 7; sc[4] = 7; sc[5] = 7; sc[6] = 7; } else if (i != 0) { int lastcar = nplayers; int startingcars = 6; // get boss car if player is not in the mad party, since that one has no boss car (you play as dr monstaa) if (sc[0] != (int)Math.floor((startingcars + (((float) i / 3) - 0.3f))) && i != 25) { sc[nplayers - 1] = (int)Math.floor((startingcars + (((float) i / 3) - 0.3f))); if (sc[nplayers - 1] >= 13) { sc[nplayers - 1] = 13 - 1; // you could put -= 5 or something here } lastcar--; // boss car won't be randomized } // DEBUG: Prints the range of possible cars to the console // System.out.println("Minimum car: " + cd.names[(i - 1) / 2] + ", maximum car: " + cd.names[nplayers + ((i - 1) / 2)] + ", therefore: " + (((i - 1) / 2) - (nplayers + ((i - 1) / 2))) + " car difference"); // create a list of car ids, each item completely unique ArrayList<Integer> list = new ArrayList<Integer>(); for (int k = (int)Math.floor(((((float) i / 3) - 0.3f))); k < (int)Math.floor((startingcars + (((float) i / 3) - 0.3f))); k++) { if (k == sc[0]) continue; list.add(new Integer(k)); } // randomize the order of this list (shuffle it like a deck of cards) Collections.shuffle(list); // which item of the list should be picked int k = 0; for (int j = 1; j < lastcar; j++) { // get an item from the "deck" - this can be any item as long as it's unique sc[j] = list.get(k); k++; // if there are more cars than tracks, reduce the car index number until it fits. // unfortunately i have no idea how to make this work properly so we'll just have to ignore the duplicates here while (sc[j] >= 13) { System.out.println("Car " + j + " is out of bounds"); sc[j] -= ThreadLocalRandom.current().nextDouble() * 5F; } //System.out.println("sc of " + j + " is " + sc[j]); } } // this error will never be thrown in a deployment environment // it is only here for extra safety for (int j = 0; j < 7; j++) { if (sc[j] > 13) throw new RuntimeException("there are too many tracks and not enough cars"); } } public void sparkeng(int i) { i++; int j = 0; do { if (i == j) { if (!pengs[j]) { engs[enginsignature[sc[0]]][j].loop(); pengs[j] = true; } } else if (pengs[j]) { engs[enginsignature[sc[0]]][j].stop(); pengs[j] = false; } } while (++j < 5); } public void drawcs(int i, String s, int j, int k, int l, int i1) { if (i1 != 3 && i1 != 4) { j = (int) (j + j * (m.snap[0] / 100F)); if (j > 255) { j = 255; } if (j < 0) { j = 0; } k = (int) (k + k * (m.snap[1] / 100F)); if (k > 255) { k = 255; } if (k < 0) { k = 0; } l = (int) (l + l * (m.snap[2] / 100F)); if (l > 255) { l = 255; } if (l < 0) { l = 0; } } if (i1 == 4) { j = (int) (j - j * (m.snap[0] / 100F)); if (j > 255) { j = 255; } if (j < 0) { j = 0; } k = (int) (k - k * (m.snap[1] / 100F)); if (k > 255) { k = 255; } if (k < 0) { k = 0; } l = (int) (l - l * (m.snap[2] / 100F)); if (l > 255) { l = 255; } if (l < 0) { l = 0; } } if (i1 == 1) { rd.setColor(new Color(0, 0, 0)); rd.drawString(s, (450 - FontHandler.fMetrics.stringWidth(s) / 2) + 1, i + 1); } if (i1 == 2) { j = (j * 2 + m.csky[0] * 1) / 3; if (j > 255) { j = 255; } if (j < 0) { j = 0; } k = (k * 2 + m.csky[1] * 1) / 3; if (k > 255) { k = 255; } if (k < 0) { k = 0; } l = (l * 2 + m.csky[2] * 1) / 3; if (l > 255) { l = 255; } if (l < 0) { l = 0; } } rd.setColor(new Color(j, k, l)); rd.drawString(s, 450 - FontHandler.fMetrics.stringWidth(s) / 2, i); } public void trackbg(boolean flag) { int i = 0; trkl++; if (trkl > trklim) { i = 1; trklim = (int) (Math.random() * 40D); trkl = 0; } if (flag) { i = 0; } int j = 0; do { rd.drawImage(trackbg[i][j], trkx[j], 0, null); trkx[j]--; if (trkx[j] <= -900) { trkx[j] = 900; } } while (++j < 2); } public void stageselect(CheckPoints checkpoints, Control control) { for (int i = 0; i < 25; i++) { mtracks[i] = null; stracks[i] = null; isMidi[i] = false; loadedt[i] = false; } if (checkpoints.stage != 1) { rd.drawImage(back[pback], 50, 350, null); } if (checkpoints.stage != 25) { rd.drawImage(next[pnext], 780, 350, null); } if (checkpoints.stage <= 12) { rd.drawImage(nextse, 780, 350, null); if (checkpoints.stage != 1) { rd.drawImage(backse, 50, 350, null); } } if (checkpoints.stage >= 13 && checkpoints.stage != 25) { if (checkpoints.stage != 25) { rd.drawImage(next[pnext], 780, 350, null); } rd.drawImage(back[pback], 50, 350, null); } rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); if (checkpoints.stage <= 12) { rd.drawImage(brse, 0, 0, null); } if (checkpoints.stage >= 13 && checkpoints.stage != 25) { rd.drawImage(br, 0, 0, null); } if (checkpoints.stage != 25) { drawcs(110, "Stage " + checkpoints.stage + " >", 30, 30, 30, 3); } else { drawcs(110, "Final Party Stage >", 30, 30, 30, 3); } drawcs(130, "<< " + checkpoints.name + " >>", 30, 30, 30, 3); rd.drawImage(contin[pcontin], 405, 425, null); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(496, "You can also use Keyboard Arrows and Enter to navigate.", 255, 255, 255, 3); if (control.handb || control.enter) { asay = "Stage " + checkpoints.stage + ": " + checkpoints.name + " "; dudo = 150; m.trk = false; m.focus_point = 500; fase = 5; control.handb = false; control.enter = false; cars.stop(); cars.unloadMod(); } if (control.right && checkpoints.stage < 25) { if (checkpoints.stage != unlocked) { checkpoints.stage++; fase = 58; control.right = false; } else { fase = 4; lockcnt = 100; control.right = false; } } if (control.left && checkpoints.stage > 1) { checkpoints.stage--; fase = 58; control.left = false; } } public void snap(int i) { dmg = loadsnap(odmg); pwr = loadsnap(opwr); was = loadsnap(owas); lap = loadsnap(olap); pos = loadsnap(opos); int j = 0; do { rank[j] = loadsnap(orank[j]); } while (++j < 7); j = 0; do { cntdn[j] = loadsnap(ocntdn[j]); } while (++j < 4); yourwasted = loadsnap(oyourwasted); youlost = loadsnap(oyoulost); youwon = loadsnap(oyouwon); youwastedem = loadsnap(oyouwastedem); gameh = loadsnap(ogameh); loadingmusic = loadopsnap(oloadingmusic, i, 76); star[0] = loadopsnap(ostar[0], i, 0); star[1] = loadopsnap(ostar[1], i, 0); flaot = loadopsnap(oflaot, i, 1); } private Image loadsnap(Image image) { int i = image.getHeight(ob); int j = image.getWidth(ob); int ai[] = new int[j * i]; PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, j, i, ai, 0, j); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } for (int k = 0; k < j * i; k++) { if (ai[k] != 0xffc0c0c0 && ai[k] != ai[j * i - 1]) { Color color = new Color(ai[k]); int l = (int) (color.getRed() + color.getRed() * (m.snap[0] / 100F)); if (l > 225) { l = 225; } if (l < 0) { l = 0; } int i1 = (int) (color.getGreen() + color.getGreen() * (m.snap[1] / 100F)); if (i1 > 225) { i1 = 225; } if (i1 < 0) { i1 = 0; } int j1 = (int) (color.getBlue() + color.getBlue() * (m.snap[2] / 100F)); if (j1 > 225) { j1 = 225; } if (j1 < 0) { j1 = 0; } Color color2 = new Color(l, i1, j1); ai[k] = color2.getRGB(); } else if (ai[k] == 0xffc0c0c0) { Color color1 = new Color(m.csky[0], m.csky[1], m.csky[2]); ai[k] = color1.getRGB(); } } Image image1 = createImage(new MemoryImageSource(j, i, ai, 0, j)); return image1; } public void resetstat(int i) { setnumber = false; arrace = false; ana = 0; cntan = 0; cntovn = 0; tcnt = 30; wasay = false; clear = 0; dmcnt = 0; pwcnt = 0; auscnt = 45; pnext = 0; pback = 0; starcnt = 130; gocnt = 3; grrd = true; aird = true; bfcrash = 0; cntwis = 0; bfskid = 0; pwait = 7; holdcnt = 0; holdit = false; winner = false; time = 0; wasted = 0; int j = 0; do { dested[j] = 0; } while (++j < nplayers); sortcars(i); } public void drawstat(int i, int j, boolean flag, float f) { int ai[] = new int[4]; int ai1[] = new int[4]; if (flag) { ai[0] = 768; ai1[0] = 11; ai[1] = 768; ai1[1] = 19; ai[2] = 865; ai1[2] = 19; ai[3] = 865; ai1[3] = 11; rd.setColor(new Color(m.csky[0], m.csky[1], m.csky[2])); rd.fillPolygon(ai, ai1, 4); } if (j > i) { j = i; } //rd.drawImage(damagebar, 677, 21, null); // rd.drawImage(powerbar, 677, 47, null); int k = (int) (98F * ((float) j / (float) i)); ai[0] = 764; ai1[0] = 30; ai[1] = 764; ai1[1] = 39; ai[2] = 764 + k; ai1[2] = 39; ai[3] = 764 + k; //532 ai1[3] = 30; int l = 244; //255, 74, 86 int i1 = 244; int j1 = 11; if (k > 33) { i1 = (int) (244F - 233F * ((k - 33) / 65F)); } if (k > 70) { if (dmcnt < 10) { if (dmflk) { i1 = 113; dmflk = false; } else { dmflk = true; } } dmcnt++; if (dmcnt > 167D - k * 1.5D) { dmcnt = 0; } } //l = (int) (l + l * (m.snap[0] / 100F)); if (l > 255) { l = 255; } if (l < 0) { l = 0; } //i1 = (int) (i1 + i1 * (m.snap[1] / 100F)); if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } //j1 = (int) (j1 + j1 * (m.snap[2] / 100F)); if (j1 > 255) { j1 = 255; } if (j1 < 0) { j1 = 0; } rd.setColor(new Color(l, i1, j1)); rd.fillPolygon(ai, ai1, 4); ai[0] = 764; ai1[0] = 56; ai[1] = 764; ai1[1] = 65; ai[2] = (int) (764F + f); ai1[2] = 65; ai[3] = (int) (764F + f); ai1[3] = 56; //comeback l = 128; if (f == 98F) { l = 64; } i1 = (int) (190D + f * 0.37D); j1 = 244; if (auscnt < 45 && aflk) { l = 128; i1 = 244; j1 = 244; } //l = (int) (l + l * (m.snap[0] / 100F)); if (l > 255) { l = 255; } if (l < 0) { l = 0; } //i1 = (int) (i1 + i1 * (m.snap[1] / 100F)); if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } //j1 = (int) (j1 + j1 * (m.snap[2] / 100F)); if (j1 > 255) { j1 = 255; } if (j1 < 0) { j1 = 0; } rd.setColor(new Color(l, i1, j1)); rd.fillPolygon(ai, ai1, 4); if (m.flex == 2 && f != 98F) { ai[0] = (int) (532F + f); ai1[0] = 31; ai[1] = (int) (532F + f); ai1[1] = 39; ai[2] = 630; ai1[2] = 39; ai[3] = 630; ai1[3] = 31; rd.setColor(new Color(m.csky[0], m.csky[1], m.csky[2])); rd.fillPolygon(ai, ai1, 4); } } private Image bressed(Image image) { int i = image.getHeight(ob); int j = image.getWidth(ob); int ai[] = new int[j * i]; PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, j, i, ai, 0, j); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } Color color = new Color(247, 255, 165); for (int k = 0; k < j * i; k++) { if (ai[k] != ai[j * i - 1]) { ai[k] = color.getRGB(); } } Image image1 = createImage(new MemoryImageSource(j, i, ai, 0, j)); return image1; } public void loading() { rd.setColor(new Color(0, 0, 0)); rd.fillRect(0, 0, 900, 500); rd.drawImage(sign, 412, 10, this); rd.drawImage(hello, 60, 80, this); rd.setFont(new Font("Adventure", 1, 32)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(440, "Loading game, please wait.", 255, 255, 255, 3); } public xtGraphics(Medium medium, Graphics2D graphics2d, Applet applet) { fase = 111; oldfase = 0; starcnt = 0; unlocked = 1; lockcnt = 0; opselect = 1; shaded = false; flipo = 0; nextc = false; gatey = 0; looped = 1; sc = new int[7]; holdit = false; holdcnt = 0; winner = false; flexpix = new int[0x6DDD0]; smokey = new int[0x16fb4]; flatrstart = 0; runtyp = 0; trackbg = new Image[2][2]; dude = new Image[3]; dudeb = new Image[3]; duds = 0; dudo = 0; next = new Image[2]; back = new Image[2]; contin = new Image[2]; ostar = new Image[2]; star = new Image[3]; pcontin = 0; pnext = 0; pback = 0; pstar = 0; orank = new Image[7]; rank = new Image[7]; ocntdn = new Image[4]; cntdn = new Image[4]; gocnt = 0; engs = new AudioClip[5][5]; pengs = new boolean[5]; air = new AudioClip[6]; aird = false; grrd = false; crash = new AudioClip[3]; lowcrash = new AudioClip[3]; pwastd = false; skid = new AudioClip[3]; dustskid = new AudioClip[3]; mutes = false; stracks = new RadicalMod[25]; mtracks = new RadicalMidi[25]; isMidi = new boolean[25]; loadedt = new boolean[25]; lastload = -1; mutem = false; sunny = false; macn = false; arrace = false; ana = 0; cntan = 0; cntovn = 0; flk = false; tcnt = 30; tflk = false; say = ""; wasay = false; clear = 0; posit = 0; wasted = 0; laps = 0; dested = new int[7]; dmcnt = 0; dmflk = false; pwcnt = 0; pwflk = false; loop = ""; spin = ""; asay = ""; auscnt = 45; aflk = false; kbload = 0; dnload = 0; shload = 0.0F; radpx = 147; pin = 60; trkl = 0; trklim = (int) (Math.random() * 40D); flkat = (int) (60D + 140D * Math.random()); movly = (int) (100D + 100D * Math.random()); xdu = 272; ydu = 2; gxdu = 0; gydu = 0; pgady = new int[9]; pgas = new boolean[9]; lxm = -10; lym = -10; pwait = 7; stopcnt = 0; cntwis = 0; crshturn = 0; bfcrash = 0; bfskid = 0; crashup = false; skidup = false; skflg = 0; dskflg = 0; flatr = 0; flyr = 0; flyrdest = 0; flang = 0; flangados = 0; blackn = 0.0F; blacknados = 0.0F; m = medium; app = applet; rd = graphics2d; MediaTracker mediatracker = new MediaTracker(app); hello = Toolkit.getDefaultToolkit().getImage(xtGraphics.class.getResource("data/hello.gif")); mediatracker.addImage(hello, 0); try { mediatracker.waitForID(0); } catch (Exception _ex) { } sign = Toolkit.getDefaultToolkit().getImage(xtGraphics.class.getResource("data/sign.gif")); mediatracker.addImage(sign, 0); try { mediatracker.waitForID(0); } catch (Exception _ex) { } loadbar = Toolkit.getDefaultToolkit().getImage(xtGraphics.class.getResource("data/loadbar.gif")); mediatracker.addImage(loadbar, 0); try { mediatracker.waitForID(0); } catch (Exception _ex) { } int i = 0; do { loadedt[i] = false; isMidi[i] = false; } while (++i < 25); } public void maini(Control control) { mainmenu.loadMod(135, 7800, 125, sunny, macn); mainmenu.play(); if (lastload >= 0 && loadedt[lastload]) { if (isMidi[lastload]) { mtracks[lastload].unloadMidi(); } else { stracks[lastload].unloadMod(); } } if (flipo == 0) { bgmy[0] = 0; bgmy[1] = 500; app.setCursor(new Cursor(0)); } int i = 0; rd.drawImage(bgmain, 0, 0, null); rd.drawImage(logocars, 12, 28, null); flipo++; if (flipo > flkat + 36) { flipo = 1; flkat = (int) (60D + 140D * Math.random()); } if (movly <= 10) { if (movly == 10 || movly == 8 || movly == 6 || movly == 4 || movly == 2) { gxdu = (int) (xdu + 200 - 500D * Math.random()); gydu = (int) (ydu + 200 - 500D * Math.random()); if (movly == 2) { gxdu = 272; gydu = 2; } movly--; } xdu += (gxdu - xdu) / 15; ydu += (gydu - ydu) / 15; if (movly != 1) { if (Utility.pys(xdu, gxdu, ydu, gydu) < 20F) { movly--; } } else { if (xdu > gxdu) { xdu--; } else { xdu++; } if (ydu > gydu) { ydu--; } else { ydu++; } if (Utility.pys(xdu, gxdu, ydu, gydu) < 2.0F) { movly--; } } if (movly == 0) { xdu = 272; ydu = 2; movly = (int) (100D + 100D * Math.random()); } } else if (flipo >= movly) { movly = 10; } rd.drawImage(opback, 179, 212, null); if (control.up) { opselect--; if (opselect == -1) { opselect = 2; } control.up = false; } if (control.down) { opselect++; if (opselect == 3) { opselect = 0; } control.down = false; } if (opselect == 0) { if (shaded) { rd.setColor(new Color(140, 70, 0)); rd.fillRect(278, 246, 110, 22); aflk = false; } if (aflk) { rd.setColor(new Color(200, 255, 0)); aflk = false; } else { rd.setColor(new Color(182, 0, 0)); aflk = true; } rd.drawRoundRect(355, 246, 207, 37, 18, 20); //rd.drawRoundRect(xcorner, ycorner, xlength, ylength, 7, 20); } else { rd.setColor(new Color(255, 255, 255)); rd.drawRoundRect(355, 246, 207, 37, 18, 20); } if (opselect == 1) { if (shaded) { rd.setColor(new Color(140, 70, 0)); rd.fillRect(234, 275, 196, 22); aflk = false; } if (aflk) { rd.setColor(new Color(200, 128, 0)); aflk = false; } else { rd.setColor(new Color(182, 0, 0)); aflk = true; } rd.drawRoundRect(305, 310, 318, 37, 18, 20); } else { rd.setColor(new Color(255, 255, 255)); rd.drawRoundRect(305, 310, 318, 37, 18, 20); } if (opselect == 2) { if (shaded) { rd.setColor(new Color(140, 70, 0)); rd.fillRect(290, 306, 85, 22); aflk = false; } if (aflk) { rd.setColor(new Color(255, 0, 0)); aflk = false; } else { rd.setColor(new Color(182, 0, 0)); aflk = true; } rd.drawRoundRect(380, 373, 160, 37, 18, 20); } else { rd.setColor(new Color(255, 255, 255)); rd.drawRoundRect(380, 373, 160, 37, 18, 20); } rd.drawImage(opti, 241, 250, null); if (control.enter || control.handb) { if (opselect == 0) { if (unlocked == 1 && oldfase == 0) { oldfase = -9; fase = 11; } else { fase = -9; } } if (opselect == 1) { oldfase = 10; fase = 11; } if (opselect == 2) { fase = 8; } flipo = 0; control.enter = false; control.handb = false; } if (shaded) { app.repaint(); try { Thread.sleep(100L); } catch (InterruptedException _ex) { } } } public void blendude(Image image) { if (!macn) { if (Math.random() > Math.random()) { dudo = 217; } else { dudo = 331; } int ai[] = new int[19520]; PixelGrabber pixelgrabber = new PixelGrabber(image, dudo, 0, 122, 160, ai, 0, 122); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { dudo = -1; } int j = 0; do { int ai1[] = new int[19520]; PixelGrabber pixelgrabber1 = new PixelGrabber(dude[j], 0, 10, 122, 160, ai1, 0, 122); try { pixelgrabber1.grabPixels(); } catch (InterruptedException _ex) { dudo = -1; } if (dudo != -1) { int k = 0; do { if (ai1[k] != ai1[0]) { Color color = new Color(ai1[k]); Color color1 = new Color(ai[k]); int l = (color.getRed() + color1.getRed() * 3) / 4; if (l > 255) { l = 255; } if (l < 0) { l = 0; } int i1 = (color.getGreen() + color1.getGreen() * 3) / 4; if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } int j1 = (color.getBlue() + color1.getBlue() * 3) / 4; if (j1 > 255) { j1 = 255; } if (j1 < 0) { j1 = 0; } Color color2 = new Color(l, i1, j1); ai1[k] = color2.getRGB(); } } while (++k < 19520); dudeb[j] = createImage(new MemoryImageSource(122, 160, ai1, 0, 122)); } } while (++j < 3); } else { if (Math.random() > Math.random()) { dudo = 176; } else { dudo = 372; } int i = 0; do { dudeb[i] = dude[i]; } while (++i < 3); } } public void musicomp(int i, Control control) { hipnoload(i, true); if (control.handb || control.enter) { System.gc(); fase = 0; control.handb = false; control.enter = false; } } public void drawSmokeCarsbg() { if (Math.abs(flyr - flyrdest) > 20) { if (flyr > flyrdest) { flyr -= 20; } else { flyr += 20; } } else { flyr = flyrdest; flyrdest = (int) ((flyr + m.random() * 160F) - 80F); } if (flyr > 160) { flyr = 160; } if (flatr > 170) { flatrstart++; flatr = flatrstart * 3; flyr = (int) (m.random() * 160F - 80F); flyrdest = (int) ((flyr + m.random() * 160F) - 80F); flang = 1; flangados = (int) (m.random() * 6F + 2.0F); blackn = 0.0F; blacknados = m.random() * 0.4F; } int i = 0; do { int j = 0; do { if (smokey[i + j * 466] != smokey[0]) { float f = Utility.pys(i, 233, j, flyr); int k = (int) (((i - 233) / f) * flatr); int l = (int) (((j - flyr) / f) * flatr); int i1 = i + k + 100 + (j + l + 110) * 900; if (i + k + 100 < 900 && i + k + 100 > 0 && j + l + 110 < 500 && j + l + 110 > 0 && i1 < 0x416e0 && i1 >= 0) { Color color = new Color(flexpix[i1]); Color color1 = new Color(smokey[i + j * 466]); float f1 = (255F - color1.getRed()) / 255F; int j1 = (int) ((color.getRed() * (flang * f1) + color1.getRed() * (1.0F - f1)) / (flang * f1 + (1.0F - f1) + blackn)); if (j1 > 255) { j1 = 255; } if (j1 < 0) { j1 = 0; } Color color2 = new Color(j1, j1, j1); flexpix[i1] = color2.getRGB(); } } } while (++j < 202); } while (++i < 466); blackn += blacknados; flang += flangados; flatr += 10 + flatrstart * 2; Image image = createImage(new MemoryImageSource(900, 500, flexpix, 0, 900)); rd.drawImage(image, 0, 0, null); } public void loaddata(int i) { kbload = 625; sunny = false; String s = "default/"; String s1 = "au"; if (i == 2) { kbload = 950; sunny = true; s = "JavaNew/"; s1 = "wav"; } String s2 = System.getProperty("os.name"); if (!s2.startsWith("Win")) { macn = true; } runtyp = 176; runner = new Thread(this); runner.start(); loadimages(); //loadnetworkimages(); cars = new RadicalMod("data/music/cars.radq", app); dnload += 27; int j = 0; do { int k = 0; do { engs[k][j] = getSound("data/sounds/" + s + "" + k + "" + j + ".au"); dnload += 3; } while (++k < 5); pengs[j] = false; } while (++j < 5); mainmenu = new RadicalMod("data/music/mainmenu.radq", app); dnload += 91; j = 0; do { air[j] = getSound("data/sounds/" + s + "air" + j + ".au"); dnload += 2; } while (++j < 6); j = 0; do { crash[j] = getSound("data/sounds/" + s + "crash" + (j + 1) + "." + s1); if (i == 2) { dnload += 10; } else { dnload += 7; } } while (++j < 3); j = 0; do { lowcrash[j] = getSound("data/sounds/" + s + "lowcrash" + (j + 1) + "." + s1); if (i == 2) { dnload += 10; } else { dnload += 3; } } while (++j < 3); tires = getSound("data/sounds/" + s + "tires." + s1); if (i == 2) { dnload += 24; } else { dnload += 4; } checkpoint = getSound("data/sounds/" + s + "checkpoint." + s1); if (i == 2) { dnload += 24; } else { dnload += 6; } carfixed = getSound("data/sounds/" + s + "carfixed." + s1); if (i == 2) { dnload += 24; } else { dnload += 10; } powerup = getSound("data/sounds/" + s + "powerup." + s1); if (i == 2) { dnload += 42; } else { dnload += 8; } three = getSound("data/sounds/" + s + "three." + s1); if (i == 2) { dnload += 24; } else { dnload += 4; } two = getSound("data/sounds/" + s + "two." + s1); if (i == 2) { dnload += 24; } else { dnload += 2; } one = getSound("data/sounds/" + s + "one." + s1); if (i == 2) { dnload += 24; } else { dnload += 4; } go = getSound("data/sounds/" + s + "go." + s1); if (i == 2) { dnload += 24; } else { dnload += 4; } wastd = getSound("data/sounds/" + s + "wasted." + s1); if (i == 2) { dnload += 24; } else { dnload += 4; } firewasted = getSound("data/sounds/" + s + "firewasted." + s1); if (i == 2) { dnload += 24; } else { dnload += 10; } j = 0; do { skid[j] = getSound("data/sounds/" + s + "skid" + (j + 1) + "." + s1); if (i == 2) { dnload += 22; } else { dnload += 6; } } while (++j < 3); j = 0; do { dustskid[j] = getSound("data/sounds/" + s + "dustskid" + (j + 1) + "." + s1); if (i == 2) { dnload += 22; } else { dnload += 7; } } while (++j < 3); } public void clicknow() { rd.setFont(new Font("Adventure", 1, 32)); if (aflk) { drawcs(485, "Click here to Start", 255, 255, 255, 3); aflk = false; } else { drawcs(485, "Click here to Start", 200, 200, 200, 3); aflk = true; } } private Image loadimage(byte abyte0[], MediaTracker mediatracker, Toolkit toolkit) { Image image = toolkit.createImage(abyte0); mediatracker.addImage(image, 0); try { mediatracker.waitForID(0); } catch (Exception _ex) { } return image; } public void rad(int i, int x) { //splash if (i == 0) { firewasted.play(); radpx = 240; pin = 0; } rd.drawImage(splash, 0, 0, null); //rd.setColor(new Color(0, 0, 0)); //rd.fillRect(0, 110, 900, 59); if (pin != 0) { rd.drawImage(radicalplay, radpx + (int) (8D * Math.random() - 4D), 185, null); } else { rd.drawImage(radicalplay, 280, 185, null); } if (radpx != 147) { radpx += 40; if (radpx > 900) { radpx = -453; } } else if (pin != 0) { pin--; } if (i == 40) { radpx = 148; pin = 7; } rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); if (aflk) { drawcs(270, "Where the crazy just got even crazier....", 200, 200, 155, 3); aflk = false; } else { drawcs(270, "Where the crazy just got even crazier....", 250, 250, 200, 3); aflk = true; } if (aflk) { drawcs(180, "Where the crazy just got even crazier....", 200, 200, 200, 3); aflk = false; } else { drawcs(180, "Where the crazy just got even crazier....", 250, 250, 250, 3); aflk = true; } } public void skid(int i, float f) { if (bfcrash == 0 && bfskid == 0 && f > 150F) { if (i == 0) { if (!mutes) { skid[skflg].play(); } if (skidup) { skflg++; } else { skflg--; } if (skflg == 3) { skflg = 0; } if (skflg == -1) { skflg = 2; } } else { if (!mutes) { dustskid[dskflg].play(); } if (skidup) { dskflg++; } else { dskflg--; } if (dskflg == 3) { dskflg = 0; } if (dskflg == -1) { dskflg = 2; } } bfskid = 35; } } public void cantreply() { rd.setColor(new Color(64, 143, 223)); rd.fillRoundRect(135, 73, 500, 23, 7, 20); rd.setColor(new Color(0, 89, 223)); rd.drawRoundRect(135, 73, 500, 23, 7, 20); drawcs(89, "Sorry not enough replay data to play available, please try again later.", 255, 255, 255, 1); } public void stopallnow() { int i = 0; do { if (loadedt[i]) { if (isMidi[i]) { mtracks[i].unloadMidi(); } else { stracks[i].unloadAll(); stracks[i] = null; } } } while (++i < 25); i = 0; do { engs[0][i].stop(); engs[1][i].stop(); } while (++i < 5); i = 0; do { air[i].stop(); } while (++i < 6); wastd.stop(); cars.unloadAll(); } public void inishcarselect() { carsbginflex(); flatrstart = 0; m.lightson = true; cars.loadMod(200, 8000, 125, sunny, macn); pnext = 0; pback = 0; } public void carsbginflex() { flatr = 0; flyr = (int) (m.random() * 160F - 80F); flyrdest = (int) ((flyr + m.random() * 160F) - 80F); flang = 1; flangados = (int) (m.random() * 6F + 2.0F); blackn = 0.0F; blacknados = m.random() * 0.4F; PixelGrabber pixelgrabber = new PixelGrabber(carstarter, 0, 0, 900, 500, flexpix, 0, 900); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } } public void carselect(Control control, ContO aconto[], Madness madness) { mainmenu.stop(); cars.play(); if (flatrstart == 6) { if (sc[0] <= 5 ) { rd.drawImage(carstarter, 0, 0, null); } if (sc[0] <= 9 && sc[0] >= 6 ) { rd.drawImage(carstreetelites, 0, 0, null); } if (sc[0] <= 13 && sc[0] >= 10) { rd.drawImage(carfuriousfour, 0, 0, null); } } else if (flatrstart <= 1) { drawSmokeCarsbg(); } else { rd.setColor(new Color(255, 255, 255)); rd.fillRect(0, 0, 900, 500); carsbginflex(); flatrstart = 6; } //rd.drawImage(selectcar, 375, 30, null); if(sc[0] == 9) { m.crs = true; m.x = -450; m.y = -550; m.z = 230; m.xz = 0; m.zy = 10; m.ground = 1500; aconto[sc[0]].d(rd); } else { m.crs = true; m.x = -450; m.y = -550; m.z = 215; m.xz = 0; m.zy = 10; m.ground = 1500; aconto[sc[0]].d(rd); } //DIM LOCKED CARS if ((sc[0] - 5) * 3 >= unlocked) { aconto[sc[0]].blackout = true; } if ((sc[0] - 5) * 3 < unlocked) { aconto[sc[0]].blackout = false; } aconto[sc[0]].d(rd); if (flipo == 0) { rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); byte byte0 = 0; if (flatrstart < 6) { byte0 = 2; } if (aflk) { drawcs(140 + byte0, "> " + names[sc[0]] + " <", 240, 240, 240, 3); drawcs(445 + byte0, "Made By: " + creators[sc[0]], 240, 240, 240, 3); drawcs(170 + byte0, "" + specialty[sc[0]] + "", 255, 0, 0, 3); aflk = false; } else { drawcs(140,"> " + names[sc[0]] + " <", 176, 176, 176, 3); drawcs(445, "Made By: " + creators[sc[0]], 176, 176, 176, 3); drawcs(170,"" + specialty[sc[0]] + "", 200, 0, 0, 3); aflk = true; } aconto[sc[0]].z = 950; if (sc[0] == 9) { aconto[sc[0]].z = 1000; } if (sc[0] == 13) { aconto[sc[0]].z = 1000; } aconto[sc[0]].y = -34 - aconto[sc[0]].grat; aconto[sc[0]].x = 0; aconto[sc[0]].xz += 3; aconto[sc[0]].xy = 0; aconto[sc[0]].zy = 0; aconto[sc[0]].wzy -= 10; if (aconto[sc[0]].wzy < -45) { aconto[sc[0]].wzy += 45; } //comeback if (sc[0] <= 5 ) { if (sc[0] != 0) { rd.drawImage(backstart, 30, 350, null); } rd.drawImage(nextstart, 810, 350, null); } if (sc[0] <= 9 && sc[0] >= 6 ) { rd.drawImage(backse, 30, 350, null); rd.drawImage(nextse, 810, 350, null); } if (sc[0] <= 13 && sc[0] >= 10) { rd.drawImage(back[pback], 30, 350, null); if (sc[0] != 13) { rd.drawImage(next[pnext], 810, 350, null); } } if ((sc[0] - 5) * 2 >= unlocked) { if (gatey == 300) { int i = 0; do { pgas[i] = false; pgady[i] = 0; } while (++i < 9); pgas[0] = true; } int j = 0; do { rd.drawImage(pgate, pgatx[j], (pgaty[j] + pgady[j]) - gatey, null); if (flatrstart == 6) { if (pgas[j]) { pgady[j] -= ((80 + 100 / (j + 1)) - Math.abs(pgady[j])) / 3; if (pgady[j] < -(70 + 100 / (j + 1))) { pgas[j] = false; if (j != 8) { pgas[j + 1] = true; } } } else { pgady[j] += ((80 + 100 / (j + 1)) - Math.abs(pgady[j])) / 3; if (pgady[j] > 0) { pgady[j] = 0; } } } } while (++j < 9); if (gatey != 0) { gatey -= 100; } if (flatrstart == 6) { drawcs(210, "[ Car Locked ]", 210, 210, 210, 3); drawcs(235, "Complete Stage " + (sc[0] - 5) * 3 + " to unlock " + names[sc[0]], 255, 255, 255, 3); rd.setColor(new Color(255,170,0)); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); } } else { if (flatrstart == 6) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); rd.drawString("Top Speed:", 631, 90); rd.drawString("Acceleration:", 621, 105); rd.drawString("Handling:", 643, 120); rd.drawString("Stunts:", 654, 135); rd.drawString("Strength:", 642, 150); rd.drawString("Endurance:", 632, 165); if (sc[0] <= 5 ) { rd.drawImage(statbstart, 695, 85, null); rd.drawImage(statbstart, 695, 100, null); rd.drawImage(statbstart, 695, 115, null); rd.drawImage(statbstart, 695, 130, null); rd.drawImage(statbstart, 695, 145, null); rd.drawImage(statbstart, 695, 160, null); } if (sc[0] <= 9 && sc[0] >= 6 ) { rd.drawImage(statbse, 695, 85, null); rd.drawImage(statbse, 695, 100, null); rd.drawImage(statbse, 695, 115, null); rd.drawImage(statbse, 695, 130, null); rd.drawImage(statbse, 695, 145, null); rd.drawImage(statbse, 695, 160, null); } if (sc[0] <= 13 && sc[0] >= 10 ) { rd.drawImage(statbff, 695, 85, null); rd.drawImage(statbff, 695, 100, null); rd.drawImage(statbff, 695, 115, null); rd.drawImage(statbff, 695, 130, null); rd.drawImage(statbff, 695, 145, null); rd.drawImage(statbff, 695, 160, null); } rd.setColor(new Color(0, 0, 0)); rd.drawImage(contin[pcontin], 405, 460, null); float f = (float)(madness.swits[sc[0]][2] - 220) / 90F; if (f < 0.20000000000000001D) { f = 0.2F; } if(statrate[0] > f) { statrate[0] -= 0.015F; } if(statrate[0] < f) { statrate[0] += 0.015F; } rd.fillRect((int) (695F + 156F * statrate[0]), 85, (int) (156F * (1.0F - statrate[0]) + 1.0F), 7); f = (madness.acelf[sc[0]][1] * madness.acelf[sc[0]][0] * madness.acelf[sc[0]][2] * madness.grip[sc[0]]) / 7700F; if (f > 1.0F) { f = 1.0F; } if(statrate[1] > f) { statrate[1] -= 0.015F; } if(statrate[1] < f) { statrate[1] += 0.015F; } rd.fillRect((int) (695F + 156F * statrate[1]), 100, (int) (156F * (1.0F - statrate[1]) + 1.0F), 7); f = dishandle[sc[0]]; if(statrate[2] > f) { statrate[2] -= 0.015F; } if(statrate[2] < f) { statrate[2] += 0.015F; } rd.fillRect((int) (695F + 156F * statrate[2]), 115, (int) (156F * (1.0F - statrate[2]) + 1.0F), 7); f = ((float)madness.airc[sc[0]] * madness.airs[sc[0]] * madness.bounce[sc[0]] + 28F) / 139F; if (f > 1.0F) { f = 1.0F; } if(statrate[3] > f) { statrate[3] -= 0.015F; } if(statrate[3] < f) { statrate[3] += 0.015F; } rd.fillRect((int) (695F + 156F * statrate[3]), 130, (int) (156F * (1.0F - statrate[3]) + 1.0F), 7); float f1 = 0.5F; if (sc[0] == 9) { f1 = 0.8F; } f = (madness.moment[sc[0]] + f1) / 2.6F; if (f > 1.0F) { f = 1.0F; } if(statrate[4] > f) { statrate[4] -= 0.015F; } if(statrate[4] < f) { statrate[4] += 0.015F; } rd.fillRect((int) (695F + 156F * statrate[4]), 145, (int) (156F * (1.0F - statrate[4]) + 1.0F), 7); f = outdam[sc[0]]; if(statrate[5] > f) { statrate[5] -= 0.015F; } if(statrate[5] < f) { statrate[5] += 0.015F; } rd.fillRect((int) (695F + 156F * statrate[5]), 160, (int) (156F * (1.0F - statrate[5]) + 1.0F), 7); if (sc[0] <= 5 ) { rd.drawImage(statbostart, 695, 85, null); rd.drawImage(statbostart, 695, 100, null); rd.drawImage(statbostart, 695, 115, null); rd.drawImage(statbostart, 695, 130, null); rd.drawImage(statbostart, 695, 145, null); rd.drawImage(statbostart, 695, 160, null); } if (sc[0] <= 9 && sc[0] >= 6 ) { rd.drawImage(statbose, 695, 85, null); rd.drawImage(statbose, 695, 100, null); rd.drawImage(statbose, 695, 115, null); rd.drawImage(statbose, 695, 130, null); rd.drawImage(statbose, 695, 145, null); rd.drawImage(statbose, 695, 160, null); } if (sc[0] <= 13 && sc[0] >= 10 ) { rd.drawImage(statboff, 695, 85, null); rd.drawImage(statboff, 695, 100, null); rd.drawImage(statboff, 695, 115, null); rd.drawImage(statboff, 695, 130, null); rd.drawImage(statboff, 695, 145, null); rd.drawImage(statboff, 695, 160, null); } rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 11)); //LORE TEXT if (sc[0] == 0) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("Able to withstand the toughest elements", 39, 105); rd.drawString("that nature has to offer, Storm Rider is", 39, 125); rd.drawString("a car that will power through any obstacle", 39, 145); rd.drawString("that it may face, including other drivers...", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 1) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("This car is deadly viper on the loose ", 39, 105); rd.drawString("with a taste for blood.... It operates on", 39, 125); rd.drawString("the most potent venom of the worlds most", 39, 145); rd.drawString("poisionus snakes.... Watch out.....", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 2) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("As normal as the Explorer may look to the", 39, 105); rd.drawString("naked eye, but this beast is no where", 39, 125); rd.drawString("near normal.... You'll definitely want to make", 39, 145); rd.drawString("decisions cautiously when he is near...", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 3) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("You may be wondering, why the hell would ", 39, 105); rd.drawString("anyone even consider racing in this tiny car?", 39, 125); rd.drawString("The answer is quite simple actually, great ", 39, 145); rd.drawString("mileage and a low financing rate of $0 down ", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 4) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("Its all in the name... Outrunner will fly", 39, 105); rd.drawString("by you on the track with its breakneck speed", 39, 125); rd.drawString("and the only thing left will be a trail", 39, 145); rd.drawString("of smoke.... You can't outrun the outrunner...", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 5) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("It is said that Solar Reflex is a concept car", 39, 105); rd.drawString("that hails from an unknown galaxy millions", 39, 125); rd.drawString("of light years away... How did it get here?", 39, 145); rd.drawString("That's the scary thing, nobody has a clue.... ", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 6) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("Zorgaro is a fierce competetior that will do", 39, 105); rd.drawString("just about damn near anything to cross that", 39, 125); rd.drawString("finish line first... Winning at all costs...", 39, 145); rd.drawString("Life is always on the line when he's near...", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 7) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("Stolen directly from FBI headquarters, this", 39, 105); rd.drawString("is a bulletproof monster of a vehicle looking", 39, 125); rd.drawString("to cause mayhem and destruction to all... If", 39, 145); rd.drawString("you ever hear sirens in the distance, run....", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 8) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("If you've ever noticed a trail of flames on a", 39, 105); rd.drawString("long stretch of road, Firestarter is always", 39, 125); rd.drawString("the first thought. Torch the competition at all", 39, 145); rd.drawString("costs, even if all costs means arson....", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 9) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); rd.drawString("and hes looking for scrap metal.... ", 39, 125); rd.drawString("Crossing paths with the Diesel King will be", 39, 145); rd.drawString("your final mistake that you ever make...", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 10) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("Capable of bending space and time with ", 39, 105); rd.drawString("sheer speed, Amethyst is not to be taken", 39, 125); rd.drawString("lightly. The chance of emerging victorious", 39, 145); rd.drawString("is slim to none, but is never zero...", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 11) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("A mad farmer's science experiment horribly", 39, 105); rd.drawString("wrong, Rampage is on the hunt for your soul!", 39, 125); rd.drawString("The only fuel that this crazy digger feeds", 39, 145); rd.drawString("off of is this little feeling called FEAR....", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } if (sc[0] == 12) { rd.setColor(new Color(255,255,255)); rd.setFont(new Font("SansSerif", 1, 12)); rd.drawString("A prototype created at the gates of heaven", 39, 105); rd.drawString("by the lord himself, Angelus is willing to do", 39, 125); rd.drawString("just about anything, even if it results in deadly", 39, 145); rd.drawString("sin.... A devils mind with angels wings...", 39, 165); //rd.drawString("Looks like the 18 Wheeler has lost its trailer", 39, 105); //rd.drawString("and hes looking for scrap metal.... ", 39, 125); //rd.drawString("Crossing paths with the Diesel King will be", 39, 145); //rd.drawString("your final mistake that you ever make...", 39, 165); } //CREATOR NAMES //make thing like names } } } else { pback = 0; pnext = 0; gatey = 300; if(flipo > 10) { aconto[sc[0]].x -= 100; if(nextc) { aconto[sc[0]].x += 20; } else { aconto[sc[0]].x -= 20; } } else { if(flipo == 10) { if(nextc) { sc[0]++; } else { sc[0]--; } aconto[sc[0]].x = 20; aconto[sc[0]].y += 10000; } } flipo--; } rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(495, "You can also use Keyboard Arrows and Enter to navigate.", 255, 255, 255, 3); if(control.right) { control.right = false; sc[0]++; if(sc[0] == 14) sc[0] = 13; } if(control.left) { control.left = false; sc[0]--; if(sc[0] == -1) sc[0] = 0; } if(control.handb || control.enter) { if(flipo == 0 && (sc[0] - 5) * 3 <= unlocked) //mainculprit if ((sc[0] - 5) * 2 >= unlocked) { lastload = -11; m.crs = false; fase = 58; } control.handb = false; control.enter = false; } } public void ctachm(int i, int j, int k, Control control) { if (fase == 1) { if (k == 1) { if (over(next[0], i, j, 560, 110)) { pnext = 1; } if (over(back[0], i, j, 50, 110)) { pback = 1; } if (over(contin[0], i, j, 290, 325)) { pcontin = 1; } } if (k == 2) { if (pnext == 1) { control.right = true; } if (pback == 1) { control.left = true; } if (pcontin == 1) { control.enter = true; } } } if (fase == 3) { if (k == 1 && over(contin[0], i, j, 290, 325)) { pcontin = 1; } if (k == 2 && pcontin == 1) { control.enter = true; pcontin = 0; } } if (fase == 4) { if (k == 1 && over(back[0], i, j, 305, 320)) { pback = 1; } if (k == 2 && pback == 1) { control.enter = true; pback = 0; } } if (fase == 6) { if (k == 1 && (over(star[0], i, j, 294, 360) || over(star[0], i, j, 294, 270))) { pstar = 2; } if (k == 2 && pstar == 2) { control.enter = true; pstar = 1; } } if (fase == 7) { if (k == 1) { if (over(next[0], i, j, 580, 250)) { pnext = 1; } if (over(back[0], i, j, 30, 250)) { pback = 1; } if (over(contin[0], i, j, 290, 360)) { pcontin = 1; } } if (k == 2) { if (pnext == 1) { control.right = true; } if (pback == 1) { control.left = true; } if (pcontin == 1) { control.enter = true; pcontin = 0; } } } if (fase == -5) { lxm = i; lym = j; if (k == 1 && over(contin[0], i, j, 290, 350 - pin)) { pcontin = 1; } if (k == 2 && pcontin == 1) { control.enter = true; pcontin = 0; } } if (fase == -7) { if (k == 1) { if (overon(264, 45, 137, 22, i, j)) { opselect = 0; shaded = true; } if (overon(255, 73, 155, 22, i, j)) { opselect = 1; shaded = true; } if (overon(238, 99, 190, 22, i, j)) { opselect = 2; shaded = true; } if (overon(276, 125, 109, 22, i, j)) { opselect = 3; shaded = true; } } if (k == 2 && shaded) { control.enter = true; shaded = false; } if (k == 0 && (i != lxm || j != lym)) { if (overon(264, 45, 137, 22, i, j)) { opselect = 0; } if (overon(255, 73, 155, 22, i, j)) { opselect = 1; } if (overon(238, 99, 190, 22, i, j)) { opselect = 2; } if (overon(276, 125, 109, 22, i, j)) { opselect = 3; } lxm = i; lym = j; } } if (fase == 10) { if (k == 1) { if (overon(278, 246, 110, 22, i, j)) { opselect = 0; shaded = true; } if (overon(234, 275, 196, 22, i, j)) { opselect = 1; shaded = true; } if (overon(290, 306, 85, 22, i, j)) { opselect = 2; shaded = true; } } if (k == 2 && shaded) { control.enter = true; shaded = false; } if (k == 0 && (i != lxm || j != lym)) { if (overon(278, 246, 110, 22, i, j)) { opselect = 0; } if (overon(234, 275, 196, 22, i, j)) { opselect = 1; } if (overon(290, 306, 85, 22, i, j)) { opselect = 2; } lxm = i; lym = j; } } if (fase == 11) { if (flipo >= 1 && flipo <= 13) { if (k == 1 && over(next[0], i, j, 600, 370)) { pnext = 1; } if (k == 2 && pnext == 1) { control.right = true; pnext = 0; } } if (flipo >= 3 && flipo <= 15) { if (k == 1 && over(back[0], i, j, 10, 370)) { pback = 1; } if (k == 2 && pback == 1) { control.left = true; pback = 0; } } if (flipo == 15) { if (k == 1 && over(contin[0], i, j, 500, 370)) { pcontin = 1; } if (k == 2 && pcontin == 1) { control.enter = true; pcontin = 0; } } } if (fase == 8) { if (flipo != 102) { if (k == 1 && over(next[0], i, j, 600, 370)) { pnext = 1; } } else { if (k == 1 && over(next[0], i, j, 600, 30)) { pnext = 1; } } if (k == 2 && pnext == 1) { control.enter = true; pnext = 0; } } } public void stopairs() { int i = 0; do { air[i].stop(); } while (++i < 6); } @Override public void run() { while (runtyp != 0) { if (runtyp >= 1 && runtyp <= 17) { hipnoload(runtyp, false); } if (runtyp == 176) { loading(); } app.repaint(); try { Thread.sleep(20L); } catch (InterruptedException _ex) { } } } public void loadingfailed(CheckPoints checkpoints, Control control, String error) { trackbg(false); rd.drawImage(select, 273, 45, null); if (checkpoints.stage <= 12) { rd.drawImage(brse, 0, 0, null); } if (checkpoints.stage >= 13 && checkpoints.stage != 25) { rd.drawImage(br, 0, 0, null); } if (checkpoints.stage != 1) { rd.drawImage(back[pback], 50, 110, null); } if (checkpoints.stage != 25) { rd.drawImage(next[pnext], 560, 110, null); } rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(140, "Error Loading Stage " + checkpoints.stage, 255, 255, 255, 3); drawcs(170, error, 177, 177, 177, 3); drawcs(220, "Check console for more info.", 177, 177, 177, 3); rd.drawImage(contin[pcontin], 290, 325, null); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(346, "You can also use Keyboard Arrows and Enter to navigate.", 255, 255, 255, 3); if (control.handb || control.enter) { fase = 58; control.handb = false; control.enter = false; } if(control.right && checkpoints.stage < 25) { if (checkpoints.stage != unlocked) { checkpoints.stage++; fase = 58; control.right = false; } else { fase = 4; lockcnt = 100; control.right = false; } } if(control.left && checkpoints.stage > 1) { checkpoints.stage--; fase = 58; control.left = false; } } public void hipnoload(int i, boolean flag) { int j = (int) (230F - 230F * (m.snap[0] / (100F * hipno[i - 1]))); if (j > 255) { j = 255; } if (j < 0) { j = 0; } int l = (int) (230F - 230F * (m.snap[1] / (100F * hipno[i - 1]))); if (l > 255) { l = 255; } if (l < 0) { l = 0; } int j1 = (int) (230F - 230F * (m.snap[2] / (100F * hipno[i - 1]))); if (j1 > 255) { j1 = 255; } if (j1 < 0) { j1 = 0; } if (i == 1) { j = 230; l = 230; j1 = 230; } rd.setColor(new Color(j, l, j1)); rd.fillRect(0, 0, 900, 500); rd.setFont(new Font("SansSerif", 1, 13)); FontHandler.fMetrics = rd.getFontMetrics(); drawcs(25, asay, 0, 0, 0, 3); byte byte0 = -90; if (i == unlocked && (i == 1 || i == 2 || i == 3 || i == 4 || i == 7 || i == 8 || i == 9 || i == 10 || i == 12 || i == 13 || i == 16)) { byte0 = 0; } if (byte0 == 0) { if (dudo > 0) { if (aflk) { if (Math.random() > Math.random()) { duds = (int) (Math.random() * 3D); } else { duds = (int) (Math.random() * 2D); } aflk = false; } else { aflk = true; } dudo--; } else { duds = 0; } rd.drawImage(dude[duds], 145, 10, null); rd.drawImage(flaot, 242, 42, null); int k = (int) (80F - 80F * (m.snap[0] / (50F * hipno[i - 1]))); if (k > 255) { k = 255; } if (k < 0) { k = 0; } int i1 = (int) (80F - 80F * (m.snap[1] / (50F * hipno[i - 1]))); if (i1 > 255) { i1 = 255; } if (i1 < 0) { i1 = 0; } int k1 = (int) (80F - 80F * (m.snap[2] / (50F * hipno[i - 1]))); if (k1 > 255) { k1 = 255; } if (k1 < 0) { k1 = 0; } if (i == 1) { k = 80; i1 = 80; k1 = 80; } rd.setColor(new Color(k, i1, k1)); rd.setFont(new Font("SansSerif", 1, 13)); if (i == 1) { rd.drawString("Hey! Don't forget, to complete a lap you must pass through", 312, 67); rd.drawString("all checkpoints in the track!", 312, 87); } if (i == 2) { rd.drawString("Remember, the more power you have the faster your car will be!", 312, 67); } if (i == 3) { rd.drawString("Watch out! Look out! The policeman might be out to get you!", 312, 67); rd.drawString("Don't upset him or you'll be arrested!", 312, 87); rd.drawString("Better run, run, run.", 312, 127); } if (i == 4) { rd.drawString("Don't waste your time. Waste them instead!", 312, 67); rd.drawString("Try a taste of sweet revenge here (if you can)!", 312, 87); rd.drawString("Press [ A ] to make the guidance arrow point to cars instead of to", 312, 127); rd.drawString("the track.", 312, 147); } if (i == 7) { rd.drawString("Welcome to the realm of the king...", 312, 67); rd.drawString("The key word here is 'POWER'. The more you have of it the faster", 312, 107); rd.drawString("and STRONGER you car will be!", 312, 127); } if (i == 8) { rd.drawString("Watch out, EL KING is out to get you now!", 312, 67); rd.drawString("He seems to be seeking revenge?", 312, 87); rd.drawString("(To fly longer distances in the air try drifting your car on the ramp", 312, 127); rd.drawString("before take off).", 312, 147); } if (i == 9) { rd.drawString("It\u2019s good to be the king!", 312, 67); } if (i == 10) { rd.drawString("Remember, forward loops give your car a push forwards in the air", 312, 67); rd.drawString("and help in racing.", 312, 87); rd.drawString("(You may need to do more forward loops here. Also try keeping", 312, 127); rd.drawString("your power at maximum at all times. Try not to miss a ramp).", 312, 147); } if (i == 12) { rd.drawString("Watch out! Beware! Take care!", 312, 67); rd.drawString("MASHEEN is hiding out there some where, don't get mashed now!", 312, 87); } if (i == 13) { rd.drawString("Anyone for a game of Digger?!", 312, 67); rd.drawString("You can have fun using MASHEEN here!", 312, 87); } if (i == 16) { rd.drawString("This is it! This is the toughest stage in the game!", 312, 67); rd.drawString("This track is actually a 4D object projected onto the 3D world.", 312, 107); rd.drawString("It's been broken down, separated and, in many ways, it is also a", 312, 127); rd.drawString("maze! GOOD LUCK!", 312, 147); } } rd.drawImage(loadingmusic, 0, 0 + byte0, null); rd.setFont(new Font("SansSerif", 1, 11)); FontHandler.fMetrics = rd.getFontMetrics(); if (!flag) { drawcs(415 + byte0, "" + sndsize[i - 1] + " KB", 0, 0, 0, 3); drawcs(450 + byte0, " Please Wait...", 0, 0, 0, 3); } else { drawcs(440 + byte0, "Loading complete! Press Start to begin...", 0, 0, 0, 3); rd.drawImage(star[pstar], 409, 460 + byte0, null); if (pstar != 2) { if (pstar == 0) { pstar = 1; } else { pstar = 0; } } } } private Image loadopsnap(Image image, int i, int j) { int k = image.getHeight(ob); int l = image.getWidth(ob); int ai[] = new int[l * k]; PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, l, k, ai, 0, l); try { pixelgrabber.grabPixels(); } catch (InterruptedException _ex) { } int i1 = 0; if (j == 1) { i1 = ai[61993]; } for (int j1 = 0; j1 < l * k; j1++) { if (ai[j1] != ai[j]) { Color color = new Color(ai[j1]); int k1 = 0; int l1 = 0; int i2 = 0; if (j == 1 && ai[j1] == i1) { k1 = (int) (237F - 237F * (m.snap[0] / (150F * hipno[i - 1]))); if (k1 > 255) { k1 = 255; } if (k1 < 0) { k1 = 0; } l1 = (int) (237F - 237F * (m.snap[1] / (150F * hipno[i - 1]))); if (l1 > 255) { l1 = 255; } if (l1 < 0) { l1 = 0; } i2 = (int) (237F - 237F * (m.snap[2] / (150F * hipno[i - 1]))); if (i2 > 255) { i2 = 255; } if (i2 < 0) { i2 = 0; } if (i == 1) { k1 = 250; l1 = 250; i2 = 250; } } else { k1 = (int) (color.getRed()- color.getRed() * (m.snap[0] / (50F * hipno[i - 1]))); if (k1 > 255) { k1 = 255; } if (k1 < 0) { k1 = 0; } l1 = (int) (color.getGreen() - color.getGreen() * (m.snap[1] / (50F * hipno[i - 1]))); if (l1 > 255) { l1 = 255; } if (l1 < 0) { l1 = 0; } i2 = (int) (color.getBlue() - color.getBlue() * (m.snap[2] / (50F * hipno[i - 1]))); if (i2 > 255) { i2 = 255; } if (i2 < 0) { i2 = 0; } if (i == 1) { k1 = color.getRed(); l1 = color.getGreen(); i2 = color.getBlue(); } } Color color1 = new Color(k1, l1, i2); ai[j1] = color1.getRGB(); } } Image image1 = createImage(new MemoryImageSource(l, k, ai, 0, l)); return image1; } /** * returns an audioclip * @param s name of clip * @return the new audio clip */ private AudioClip getSound(String s) { return Applet.newAudioClip(getClass().getResource(s)); } int time; float speed; DecimalFormat dc = new DecimalFormat("00"); String getTime (long millis) { long cent = (millis%1000)/10; int secs = (int)((millis/1000)%60); int mins = (int)((millis/1000)/60); return dc.format(mins) + ":" + dc.format(secs) + "." + dc.format(cent); } //DecimalFormat dc = new DecimalFormat(""); //String getSpeed (float speed) { //return dc.format(speed) + ":" + dc.format(secs) + "." + dc.format(cent); //} }
true
86f9b2330f282881102a5f5054e671b9e3b5ce34
Java
oooJerry/dibaidanche
/DBDC/app/src/main/java/com/wuwutongkeji/dibaidanche/common/util/TextUtil.java
UTF-8
2,745
2.6875
3
[]
no_license
package com.wuwutongkeji.dibaidanche.common.util; import android.text.TextUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Mr.Bai on 2016/4/13. */ public class TextUtil { /** * 是否为空 * * @param value * @return */ public static boolean isEmpty(String value) { return TextUtils.isEmpty(value); } /**** * 检查手机号 * * 正确返回 true , 错误返回 false */ public static boolean isCheckPhone(String mobile){ String pattern = "^1(3|4|5|7|8)\\d{9}$"; return mobile.matches(pattern); } public static String getThumbPhone(String phone){ return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"); } public static boolean checkNikeName(String nikeName){ String pattern = "[\\u4e00-\\u9fa5a-zA-Z0-9\\-\\_]{1,16}"; return nikeName.matches(pattern); } /*** * 分转换元 * @param penny * @return */ public static String getMoneyByPenny(long penny){ return getMoneyByPenny(penny,"%.2f"); } public static String getMoneyByPenny(long penny,String patten){ return String.format(patten,penny / 100f); } /** * 15位和18位身份证号码的基本数字和位数验校 * * @param idcard * @return */ public static boolean isIdcard(String idcard) { return is15Idcard(idcard) || is18Idcard(idcard); } /** * 15位身份证号码的基本数字和位数验校 * * @param idcard * @return */ public static boolean is15Idcard(String idcard) { return idcard == null || "".equals(idcard) ? false : Pattern.matches( "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$", idcard); } /** * 18位身份证号码的基本数字和位数验校 * * @param idcard * @return */ public static boolean is18Idcard(String idcard) { return Pattern .matches( "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([\\d|x|X]{1})$", idcard); } public static String getScanCode(String url){ if(TextUtil.isEmpty(url)){ return null; } if(!(url.contains("dibaibike.com") || url.contains("angledog.net"))){ return null; } String[] codes = url.split("/"); if(codes.length == 0){ return null; } String regEx="[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(codes[codes.length - 1]); return m.replaceAll("").trim(); } }
true
7d42f88483fa52948a4004dbeb45974d93ac6335
Java
ilumer/AlgTest
/src/alg4/directedgraphs/TransitiveClosure.java
UTF-8
447
3.140625
3
[]
no_license
package alg4.directedgraphs; /** * Created by ilumer on 17-5-19. * 如何判断图中任意两点是否是可达的 */ public class TransitiveClosure { DirectedDFS[] directedDfs; public TransitiveClosure(Digraph G) { directedDfs = new DirectedDFS[G.V()]; for (int i = 0 ; i < G.V();i++){ directedDfs[i] = new DirectedDFS(G,i); } } public boolean reachable(int v,int w){ return directedDfs[v].marked(w); } }
true
ae63a29609498bb91840ea533987fae532af7b1f
Java
wind-summer/basic
/core/src/main/java/com/basic/core/module/sys/entity/BaseEntity.java
UTF-8
466
1.976563
2
[]
no_license
package com.basic.core.module.sys.entity; import com.baomidou.mybatisplus.activerecord.Model; import com.baomidou.mybatisplus.annotations.TableField; import java.io.Serializable; /** * @author wenlf * @since 2018/4/24 */ public class BaseEntity<T extends Model> extends Model<T> implements Serializable { @TableField("id") private Long id; /** * 主键值 */ @Override protected Serializable pkVal() { return id; } }
true
96e227e8cade5629e35a08235a269b3ad63201e7
Java
CyberPlay1337/CyberPlayJava
/app/src/main/java/ru/startandroid/develop/cyberplayjava/FragmentNades.java
UTF-8
4,935
2.34375
2
[]
no_license
package ru.startandroid.develop.cyberplayjava; import android.content.Context; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. * Use the {@link FragmentNades#newInstance} factory method to * create an instance of this fragment. */ public class FragmentNades extends Fragment { ArrayList<StateMap> states = new ArrayList(); ListView mapList; public FragmentNades() { // Required empty public constructor } public static FragmentNades newInstance() { return new FragmentNades(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_nades, container, false); setInitialData(); mapList = (ListView) root.findViewById(R.id.mapList); // создаем адаптер StateMapAdapter stateAdapter = new StateMapAdapter(root.getContext(), R.layout.list_item_map, states); mapList.setAdapter(stateAdapter); AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // получаем выбранный пункт StateMap selectedState = (StateMap)parent.getItemAtPosition(position); Toast.makeText(getActivity(),"Был выбран пункт " + selectedState.getName(), Toast.LENGTH_SHORT).show(); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fl_content, new FragmentItemNades(selectedState.getName())); fragmentTransaction.commit(); } }; mapList.setOnItemClickListener(itemListener); return root; } @Override public void onAttach(Context context) { super.onAttach(context); } private void setInitialData(){ states.clear(); states.add(new StateMap("Dust 2", R.drawable.de_dust2)); states.add(new StateMap("Inferno", R.drawable.de_inferno)); states.add(new StateMap("Mirage", R.drawable.de_mirage)); states.add(new StateMap("Ancient", R.drawable.de_ancient)); states.add(new StateMap("Overpass", R.drawable.de_overpass)); states.add(new StateMap("Vertigo", R.drawable.de_vertigo)); states.add(new StateMap("Nuke", R.drawable.de_nuke)); } /* // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public FragmentNades() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FragmentNades. */ /* // TODO: Rename and change types and number of parameters public static FragmentNades newInstance(String param1, String param2) { FragmentNades fragment = new FragmentNades(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_nades, container, false); } */ }
true
faa800ff7cb0b74f1ff1dde5eb302de338eb824f
Java
mim321/NichapaWork
/nicha2.java
UTF-8
507
2.828125
3
[]
no_license
class nicha2 { public static void main(String args[]) { String a1 = "nicha"; byte a2 = -17; short a3 = 20; char a4 = 'm'; int a5 = 3456; long a6 = 456l; float a7 = 567.76f; double a8 = 345345.345; System.out.println(a1 + a6); System.out.println(a7 - a8); System.out.println(a4 * a7); System.out.println(a2 / a3); System.out.println(a8 - a4); System.out.println(a6 + a1); System.out.println(a5 / a5); System.out.println(a2 * a2); } }
true
c39632d126d9fbc9c401dde974abbd50f55029b0
Java
WangScaler/jetlinks-community
/jetlinks-manager/authentication-manager/src/main/java/org/jetlinks/community/auth/web/MenuController.java
UTF-8
3,827
2.03125
2
[ "Apache-2.0" ]
permissive
package org.jetlinks.community.auth.web; import io.swagger.v3.oas.annotations.Hidden; import org.hswebframework.web.api.crud.entity.TreeSupportEntity; import org.hswebframework.web.authorization.Authentication; import org.hswebframework.web.authorization.AuthenticationUtils; import org.hswebframework.web.authorization.annotation.Authorize; import org.hswebframework.web.authorization.annotation.Resource; import org.hswebframework.web.authorization.exception.UnAuthorizedException; import org.hswebframework.web.crud.service.ReactiveCrudService; import org.hswebframework.web.crud.web.reactive.ReactiveServiceCrudController; import org.jetlinks.community.auth.entity.MenuEntity; import org.jetlinks.community.auth.service.DefaultMenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; /** * 菜单管理 * @author wangzheng * @since 1.0 */ @RestController @RequestMapping("/menu") @Authorize @Resource(id = "menu", name = "菜单管理", group = "system") @Hidden public class MenuController implements ReactiveServiceCrudController<MenuEntity, String> { @Autowired private DefaultMenuService defaultMenuService; @Override public ReactiveCrudService<MenuEntity, String> getService() { return defaultMenuService; } public Collection<MenuEntity> predicateUserMenu(Map<String, MenuEntity> menuMap, Authentication autz) { Map<String, MenuEntity> group = new HashMap<>(); for (MenuEntity menu : menuMap.values()) { if (group.containsKey(menu.getId())) { continue; } if (autz.getUser().getUsername().equals("admin") || AuthenticationUtils.createPredicate(menu.getPermissionExpression()).test(autz)) { String parentId = menu.getParentId(); MenuEntity parent; group.put(menu.getId(), menu); while (!StringUtils.isEmpty(parentId)) { parent = menuMap.get(parentId); if (parent == null) { break; } parentId = parent.getParentId(); group.put(parent.getId(), parent); } } } List<MenuEntity> list = new ArrayList<>(group.values()); Collections.sort(list); return list; } /** * 获取用户自己的菜单列表 * @return 菜单列表 */ @GetMapping("user-own/tree") @Authorize(merge = false) public Flux<MenuEntity> getUserMenuAsTree() { return Authentication .currentReactive() .switchIfEmpty(Mono.error(UnAuthorizedException::new)) .flatMapMany(autz -> defaultMenuService .createQuery() .fetch() .collect(Collectors.toMap(MenuEntity::getId, Function.identity())) .map(menuMap -> predicateUserMenu(menuMap, autz)) .map(menus -> TreeSupportEntity.list2tree( menus, MenuEntity::setChildren, (Predicate<MenuEntity>) n -> StringUtils.isEmpty(n.getParentId()) || "-1".equals(n.getParentId()))).flatMapMany(Flux::fromIterable)); } }
true
789ce098c60b0fae384ba0530ea427cef1b76ce9
Java
killagu/SoftwareDevelopmentPrinciplesAndPatterns
/com/lianlianDesign/ISP/Timer.java
UTF-8
357
2.4375
2
[]
no_license
package com.lianlianDesign.ISP; import com.lianlianDesign.ISP.TimerClient; public class Timer { public void Register(int timeout,TimerClient client){ for(int i = 0;i< timeout;i++){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } client.timeOut(); } }
true
9d424b6bcf853c3a2c6aa4c7d99911643f08fa7c
Java
zmffjtmxjs/WiFi_Based_Todolist_Application
/app/src/main/java/com/cookandroid/wifi_based_todolist/page/MainActivity.java
UTF-8
4,758
2.359375
2
[]
no_license
package com.cookandroid.wifi_based_todolist.page; import androidx.appcompat.app.AppCompatActivity; import androidx.drawerlayout.widget.DrawerLayout; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import com.cookandroid.wifi_based_todolist.DB.DAO.TodoDB; import com.cookandroid.wifi_based_todolist.DB.DAO.WifiDB; import com.cookandroid.wifi_based_todolist.DB.DTO.Todo; import com.cookandroid.wifi_based_todolist.DB.DTO.Wifi; import com.cookandroid.wifi_based_todolist.R; import com.cookandroid.wifi_based_todolist.module.AlarmSetting; import com.cookandroid.wifi_based_todolist.module.BackgroundService; import com.cookandroid.wifi_based_todolist.module.CustomAdapter; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { /* TODO * DB 연동하여 할 일 목록(리스트)을 출력 */ /* TODO * 출력된 리스트의 각 항목 왼쪽에 완료 체크 버튼을 생성 및 체크 시 평시에는 보이지 않음 설정 */ /* TODO (우선순위 : 하) 사용자가 원하는 조건(분류)를 선택하여 해당하는 할 일만 출력 */ //ListView private ListView lv_todo; CustomAdapter customAdapter; private FloatingActionButton addToDoButton; private ArrayList<Todo> todos; private TodoDB todoDB; ImageView sideBarButton; DrawerLayout sideBarDrawer; Button SetWiFiButton; //DB부분 추가 private WifiDB wifiDB; protected void onResume() { super.onResume(); //ListView에 할 일목록 가져오기 todoDB = new TodoDB(this); todos = todoDB.getTodoList("all"); customAdapter = new CustomAdapter(todos,this); //ListView 등록 lv_todo = findViewById(R.id.lv_todo); lv_todo.setAdapter(customAdapter); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //백그라운드 서비스 계속 작동시키기 Intent intent = new Intent( getApplicationContext(), BackgroundService.class); startService(intent);// 백그라운드 서비스 "BackgroundService"를 시작합니다. 일단 어플이 시작되면 멈추지 않습니다.onStartCommand()가 실행됩니다. //알람 설정하기 Intent intent2 = new Intent( getApplicationContext(), AlarmSetting.class); startService(intent2); //ImageView 등록 sideBarButton = (ImageView) findViewById(R.id.sideBarButton); //DrawerLayout 등록 sideBarDrawer = (DrawerLayout) findViewById(R.id.drawerLayout); //FloatingActionButton 등록 addToDoButton = (FloatingActionButton) findViewById(R.id.addToDoButton); //Button 등록 SetWiFiButton = (Button) findViewById(R.id.goSetWiFi); //사이드 메뉴 버튼 터치 시 사이드 바 활성화 기능 sideBarButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sideBarDrawer.openDrawer(Gravity.LEFT); } }); //할일 추가 화면 이동 addToDoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), AddToDoActivity.class); startActivity(intent); AddToDoActivity.toDoId = 0; //addTodo에 들어가서 생성할 제목 내용 시간 등을 findView 설정하고 save눌렸을 때(save.setOnclick) insert문에 제목 내용 등 입력하여 저장 -> db에 저장 //UI 쪽에도 표현해야함 -> 어댑터 사용 // // Todo todo = new Todo(); // todo.setContent(ToDoTiTle.getText().toString()); // todo.setMemo(ToDoNote.getText().toString()); // adapter.addItem(item); // lv_todo.smoothScrollToPosition(0); } }); //WiFi 설정 화면 이동 SetWiFiButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), SetWiFiActivity.class); startActivity(intent); } }); } }
true
2ff2421809a2cc9ffe648ba1d4ca41e93747773e
Java
mauriciocoder/sandbox
/src/main/java/com/bon/sand/CrossOver2.java
UTF-8
3,914
3.421875
3
[]
no_license
// CrossOver2 package com.bon.sand; import java.io.IOException; import java.util.*; public class CrossOver2 { static boolean isBalanced(String str) { Stack<Character> tagstack = new Stack<Character>(); boolean isBalanced = false; String s = str.trim(); for(int i = 0; i < s.length(); i++) { if(str.charAt(i) == '<') tagstack.push('<'); if(str.charAt(i) == '>') { if (tagstack.isEmpty()) return isBalanced; else tagstack.pop(); } } if(tagstack.isEmpty()) isBalanced = true; return isBalanced; } /** * Complete the function below. * DO NOT MODIFY anything outside this method. */ static int[] balancedOrNot(String[] expressions, int[] maxReplacements) { List<Integer> result = new ArrayList<>(); if (expressions != null && expressions.length > 0) { for (int i = 0; i < expressions.length; i++) { int maxRepl = maxReplacements[i]; String exp = expressions[i]; if (isBalanced(exp)) { result.add(i, 1); } else { // faz tudo aqui dentro String[] exploded = exp.split(""); int opens = 0; int maxCount = maxRepl; for (int j = 0; j < exploded.length; j++) { if (exploded[j].equalsIgnoreCase("<")) { opens++; } else if (exploded[j].equalsIgnoreCase(">")) { if (opens > 0) { opens--; } else { if (maxCount > 0) { maxCount--; exploded[j] = "<>"; } else { // Nao consegue se tornar balanceada } } } } String join = String.join("", exploded); result.add(isBalanced(join) ? 1 : 0); } } } //System.out.println(result); int[] r = new int[result.size()]; for (int i = 0; i < result.size(); i++) { r[i] = result.get(i); } return r; } /** * DO NOT MODIFY THIS METHOD! */ public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); int[] res; int _expressions_size = 0; _expressions_size = Integer.parseInt(in.nextLine().trim()); String[] _expressions = new String[_expressions_size]; String _expressions_item; for(int _expressions_i = 0; _expressions_i < _expressions_size; _expressions_i++) { try { _expressions_item = in.nextLine(); } catch (Exception e) { _expressions_item = null; } _expressions[_expressions_i] = _expressions_item; } int _maxReplacements_size = 0; _maxReplacements_size = Integer.parseInt(in.nextLine().trim()); int[] _maxReplacements = new int[_maxReplacements_size]; int _maxReplacements_item; for(int _maxReplacements_i = 0; _maxReplacements_i < _maxReplacements_size; _maxReplacements_i++) { _maxReplacements_item = Integer.parseInt(in.nextLine().trim()); _maxReplacements[_maxReplacements_i] = _maxReplacements_item; } res = balancedOrNot(_expressions, _maxReplacements); for(int res_i=0; res_i < res.length; res_i++) { System.out.println(String.valueOf(res[res_i])); } } }
true
87ca3ff82a26fcdfaef501b36467abeaee07d781
Java
254nm/ExploitsX
/src/main/java/me/bait/exploitfixer/util/Update.java
UTF-8
4,716
2.09375
2
[]
no_license
/* * .. _____________________ .. * -- // WARNING \\ -- * -- THIS WORK IS UNDER EXCLUSIVE COPRIGHT FOR BAITCORP LABS. DISTRIBUTION, MODIFICATION, SELLING, OR SHARING WITHOUT EXPLICIT PERMISSION FROM BAITCORP LABS IS STRICTLY PROHIBITED. * -- THIS PROGRAM IS LICENSED FOR MODIFICATION TO AND ONLY TO: "BAITCORP LABS" [FR], "CCHOST PARIS" [FR]. * -- * -- ExploitsX Sebastian Giheta 2019-2020 * .. _____________________ .. * * .. _____________________ .. * ___________ .__ .__ __ ____ ___ _________ .__ __ _________ * \_ _____/__ _________ | | ____ |__|/ |_ _____\ \/ / .__ \_ ___ \| |__ _____ _/ |_ \_ ___ \ ____ * | __)_\ \/ /\____ \| | / _ \| \ __\/ ___/\ / __| |___ / \ \/| | \\__ \\ __\/ \ \/ / _ \ * | \> < | |_> > |_( <_> ) || | \___ \ / \ /__ __/ \ \___| Y \/ __ \| | \ \___( <_> ) * /_______ /__/\_ \| __/|____/\____/|__||__| /____ >___/\ \ |__| \______ /___| (____ /__| \______ /\____/ * \/ \/|__| \/ \_/ \/ \/ \/ \/ * * ExploitsX by Sebastian Giheta, owner of 8b8t.xyz * .. _____________________ .. */ package me.bait.exploitfixer.util; import me.bait.exploitfixer.exploitfixer; import org.bukkit.Server; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import java.io.*; public class Update { public static File NewConfig; public static File NewLists; public static File dataFolder; public static void checkUpdates() { dataFolder = exploitfixer.getPlugin().getDataFolder(); Server server = exploitfixer.getPlugin().getServer(); FileConfiguration config = exploitfixer.getPlugin().getConfig(); YamlConfiguration cfgold = YamlConfiguration.loadConfiguration(new InputStreamReader(exploitfixer.getPlugin().getResource("config.yml"))); YamlConfiguration cfyml = YamlConfiguration.loadConfiguration(new InputStreamReader(exploitfixer.getPlugin().getResource("lists.yml"))); NewLists = new File(dataFolder, "listsupdate.txt"); if (CH.getInt("listsymlversion", 0) < cfyml.getInt("listsymlversion")) { server.getLogger().warning("ExploitsX > Lists file out of date. Please look at the new lists file (listsipdate.yml) and compare the variables to see what's missing in order to fix it. Change the last line in the config 'version' to the new version described in listsupdate.yml to disable this message."); NewLists.getParentFile().mkdirs(); copy(exploitfixer.getPlugin().getResource("lists.yml"), NewLists); } else if (CH.getInt("listsymlversion") > cfyml.getInt("listsymlversion")) { server.getLogger().warning("ExploitsX > Future Lists file found. Are you a time traveller? I hope not... I created listsupdate.yml so you can see if you're missing anything this version needs."); NewLists.getParentFile().mkdirs(); copy(exploitfixer.getPlugin().getResource("lists.yml"), NewLists); } else { File cl2 = new File("plugins/ExploitsX/listsupdate.txt"); if (cl2.exists()) cl2.delete(); if (CH.getInt("logging-level") > 0) API.println(API.getPrefix() + "lists.yml is up to date"); } NewConfig = new File(dataFolder, "configupdate.txt"); if (config.getInt("confversion") < cfgold.getInt("confversion")) { server.getLogger().warning("ExploitsX > Config out of date. Please look at the new config file and compare the variables to see what's missing in order to fix it. Change the last line in the config to the new version described in configupdate.yml to disable this message."); NewConfig.getParentFile().mkdirs(); copy(exploitfixer.getPlugin().getResource("config.yml"), NewConfig); } else if (config.getInt("confversion") > cfgold.getInt("confversion")) { server.getLogger().warning("ExploitsX > Future config found. Are you a time traveller? I hope not... I created configupdate.yml so you can see if you're missing anything this version needs."); NewConfig.getParentFile().mkdirs(); copy(exploitfixer.getPlugin().getResource("config.yml"), NewConfig); } else { File cl2 = new File("plugins/ExploitsX/configupdate.txt"); if (cl2.exists()) cl2.delete(); if (CH.getInt("logging-level") > 0) API.println(API.getPrefix() + "config.yml is up to date"); } } private static void copy(InputStream in, File file) { try { OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } }
true
9490c281c3a8ff826c5f29a02fb75fcaad9e48ec
Java
Rexben001/Rexy
/app/src/main/java/com/android/rexben/rexy/Quiz4.java
UTF-8
3,967
2.671875
3
[]
no_license
package com.android.rexben.rexy; import android.content.Intent; import android.support.annotation.IdRes; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.RadioGroup; import android.widget.Toast; public class Quiz4 extends AppCompatActivity { private int score = 0; private int points = 0; private int newScore; private int newPoints; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz4); // Casting views by ResourceID RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGrp); Intent intent = getIntent(); final int mScore = intent.getIntExtra("score", 0); //Getting the score from the previous activity final int mPoints = intent.getIntExtra("points", 0); //Getting the score from the previous activity /* * If radioButton6 is checked, the toast message shows Corroect * 5 is added to the score and the user is taken to the * next question */ radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) { String answer = getString(R.string.answer_4); //answer switch (i) { case R.id.radioButton4: // Toast message display "wrong" and the right answer and takes the user to the next quesstion Toast toast = Toast.makeText(getApplicationContext(), "Wrong " + "\n Answer is: " +answer, Toast.LENGTH_SHORT); toast.show(); newScore = mScore + score; //Update score newPoints = mPoints + points; //Update points Intent intent0 = new Intent(getApplicationContext(), Quiz5.class); intent0.putExtra("score", newScore); //Send the updated score to the next activity intent0.putExtra("points", newPoints); //Send the updated points to the next activity startActivity(intent0); break; case R.id.radioButton5: // Toast message display "wrong" and the right answer and takes the user to the next quesstion Toast toast1 = Toast.makeText(getApplicationContext(), "Wrong." + "\n Answer is: " + answer, Toast.LENGTH_SHORT); toast1.show(); newScore = mScore + score; newPoints = mPoints + points; Intent intent1 = new Intent(getApplicationContext(), Quiz5.class); intent1.putExtra("score", newScore); intent1.putExtra("points", newPoints); startActivity(intent1); break; case R.id.radioButton6: //Toast message displays "Correct" //Update score with 1 //Update points with 5 score += 1; newScore = mScore + score; points += 5; newPoints = mPoints + points; Toast toast2 = Toast.makeText(getApplicationContext(), "Correct ", Toast.LENGTH_SHORT); toast2.show(); Intent intent2 = new Intent(getApplicationContext(), Quiz5.class); //send the new score and points to the next activity intent2.putExtra("score", newScore); intent2.putExtra("points", newPoints); startActivity(intent2); break; } } }); } }
true
00bd16677eecd3746e38eb8823412fa8e8be4ec1
Java
KrunalKaneriya/JavaProgramming
/Keywords Expressions Codeblocks And Methods/methodOverloading/src/Main.java
UTF-8
1,941
3.515625
4
[]
no_license
public class Main { public static void main(String[] args) { // int newScore = calculateScore("Krunal",500); //// System.out.println("New Score is "+newScore); // calculateScore(newScore); // calculateScore(); // public static int calculateScore(String playerName,int score) { // System.out.println("Player " + playerName + " scored " + score + " points "); // return score*10 ; // } // // public static int calculateScore(int score) { // System.out.println("Unnamed Player" + " scored " + score + " points "); // return score*1000 ; // } // // public static int calculateScore() { // System.out.println("No Player name ,no player score." ); // return 0; double centimeters = calcFeetAndInchesToCentimeters(-157); if(centimeters<0) { System.out.println("Invalid Parameters"); } } public static double calcFeetAndInchesToCentimeters (double feet,double inches) { if ((feet < 0) || (inches < 0 || inches > 12)) { System.out.println("Invalid Feet Or Inches Parameters"); return -1; } else { double feetAndInchestoCm = (feet * 30.48) + (inches * 2.54); System.out.println(feet + " Feet ,"+ inches + " Inches = "+feetAndInchestoCm + " Centimeters"); return feetAndInchestoCm; } } public static double calcFeetAndInchesToCentimeters(double inches) { if(inches<0) { return -1; } else { double feet = inches / 12; double randomCentimeter = calcFeetAndInchesToCentimeters(feet, inches); System.out.println("The Conversion of Inches: " + inches + " is feet: " + feet); return randomCentimeter; } } }
true
690049a4bbbf2e61fcccfd0eea5dfcda6c443f16
Java
XM-XiaoMa/DemoRetrofit
/app/src/main/java/com/example/MainActivity.java
UTF-8
1,362
2.140625
2
[]
no_license
package com.example; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.example.mabaochang.component_base.R; import com.example.manager.AppManager; import com.example.manager.HttpManager; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.main_list_btn).setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.main_list_btn: HttpManager.getInstance(AppManager.getInstance().getApp()).getMainList(0, new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { String a = ""; } @Override public void onFailure(Call<String> call, Throwable t) { String a = ""; } }); break; } } }
true
aa9b41474674aff151252845187d7ef8f96c5191
Java
csabatini/daggermvpstarter
/app/src/main/java/com/csab/daggermvpstarter/mvp/view/NoteDialogView.java
UTF-8
163
1.601563
2
[]
no_license
package com.csab.daggermvpstarter.mvp.view; public interface NoteDialogView { void createDialog(); void dismissDialog(); String captureInputText(); }
true
cdea8b2c1456ab18f9fa147511d10f01402b4949
Java
roudane1994/PFE_Master_Big_Data
/rachid/src/main/java/ocp/sta4/Service.java
UTF-8
885
2.1875
2
[]
no_license
package ocp.sta4; import java.util.Set; public class Service { private String id; private String nom; private String email; private String tele; private String address; private String specialite; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTele() { return tele; } public void setTele(String tele) { this.tele = tele; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getSpecialite() { return specialite; } public void setSpecialite(String specialite) { this.specialite = specialite; } }
true
c26546ffe7d13e94e322a7205c30040b9cad2596
Java
thymargo13/Java-OOP
/Combined_CFD/CFDress/src/java/cfd/db/AddressBook_DB.java
UTF-8
6,248
2.640625
3
[]
no_license
package cfd.db; import cfd.bean.CustomerAddressBean; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; /** * * @author Daniel */ public class AddressBook_DB { private String url, username, password; public AddressBook_DB(String url, String username, String password) { this.url = url; this.username = username; this.password = password; } public Connection getConnection() throws SQLException, IOException { System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver"); return DriverManager.getConnection(url, username, password); } public boolean addUserAddress(String id, String address) { // insert method 2 by system min requirement informarion Connection conn = null; PreparedStatement preStatement = null; boolean isSuccess = false; try { conn = getConnection(); String sql = "insert into AddressBook (cid, address)values(?,?)"; preStatement = conn.prepareStatement(sql); preStatement.setString(1, id); preStatement.setString(2, address); int rowsNum = preStatement.executeUpdate(); if (rowsNum >= 1) { isSuccess = true; } preStatement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return isSuccess; } public List<CustomerAddressBean> getAddressesByCustomer(String id) { Connection conn = null; PreparedStatement preStatement = null; List<CustomerAddressBean> list = null; String sql = ""; try { list = new LinkedList<CustomerAddressBean>(); conn = getConnection(); sql = "select * from AddressBook where cid = ?"; preStatement = conn.prepareStatement(sql); preStatement.setString(1, id); ResultSet rs = preStatement.executeQuery(); while (rs.next()) { int aid = rs.getInt(1); String address = rs.getString(2); String cid = rs.getString(3); String status = rs.getString(4); //custBean.setStatus(rs.getString(12)); CustomerAddressBean cab = new CustomerAddressBean(aid, cid, address, status); list.add(cab); } preStatement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return list; } public List<CustomerAddressBean> getValidAddressesByCustomer(String id, String status) { Connection conn = null; PreparedStatement preStatement = null; List<CustomerAddressBean> list = null; String sql = ""; try { list = new LinkedList<CustomerAddressBean>(); conn = getConnection(); sql = "select * from AddressBook where cid = ? and status = ?"; preStatement = conn.prepareStatement(sql); preStatement.setString(1, id); preStatement.setString(2, status); ResultSet rs = preStatement.executeQuery(); while (rs.next()) { int aid = rs.getInt(1); String address = rs.getString(2); String cid = rs.getString(3); String status_db = rs.getString(4); //custBean.setStatus(rs.getString(12)); CustomerAddressBean cab = new CustomerAddressBean(aid, cid, address, status_db); list.add(cab); } preStatement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return list; } public boolean isDuplicateAddress(String id, String address) { Connection conn = null; PreparedStatement preStatement = null; boolean isDuplicate = false; try { conn = getConnection(); String sql = "select count(*) from AddressBook where cid = ? and address = ?"; preStatement = conn.prepareStatement(sql); preStatement.setString(1, id); preStatement.setString(2, address); ResultSet rs = preStatement.executeQuery(); rs.next(); System.out.print(rs.getInt(1)); if (rs.getInt(1) > 0) { isDuplicate = true; } preStatement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return isDuplicate; } public boolean updateUserAddress(String aid, String address) { Connection conn = null; PreparedStatement preStatement = null; boolean isSuccess = false; try { conn = getConnection(); String sql = "update AddressBook set address = ? where aid = ?"; preStatement = conn.prepareStatement(sql); preStatement.setString(2, aid); preStatement.setString(1, address); int rowsNum = preStatement.executeUpdate(); if (rowsNum >= 1) { isSuccess = true; } preStatement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return isSuccess; } public boolean removeUserAddress(int aid) { Connection conn = null; PreparedStatement preStatement = null; boolean isSuccess = false; try { conn = getConnection(); String sql = "delete from AddressBook where aid = ?"; preStatement = conn.prepareStatement(sql); preStatement.setInt(1, aid); int rowsNum = preStatement.executeUpdate(); if (rowsNum >= 1) { isSuccess = true; } preStatement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return isSuccess; } }
true
05c6e01da1e6630e593c79da8dce7dc904fed3fa
Java
devlopper/org.cyk.system.sibua.client
/sibua-client-controller-impl/src/main/java/org/cyk/system/sibua/client/controller/impl/user/UserActivatePage.java
UTF-8
1,705
2.0625
2
[]
no_license
package org.cyk.system.sibua.client.controller.impl.user; import java.io.Serializable; import javax.faces.view.ViewScoped; import javax.inject.Named; import org.cyk.system.sibua.client.controller.api.user.UserController; import org.cyk.system.sibua.client.controller.entities.user.User; import org.cyk.utility.__kernel__.properties.Properties; import org.cyk.utility.__kernel__.string.StringHelper; import org.cyk.utility.__kernel__.system.action.SystemActionCustom; import org.cyk.utility.client.controller.component.command.Commandable; import org.cyk.utility.client.controller.component.command.CommandableBuilder; import lombok.Getter; import lombok.Setter; @Named @ViewScoped @Getter @Setter public class UserActivatePage extends AbstractUserPage implements Serializable { private static final long serialVersionUID = 1L; private Commandable activateCommandable; @Override protected void __listenPostConstruct__() { super.__listenPostConstruct__(); CommandableBuilder createCommandableBuilder = __inject__(CommandableBuilder.class); createCommandableBuilder.setName("Activer").setCommandFunctionActionClass(SystemActionCustom.class).addCommandFunctionTryRunRunnable( new Runnable() { @Override public void run() { create(); } } ); activateCommandable = createCommandableBuilder.execute().getOutput(); } @Override protected String __getWindowTitleValue__() { return "Activation de fiche d'identification"; } public void create() { if(StringHelper.isBlank(user.getActivationDate())) __inject__(UserController.class).update(user,new Properties().setFields(User.FIELD_ACTIVATION_DATE)); } }
true
41f22324fc077e26068adb2eb0e310d237189f2a
Java
meghanacs277/Meghana
/Exception1/TestExam.java
UTF-8
2,589
3.015625
3
[]
no_license
import java.util.Scanner; public class TestExam { public static void main(String []ar) { Scanner sc=new Scanner(System.in); System.out.println("Enter the choice :hallticket,idcard,pen,copy,calculator"); String a=sc.nextLine(); switch(a) { case "hallticket": System.out.println("type yes if hallticket is present and type no"); String b=sc.nextLine(); try { if(b.equals("yes")) { System.out.println("can attend exam"); } else { throw new ExamException("can not attend exam"); } }catch(ExamException e) { System.err.println(e.getMessage()); } break; case "idcard": System.out.println("type yes if idcard is present and type no"); String c=sc.nextLine(); try { if(c.equals("yes")) { System.out.println("can attend exam"); } else { throw new ExamException("can not attend exam"); } }catch(ExamException e) { System.err.println(e.getMessage()); } break; case "pen": System.out.println("type yes if idcard is present and else type no"); String d=sc.nextLine(); try { if(d.equals("yes")) { System.out.println("can attend exam"); } else { throw new ExamException("can not attend exam"); } }catch(ExamException e) { System.err.println(e.getMessage()); } break; case "copy": System.out.println("type yes if copy is present and else type no"); String f=sc.nextLine(); try { if(f.equals("yes")) { System.out.println("cannot attend exam"); } else { throw new ExamException("can attend exam"); } }catch(ExamException e) { System.err.println(e.getMessage()); } break; case "calculator": System.out.println("type yes if calculator is present and else type no"); String g=sc.nextLine(); try { if(g.equals("yes")) { System.out.println("can attend exam"); } else { throw new ExamException("can not attend exam"); } }catch(ExamException e) { System.err.println(e.getMessage()); } break; case "vaccinated": System.out.println("type yes if vaccinated is present and else type no"); String h=sc.nextLine(); try { if(h.equals("yes")) { System.out.println("can attend exam"); } else { throw new ExamException("can not attend exam"); } }catch(ExamException e) { System.err.println(e.getMessage()); } break; } } }
true
a20fe27cacf05566d3516a467b8c6df739d077ec
Java
JetBrains/intellij-community
/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyNodeDescriptor.java
UTF-8
5,157
2.015625
2
[ "Apache-2.0" ]
permissive
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.hierarchy.method; import com.intellij.icons.AllIcons; import com.intellij.ide.hierarchy.HierarchyNodeDescriptor; import com.intellij.ide.hierarchy.JavaHierarchyUtil; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ui.util.CompositeAppearance; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Iconable; import com.intellij.psi.*; import com.intellij.psi.presentation.java.ClassPresentationUtil; import com.intellij.ui.IconManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; public final class MethodHierarchyNodeDescriptor extends HierarchyNodeDescriptor { private Icon myRawIcon; private Icon myStateIcon; private MethodHierarchyTreeStructure myTreeStructure; MethodHierarchyNodeDescriptor(@NotNull Project project, HierarchyNodeDescriptor parentDescriptor, @NotNull PsiElement aClass, boolean isBase, @NotNull MethodHierarchyTreeStructure treeStructure) { super(project, parentDescriptor, aClass, isBase); myTreeStructure = treeStructure; } public void setTreeStructure(MethodHierarchyTreeStructure treeStructure) { myTreeStructure = treeStructure; } @Nullable PsiMethod getMethod(PsiClass aClass, boolean checkBases) { try { return MethodHierarchyUtil.findBaseMethodInClass(myTreeStructure.getBaseMethod(), aClass, checkBases); } catch (IndexNotReadyException e) { return null; } } public PsiElement getPsiClass() { return getPsiElement(); } /** * Element for OpenFileDescriptor */ public PsiElement getTargetElement() { PsiElement element = getPsiClass(); if (!(element instanceof PsiClass)) return element; PsiClass aClass = (PsiClass)getPsiClass(); if (!aClass.isValid()) return null; PsiMethod method = getMethod(aClass, false); if (method != null) return method; return aClass; } @Override public boolean update() { int flags = Iconable.ICON_FLAG_VISIBILITY; if (isMarkReadOnly()){ flags |= Iconable.ICON_FLAG_READ_STATUS; } boolean changes = super.update(); PsiElement psiClass = getPsiClass(); if (psiClass == null){ return invalidElement(); } Icon newRawIcon = psiClass.getIcon(flags); Icon newStateIcon = psiClass instanceof PsiClass ? calculateState((PsiClass)psiClass) : AllIcons.Hierarchy.MethodDefined; if (changes || newRawIcon != myRawIcon || newStateIcon != myStateIcon) { changes = true; myRawIcon = newRawIcon; myStateIcon = newStateIcon; Icon newIcon = myRawIcon; if (myIsBase) { newIcon = getBaseMarkerIcon(newIcon); } if (myStateIcon != null) { newIcon = IconManager.getInstance().createRowIcon(myStateIcon, newIcon); } setIcon(newIcon); } CompositeAppearance oldText = myHighlightedText; myHighlightedText = new CompositeAppearance(); TextAttributes classNameAttributes = null; if (myColor != null) { classNameAttributes = new TextAttributes(myColor, null, null, null, Font.PLAIN); } if (psiClass instanceof PsiClass) { myHighlightedText.getEnding().addText(ClassPresentationUtil.getNameForClass((PsiClass)psiClass, false), classNameAttributes); myHighlightedText.getEnding().addText(" (" + JavaHierarchyUtil.getPackageName((PsiClass)psiClass) + ")", HierarchyNodeDescriptor.getPackageNameAttributes()); } else if (psiClass instanceof PsiFunctionalExpression) { myHighlightedText.getEnding().addText(ClassPresentationUtil.getFunctionalExpressionPresentation((PsiFunctionalExpression)psiClass, false)); } myName = myHighlightedText.getText(); if (!Comparing.equal(myHighlightedText, oldText)) { changes = true; } return changes; } private Icon calculateState(PsiClass psiClass) { PsiMethod method = getMethod(psiClass, false); if (method != null) { if (method.hasModifierProperty(PsiModifier.ABSTRACT)) { return null; } return AllIcons.Hierarchy.MethodDefined; } if (myTreeStructure.isSuperClassForBaseClass(psiClass)) { return AllIcons.Hierarchy.MethodNotDefined; } boolean isAbstractClass = psiClass.hasModifierProperty(PsiModifier.ABSTRACT); // was it implemented is in superclasses? PsiMethod baseClassMethod = getMethod(psiClass, true); boolean hasBaseImplementation = baseClassMethod != null && !baseClassMethod.hasModifierProperty(PsiModifier.ABSTRACT); if (hasBaseImplementation || isAbstractClass) { return AllIcons.Hierarchy.MethodNotDefined; } else { return AllIcons.Hierarchy.ShouldDefineMethod; } } }
true
8098fdf795e734d0037bd9c4349e2131e4947b66
Java
ScreamHyy/anyidianManager
/src/com/anyidian/controller/ManagerController.java
UTF-8
7,257
2.140625
2
[]
no_license
package com.anyidian.controller; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import net.sf.json.JSONObject; import com.anyidian.dao.ManagerDao; import com.anyidian.dao.UserDao; import com.anyidian.model.Manager; import com.anyidian.model.Menu; import com.anyidian.model.MenuTree; import com.anyidian.model.PageBean; import com.anyidian.model.Role; import com.anyidian.model.TopBanner; import com.anyidian.util.DBManager; import com.anyidian.util.ResponseUtil; import com.anyidian.util.StringUtil; import com.google.gson.Gson; @Controller public class ManagerController { private Manager manager; private List<Manager> mList; private String json; DBManager dbManager = new DBManager(); @Autowired ManagerDao managerDao = new ManagerDao(); public ManagerDao getManagerDao() { return managerDao; } public void setManagerDao(ManagerDao managerDao) { this.managerDao = managerDao; } private Connection con; private int flagNums; @RequestMapping(value = "/updatePwd") public void updatePwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); request.setCharacterEncoding("utf-8"); String newpwd = request.getParameter("newpwd"); String oldpwd = request.getParameter("oldpwd"); String username = (String) session.getAttribute("username"); try { con = dbManager.getCon(); JSONObject result = new JSONObject(); flagNums = managerDao.updatePwd(con, username, oldpwd, newpwd); if (flagNums > 0) { result.put("success", "true"); } else { result.put("errorMsg", "密码错误"); } ResponseUtil.write(response, result); } catch (Exception e) { e.printStackTrace(); } finally { try { dbManager.closeCon(con); } catch (Exception e) { e.printStackTrace(); } } } @RequestMapping(value = "/managerList") public void managerList(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("utf-8"); String rows = request.getParameter("rows"); String page = request.getParameter("page"); PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows)); mList = new ArrayList<Manager>(); mList = managerDao.managerList(pageBean); json = new Gson().toJson(mList); JSONObject result = new JSONObject(); int total = mList.size(); result.put("rows", json); result.put("total", total); ResponseUtil.write(response, result); } @RequestMapping(value="/authorization") public void authorization(HttpServletRequest request, HttpServletResponse response) throws Exception{ request.setCharacterEncoding("UTF-8"); String id = request.getParameter("listId"); int rid = Integer.parseInt(request.getSession().getAttribute("rid").toString()); manager = new Manager(); if(StringUtil.isNotEmpty(id)){ manager.setId(Integer.parseInt(id)); } boolean success = managerDao.updateState(manager); JSONObject result = new JSONObject(); if (success) { result.put("success", "操作成功!"); } else { result.put("errorMsg", "服务器内部错误"); } ResponseUtil.write(response, result); } @RequestMapping(value="/addManager") public ModelAndView addTopBannerInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{ request.setCharacterEncoding("UTF-8"); Map model = new HashMap(); ModelAndView mav = new ModelAndView("addManager",model); return mav; } @RequestMapping(value="/addRole") public ModelAndView addRoleInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{ request.setCharacterEncoding("UTF-8"); Map model = new HashMap(); ModelAndView mav = new ModelAndView("addRole",model); return mav; } @SuppressWarnings("unused") @RequestMapping(value="/getAllMenu") public void getAllMenu(HttpServletRequest request, HttpServletResponse response) throws Exception{ request.setCharacterEncoding("UTF-8"); int rid = Integer.parseInt(request.getSession().getAttribute("rid").toString()); List<Menu> mList = new ArrayList<Menu>(); mList = managerDao.getAllMenu(); List<MenuTree> tList = new ArrayList<MenuTree>(); tList = managerDao.menuToTree(mList); json = new Gson().toJson(tList); System.out.println(json); ResponseUtil.write(response, json); } @RequestMapping(value="/saveManager") public void saveManager(HttpServletRequest request, HttpServletResponse response) throws Exception{ request.setCharacterEncoding("UTF-8"); String username = request.getParameter("uname"); String password = request.getParameter("password"); String rname = request.getParameter("rname"); String mobile = request.getParameter("mobile"); JSONObject result = new JSONObject(); Role role = new Role(); manager = new Manager(); if(StringUtil.isNotEmpty(username)){ manager.setUsername(username); } if(StringUtil.isNotEmpty(password)){ manager.setPassword(password); } if(StringUtil.isNotEmpty(mobile)){ manager.setMobile(mobile); } if(StringUtil.isNotEmpty(rname)){ role.setRname(rname); } boolean success = managerDao.addManager(manager) && managerDao.addRole(role); if (success) { result.put("success", "添加成功!"); } else { result.put("errorMsg", "添加失败!"); } ResponseUtil.write(response, result); } @RequestMapping(value="/addUserRole") public void addRole(HttpServletRequest request, HttpServletResponse response) throws Exception{ request.setCharacterEncoding("UTF-8"); String str = request.getParameter("str"); for(int i = 0; i< 5;i++){ int y = i+1; str+=","+y; } String a[] = str.split(","); boolean success = false; for(int i = 0; i<a.length;i++){ success = managerDao.addRoleAndUser(a[i]); } JSONObject result = new JSONObject(); if(success){ result.put("success", "添加成功!"); }else{ result.put("errorMsg", "添加失败!"); } ResponseUtil.write(response,result); } /** * * 删除 * * @author ScreamHyy * @param request * @param response * @return * @throws Exception * **/ @RequestMapping(value="/deleteManager") public void deleteNewStatus(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("UTF-8"); String delIds = request.getParameter("delIds"); JSONObject result = new JSONObject(); boolean deleteInfo = managerDao.deleteData(delIds); if (deleteInfo) { result.put("success", "删除成功"); } else { result.put("errorMsg", "服务器内部错误"); } ResponseUtil.write(response, result); } }
true
d4f382dec01cc06c67245a1c3700580575963873
Java
clagms/TrNet
/TrNetCompilation/test-src/activitymigrationgeneratedfromdsltransoriginal/TrNetPat249InstancePublisher.java
UTF-8
235
1.601563
2
[]
no_license
package activitymigrationgeneratedfromdsltransoriginal; public interface TrNetPat249InstancePublisher{ public void registerListener(TrNetPat249InstanceListener listener); public void notifyListeners(TrNetPat249Instance element); }
true
a5db86e35792ef86a9288f06bd643d337d1440a1
Java
duythien24/Android_lab3
/src/bai5/Conection/ConnectionJDBC.java
UTF-8
747
2.640625
3
[]
no_license
package bai5.Conection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionJDBC { public static Connection getKetNoi() { Connection ketNoi = null; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url = "jdbc:sqlserver://localhost:1433;databaseName=CartBean"; try { ketNoi = DriverManager.getConnection(url, "sa", "sapassword"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Kết nối cơ sở dữ liệu thành công!!!"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ketNoi; } }
true
d1b049a52f143887d4a88325cb869fe8aaf876de
Java
Satkeev/codefellowship
/src/main/java/com/satkeev/codefellowship/Post.java
UTF-8
959
2.21875
2
[]
no_license
package com.satkeev.codefellowship; import javax.persistence.*; import java.util.Date; @Entity public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String body; private String createdAt; @ManyToOne private ApplicationUser postedBy; public long getId() { return this.id; } public String getBody() { return this.body; } public String getCreatedAt() { return this.createdAt; } public ApplicationUser getPostedBy() { return this.postedBy; } public void setBody(String body) { this.body = body; } public void setPostedBy(ApplicationUser postedBy) { this.postedBy = postedBy; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public void setId(long id) { this.id = id; } }
true
c4de0487d3bfff7eedec216fc6f357cb02fc27d7
Java
andrey-kravchuk/java_elementary
/src/HomeWork/HomeWork9/Squre.java
UTF-8
500
3.203125
3
[]
no_license
/** * Created by user on 27.07.2017. */ public class Squre implements Shape { private double a; private double b; private String color; Squre(double a, double b, String color){ this.color = color; this.a = a; this.b = b; } @Override public double size(){ double size; size = this.a * this.b; return size; } @Override public EnumColours colour() { return EnumColours.valueOf(color); } }
true
0fe61faa535142471a09db47fa94166c99af6fc2
Java
CnLight/blog
/src/main/java/com/wl/blog/service/admin/PictureService.java
UTF-8
928
1.96875
2
[]
no_license
package com.wl.blog.service.admin; import com.wl.blog.dao.ArticleMapper; import com.wl.blog.dao.PictureMapper; import com.wl.blog.pojo.BlogArticle; import com.wl.blog.pojo.Picture; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class PictureService { @Resource PictureMapper pictureMapper; //查询所有的文章 public List<Picture> findAllPictures() { return pictureMapper.findAllPictures(); } //创建一篇文章 public int addPicture(Picture picture) { pictureMapper.addPicture(picture); return picture.getPictureRowId(); } public int findPictureByPath(String path) { return pictureMapper.findPictureByPath(path); } //查找文章的路径 public String findPicturePathById(int id) { return pictureMapper.findPictureById(id).getPicturePath(); } }
true
e28d86b6b9537384a9aa1925df6d8e985f68c95c
Java
gabrielfeo/DaggerMultibindingLimit
/build/generated/sources/annotationProcessor/java/main/HeavyMultibindingModule_ProvideObject415Factory.java
UTF-8
1,033
1.929688
2
[]
no_license
import dagger.internal.DaggerGenerated; import dagger.internal.Factory; import dagger.internal.Preconditions; import javax.annotation.processing.Generated; @DaggerGenerated @Generated( value = "dagger.internal.codegen.ComponentProcessor", comments = "https://dagger.dev" ) @SuppressWarnings({ "unchecked", "rawtypes" }) public final class HeavyMultibindingModule_ProvideObject415Factory implements Factory<Object> { private final HeavyMultibindingModule module; public HeavyMultibindingModule_ProvideObject415Factory(HeavyMultibindingModule module) { this.module = module; } @Override public Object get() { return provideObject415(module); } public static HeavyMultibindingModule_ProvideObject415Factory create( HeavyMultibindingModule module) { return new HeavyMultibindingModule_ProvideObject415Factory(module); } public static Object provideObject415(HeavyMultibindingModule instance) { return Preconditions.checkNotNullFromProvides(instance.provideObject415()); } }
true
21035c5fbb80302012bd1ac2572b83b5fd12b9b0
Java
Mariano95/Algomon
/Algomon/src/ataque/AtaqueDeAgua.java
UTF-8
285
2.5
2
[]
no_license
package ataque; import excepciones.PokemonSeDebilitoException; import pokemon.Pokemon; public abstract class AtaqueDeAgua extends Ataque { protected double realizarAtaqueContra(Pokemon objetivo) throws PokemonSeDebilitoException{ return objetivo.recibirAtaqueDeAgua(this); } }
true
6b27366d672594ee01edf981630ac07c1da7b2d6
Java
JavaMoney/javamoney-examples
/swing/javamoney-ez/common/src/main/java/org/javamoney/examples/ez/common/utility/I18NHelper.java
UTF-8
4,579
2.890625
3
[ "Apache-2.0" ]
permissive
// I18NHelper package org.javamoney.examples.ez.common.utility; import static org.javamoney.examples.ez.common.utility.ResourceHelper.getResource; import java.net.URL; import java.util.ArrayList; import java.util.Locale; import java.util.Properties; /** * This class facilitates accessing internationalized properties. All methods in * this class are static. */ public final class I18NHelper { /** * This method returns the language being used for loading properties files. * * @return The language being used for loading properties files. */ public static Locale getLanguage() { return itsLanguage; } /** * This method the available languages. * * @return An array of the available languages. */ public static Locale[] getLanguages() { Locale[] languages = { ENGLISH, FINNISH, ITALIAN, PORTUGUESE, RUSSIAN }; return languages; } /** * This method returns a value from the properties. * * @param key The key that references the value. * * @return A value from the properties. */ public static String getProperty(String key) { return PROPERTIES.getProperty(key, DEFAULT_PROPERTY); } /** * This method returns a value from the properties where the key is prefixed * with "shared.". * <p> * <b>Note:</b> It is good practice to use this scheme for properties that are * shared among numerous classes. Otherwise, the protocol is to prefix the key * with the class' simple name. * * @param key The key that references the value. * * @return A value from the properties. */ public static String getSharedProperty(String key) { return getProperty("shared." + key); } /** * This method loads the common properties for the currently set language. */ public static void loadCommonProperties() { loadProperties("org/javamoney/examples/ez/common/i18n/"); } /** * This method reads in the properties file for the currently set language. * <p> * <b>Note:</b> This method is expecting the properties file name to equal * that of the set language's "ISO 639-2/T" code. Example, for English, the * file name would be "eng.properties". * * @param folder The folder that contains the properties files. */ public static void loadProperties(String folder) { try { URL url = getResource(folder + getPropertiesFile()); PROPERTIES.load(url.openStream()); } catch(Exception exception) { // Ignored. } } /** * This method sets the language. * * @param locale The language to use. */ public static void setLanguage(Locale locale) { itsLanguage = locale; } ////////////////////////////////////////////////////////////////////////////// // Start of private methods. ////////////////////////////////////////////////////////////////////////////// private static String getPropertiesFile() { ArrayList<String> languages = new ArrayList<String>(getLanguages().length); String iso3 = getLanguage().getISO3Language(); String file = null; // Add available language properties files. for(Locale locale : getLanguages()) { languages.add(locale.getISO3Language()); } // If the language does not have a properties file, default to English. if(languages.contains(iso3) == true) { file = iso3; } else { file = ENGLISH.getISO3Language(); } return file + ".properties"; } ////////////////////////////////////////////////////////////////////////////// // Start of class members. ////////////////////////////////////////////////////////////////////////////// private static Locale itsLanguage; private static final Properties PROPERTIES = new Properties(); /** * The default value for a property when a key is not found. */ public static final String DEFAULT_PROPERTY = "null"; /** * A constant for the English language. */ public static final Locale ENGLISH = Locale.US; /** * A constant for the Finnish language. */ public static final Locale FINNISH = new Locale("fi", "fi"); /** * A constant for the Italian language. */ public static final Locale ITALIAN = Locale.ITALY; /** * A constant for the Portuguese (Brazil) language. */ public static final Locale PORTUGUESE = new Locale("pt", "br"); /** * A constant for the Russian language. */ public static final Locale RUSSIAN = new Locale("ru", "ru"); }
true
3b337cc1cc6d2676f5b6ed3c13d7784a23b3c45c
Java
1016135097/yoga
/yoga-imessager/src/main/java/com/yoga/imessager/user/model/User.java
UTF-8
1,547
2.21875
2
[]
no_license
package com.yoga.imessager.user.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity(name = "imUser") @Table(name = "im_user") public class User { @Id private Long id; @Column(name = "tenant_id") private Long tenantId; @Column(name = "nickname") private String nickname; @Column(name = "token") private String token; @Column(name = "avatar") private String avatar; public User() { } public User(Long id, Long tenantId, String nickname, String avatar) { this.id = id; this.tenantId = tenantId; if (nickname == null) this.nickname = ""; else this.nickname = nickname; this.avatar = avatar; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getTenantId() { return tenantId; } public void setTenantId(Long tenantId) { this.tenantId = tenantId; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } }
true
f0c1d056843a5a5b02b158c332e66f0a5f77daf6
Java
Braunch/monticore
/monticore-generator/src/main/java/de/monticore/codegen/cd2java/_ast/builder/inheritedmethods/InheritedBuilderOptionalMutatorDecorator.java
UTF-8
2,478
2
2
[]
no_license
/* (c) https://github.com/MontiCore/monticore */ package de.monticore.codegen.cd2java._ast.builder.inheritedmethods; import de.monticore.cd.cd4analysis._ast.ASTCDAttribute; import de.monticore.cd.cd4analysis._ast.ASTCDMethod; import de.monticore.cd.cd4analysis._ast.ASTCDParameter; import de.monticore.codegen.cd2java._ast.builder.buildermethods.BuilderOptionalMutatorDecorator; import de.monticore.generating.templateengine.GlobalExtensionManagement; import de.monticore.generating.templateengine.TemplateHookPoint; import de.monticore.types.mcbasictypes._ast.ASTMCReturnType; import de.monticore.types.mcbasictypes._ast.ASTMCType; import de.monticore.types.mcbasictypes.MCBasicTypesMill; import static de.monticore.cd.facade.CDModifier.PUBLIC; import static de.monticore.codegen.cd2java.CoreTemplates.EMPTY_BODY; /** * changes return type of builder setters for optional attributes */ public class InheritedBuilderOptionalMutatorDecorator extends BuilderOptionalMutatorDecorator { public InheritedBuilderOptionalMutatorDecorator(final GlobalExtensionManagement glex, final ASTMCType builderType) { super(glex, builderType); } @Override protected ASTCDMethod createSetMethod(final ASTCDAttribute attribute) { String name = String.format(SET, naiveAttributeName); ASTMCType parameterType = getDecorationHelper().getReferenceTypeFromOptional(attribute.getMCType()).getMCTypeOpt().get().deepClone(); ASTCDParameter parameter = this.getCDParameterFacade().createParameter(parameterType, attribute.getName()); ASTCDMethod method = this.getCDMethodFacade().createMethod(PUBLIC, name, parameter); ASTMCReturnType returnType = MCBasicTypesMill.mCReturnTypeBuilder().setMCType(builderType).build(); method.setMCReturnType(returnType); this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint("_ast.builder.SetInherited", attribute, name)); return method; } @Override protected ASTCDMethod createSetAbsentMethod(final ASTCDAttribute attribute) { String name = String.format(SET_ABSENT, naiveAttributeName); ASTCDMethod method = this.getCDMethodFacade().createMethod(PUBLIC, name); ASTMCReturnType returnType = MCBasicTypesMill.mCReturnTypeBuilder().setMCType(builderType).build(); method.setMCReturnType(returnType); this.replaceTemplate(EMPTY_BODY, method, new TemplateHookPoint("_ast.builder.opt.SetAbsentInherited", name)); return method; } }
true
aaed9aa767205763ee916d5a2b0461f5a3428c92
Java
luhenchang/hdx
/app/src/main/java/com/accuvally/hdtui/model/SessionInfo.java
UTF-8
7,975
1.851563
2
[]
no_license
package com.accuvally.hdtui.model; import android.text.TextUtils; import com.accuvally.hdtui.manager.AccountManager; import com.accuvally.hdtui.utils.TimeUtils; import com.alibaba.fastjson.JSON; import com.avos.avoscloud.im.v2.AVIMConversation; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.List; /** * 会话列表 * * @author Semmer Wang * */ public class SessionInfo implements Serializable { public String inboxType=""; public String userId = AccountManager.getAccount();// 当前用户id public String friendId;// 一对一聊天对方id public int extend;// 1代表新朋友请求 public boolean isSelfSend;//是自己发送的消息 public SessionInfo() {} public SessionInfo(NotificationInfo info, AVIMConversation avimConversation, boolean isFristReceive) { setNotificationInfo(info); setAVIMConversation(avimConversation, isFristReceive); } public SessionInfo(NotificationInfo info) { setNotificationInfo(info); } public SessionInfo(AVIMConversation avimConversation, boolean isFristReceive) { setAVIMConversation(avimConversation, isFristReceive); } private void setNotificationInfo(NotificationInfo info) { isSelfSend = AccountManager.getAccount().equals(info.getSource_id()); setLogoUrl(info.getLogo_url()); setTitle(info.getTitle()); setNickName(info.getSource_name()); setContent(info.getMessage()); setTime(info.getTime()); setUnReadNum(info.getUnreadNum()); setFromUserId(info.getSource_id()); setMessageId(info.getMsgId()); setSessionType(info.getMessage_type()); setMessageType(info.getType()); setIsNotification(info.getIsNotification()); setOp_type(info.getOp_type()); setOp_value(info.getOp_value()); extend = info.extend; } public void setAVIMConversation(AVIMConversation conversation, boolean isFristReceive) { sessionId = conversation.getConversationId(); creator = conversation.getCreator(); if (TextUtils.isEmpty(logoUrl)) { Object obj = conversation.getAttribute("logo"); if (obj != null) { logoUrl = (String) obj; } } try { Object type = conversation.getAttribute("type"); if (type != null && (Integer) type == 1) {// 1 代表一对一聊天 0 群聊 Object users = conversation.getAttribute("users"); if (users != null) { List<FriendInfo> friendList = JSON.parseArray(users.toString(), FriendInfo.class); setFriendList(friendList, isFristReceive); } } } catch (Exception e) { } } public void setFriendList(List<FriendInfo> friendList, boolean isFristReceive) { boolean isSelf = userId.equals(friendList.get(0).account); FriendInfo friendInfo = isSelf ? friendList.get(1) : friendList.get(0); friendId = friendInfo.account; if (isFristReceive) { title = friendInfo.nick; logoUrl = friendInfo.logo; } } private String sessionId;// 会话Id private String title;// 会话名称 public String creator;// 会话创建人id private String content;// 会话内容 private long time;// 接收时间 private String logoUrl;// 会话头像 private int unReadNum;// 未读消息条数 private String fromUserId;// 发送者id private String toUserId;// 接收者id private String messageId;// 消息Id private String nickName;// 发送者昵称 // 1:新版本更新通知 // 2:已报名的活动开始前一天 // 3:已报名的活动开始前2个小时 // 4:已关注的活动开始前一天 // 5:参与的活动结束后的相关活动推荐 // 6:关注的主办方发布新的活动 // 7:有圈的成立邀请通知 // 8:圈友送过来的信息 // 9:有新的专题的 通知 // 10:有人邀请你当圈友 // 11:有人@你的 通知 // 12:报名审核通过的 通知 // 13:聊天 private int sessionType;// 会话类型 // 1为语音 2为图片 3为文本4为文件 private int messageType;// 消息类型 private int isNotification;// 是否是通知 1是通知 0不是通知 private int op_type; private String op_value; // boolean 1-true 0-false public boolean isDBMessage;// 对应的sessionId是否插入了所有消息 public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public int getUnReadNum() { return unReadNum; } public void setUnReadNum(int unReadNum) { this.unReadNum = unReadNum; } public String getFromUserId() { return fromUserId; } public void setFromUserId(String fromUserId) { this.fromUserId = fromUserId; } public String getToUserId() { return toUserId; } public void setToUserId(String toUserId) { this.toUserId = toUserId; } public String getMessageId() { return messageId; } public void setMessageId(String messageId) { this.messageId = messageId; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public int getSessionType() { return sessionType; } public void setSessionType(int sessionType) { this.sessionType = sessionType; } public int getMessageType() { return messageType; } public void setMessageType(int messageType) { this.messageType = messageType; } public int getIsNotification() { return isNotification; } public void setIsNotification(int isNotification) { this.isNotification = isNotification; } public int getOp_type() { return op_type; } public void setOp_type(int op_type) { this.op_type = op_type; } public String getOp_value() { return op_value; } public void setOp_value(String op_value) { this.op_value = op_value; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public String toString() { return "SessionInfo [sessionId=" + sessionId + ", title=" + title + ", content=" + content + ", time=" + time + ", logoUrl=" + logoUrl + ", unReadNum=" + unReadNum + ", fromUserId=" + fromUserId + ", toUserId=" + toUserId + ", messageId=" + messageId + ", nickName=" + nickName + ", sessionType=" + sessionType + ", messageType=" + messageType + ", isNotification=" + isNotification + ", op_type=" + op_type + ", op_value=" + op_value + "]"; } public String getSessionTime() { if (time == 0) { return ""; } Date receiveDate = new Date(time); Calendar now = Calendar.getInstance(); Calendar receive = Calendar.getInstance(); receive.setTime(receiveDate); if (now.get(Calendar.YEAR) == receive.get(Calendar.YEAR)) { boolean sameMonth = now.get(Calendar.MONTH) == receive.get(Calendar.MONTH); if (sameMonth && now.get(Calendar.DAY_OF_MONTH) == receive.get(Calendar.DAY_OF_MONTH)) { return TimeUtils.SD_HM.format(receiveDate); } else { return TimeUtils.mdFormat.format(receiveDate); } } else { return TimeUtils.yyyyMMdd.format(receiveDate); } } public String getTypeContent() { String typeContent = ""; if (TextUtils.isEmpty(nickName)) { return typeContent; } switch (messageType) { case MessageInfo.TYPE_TEXT: typeContent = nickName + ":" + content; break; case MessageInfo.TYPE_PHOTO: typeContent = nickName + ":[图片]"; break; case MessageInfo.TYPE_RECORDER: typeContent = nickName + ":[语音]"; break; } return typeContent; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public void setLogoUrl(String logoUrl) { this.logoUrl = logoUrl; } public String getLogoUrl() { return logoUrl; } public boolean isNotification() { return isNotification == 1; } public boolean isPrivateChat() { return !TextUtils.isEmpty(friendId); } public boolean isAddNewFriend() { return extend == 1; } }
true
3f2702a4912c78362c54bfba16ac50e28fe26586
Java
deepak1084/WalmartPool
/app/src/main/java/com/example/dagrawa/walmarthack315/MyOrdersFragment.java
UTF-8
3,601
2.0625
2
[]
no_license
package com.example.dagrawa.walmarthack315; /** * Created by hp on 02-04-2016. */ import android.annotation.TargetApi; import android.app.Activity; import android.app.Fragment; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MyOrdersFragment extends Fragment { View root; Activity context; public MyOrdersFragment(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.orders_fragment, container, false); root = rootView; context = this.getActivity(); final ArrayList<OrderDetail> arrayList = new ArrayList<>(); setJsonValueInterface s = new setJsonValueInterface() { @Override public void SetJSONObject(JSONArray j) { Log.i("Coming under setJSOn","Deepak"); if(j!=null) { Log.i("In orders fragment", j.toString()); for(int i=0;i<j.length();i++) { try { JSONObject ob = j.getJSONObject(i); JSONArray gArry = ob.getJSONArray("groups"); String groupsValue=""; if(gArry != null) { for (int k = 0; k < gArry.length(); k++) { groupsValue += gArry.getJSONObject(k).getString("name"); if(k!=gArry.length()-1) { groupsValue+=","; } } } arrayList.add(new OrderDetail(ob.getString("order_id"),ob.getString("time"), ob.getString("amount"),ob.getString("status"),groupsValue, ob.getString("shipping_price"), ob.getString("saving"))); // } catch (Exception e) { e.printStackTrace(); } } Log.i("Coming under setJSOn", "Deepak"); ListAdapter myAdapter = new CustomAdapterWithoutImageOrders(context, arrayList); ListView listView = (ListView) root.findViewById(R.id.listView); listView.setAdapter(myAdapter); listView.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // String item = String.valueOf(parent.getItemAtPosition(position)); // Toast.makeText(getActivity(),item, Toast.LENGTH_LONG).show(); } } ); } } }; new CreditsFetchingTask(s).execute(); return rootView; } }
true
9245fea8efbc5062bac596f514cbe09d406349b0
Java
CoderInOne/jcip
/src/main/java/xunshan/jcip/cas/MyLock.java
UTF-8
397
2.71875
3
[]
no_license
package xunshan.jcip.cas; // non-thread-safe lock public class MyLock { private boolean locked = false; // synchronized make it thread safe, but only one thread can // check-and-act, maybe fail to get lock, but still wait public /*synchronized*/ boolean lock() { if (!locked) { locked = true; return true; } return false; } }
true
d1a9d88c72a998a770b0be5969d7b8d74011a8e5
Java
bazelbuild/bazel
/src/main/java/com/google/devtools/build/lib/actions/InputMetadataProvider.java
UTF-8
2,954
2.109375
2
[ "Apache-2.0" ]
permissive
// Copyright 2017 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.actions; import com.google.devtools.build.lib.actions.Artifact.DerivedArtifact; import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe; import com.google.devtools.build.lib.vfs.FileSystem; import java.io.IOException; import javax.annotation.Nullable; /** Provides {@link ActionInput} metadata. */ @ThreadSafe public interface InputMetadataProvider { /** * Returns a {@link FileArtifactValue} for the given {@link ActionInput}. * * <p>The returned {@link FileArtifactValue} instance corresponds to the final target of a symlink * and therefore must not have a type of {@link FileStateType#SYMLINK}. * * <p>If {@link #mayGetGeneratingActionsFromSkyframe} is {@code true} and the {@linkplain * DerivedArtifact#getGeneratingActionKey generating action} is not immediately available, this * method returns {@code null} to signify that a skyframe restart is necessary to obtain the * metadata for the requested {@link Artifact.DerivedArtifact}. * * @param input the input to retrieve the digest for * @return the artifact's digest or null if digest cannot be obtained (due to artifact * non-existence, lookup errors, or any other reason) * @throws IOException if the action input cannot be digested */ @Nullable FileArtifactValue getInputMetadata(ActionInput input) throws IOException; /** Looks up an input from its exec path. */ @Nullable ActionInput getInput(String execPath); /** * Returns a {@link FileSystem} which, if not-null, should be used instead of the one associated * with {@linkplain Artifact#getPath() the path provided for input artifacts}. * * <p>For {@linkplain ActionInput ActionInputs} which are {@linkplain Artifact Artifacts}, we can * perform direct operations on the {@linkplain Artifact#getPath path}. Doing so, may require * {@link FileSystem} redirection. This method defines whether that is the case and which {@link * FileSystem} to use for that. */ @Nullable default FileSystem getFileSystemForInputResolution() { return null; } /** * Indicates whether calls to {@link #getInputMetadata} with a {@link Artifact.DerivedArtifact} * may require a skyframe lookup. */ default boolean mayGetGeneratingActionsFromSkyframe() { return false; } }
true
0264b4677fc7371dc239322a08ee186dfb485031
Java
jared854/GUI-Sketch
/A08Sketcheroo/src/DrawingShapes.java
UTF-8
446
2.578125
3
[]
no_license
import java.awt.Color; import java.awt.Graphics2D; import java.awt.Shape; import javax.swing.JComponent; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Random; public class DrawingShapes{ public static ArrayList<Shape> drawingShapes; public DrawingShapes(){ drawingShapes = new ArrayList<Shape>(); } public void addNewShapes(Shape shapes){ drawingShapes.add(shapes); } }
true