blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4bec247cb7462ed925eb76880b4d5f27ad9ea205 | 6,124,623,423,366 | f3564421ce5bf0add657df8469e08f8644284c2d | /receiver/GUI.java | e199e62e13aa08db634d9c2c44ced282d2d5a9c2 | []
| no_license | qizhex/SensorNetwork | https://github.com/qizhex/SensorNetwork | 540d9c84abd288725480264d0c240da1ae90e737 | a1cfc17738af22a17932caf7e93fd07d4e0b1904 | refs/heads/master | 2021-05-28T18:55:54.573000 | 2015-06-27T04:38:09 | 2015-06-27T04:38:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package receiver;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Iterator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.time.Second;
public class GUI{
int senNum;
final static int typeNum = 3;
int sensors[];
final static String typeName[] = {"Temperature", "Humidity", "Light"};
final static int winS = 100000;
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
JFrame frame = new JFrame();
int sen = 0;
int typ = 1;
java.util.Date time = new java.util.Date();
ArrayList<Pac>[] sensorData;
private class Pac {
public java.util.Date time;
public int data[];
Pac(java.util.Date t, int k1, int k2, int k3) {
time = t;
data = new int[3];
data[0] = k1;
data[1] = k2;
data[2] = k3;
}
}
public void addPac(int sen, java.util.Date t, int k1, int k2, int k3) {
int i;
for (i = 0; i < senNum; ++i)
if (sensors[i] == sen) {
Pac p = new Pac(t, k1, k2, k3);
sensorData[i].add(p);
return;
}
assert(false);
}
public GUI(int senNum) {
this.senNum = senNum;
sensorData = new ArrayList[senNum];
this.sensors = new int[senNum];
System.out.print(senNum);
for (int i = 0; i < senNum; ++i) {
sensorData[i] = new ArrayList<Pac>();
this.sensors[i] = i;
}
frame.getContentPane().setLayout(layout);
JButton[][] typeButton = new JButton[senNum][typeNum];
for (int j = 0; j < senNum; ++j)
for (int i = 0; i < typeNum; ++i) {
typeButton[j][i] = new JButton(typeName[i] + sensors[j]);
typeButton[j][i].addMouseListener(new MA(this, j, i));
typeButton[j][i].setFont(new Font("Serif", Font.PLAIN, 10));
c.gridx = i + 1;
c.gridy = j;
layout.setConstraints(typeButton[j][i], c);
frame.getContentPane().add(typeButton[j][i]);
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class MA extends MouseAdapter implements MouseListener {
int sen, typ;
GUI frame;
public MA(GUI f, int sensor, int type) {
super();
frame = f;
sen = sensor;
typ = type;
}
@Override
public void mouseClicked(MouseEvent evt) {
if (sen != -1 && typ != -1) {
frame.typ = typ;
frame.sen = sen;
} else
assert (false);
System.out.println("sensor: " + frame.sen + "frame: " + frame.typ);
frame.display();
}
}
public static void setXYPolt(XYPlot plot) {
plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
XYItemRenderer r = plot.getRenderer();
if (r instanceof XYLineAndShapeRenderer) {
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
renderer.setBaseShapesVisible(true);
renderer.setBaseShapesFilled(false);
}
}
public void display()
{
TimeSeriesCollection sc = new TimeSeriesCollection();
TimeSeries ss = new TimeSeries(typeName[typ] + sen, Millisecond.class);
int i = sen;
while ((!sensorData[i].isEmpty()) && (sensorData[i].get(0).time.getTime() + winS < time.getTime()))
sensorData[i].remove(0);
Iterator<Pac> it = sensorData[i].iterator();
while (it.hasNext()){
Pac a = it.next();
ss.add(new Millisecond(a.time), a.data[typ]);
}
sc.addSeries(ss);
JFreeChart chart = ChartFactory.createTimeSeriesChart(typeName[typ] + sensors[sen], "time", "value", sc, true, true, false);
chart.setBackgroundPaint(Color.YELLOW);
XYPlot plot = chart.getXYPlot();
setXYPolt(plot);
ChartPanel cp = new ChartPanel(chart, true);
c.gridx = 0;
c.gridy = senNum + 1;
layout.setConstraints(cp, c);
frame.getContentPane().add(cp);
frame.pack();
frame.setVisible(true);
}
} | UTF-8 | Java | 5,105 | java | GUI.java | Java | []
| null | []
| package receiver;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Iterator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.time.Second;
public class GUI{
int senNum;
final static int typeNum = 3;
int sensors[];
final static String typeName[] = {"Temperature", "Humidity", "Light"};
final static int winS = 100000;
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
JFrame frame = new JFrame();
int sen = 0;
int typ = 1;
java.util.Date time = new java.util.Date();
ArrayList<Pac>[] sensorData;
private class Pac {
public java.util.Date time;
public int data[];
Pac(java.util.Date t, int k1, int k2, int k3) {
time = t;
data = new int[3];
data[0] = k1;
data[1] = k2;
data[2] = k3;
}
}
public void addPac(int sen, java.util.Date t, int k1, int k2, int k3) {
int i;
for (i = 0; i < senNum; ++i)
if (sensors[i] == sen) {
Pac p = new Pac(t, k1, k2, k3);
sensorData[i].add(p);
return;
}
assert(false);
}
public GUI(int senNum) {
this.senNum = senNum;
sensorData = new ArrayList[senNum];
this.sensors = new int[senNum];
System.out.print(senNum);
for (int i = 0; i < senNum; ++i) {
sensorData[i] = new ArrayList<Pac>();
this.sensors[i] = i;
}
frame.getContentPane().setLayout(layout);
JButton[][] typeButton = new JButton[senNum][typeNum];
for (int j = 0; j < senNum; ++j)
for (int i = 0; i < typeNum; ++i) {
typeButton[j][i] = new JButton(typeName[i] + sensors[j]);
typeButton[j][i].addMouseListener(new MA(this, j, i));
typeButton[j][i].setFont(new Font("Serif", Font.PLAIN, 10));
c.gridx = i + 1;
c.gridy = j;
layout.setConstraints(typeButton[j][i], c);
frame.getContentPane().add(typeButton[j][i]);
}
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class MA extends MouseAdapter implements MouseListener {
int sen, typ;
GUI frame;
public MA(GUI f, int sensor, int type) {
super();
frame = f;
sen = sensor;
typ = type;
}
@Override
public void mouseClicked(MouseEvent evt) {
if (sen != -1 && typ != -1) {
frame.typ = typ;
frame.sen = sen;
} else
assert (false);
System.out.println("sensor: " + frame.sen + "frame: " + frame.typ);
frame.display();
}
}
public static void setXYPolt(XYPlot plot) {
plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
XYItemRenderer r = plot.getRenderer();
if (r instanceof XYLineAndShapeRenderer) {
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
renderer.setBaseShapesVisible(true);
renderer.setBaseShapesFilled(false);
}
}
public void display()
{
TimeSeriesCollection sc = new TimeSeriesCollection();
TimeSeries ss = new TimeSeries(typeName[typ] + sen, Millisecond.class);
int i = sen;
while ((!sensorData[i].isEmpty()) && (sensorData[i].get(0).time.getTime() + winS < time.getTime()))
sensorData[i].remove(0);
Iterator<Pac> it = sensorData[i].iterator();
while (it.hasNext()){
Pac a = it.next();
ss.add(new Millisecond(a.time), a.data[typ]);
}
sc.addSeries(ss);
JFreeChart chart = ChartFactory.createTimeSeriesChart(typeName[typ] + sensors[sen], "time", "value", sc, true, true, false);
chart.setBackgroundPaint(Color.YELLOW);
XYPlot plot = chart.getXYPlot();
setXYPolt(plot);
ChartPanel cp = new ChartPanel(chart, true);
c.gridx = 0;
c.gridy = senNum + 1;
layout.setConstraints(cp, c);
frame.getContentPane().add(cp);
frame.pack();
frame.setVisible(true);
}
} | 5,105 | 0.583937 | 0.576494 | 150 | 33.040001 | 21.365044 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.946667 | false | false | 10 |
c4405d125f477e662d3f167d58e2b8b29caab2f4 | 6,124,623,425,644 | d0ea4105b3f3c881ee901d226e8848a5a7a7707d | /pss-core/src/main/java/cn/jely/cd/sys/web/UserAction.java | f02738763fea130ada6ab1f62687eed55bfe9127 | []
| no_license | jelycom/pss | https://github.com/jelycom/pss | 5408ba62546e078c18a8f1b8f63a1f5145ff043d | 3e4e8fb621ac6ad02673b6625e243982259d37e0 | refs/heads/master | 2021-01-10T19:41:20.252000 | 2013-11-20T01:00:08 | 2013-11-20T01:00:08 | 11,272,019 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 捷利商业进销存管理系统
* @(#)User.java
* Copyright (c) 2002-2013 Jely Corporation
*/
package cn.jely.cd.sys.web;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import cn.jely.cd.domain.Employee;
import cn.jely.cd.sys.domain.User;
import cn.jely.cd.sys.service.IUserService;
import cn.jely.cd.util.ActionJsonResult;
import cn.jely.cd.util.ActionJsonResult.MessageType;
import cn.jely.cd.util.ConstValue;
import cn.jely.cd.util.Pager;
import cn.jely.cd.web.JQGridAction;
/**
* @ClassName:UserAction
* @Description:Action
* @author
* @version 2013-10-08 21:14:26
*
*/
public class UserAction extends JQGridAction<User> {// 有针对树的操作需继承自TreeOperateAction
/**long:serialVersionUID:*/
private static final long serialVersionUID = 1L;
private User user;
private IUserService userService;
private Pager<User> pager;
public void setUserService(IUserService userService) {
this.userService = userService;
}
public Pager<User> getPager() {
return pager;
}
@Override
public User getModel() {
return user;
}
@Override
public String list() {
// 将需要在列表页面展示的关联对象放入Context;
// putContext(key,value);
return SUCCESS;
}
@Override
public String listjson() {
parseCondition();
pager = userService.findPager(objectQuery);
actionJsonResult = new ActionJsonResult(pager);
return JSONALL;
}
@Override
public String listall() {
actionJsonResult = new ActionJsonResult(userService.getAll());
return JSONALL;
}
// @Validations(requiredStrings={@RequiredStringValidator(fieldName="name",message="名称必须输入")})
// @InputConfig(methodName="list")
@Override
public String save() {
try {
if (StringUtils.isNotBlank(id)) {
userService.update(user);
} else {
userService.save(user);
}
actionJsonResult = new ActionJsonResult(user);
} catch (Exception e) {
actionJsonResult = new ActionJsonResult(false,e.getMessage());
}
return JSONLIST;
}
@Override
public String delete() {
// id对应的记录不存在已经在Dao作了处理
if (StringUtils.isNotBlank(id)) {
userService.delete(id);
// userService.setDeleteState(id);//置为删除状态。不是真正删除
}
actionJsonResult = new ActionJsonResult(true, null);
return JSONLIST;
}
@Override
protected void beforInputSave() {
if (StringUtils.isBlank(id)) {
if (isEditSave()) {
// 新增的时候不需要初始化,保存的时候要有个对象保存值
user = new User();
}
} else {
user = userService.getById(id);
if (isEditSave()) {
// 如果是修改后的保存,因为prepare到save前会执行一次Set操作(modelDriven),
// 所以要在保存前将其关联的对象置空
}
}
}
public String changepwd() {
HttpServletRequest request = getRequest();
String oldPassword = request.getParameter("oldPassword");
String newPassword = request.getParameter("newPassword");
String confirmPassword = request.getParameter("confirmPassword");
if (StringUtils.isBlank(oldPassword)) {
actionJsonResult = new ActionJsonResult(false, MessageType.ERROR, "原密码不能为空");
} else if (StringUtils.isBlank(newPassword) || StringUtils.isBlank(confirmPassword)) {
actionJsonResult = new ActionJsonResult(false, MessageType.ERROR, "新密码和确认密码不能为空");
} else if (!newPassword.equals(confirmPassword)) {
actionJsonResult = new ActionJsonResult(false, MessageType.ERROR, "新密码、确认密码不一致");
} else {
Employee employee = getLoginUser();
user = employee.getUser();
if (user != null && oldPassword.equals(user.getPassword())) {
user.setPassword(newPassword);
userService.update(user);
actionJsonResult = new ActionJsonResult(true, "修改密码成功");
} else {
actionJsonResult = new ActionJsonResult(MessageType.ERROR, "原密码不正确");
}
}
return JSONLIST;
}
public String changeskin() {
HttpServletRequest request = getRequest();
String skin = request.getParameter(ConstValue.USERSKIN);
if(StringUtils.isNotBlank(skin)){
user = getLoginUser().getUser();
if(user != null){
user = userService.getById(user.getId());
user.setSkin(skin);
userService.update(user);
getSession().put(ConstValue.USERSKIN, skin);
actionJsonResult = new ActionJsonResult(true,"");
}else{
actionJsonResult = new ActionJsonResult(false,"此员工无登陆帐户");
}
}else {
actionJsonResult = new ActionJsonResult(false,MessageType.ERROR,"skin不能为空");
}
return JSONLIST;
}
}
| UTF-8 | Java | 4,626 | java | UserAction.java | Java | [
{
"context": "quals(user.getPassword())) {\n\t\t\t\tuser.setPassword(newPassword);\n\t\t\t\tuserService.update(user);\n\t\t\t\tactionJsonRes",
"end": 3402,
"score": 0.9979957342147827,
"start": 3391,
"tag": "PASSWORD",
"value": "newPassword"
}
]
| null | []
| /*
* 捷利商业进销存管理系统
* @(#)User.java
* Copyright (c) 2002-2013 Jely Corporation
*/
package cn.jely.cd.sys.web;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import cn.jely.cd.domain.Employee;
import cn.jely.cd.sys.domain.User;
import cn.jely.cd.sys.service.IUserService;
import cn.jely.cd.util.ActionJsonResult;
import cn.jely.cd.util.ActionJsonResult.MessageType;
import cn.jely.cd.util.ConstValue;
import cn.jely.cd.util.Pager;
import cn.jely.cd.web.JQGridAction;
/**
* @ClassName:UserAction
* @Description:Action
* @author
* @version 2013-10-08 21:14:26
*
*/
public class UserAction extends JQGridAction<User> {// 有针对树的操作需继承自TreeOperateAction
/**long:serialVersionUID:*/
private static final long serialVersionUID = 1L;
private User user;
private IUserService userService;
private Pager<User> pager;
public void setUserService(IUserService userService) {
this.userService = userService;
}
public Pager<User> getPager() {
return pager;
}
@Override
public User getModel() {
return user;
}
@Override
public String list() {
// 将需要在列表页面展示的关联对象放入Context;
// putContext(key,value);
return SUCCESS;
}
@Override
public String listjson() {
parseCondition();
pager = userService.findPager(objectQuery);
actionJsonResult = new ActionJsonResult(pager);
return JSONALL;
}
@Override
public String listall() {
actionJsonResult = new ActionJsonResult(userService.getAll());
return JSONALL;
}
// @Validations(requiredStrings={@RequiredStringValidator(fieldName="name",message="名称必须输入")})
// @InputConfig(methodName="list")
@Override
public String save() {
try {
if (StringUtils.isNotBlank(id)) {
userService.update(user);
} else {
userService.save(user);
}
actionJsonResult = new ActionJsonResult(user);
} catch (Exception e) {
actionJsonResult = new ActionJsonResult(false,e.getMessage());
}
return JSONLIST;
}
@Override
public String delete() {
// id对应的记录不存在已经在Dao作了处理
if (StringUtils.isNotBlank(id)) {
userService.delete(id);
// userService.setDeleteState(id);//置为删除状态。不是真正删除
}
actionJsonResult = new ActionJsonResult(true, null);
return JSONLIST;
}
@Override
protected void beforInputSave() {
if (StringUtils.isBlank(id)) {
if (isEditSave()) {
// 新增的时候不需要初始化,保存的时候要有个对象保存值
user = new User();
}
} else {
user = userService.getById(id);
if (isEditSave()) {
// 如果是修改后的保存,因为prepare到save前会执行一次Set操作(modelDriven),
// 所以要在保存前将其关联的对象置空
}
}
}
public String changepwd() {
HttpServletRequest request = getRequest();
String oldPassword = request.getParameter("oldPassword");
String newPassword = request.getParameter("newPassword");
String confirmPassword = request.getParameter("confirmPassword");
if (StringUtils.isBlank(oldPassword)) {
actionJsonResult = new ActionJsonResult(false, MessageType.ERROR, "原密码不能为空");
} else if (StringUtils.isBlank(newPassword) || StringUtils.isBlank(confirmPassword)) {
actionJsonResult = new ActionJsonResult(false, MessageType.ERROR, "新密码和确认密码不能为空");
} else if (!newPassword.equals(confirmPassword)) {
actionJsonResult = new ActionJsonResult(false, MessageType.ERROR, "新密码、确认密码不一致");
} else {
Employee employee = getLoginUser();
user = employee.getUser();
if (user != null && oldPassword.equals(user.getPassword())) {
user.setPassword(<PASSWORD>);
userService.update(user);
actionJsonResult = new ActionJsonResult(true, "修改密码成功");
} else {
actionJsonResult = new ActionJsonResult(MessageType.ERROR, "原密码不正确");
}
}
return JSONLIST;
}
public String changeskin() {
HttpServletRequest request = getRequest();
String skin = request.getParameter(ConstValue.USERSKIN);
if(StringUtils.isNotBlank(skin)){
user = getLoginUser().getUser();
if(user != null){
user = userService.getById(user.getId());
user.setSkin(skin);
userService.update(user);
getSession().put(ConstValue.USERSKIN, skin);
actionJsonResult = new ActionJsonResult(true,"");
}else{
actionJsonResult = new ActionJsonResult(false,"此员工无登陆帐户");
}
}else {
actionJsonResult = new ActionJsonResult(false,MessageType.ERROR,"skin不能为空");
}
return JSONLIST;
}
}
| 4,625 | 0.71934 | 0.713915 | 157 | 26.006369 | 22.589806 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.140127 | false | false | 10 |
8c18decd1a00b0b0fd28a8860b2f480fec075920 | 37,409,165,149,918 | 95e7349441dfc33f8902fb76c0875fdefcd13d05 | /neuronSimulator.java | 7e3bd97c9b1b25b65d2df17fc132f68980344ad2 | []
| no_license | parag1102/NeuralSimulator | https://github.com/parag1102/NeuralSimulator | 373633abaae22d36a91ef96d278abbc7885ffe63 | c2238afc0adc7838c8e511a7cc40185e8986796c | refs/heads/master | 2020-05-29T11:30:35.518000 | 2013-10-27T04:28:45 | 2013-10-27T04:28:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.cmu.lti;
import java.text.DecimalFormat;
import java.util.ArrayDeque;
import java.util.Queue;
public class neuronSimulator {
private double startCurrent;
private double dampingFactor;
public void setStartCurrent(double c) {
this.startCurrent = c;
}
public void setDampingFactor(double d) {
this.dampingFactor = d;
}
public void run(mesh M) {
DecimalFormat myForm = new DecimalFormat("#0.0000");
System.out.println("\n------Simulating the Neural Graph------");
System.out.println("\n------Our Simulation also supports parallelism------");
System.out.println("------where a neuron is able to send current simultaneously to all its connections.------\n");
System.out.println("------Starting with a signal strength of "+ this.startCurrent + "------\n");
System.out.println("------Loss in strength per hop is "+ this.dampingFactor + "------\n");
Queue<neuron> cq = new ArrayDeque<neuron>();
Queue<neuron> nq = new ArrayDeque<neuron>();
double nowCurrent = this.startCurrent;
System.out.println("Neuron 00 => isOn: true Current: " + myForm.format(nowCurrent) + " #Connections: " + M.getat(0).size());
double nextCurrent = nowCurrent*this.dampingFactor;
if (nextCurrent >= 0.001) {
for (int j= 0; j<M.getat(0).size();j++) {
cq.add(M.getat(0).get(j));
M.getat(0).get(j).setCurrent(nextCurrent);
}
}
int countHops = 1;
while (null != cq.peek()) {
neuron tempne = cq.poll();
int i = tempne.getId();
tempne.setConnections(M.getat(i).size());
tempne.printState();
//System.out.print(i + " ");
nowCurrent = tempne.getCurrent();
nextCurrent = nowCurrent*this.dampingFactor;
if (nextCurrent >= 0.001) {
for (int j= 0; j<M.getat(i).size();j++) {
nq.add(M.getat(i).get(j));
M.getat(i).get(j).setCurrent(nextCurrent);
}
}
if(null == cq.peek()) {
System.out.println();
countHops++;
this.swap(cq,nq);
}
}
System.out.println("\n------Total number of hops over which the signal propagated is "+ countHops + "------\n");
}
private void swap(Queue<neuron> cq, Queue<neuron> nq) {
Queue<neuron> temp = new ArrayDeque<neuron>(cq);
cq.clear();
cq.addAll(nq);
nq.clear();
nq.addAll(temp);
}
}
| UTF-8 | Java | 2,412 | java | neuronSimulator.java | Java | []
| null | []
| package edu.cmu.lti;
import java.text.DecimalFormat;
import java.util.ArrayDeque;
import java.util.Queue;
public class neuronSimulator {
private double startCurrent;
private double dampingFactor;
public void setStartCurrent(double c) {
this.startCurrent = c;
}
public void setDampingFactor(double d) {
this.dampingFactor = d;
}
public void run(mesh M) {
DecimalFormat myForm = new DecimalFormat("#0.0000");
System.out.println("\n------Simulating the Neural Graph------");
System.out.println("\n------Our Simulation also supports parallelism------");
System.out.println("------where a neuron is able to send current simultaneously to all its connections.------\n");
System.out.println("------Starting with a signal strength of "+ this.startCurrent + "------\n");
System.out.println("------Loss in strength per hop is "+ this.dampingFactor + "------\n");
Queue<neuron> cq = new ArrayDeque<neuron>();
Queue<neuron> nq = new ArrayDeque<neuron>();
double nowCurrent = this.startCurrent;
System.out.println("Neuron 00 => isOn: true Current: " + myForm.format(nowCurrent) + " #Connections: " + M.getat(0).size());
double nextCurrent = nowCurrent*this.dampingFactor;
if (nextCurrent >= 0.001) {
for (int j= 0; j<M.getat(0).size();j++) {
cq.add(M.getat(0).get(j));
M.getat(0).get(j).setCurrent(nextCurrent);
}
}
int countHops = 1;
while (null != cq.peek()) {
neuron tempne = cq.poll();
int i = tempne.getId();
tempne.setConnections(M.getat(i).size());
tempne.printState();
//System.out.print(i + " ");
nowCurrent = tempne.getCurrent();
nextCurrent = nowCurrent*this.dampingFactor;
if (nextCurrent >= 0.001) {
for (int j= 0; j<M.getat(i).size();j++) {
nq.add(M.getat(i).get(j));
M.getat(i).get(j).setCurrent(nextCurrent);
}
}
if(null == cq.peek()) {
System.out.println();
countHops++;
this.swap(cq,nq);
}
}
System.out.println("\n------Total number of hops over which the signal propagated is "+ countHops + "------\n");
}
private void swap(Queue<neuron> cq, Queue<neuron> nq) {
Queue<neuron> temp = new ArrayDeque<neuron>(cq);
cq.clear();
cq.addAll(nq);
nq.clear();
nq.addAll(temp);
}
}
| 2,412 | 0.593698 | 0.584577 | 79 | 29.531645 | 28.570957 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.582278 | false | false | 10 |
9c8e47209bde823aa8462641d78b61f65d8ecae9 | 21,242,908,310,556 | e393f54fd7806060110d3be504174930ef94a07c | /src/main/java/com/huayuan/domain/crawler/billparser/BillEmailParserFactory.java | 64f0f8792b24e50616b6798149b5df7553bd0488 | []
| no_license | qiaohe/repaymentApp | https://github.com/qiaohe/repaymentApp | 6480633d997f11fb243b8b268d9486d1af9e6668 | 324d6012ae7ed19f48eec021ec35425d5cf4fbc5 | refs/heads/master | 2021-01-22T22:57:10.618000 | 2014-09-05T09:06:32 | 2014-09-05T09:06:32 | 17,904,833 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huayuan.domain.crawler.billparser;
/**
* Created by dell on 14-6-5.
*/
public class BillEmailParserFactory {
private static final BillEmailParserFactory INSTANCE = new BillEmailParserFactory();
private BillEmailParserFactory() {
}
public static BillEmailParserFactory getInstance() {
return INSTANCE;
}
/*
VALUE NAME
1 工商银行
2 农业银行
3 中国银行
4 建设银行
5 交通银行
6 光大银行
7 广发银行
8 华夏银行
9 民生银行
10 平安银行
11 兴业银行
12 招商银行
13 浦发银行
14 中信银行
15 邮储银行
16 上海银行
17 北京银行
*/
public BillEmailParser create(final Integer bankId) {
switch (bankId) {
case 4:
return new CcbEmailParser();
case 7:
return new CgbEmailParser();
case 12:
return new CgbEmailParser();
default:
throw new IllegalStateException("This bank can not be supported.");
}
}
}
| UTF-8 | Java | 1,046 | java | BillEmailParserFactory.java | Java | [
{
"context": "yuan.domain.crawler.billparser;\n\n/**\n * Created by dell on 14-6-5.\n */\npublic class BillEmailParserFactor",
"end": 70,
"score": 0.9779123067855835,
"start": 66,
"tag": "USERNAME",
"value": "dell"
}
]
| null | []
| package com.huayuan.domain.crawler.billparser;
/**
* Created by dell on 14-6-5.
*/
public class BillEmailParserFactory {
private static final BillEmailParserFactory INSTANCE = new BillEmailParserFactory();
private BillEmailParserFactory() {
}
public static BillEmailParserFactory getInstance() {
return INSTANCE;
}
/*
VALUE NAME
1 工商银行
2 农业银行
3 中国银行
4 建设银行
5 交通银行
6 光大银行
7 广发银行
8 华夏银行
9 民生银行
10 平安银行
11 兴业银行
12 招商银行
13 浦发银行
14 中信银行
15 邮储银行
16 上海银行
17 北京银行
*/
public BillEmailParser create(final Integer bankId) {
switch (bankId) {
case 4:
return new CcbEmailParser();
case 7:
return new CgbEmailParser();
case 12:
return new CgbEmailParser();
default:
throw new IllegalStateException("This bank can not be supported.");
}
}
}
| 1,046 | 0.613187 | 0.576923 | 49 | 17.571428 | 20.879635 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510204 | false | false | 10 |
1c5611ad6690826443f32e9e2054d24868c38dc1 | 27,273,042,382,215 | 8272621b14b78f025bd092d69bae3778cde62b55 | /src/main/java/honours/ing/banq/util/StringUtil.java | f5c1308befb52cfeb629249f3660d9ec257ebf4f | []
| no_license | jeffreybakker/ING_Project | https://github.com/jeffreybakker/ING_Project | 6d5c76015782ba1960179b0e4492c384732a201b | 6423462362084a25673e1b668dbc41a67fdfadfd | refs/heads/master | 2021-01-19T20:56:45.640000 | 2017-08-13T22:25:51 | 2017-08-13T22:25:51 | 82,464,170 | 0 | 1 | null | false | 2017-08-13T22:25:52 | 2017-02-19T14:19:00 | 2017-03-13T20:17:01 | 2017-08-13T22:25:52 | 270 | 0 | 1 | 0 | Java | null | null | package honours.ing.banq.util;
import java.util.Random;
/**
* @author jeffrey
* @since 9-6-17
*/
public class StringUtil {
public static String generate(int length) {
Random random = new Random();
StringBuilder res = new StringBuilder();
for (int i = 0; i < 10; i++) {
res.append((char) ((int) 'a') - 1 + random.nextInt(26));
}
return res.toString();
}
}
| UTF-8 | Java | 424 | java | StringUtil.java | Java | [
{
"context": "nq.util;\n\nimport java.util.Random;\n\n/**\n * @author jeffrey\n * @since 9-6-17\n */\npublic class StringUtil {\n\n ",
"end": 80,
"score": 0.9857825636863708,
"start": 73,
"tag": "NAME",
"value": "jeffrey"
}
]
| null | []
| package honours.ing.banq.util;
import java.util.Random;
/**
* @author jeffrey
* @since 9-6-17
*/
public class StringUtil {
public static String generate(int length) {
Random random = new Random();
StringBuilder res = new StringBuilder();
for (int i = 0; i < 10; i++) {
res.append((char) ((int) 'a') - 1 + random.nextInt(26));
}
return res.toString();
}
}
| 424 | 0.561321 | 0.537736 | 22 | 18.272728 | 19.435633 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 10 |
f501125a6eeee431ea9b2d07070d6bde3bf1ebb6 | 10,771,778,030,759 | 40bf3ef50b15df1b3abdd5fd2bdf4b6a3594e652 | /src/main/java/net/dfrz/dao/SheetDao.java | 5253ad92a6b22ac4b955fc1d887e614953e46f3d | [
"Apache-2.0"
]
| permissive | 1761267410/111 | https://github.com/1761267410/111 | 2d2bd6080e65b9d111aaf1555604db28909e1380 | a2d67ef8d332ab6879f780febc1a2b9f6ee3531a | refs/heads/master | 2020-03-27T08:20:52.361000 | 2018-08-30T06:19:38 | 2018-08-30T06:21:10 | 146,246,446 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.dfrz.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import net.dfrz.bean.po.SheetPO;
@Repository
public class SheetDao extends BaseDao<SheetPO, Integer> {
@Autowired
JdbcTemplate jdbcTemplate;
public int UpdateSheet(String progress, int id, String currentUser, int status) {
// TODO Auto-generated method stub
int result = 0;
String user = currentUser == null ? "" : currentUser;
StringBuilder sql = new StringBuilder();
sql.append("update f_sheet a,f_flow b");
sql.append(
" set b.flow_status = " + status + ",a.flow_status = " + status + ", a.progress = '" + progress + "',");
sql.append(" b.currentUser = '" + user + "'");
sql.append(" where a.id = '" + id + "'");
sql.append(" and a.flowId = b.flowId");
try {
jdbcTemplate.execute(sql.toString());
result = 1;
} catch (Exception e) {
// TODO: handle exception
System.out.println("修改失败");
result = 0;
}
return result;
}
}
| UTF-8 | Java | 1,071 | java | SheetDao.java | Java | []
| null | []
| package net.dfrz.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import net.dfrz.bean.po.SheetPO;
@Repository
public class SheetDao extends BaseDao<SheetPO, Integer> {
@Autowired
JdbcTemplate jdbcTemplate;
public int UpdateSheet(String progress, int id, String currentUser, int status) {
// TODO Auto-generated method stub
int result = 0;
String user = currentUser == null ? "" : currentUser;
StringBuilder sql = new StringBuilder();
sql.append("update f_sheet a,f_flow b");
sql.append(
" set b.flow_status = " + status + ",a.flow_status = " + status + ", a.progress = '" + progress + "',");
sql.append(" b.currentUser = '" + user + "'");
sql.append(" where a.id = '" + id + "'");
sql.append(" and a.flowId = b.flowId");
try {
jdbcTemplate.execute(sql.toString());
result = 1;
} catch (Exception e) {
// TODO: handle exception
System.out.println("修改失败");
result = 0;
}
return result;
}
}
| 1,071 | 0.677328 | 0.674506 | 36 | 28.527779 | 24.878021 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.111111 | false | false | 10 |
22a3f930646ca62a9f0ee8292292ca13f2567bf2 | 17,317,308,195,864 | d761019032b207b3b85990406e8983941d1de46a | /chrome/android/java/src/org/chromium/chrome/browser/notifications/channels/ChannelDefinitions.java | 3973476e00bf0e4893aa7d9119a4a153e9fb6302 | [
"BSD-3-Clause"
]
| permissive | lxq2537664558/chromium | https://github.com/lxq2537664558/chromium | 6fd1133e0a4217313bf5ef2667db0352a2592c0a | 41a50f3730236f4252c34e8a33bca612485695f8 | refs/heads/master | 2023-03-17T22:41:38.190000 | 2020-04-28T09:50:35 | 2020-04-28T09:50:35 | 187,134,373 | 0 | 0 | NOASSERTION | true | 2020-04-28T09:50:36 | 2019-05-17T02:39:27 | 2019-05-17T02:46:42 | 2020-04-28T09:50:36 | 13,078,256 | 0 | 0 | 0 | null | false | false | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.notifications.channels;
public class ChannelDefinitions {
public @interface ChannelId {
static String BROWSER = "browser";
}
}
| UTF-8 | Java | 346 | java | ChannelDefinitions.java | Java | []
| null | []
| // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.notifications.channels;
public class ChannelDefinitions {
public @interface ChannelId {
static String BROWSER = "browser";
}
}
| 346 | 0.739884 | 0.728324 | 11 | 30.454546 | 25.256371 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 10 |
9f439989b0f2bd060646c46f313f88e391b31bd2 | 27,075,473,894,238 | fb04ad78f6f53e5f733b4a055066263734d38799 | /rxjava/src/main/java/com/yangxvhao/demo/proxy/RxJavaTest.java | 9096c3c068a7a047e135d26393b3a3dd47aa100e | []
| no_license | yangxvhao/dailytrain | https://github.com/yangxvhao/dailytrain | 5b92e854a3f55544381d204e7e6bfe0080e279f1 | fe0f3732a65d374dff46f57ddf2a8ef02ea0f100 | refs/heads/master | 2023-02-12T18:42:00.314000 | 2023-02-07T13:16:02 | 2023-02-07T13:16:02 | 114,737,452 | 0 | 0 | null | false | 2022-10-12T20:13:01 | 2017-12-19T08:12:09 | 2022-05-28T12:34:27 | 2022-10-12T20:12:59 | 435 | 0 | 0 | 8 | Java | false | false | package com.yangxvhao.demo.proxy;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author yangxvhao
* @date 18-5-15.
*/
@Slf4j
public class RxJavaTest {
public static void main(String[] args) {
// integerTest();
// create();
interval();
}
public static void interval(){
List<Integer> integers = new ArrayList<Integer>(){{
add(1);add(2);add(3);add(4);
}};
Observable.from(integers)
.map(RxJavaTest::add)
.flatMap(integer -> Observable.interval(2, TimeUnit.MINUTES))
.subscribe(System.out::println);
}
public static void create(){
List<Integer> integers = new ArrayList<>();
Observable.create(subscriber -> {
try {
if (!subscriber.isUnsubscribed()) {
for (int i = 1000; i < 1005; i++) {
subscriber.onNext(new Integer(i));
log.info(String.valueOf(i));
}
subscriber.onCompleted();
}
}catch (Exception e){
subscriber.onError(e);
}
}).map(o -> add((Integer) o))
.filter(integer -> integer >= 3)
.subscribe(o -> integers.add( o * 10));
System.out.println(integers);
}
public static void integerTest(){
//Integer会缓存-127~127的数据
Integer i = 127;
Integer tmp = i;
try {
Field field = tmp.getClass().getDeclaredField("value");
field.setAccessible(true);
field.set(tmp, 1000);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
add(i);
i = i + 1;
Integer j = i;
System.out.println(i);
System.out.println(j);
}
public static Integer add (Integer a){
// a = a + 1;
return new Integer((a) + 1);
}
}
| UTF-8 | Java | 2,143 | java | RxJavaTest.java | Java | [
{
"context": "ort java.util.concurrent.TimeUnit;\n\n/**\n * @author yangxvhao\n * @date 18-5-15.\n */\n@Slf4j\npublic class RxJavaT",
"end": 238,
"score": 0.9995850920677185,
"start": 229,
"tag": "USERNAME",
"value": "yangxvhao"
}
]
| null | []
| package com.yangxvhao.demo.proxy;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author yangxvhao
* @date 18-5-15.
*/
@Slf4j
public class RxJavaTest {
public static void main(String[] args) {
// integerTest();
// create();
interval();
}
public static void interval(){
List<Integer> integers = new ArrayList<Integer>(){{
add(1);add(2);add(3);add(4);
}};
Observable.from(integers)
.map(RxJavaTest::add)
.flatMap(integer -> Observable.interval(2, TimeUnit.MINUTES))
.subscribe(System.out::println);
}
public static void create(){
List<Integer> integers = new ArrayList<>();
Observable.create(subscriber -> {
try {
if (!subscriber.isUnsubscribed()) {
for (int i = 1000; i < 1005; i++) {
subscriber.onNext(new Integer(i));
log.info(String.valueOf(i));
}
subscriber.onCompleted();
}
}catch (Exception e){
subscriber.onError(e);
}
}).map(o -> add((Integer) o))
.filter(integer -> integer >= 3)
.subscribe(o -> integers.add( o * 10));
System.out.println(integers);
}
public static void integerTest(){
//Integer会缓存-127~127的数据
Integer i = 127;
Integer tmp = i;
try {
Field field = tmp.getClass().getDeclaredField("value");
field.setAccessible(true);
field.set(tmp, 1000);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
add(i);
i = i + 1;
Integer j = i;
System.out.println(i);
System.out.println(j);
}
public static Integer add (Integer a){
// a = a + 1;
return new Integer((a) + 1);
}
}
| 2,143 | 0.512905 | 0.494134 | 77 | 26.675325 | 18.581125 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532468 | false | false | 10 |
e9f47f5dc0ddddb391a7520f0503db9f6d818317 | 28,089,086,157,038 | b5f3b53782e9a07882c03c478c9f9490f59afc3c | /app/src/main/java/com/auvgo/tmc/views/MyDialog.java | 4498158dccf3bb8fdbd91e3c68b90efea083e483 | []
| no_license | Ciscen/Tmc_compony | https://github.com/Ciscen/Tmc_compony | 890cff659fc2eb08b5df791f203a760e2a3aaa05 | 51164edbe6e935aaa22446541bb6c2f22c95bdaf | refs/heads/master | 2021-01-20T13:11:32.973000 | 2017-05-19T06:29:56 | 2017-05-19T06:29:56 | 90,459,570 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.auvgo.tmc.views;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import com.auvgo.tmc.R;
import com.auvgo.tmc.utils.DeviceUtils;
/**
* Created by lc on 2016/11/09
*/
public class MyDialog extends Dialog {
private TextView title_tv;
private View divider;
private TextView tv1;
private TextView tv2;
private TextView content_tv;
private Context context;
private OnButtonClickListener listener;
private String title, left, right, content;
public interface OnButtonClickListener {
void onLeftClick();
void onRightClick();
}
/**
* @param context
* @param left 左键
* @param right 右键
* @param content 内容
* @param listener 监听
*/
public MyDialog(Context context, String left, String right, String content, final OnButtonClickListener listener) {
super(context, R.style.Dialog);
setContentView(R.layout.dialog_mine);
this.context = context;
this.listener = listener;
this.left = left;
this.right = right;
this.content = content;
initViews();
}
private void initViews() {
findViews();
setText();
}
private void findViews() {
divider = findViewById(R.id.dialog_divider);
tv1 = (TextView) findViewById(R.id.MyDialog_click_one);
tv2 = (TextView) findViewById(R.id.MyDialog_click_two);
content_tv = (TextView) findViewById(R.id.MyDialog_massage);
title_tv = (TextView) findViewById(R.id.MyDialog_title);
content_tv.setText(content);
}
private void setText() {
if (!TextUtils.isEmpty(left)) {
tv1.setText(left);
tv1.setVisibility(View.VISIBLE);
} else {
tv1.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(right)) {
tv2.setText(right);
tv2.setVisibility(View.VISIBLE);
} else {
tv2.setText("");
tv2.setVisibility(View.GONE);
}
if (TextUtils.isEmpty(right) || TextUtils.isEmpty(left)) {
divider.setVisibility(View.GONE);
} else {
divider.setVisibility(View.VISIBLE);
}
if (!TextUtils.isEmpty(title)) {
title_tv.setText(title);
title_tv.setVisibility(View.VISIBLE);
}
tv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (MyDialog.this.listener != null)
MyDialog.this.listener.onLeftClick();
dismiss();
}
});
tv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (MyDialog.this.listener != null)
MyDialog.this.listener.onRightClick();
dismiss();
}
});
}
public MyDialog(Context context, String title, String left, String right, String content, OnButtonClickListener listener) {
super(context, R.style.Dialog);
setContentView(R.layout.dialog_mine);
this.context = context;
this.listener = listener;
this.left = left;
this.right = right;
this.content = content;
this.title = title;
initViews();
}
@Override
public void show() {
super.show();
// WindowManager.LayoutParams lp = getWindow().getAttributes();
// lp.width = DeviceUtils.deviceWidth() - 210; //设置宽度
// getWindow().setAttributes(lp);
}
public void setTitle(String title) {
this.title = title;
}
public void setLeft(String left) {
this.left = left;
}
public void setRight(String right) {
this.right = right;
}
public void setContent(String content) {
this.content = content;
}
public Context getmContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public void setListener(OnButtonClickListener listener) {
this.listener = listener;
}
//改动后生效
public void invalicade() {
initViews();
}
}
| UTF-8 | Java | 4,519 | java | MyDialog.java | Java | [
{
"context": "m.auvgo.tmc.utils.DeviceUtils;\n\n\n/**\n * Created by lc on 2016/11/09\n */\npublic class MyDialog extends D",
"end": 418,
"score": 0.9976137280464172,
"start": 416,
"tag": "USERNAME",
"value": "lc"
}
]
| null | []
| package com.auvgo.tmc.views;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import com.auvgo.tmc.R;
import com.auvgo.tmc.utils.DeviceUtils;
/**
* Created by lc on 2016/11/09
*/
public class MyDialog extends Dialog {
private TextView title_tv;
private View divider;
private TextView tv1;
private TextView tv2;
private TextView content_tv;
private Context context;
private OnButtonClickListener listener;
private String title, left, right, content;
public interface OnButtonClickListener {
void onLeftClick();
void onRightClick();
}
/**
* @param context
* @param left 左键
* @param right 右键
* @param content 内容
* @param listener 监听
*/
public MyDialog(Context context, String left, String right, String content, final OnButtonClickListener listener) {
super(context, R.style.Dialog);
setContentView(R.layout.dialog_mine);
this.context = context;
this.listener = listener;
this.left = left;
this.right = right;
this.content = content;
initViews();
}
private void initViews() {
findViews();
setText();
}
private void findViews() {
divider = findViewById(R.id.dialog_divider);
tv1 = (TextView) findViewById(R.id.MyDialog_click_one);
tv2 = (TextView) findViewById(R.id.MyDialog_click_two);
content_tv = (TextView) findViewById(R.id.MyDialog_massage);
title_tv = (TextView) findViewById(R.id.MyDialog_title);
content_tv.setText(content);
}
private void setText() {
if (!TextUtils.isEmpty(left)) {
tv1.setText(left);
tv1.setVisibility(View.VISIBLE);
} else {
tv1.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(right)) {
tv2.setText(right);
tv2.setVisibility(View.VISIBLE);
} else {
tv2.setText("");
tv2.setVisibility(View.GONE);
}
if (TextUtils.isEmpty(right) || TextUtils.isEmpty(left)) {
divider.setVisibility(View.GONE);
} else {
divider.setVisibility(View.VISIBLE);
}
if (!TextUtils.isEmpty(title)) {
title_tv.setText(title);
title_tv.setVisibility(View.VISIBLE);
}
tv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (MyDialog.this.listener != null)
MyDialog.this.listener.onLeftClick();
dismiss();
}
});
tv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (MyDialog.this.listener != null)
MyDialog.this.listener.onRightClick();
dismiss();
}
});
}
public MyDialog(Context context, String title, String left, String right, String content, OnButtonClickListener listener) {
super(context, R.style.Dialog);
setContentView(R.layout.dialog_mine);
this.context = context;
this.listener = listener;
this.left = left;
this.right = right;
this.content = content;
this.title = title;
initViews();
}
@Override
public void show() {
super.show();
// WindowManager.LayoutParams lp = getWindow().getAttributes();
// lp.width = DeviceUtils.deviceWidth() - 210; //设置宽度
// getWindow().setAttributes(lp);
}
public void setTitle(String title) {
this.title = title;
}
public void setLeft(String left) {
this.left = left;
}
public void setRight(String right) {
this.right = right;
}
public void setContent(String content) {
this.content = content;
}
public Context getmContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public void setListener(OnButtonClickListener listener) {
this.listener = listener;
}
//改动后生效
public void invalicade() {
initViews();
}
}
| 4,519 | 0.595318 | 0.589967 | 164 | 26.347561 | 21.111086 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.560976 | false | false | 10 |
58191c5e719244084ea432f4d7ff63db0cda4f27 | 19,267,223,336,781 | bf9031bcf29d7859d603640d0278e9bac44bda17 | /5-Source_Code/NetBeans Projects/StockMarketSim/src/stockmarketsim/Stock.java | 61f3af53a1b9d552211c042876e5e5c851f57903 | []
| no_license | lonewolffcoder/StockMarketSim | https://github.com/lonewolffcoder/StockMarketSim | 08df3d4e9cec96ead620f20df8d499a793743171 | 80d8722dc2c35629229f4b01af18968c3319cff4 | refs/heads/master | 2021-08-07T05:53:38.029000 | 2017-11-07T17:33:11 | 2017-11-07T17:33:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package stockmarketsim;
/**
* Represents a collection of stocks.
*
* @author lh340, jc570
*/
public class Stock {
private Company company;
private int quantity;
/**
* Constructor for stock objects.
*
* @param company The company associated with thee stocks.
* @param quantity The amount of stocks represented by this object.
*/
public Stock(Company company, int quantity) {
this.company = company;
this.quantity = quantity;
}
/**
*
* @return The company the stocks belong to.
*/
public Company getCompany() {
return company;
}
/**
*
* @return The amount of stocks represented by this object.
*/
public int getQuantity() {
return quantity;
}
/**
*
* @return The value of these stocks.
*/
public int getValue() {
return (int)Math.round(company.getPrice() * (double)quantity);
}
/**
* Sets the quantity of stocks represented by this object.
*
* @param newQuantity The new quantity.
*/
public void setQuantity(int newQuantity) {
quantity = newQuantity;
}
}
| UTF-8 | Java | 1,076 | java | Stock.java | Java | [
{
"context": "* Represents a collection of stocks.\n *\n * @author lh340, jc570\n */\npublic class Stock {\n\n private Compan",
"end": 86,
"score": 0.9996994137763977,
"start": 81,
"tag": "USERNAME",
"value": "lh340"
},
{
"context": "sents a collection of stocks.\n *\n * @author lh340, jc570\n */\npublic class Stock {\n\n private Company compa",
"end": 93,
"score": 0.9996883273124695,
"start": 88,
"tag": "USERNAME",
"value": "jc570"
}
]
| null | []
| package stockmarketsim;
/**
* Represents a collection of stocks.
*
* @author lh340, jc570
*/
public class Stock {
private Company company;
private int quantity;
/**
* Constructor for stock objects.
*
* @param company The company associated with thee stocks.
* @param quantity The amount of stocks represented by this object.
*/
public Stock(Company company, int quantity) {
this.company = company;
this.quantity = quantity;
}
/**
*
* @return The company the stocks belong to.
*/
public Company getCompany() {
return company;
}
/**
*
* @return The amount of stocks represented by this object.
*/
public int getQuantity() {
return quantity;
}
/**
*
* @return The value of these stocks.
*/
public int getValue() {
return (int)Math.round(company.getPrice() * (double)quantity);
}
/**
* Sets the quantity of stocks represented by this object.
*
* @param newQuantity The new quantity.
*/
public void setQuantity(int newQuantity) {
quantity = newQuantity;
}
}
| 1,076 | 0.641264 | 0.635688 | 56 | 18.214285 | 19.823971 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.196429 | false | false | 10 |
0b7a2d15b4ac3604d49fe8bb9f2ba9f4b1e27009 | 11,519,102,338,694 | 28b90c0de28d060d43e0ec67b101fdb9d8035e57 | /src/main/java/com/widgets/example/demo/exceptions/InvalidPaginationParamsException.java | 3e1ae4d0fdfeede238f98a113fd81570033be6ee | []
| no_license | DmitriyBorodulin/demo.java | https://github.com/DmitriyBorodulin/demo.java | 62bec3ff08692192f4302ae25ea8ca297329836d | 355b3544b7849b37630d547a686721b61e30879c | refs/heads/master | 2022-11-13T04:35:01.709000 | 2020-07-12T15:31:28 | 2020-07-12T15:31:28 | 276,196,028 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.widgets.example.demo.exceptions;
public class InvalidPaginationParamsException extends Exception {
public InvalidPaginationParamsException(String errorMessage) {
super(errorMessage);
}
}
| UTF-8 | Java | 216 | java | InvalidPaginationParamsException.java | Java | []
| null | []
| package com.widgets.example.demo.exceptions;
public class InvalidPaginationParamsException extends Exception {
public InvalidPaginationParamsException(String errorMessage) {
super(errorMessage);
}
}
| 216 | 0.787037 | 0.787037 | 7 | 29.857143 | 26.95726 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 10 |
41ca295fc7c2341045a822594d4b767b53580147 | 20,521,353,745,063 | 5f392d2e16ccd1feefa3d62e31ef1453df00273e | /app/src/main/java/com/zx/zhuangxiu/activity/MingXiActivity.java | cb5f4bbb0833b7162d3071d11b621c99a28e5ba7 | []
| no_license | daoyua/zhuangxiu | https://github.com/daoyua/zhuangxiu | 631dea0135c7e9c354ba83ac1786d7d4b05a8eb6 | d33b8e80148f19252feef3879886d43944cbc666 | refs/heads/master | 2020-04-05T18:04:21.826000 | 2019-02-18T14:28:14 | 2019-02-18T14:28:14 | 157,087,638 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zx.zhuangxiu.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zx.zhuangxiu.OkHttpUtils;
import com.zx.zhuangxiu.R;
import com.zx.zhuangxiu.URLS;
import com.zx.zhuangxiu.adapter.MingXiAdapter;
import com.zx.zhuangxiu.model.MingXiBean;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class MingXiActivity extends AppCompatActivity {
private ListView mMingxiListview;
private TextView mingxi_back;
private MingXiAdapter mingXiAdapter;
private List<MingXiBean.DataBean> jinEMxTwoList = new ArrayList<>();
private SmartRefreshLayout mRefresh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ming_xi);
initView();
getMingXiInfo();
}
private void initView() {
mMingxiListview = (ListView) findViewById(R.id.mingxi_listview);
mingxi_back=(TextView)findViewById(R.id.mingxi_back);
mingxi_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mRefresh = findViewById(R.id.refresh);
mRefresh.setRefreshHeader(new ClassicsHeader(this).setEnableLastTime(true));
mRefresh.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshLayout) {
getMingXiInfo();
}
});
}
private void getMingXiInfo() {
String url = URLS.JinEMingXi(URLS.getUser_id());
OkHttpUtils.get(url, new OkHttpUtils.ResultCallback<MingXiBean>() {
@Override
public void onSuccess(MingXiBean response) {
if (mRefresh!=null){
mRefresh.finishRefresh();
}
if(response.getResult() == 1){
jinEMxTwoList.clear();
List<MingXiBean.DataBean> data = response.getData();
// Collections.reverse(data);
Collections.sort(data, new Comparator<MingXiBean.DataBean>() {
@Override
public int compare(MingXiBean.DataBean o1, MingXiBean.DataBean o2) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date dt1 = format.parse(o1.getTime());
Date dt2 = format.parse(o2.getTime());
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
Collections.reverse(data);
jinEMxTwoList.addAll(data);
mingXiAdapter = new MingXiAdapter(MingXiActivity.this, jinEMxTwoList);
mMingxiListview.setAdapter(mingXiAdapter);
}else {
Toast.makeText(MingXiActivity.this, "抱歉,暂时还没有交易!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Exception e) {
if (mRefresh!=null){
mRefresh.finishRefresh();
}
}
});
}
}
| UTF-8 | Java | 4,293 | java | MingXiActivity.java | Java | []
| null | []
| package com.zx.zhuangxiu.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zx.zhuangxiu.OkHttpUtils;
import com.zx.zhuangxiu.R;
import com.zx.zhuangxiu.URLS;
import com.zx.zhuangxiu.adapter.MingXiAdapter;
import com.zx.zhuangxiu.model.MingXiBean;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class MingXiActivity extends AppCompatActivity {
private ListView mMingxiListview;
private TextView mingxi_back;
private MingXiAdapter mingXiAdapter;
private List<MingXiBean.DataBean> jinEMxTwoList = new ArrayList<>();
private SmartRefreshLayout mRefresh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ming_xi);
initView();
getMingXiInfo();
}
private void initView() {
mMingxiListview = (ListView) findViewById(R.id.mingxi_listview);
mingxi_back=(TextView)findViewById(R.id.mingxi_back);
mingxi_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
mRefresh = findViewById(R.id.refresh);
mRefresh.setRefreshHeader(new ClassicsHeader(this).setEnableLastTime(true));
mRefresh.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshLayout) {
getMingXiInfo();
}
});
}
private void getMingXiInfo() {
String url = URLS.JinEMingXi(URLS.getUser_id());
OkHttpUtils.get(url, new OkHttpUtils.ResultCallback<MingXiBean>() {
@Override
public void onSuccess(MingXiBean response) {
if (mRefresh!=null){
mRefresh.finishRefresh();
}
if(response.getResult() == 1){
jinEMxTwoList.clear();
List<MingXiBean.DataBean> data = response.getData();
// Collections.reverse(data);
Collections.sort(data, new Comparator<MingXiBean.DataBean>() {
@Override
public int compare(MingXiBean.DataBean o1, MingXiBean.DataBean o2) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date dt1 = format.parse(o1.getTime());
Date dt2 = format.parse(o2.getTime());
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
Collections.reverse(data);
jinEMxTwoList.addAll(data);
mingXiAdapter = new MingXiAdapter(MingXiActivity.this, jinEMxTwoList);
mMingxiListview.setAdapter(mingXiAdapter);
}else {
Toast.makeText(MingXiActivity.this, "抱歉,暂时还没有交易!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Exception e) {
if (mRefresh!=null){
mRefresh.finishRefresh();
}
}
});
}
}
| 4,293 | 0.557247 | 0.5535 | 114 | 36.464912 | 24.218008 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 10 |
0a2a7a72081a501e24708229a3c536f2bd842bee | 18,038,862,704,388 | 2dbf70f1d7aa05924971750587e9605dd5ffc0c6 | /src/com/crust87/paint/example3/factory/EllipseFactory.java | 211f7988da6c4a80f0480f5c8aa13cbd5b36bfc3 | []
| no_license | Koiwaiii/DesignPatternsExample | https://github.com/Koiwaiii/DesignPatternsExample | 7303a2c74205a067d2e9edbf60cead5aab0e9826 | 01e49152f4a81554ee9b1d4f60eed33c17e231cd | refs/heads/master | 2023-03-15T01:17:53.139000 | 2016-01-07T02:51:14 | 2016-01-07T02:51:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.crust87.paint.example3.factory;
import com.crust87.paint.drawingtools.PaintEllipse;
import com.crust87.paint.drawingtools.PaintShape;
public class EllipseFactory extends ShapeFactory {
@Override
public PaintShape makeShape() {
return new PaintEllipse();
}
}
| UTF-8 | Java | 278 | java | EllipseFactory.java | Java | []
| null | []
| package com.crust87.paint.example3.factory;
import com.crust87.paint.drawingtools.PaintEllipse;
import com.crust87.paint.drawingtools.PaintShape;
public class EllipseFactory extends ShapeFactory {
@Override
public PaintShape makeShape() {
return new PaintEllipse();
}
}
| 278 | 0.802158 | 0.776978 | 12 | 22.166666 | 21.149599 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 10 |
380c4b4ce3491b5b868cc0848e94c73c96e24fc5 | 25,417,616,514,632 | 7949b5eb90ace3ebf207add07746dd261702a1bd | /src/test/java/utilities/LoggerWrapper.java | d2fb711c307f24149ee3d5d204de00940cff3bd4 | []
| no_license | thedarkman123/remoteAutoFramework | https://github.com/thedarkman123/remoteAutoFramework | 34c610d1704c2de04311e0c88b0909fc5e9a7a69 | 5d772aa589d721770bf26e0c55569ec6c93873cf | refs/heads/master | 2020-04-09T02:27:40.115000 | 2018-12-02T06:27:42 | 2018-12-02T06:27:42 | 159,941,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package utilities;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
public class LoggerWrapper {
public static ThreadLocal<Logger> loggerThread=
new ThreadLocal<Logger>();
public static Logger init(String path,String name) {
FileAppender appender = new FileAppender();
Logger logger = null;
appender.setFile(path);
appender.setLayout(new PatternLayout("%d [%t] %-5p %c - %m%n"));
appender.activateOptions();
logger.getLogger(name);
logger.setAdditivity(false);
logger.addAppender(appender);
return logger;
}
public static void setLogger(Logger lg) {
loggerThread.set(lg);
}
public static Logger getLogger() {
return loggerThread.get();
}
// public static void setAppender(FileAppender appender) {
// appenderThread.set(appender);
// }
//
// public static FileAppender getAppender() {
// return appenderThread.get();
// }
public static void logToFile(String strTofile) {
getLogger().info(strTofile);
}
// public static void closeLog() {
// // Remove appender
// getLogger().removeAppender(getAppender());
// }
}
| UTF-8 | Java | 1,251 | java | LoggerWrapper.java | Java | []
| null | []
| package utilities;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
public class LoggerWrapper {
public static ThreadLocal<Logger> loggerThread=
new ThreadLocal<Logger>();
public static Logger init(String path,String name) {
FileAppender appender = new FileAppender();
Logger logger = null;
appender.setFile(path);
appender.setLayout(new PatternLayout("%d [%t] %-5p %c - %m%n"));
appender.activateOptions();
logger.getLogger(name);
logger.setAdditivity(false);
logger.addAppender(appender);
return logger;
}
public static void setLogger(Logger lg) {
loggerThread.set(lg);
}
public static Logger getLogger() {
return loggerThread.get();
}
// public static void setAppender(FileAppender appender) {
// appenderThread.set(appender);
// }
//
// public static FileAppender getAppender() {
// return appenderThread.get();
// }
public static void logToFile(String strTofile) {
getLogger().info(strTofile);
}
// public static void closeLog() {
// // Remove appender
// getLogger().removeAppender(getAppender());
// }
}
| 1,251 | 0.646683 | 0.643485 | 50 | 23.02 | 18.827097 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.52 | false | false | 10 |
3863f3c0d989567ea7a286d473b1e2689127fe6e | 12,687,333,445,296 | ce1c71509b8a8924678d6f32b9eee00329ade5af | /tn.edu.esprit.info1.toEJB/ejbModule/domain/CategorieChambreProduit.java | 54d76b690609596593c500eacc58c804f82a12a1 | []
| no_license | wess1984/to-repo | https://github.com/wess1984/to-repo | d418cbf44ff269a71ef1b4e23a9ea0adfac6f16c | 88cd3d0c8c6502a704f7832b34238036b5f93409 | refs/heads/master | 2016-09-05T23:29:40.122000 | 2015-04-11T12:30:31 | 2015-04-11T12:30:31 | 32,886,021 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package domain;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
/**
* Entity implementation class for Entity: CategorieChambreProduit
*
*/
@Entity
public class CategorieChambreProduit implements Serializable {
private CategorieChambreProduitId categorieChambreProduitId;
private String typeChambre;
private Integer stock;
private static final long serialVersionUID = 1L;
private Hotel produit;
private CategorieChambre categorieChambre;
public CategorieChambreProduit(
CategorieChambreProduitId categorieChambreProduitId,
String typeChambre, Integer stock, Hotel produit,
CategorieChambre categorieChambre) {
super();
this.categorieChambreProduitId = categorieChambreProduitId;
this.typeChambre = typeChambre;
this.stock = stock;
this.produit = produit;
this.categorieChambre = categorieChambre;
}
public CategorieChambreProduit() {
super();
}
public String getTypeChambre() {
return this.typeChambre;
}
public void setTypeChambre(String typeChambre) {
this.typeChambre = typeChambre;
}
public Integer getStock() {
return this.stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
@EmbeddedId
public CategorieChambreProduitId getCategorieChambreProduitId() {
return categorieChambreProduitId;
}
public void setCategorieChambreProduitId(CategorieChambreProduitId categorieChambreProduitId) {
this.categorieChambreProduitId = categorieChambreProduitId;
}
@ManyToOne()
@JoinColumn(name="idProduit",referencedColumnName="id",insertable=false,updatable=false)
public Hotel getProduit() {
return produit;
}
public void setProduit(Hotel produit) {
this.produit = produit;
}
@ManyToOne
@JoinColumn(name="idCategorieChambre",referencedColumnName="id",insertable=false,updatable=false)
public CategorieChambre getCategorieChambre() {
return categorieChambre;
}
public void setCategorieChambre(CategorieChambre categorieChambre) {
this.categorieChambre = categorieChambre;
}
@Override
public String toString() {
return "CategorieChambreProduit [categorieChambreProduitId="
+ categorieChambreProduitId + ", typeChambre=" + typeChambre
+ ", stock=" + stock + ", produit=" + produit
+ ", categorieChambre=" + categorieChambre + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((categorieChambre == null) ? 0 : categorieChambre.hashCode());
result = prime
* result
+ ((categorieChambreProduitId == null) ? 0
: categorieChambreProduitId.hashCode());
result = prime * result + ((produit == null) ? 0 : produit.hashCode());
result = prime * result + ((stock == null) ? 0 : stock.hashCode());
result = prime * result
+ ((typeChambre == null) ? 0 : typeChambre.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CategorieChambreProduit other = (CategorieChambreProduit) obj;
if (categorieChambre == null) {
if (other.categorieChambre != null)
return false;
} else if (!categorieChambre.equals(other.categorieChambre))
return false;
if (categorieChambreProduitId == null) {
if (other.categorieChambreProduitId != null)
return false;
} else if (!categorieChambreProduitId
.equals(other.categorieChambreProduitId))
return false;
if (produit == null) {
if (other.produit != null)
return false;
} else if (!produit.equals(other.produit))
return false;
if (stock == null) {
if (other.stock != null)
return false;
} else if (!stock.equals(other.stock))
return false;
if (typeChambre == null) {
if (other.typeChambre != null)
return false;
} else if (!typeChambre.equals(other.typeChambre))
return false;
return true;
}
}
| UTF-8 | Java | 3,929 | java | CategorieChambreProduit.java | Java | []
| null | []
| package domain;
import java.io.Serializable;
import java.lang.Integer;
import java.lang.String;
import javax.persistence.*;
/**
* Entity implementation class for Entity: CategorieChambreProduit
*
*/
@Entity
public class CategorieChambreProduit implements Serializable {
private CategorieChambreProduitId categorieChambreProduitId;
private String typeChambre;
private Integer stock;
private static final long serialVersionUID = 1L;
private Hotel produit;
private CategorieChambre categorieChambre;
public CategorieChambreProduit(
CategorieChambreProduitId categorieChambreProduitId,
String typeChambre, Integer stock, Hotel produit,
CategorieChambre categorieChambre) {
super();
this.categorieChambreProduitId = categorieChambreProduitId;
this.typeChambre = typeChambre;
this.stock = stock;
this.produit = produit;
this.categorieChambre = categorieChambre;
}
public CategorieChambreProduit() {
super();
}
public String getTypeChambre() {
return this.typeChambre;
}
public void setTypeChambre(String typeChambre) {
this.typeChambre = typeChambre;
}
public Integer getStock() {
return this.stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
@EmbeddedId
public CategorieChambreProduitId getCategorieChambreProduitId() {
return categorieChambreProduitId;
}
public void setCategorieChambreProduitId(CategorieChambreProduitId categorieChambreProduitId) {
this.categorieChambreProduitId = categorieChambreProduitId;
}
@ManyToOne()
@JoinColumn(name="idProduit",referencedColumnName="id",insertable=false,updatable=false)
public Hotel getProduit() {
return produit;
}
public void setProduit(Hotel produit) {
this.produit = produit;
}
@ManyToOne
@JoinColumn(name="idCategorieChambre",referencedColumnName="id",insertable=false,updatable=false)
public CategorieChambre getCategorieChambre() {
return categorieChambre;
}
public void setCategorieChambre(CategorieChambre categorieChambre) {
this.categorieChambre = categorieChambre;
}
@Override
public String toString() {
return "CategorieChambreProduit [categorieChambreProduitId="
+ categorieChambreProduitId + ", typeChambre=" + typeChambre
+ ", stock=" + stock + ", produit=" + produit
+ ", categorieChambre=" + categorieChambre + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((categorieChambre == null) ? 0 : categorieChambre.hashCode());
result = prime
* result
+ ((categorieChambreProduitId == null) ? 0
: categorieChambreProduitId.hashCode());
result = prime * result + ((produit == null) ? 0 : produit.hashCode());
result = prime * result + ((stock == null) ? 0 : stock.hashCode());
result = prime * result
+ ((typeChambre == null) ? 0 : typeChambre.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CategorieChambreProduit other = (CategorieChambreProduit) obj;
if (categorieChambre == null) {
if (other.categorieChambre != null)
return false;
} else if (!categorieChambre.equals(other.categorieChambre))
return false;
if (categorieChambreProduitId == null) {
if (other.categorieChambreProduitId != null)
return false;
} else if (!categorieChambreProduitId
.equals(other.categorieChambreProduitId))
return false;
if (produit == null) {
if (other.produit != null)
return false;
} else if (!produit.equals(other.produit))
return false;
if (stock == null) {
if (other.stock != null)
return false;
} else if (!stock.equals(other.stock))
return false;
if (typeChambre == null) {
if (other.typeChambre != null)
return false;
} else if (!typeChambre.equals(other.typeChambre))
return false;
return true;
}
}
| 3,929 | 0.723594 | 0.721303 | 143 | 26.475525 | 22.344671 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.153846 | false | false | 10 |
9026f110dce943f09d3027def954ffc8e0b27b8f | 13,469,017,489,938 | 4038565b4118848593a863f5649b98aca299e0a5 | /chapter07/core/src/test/java/com/manning/neo4jia/chapter07/core/LockAndDeadlockTests.java | afa51ade3df7b93e31ec763d69662794363ccf9a | []
| no_license | theMoreTheBetter/copyneo4jaction | https://github.com/theMoreTheBetter/copyneo4jaction | 86735447790b8323b7c911fb0a41d726f29f3483 | def637ac78c7fedfb66a96c4a62b0da167839c60 | refs/heads/master | 2022-12-20T03:56:50.418000 | 2020-03-08T05:43:03 | 2020-03-08T05:43:03 | 245,759,098 | 0 | 0 | null | false | 2022-12-16T00:50:31 | 2020-03-08T05:41:46 | 2020-03-08T05:43:14 | 2022-12-16T00:50:28 | 134 | 0 | 0 | 16 | Java | false | false | package com.manning.neo4jia.chapter07.core;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.kernel.DeadlockDetectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class LockAndDeadlockTests extends AbstractTransactionTests {
private static final Logger logger = LoggerFactory.getLogger(LockAndDeadlockTests.class);
private ExecutorService executorService;
@Before
public void setup() {
super.setup();
this.executorService = Executors.newFixedThreadPool(2);
}
@Test
@Ignore("This test hangs as the write lock cannot be acquire whilst there is " +
"a read lock in place and the current code (reading) is waiting for " +
"the update to occur .... stalemate ")
public void unrecoverableWriteLockWaitingForReadLockToBeReleased() throws Exception {
try (Transaction tx = this.graphDatabaseService.beginTx()) {
// Acquire the lock on John, so that everything we do in here
// will only be what is visible to us
tx.acquireReadLock(john);
assertNameAndAgeViaLookup(john.getId(), "John", 34, "John");
// Do the update in a separate Thread and ensure its actually updated
doUpdateInSeparateThread(new PersonUpdater("John", 44));
// Now, back in our thread, ensure we read the original value
// (i.e. NOT the value that was committed in the separate thread)
assertNameAndAgeViaLookup(john.getId(), "John", 34, "John");
tx.success();
}
// But now, outside of our lock and TX, we should be able to read the latest value
try (Transaction tx = this.graphDatabaseService.beginTx()) {
assertNameAndAgeViaLookup(john.getId(), "John", 44, "John");
}
}
@Test
public void writeLockBlockedUntilReadLockIsReleased() throws Exception {
PersonUpdater personUpdater = new PersonUpdater("John", 44);
Future<Integer> confirmationOfUpdatedAge;
try (Transaction tx = this.graphDatabaseService.beginTx()) {
// Acquire the lock on John, so that everything we do in here
// will only be what is visible to us
tx.acquireReadLock(john);
assertNameAndAgeViaLookup(john.getId(), "John", 34, "John");
// Do the update in a separate Thread
// NB - We cannot actually call get on the future as it will block until
// the read releases the lock
confirmationOfUpdatedAge = executorService.submit(personUpdater);
// Now, back in our thread, ensure we read the original value
// (i.e. NOT the value that was committed in the separate thread)
assertNameAndAgeViaLookup(john.getId(), "John", 34, "John");
tx.success();
}
// But now, the lock has been released and we should be able to read the
// latest value after ensuring the update in the other thread finished.
try (Transaction tx = this.graphDatabaseService.beginTx()) {
assertEquals(personUpdater.newAge, confirmationOfUpdatedAge.get());
assertNameAndAgeViaLookup(john.getId(), "John", 44, "John");
}
}
@Test
public void deadlockScenarioAvoidedByOrderingUpdates() throws Exception {
DualPersonUpdater dru1 = new DualPersonUpdater("John", "Bob", 44, 46);
DualPersonUpdater dru2 = new DualPersonUpdater("John", "Bob", 54, 56);
Future<Boolean> dru1Done = executorService.submit(dru1);
sleepABit();
Future<Boolean> dru2Done = executorService.submit(dru2);
dru1Done.get();
dru2Done.get();
}
//Can't test this directly as the expected exception is nested
//@Test(expected = DeadlockDetectedException.class)
@Test
public void deadlockScenarioDetectedWithBadlyOrderedUpdates() throws Exception {
try {
DualPersonUpdater dru1 = new DualPersonUpdater("John", "Bob", 44, 46);
DualPersonUpdater dru2 = new DualPersonUpdater("Bob", "John", 56, 54);
Future<Boolean> dru1Done = executorService.submit(dru1);
sleepABit();
Future<Boolean> dru2Done = executorService.submit(dru2);
dru1Done.get();
dru2Done.get();
} catch (ExecutionException e) {
assertTrue(
"Expected Neo4j to detect this deadlock but rather issue was" + e.getMessage(),
(e.getCause() instanceof DeadlockDetectedException));
}
}
private void sleepABit() throws InterruptedException {
Thread.sleep(500);
}
private void doUpdateInSeparateThread(PersonUpdater personUpdater) throws Exception {
try (Transaction tx = this.graphDatabaseService.beginTx()) {
Future<Integer> confirmationOfUpdatedAge = executorService.submit(personUpdater);
assertEquals(personUpdater.newAge, confirmationOfUpdatedAge.get());
tx.success();
}
}
private void assertNameAndAgeViaLookup(long personId, String personName, Integer expectedAge, String expectedName) {
String lookedUpName = lookupNameForId(personId);
Integer lookedUpAge = lookupAgeForPerson(personName);
assertEquals(expectedAge, lookedUpAge);
assertEquals(expectedName, lookedUpName);
}
private int lookupAgeForPerson(String name) {
Node n = this.graphDatabaseService.index().forNodes("byName").get("name", name).getSingle();
int age = (Integer) n.getProperty("age");
return age;
}
private String lookupNameForId(long id) {
Node n = this.graphDatabaseService.getNodeById(id);
String name = (String) n.getProperty("name");
return name;
}
class DualPersonUpdater implements Callable<Boolean> {
String person1name;
String person2name;
Integer age1;
Integer age2;
DualPersonUpdater(String person1name, String person2name, Integer age1, Integer age2) {
this.person1name = person1name;
this.person2name = person2name;
this.age1 = age1;
this.age2 = age2;
}
private void updatePerson(String name, Integer age) {
try (Transaction tx = graphDatabaseService.beginTx()) {
Node n = graphDatabaseService.index().forNodes("byName").get("name", name).getSingle();
n.setProperty("age", age);
tx.success();
}
}
@Override
public Boolean call() throws Exception {
logger.info("Txt begun...");
try (Transaction tx = graphDatabaseService.beginTx()) {
logger.info("Starting Person1 update...");
updatePerson(person1name, age1);
logger.info("Finished Person1 update ...");
Thread.sleep(1000);
logger.info("Starting Person2 update...");
updatePerson(person2name, age2);
logger.info("Finished Person2 update ...");
tx.success();
return Boolean.TRUE;
}
}
}
class PersonUpdater implements Callable<Integer> {
private String personName;
private Integer newAge;
private Integer sleepTime;
PersonUpdater(String personName, Integer newAge) {
this(personName, newAge, null);
}
PersonUpdater(String personName, Integer newAge, Integer sleepTime) {
this.personName = personName;
this.newAge = newAge;
this.sleepTime = sleepTime;
}
@Override
public Integer call() throws Exception {
Transaction tx = graphDatabaseService.beginTx();
try {
Node n = graphDatabaseService.index().forNodes("byName").get("name", personName).getSingle();
tx.acquireWriteLock(n);
n.setProperty("age", newAge);
if (sleepTime != null) {
Thread.sleep(sleepTime);
}
tx.success();
return newAge;
} catch (InterruptedException e) {
logger.info("Caught InterruptedException " + e.getMessage());
throw e;
} finally {
tx.finish();
}
}
}
}
| UTF-8 | Java | 8,693 | java | LockAndDeadlockTests.java | Java | [
{
"context": "e.beginTx()) {\n\n // Acquire the lock on John, so that everything we do in here\n // ",
"end": 1191,
"score": 0.9871026277542114,
"start": 1187,
"tag": "NAME",
"value": "John"
},
{
"context": " assertNameAndAgeViaLookup(john.getId(), \"John\", 34, \"John\");\n\n // Do the update in a",
"end": 1371,
"score": 0.9997395873069763,
"start": 1367,
"tag": "NAME",
"value": "John"
},
{
"context": "ertNameAndAgeViaLookup(john.getId(), \"John\", 34, \"John\");\n\n // Do the update in a separate Th",
"end": 1383,
"score": 0.9997389912605286,
"start": 1379,
"tag": "NAME",
"value": "John"
},
{
"context": " doUpdateInSeparateThread(new PersonUpdater(\"John\", 44));\n\n // Now, back in our thread, ",
"end": 1530,
"score": 0.9993292689323425,
"start": 1526,
"tag": "NAME",
"value": "John"
},
{
"context": " assertNameAndAgeViaLookup(john.getId(), \"John\", 34, \"John\");\n tx.success();\n ",
"end": 1749,
"score": 0.9997262358665466,
"start": 1745,
"tag": "NAME",
"value": "John"
},
{
"context": "ertNameAndAgeViaLookup(john.getId(), \"John\", 34, \"John\");\n tx.success();\n }\n\n /",
"end": 1761,
"score": 0.9997302293777466,
"start": 1757,
"tag": "NAME",
"value": "John"
},
{
"context": " assertNameAndAgeViaLookup(john.getId(), \"John\", 44, \"John\");\n }\n }\n\n @Test\n pub",
"end": 2019,
"score": 0.9996927976608276,
"start": 2015,
"tag": "NAME",
"value": "John"
},
{
"context": "ertNameAndAgeViaLookup(john.getId(), \"John\", 44, \"John\");\n }\n }\n\n @Test\n public void wri",
"end": 2031,
"score": 0.9997101426124573,
"start": 2027,
"tag": "NAME",
"value": "John"
},
{
"context": " PersonUpdater personUpdater = new PersonUpdater(\"John\", 44);\n Future<Integer> confirmationOfUpda",
"end": 2201,
"score": 0.9998319745063782,
"start": 2197,
"tag": "NAME",
"value": "John"
},
{
"context": "e.beginTx()) {\n\n // Acquire the lock on John, so that everything we do in here\n // ",
"end": 2368,
"score": 0.9974007606506348,
"start": 2364,
"tag": "NAME",
"value": "John"
},
{
"context": " assertNameAndAgeViaLookup(john.getId(), \"John\", 34, \"John\");\n\n // Do the update in a",
"end": 2548,
"score": 0.9998145699501038,
"start": 2544,
"tag": "NAME",
"value": "John"
},
{
"context": "ertNameAndAgeViaLookup(john.getId(), \"John\", 34, \"John\");\n\n // Do the update in a separate Th",
"end": 2560,
"score": 0.9997977018356323,
"start": 2556,
"tag": "NAME",
"value": "John"
},
{
"context": " assertNameAndAgeViaLookup(john.getId(), \"John\", 34, \"John\");\n tx.success();\n ",
"end": 3035,
"score": 0.9998170137405396,
"start": 3031,
"tag": "NAME",
"value": "John"
},
{
"context": "ertNameAndAgeViaLookup(john.getId(), \"John\", 34, \"John\");\n tx.success();\n }\n\n /",
"end": 3047,
"score": 0.9997798800468445,
"start": 3043,
"tag": "NAME",
"value": "John"
},
{
"context": " assertNameAndAgeViaLookup(john.getId(), \"John\", 44, \"John\");\n }\n }\n\n @Test\n pub",
"end": 3455,
"score": 0.9998328685760498,
"start": 3451,
"tag": "NAME",
"value": "John"
},
{
"context": "ertNameAndAgeViaLookup(john.getId(), \"John\", 44, \"John\");\n }\n }\n\n @Test\n public void dea",
"end": 3467,
"score": 0.9997959136962891,
"start": 3463,
"tag": "NAME",
"value": "John"
},
{
"context": " DualPersonUpdater dru1 = new DualPersonUpdater(\"John\", \"Bob\", 44, 46);\n DualPersonUpdater dru2 ",
"end": 3637,
"score": 0.9998196959495544,
"start": 3633,
"tag": "NAME",
"value": "John"
},
{
"context": "rsonUpdater dru1 = new DualPersonUpdater(\"John\", \"Bob\", 44, 46);\n DualPersonUpdater dru2 = new D",
"end": 3644,
"score": 0.9998224973678589,
"start": 3641,
"tag": "NAME",
"value": "Bob"
},
{
"context": " DualPersonUpdater dru2 = new DualPersonUpdater(\"John\", \"Bob\", 54, 56);\n\n Future<Boolean> dru1Do",
"end": 3716,
"score": 0.9998223185539246,
"start": 3712,
"tag": "NAME",
"value": "John"
},
{
"context": "rsonUpdater dru2 = new DualPersonUpdater(\"John\", \"Bob\", 54, 56);\n\n Future<Boolean> dru1Done = ex",
"end": 3723,
"score": 0.9997994303703308,
"start": 3720,
"tag": "NAME",
"value": "Bob"
},
{
"context": " DualPersonUpdater dru1 = new DualPersonUpdater(\"John\", \"Bob\", 44, 46);\n DualPersonUpdater d",
"end": 4240,
"score": 0.9998200535774231,
"start": 4236,
"tag": "NAME",
"value": "John"
},
{
"context": "rsonUpdater dru1 = new DualPersonUpdater(\"John\", \"Bob\", 44, 46);\n DualPersonUpdater dru2 = n",
"end": 4247,
"score": 0.9998030066490173,
"start": 4244,
"tag": "NAME",
"value": "Bob"
},
{
"context": " DualPersonUpdater dru2 = new DualPersonUpdater(\"Bob\", \"John\", 56, 54);\n\n Future<Boolean> d",
"end": 4322,
"score": 0.9996833801269531,
"start": 4319,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ersonUpdater dru2 = new DualPersonUpdater(\"Bob\", \"John\", 56, 54);\n\n Future<Boolean> dru1Done ",
"end": 4330,
"score": 0.9997710585594177,
"start": 4326,
"tag": "NAME",
"value": "John"
}
]
| null | []
| package com.manning.neo4jia.chapter07.core;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.kernel.DeadlockDetectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class LockAndDeadlockTests extends AbstractTransactionTests {
private static final Logger logger = LoggerFactory.getLogger(LockAndDeadlockTests.class);
private ExecutorService executorService;
@Before
public void setup() {
super.setup();
this.executorService = Executors.newFixedThreadPool(2);
}
@Test
@Ignore("This test hangs as the write lock cannot be acquire whilst there is " +
"a read lock in place and the current code (reading) is waiting for " +
"the update to occur .... stalemate ")
public void unrecoverableWriteLockWaitingForReadLockToBeReleased() throws Exception {
try (Transaction tx = this.graphDatabaseService.beginTx()) {
// Acquire the lock on John, so that everything we do in here
// will only be what is visible to us
tx.acquireReadLock(john);
assertNameAndAgeViaLookup(john.getId(), "John", 34, "John");
// Do the update in a separate Thread and ensure its actually updated
doUpdateInSeparateThread(new PersonUpdater("John", 44));
// Now, back in our thread, ensure we read the original value
// (i.e. NOT the value that was committed in the separate thread)
assertNameAndAgeViaLookup(john.getId(), "John", 34, "John");
tx.success();
}
// But now, outside of our lock and TX, we should be able to read the latest value
try (Transaction tx = this.graphDatabaseService.beginTx()) {
assertNameAndAgeViaLookup(john.getId(), "John", 44, "John");
}
}
@Test
public void writeLockBlockedUntilReadLockIsReleased() throws Exception {
PersonUpdater personUpdater = new PersonUpdater("John", 44);
Future<Integer> confirmationOfUpdatedAge;
try (Transaction tx = this.graphDatabaseService.beginTx()) {
// Acquire the lock on John, so that everything we do in here
// will only be what is visible to us
tx.acquireReadLock(john);
assertNameAndAgeViaLookup(john.getId(), "John", 34, "John");
// Do the update in a separate Thread
// NB - We cannot actually call get on the future as it will block until
// the read releases the lock
confirmationOfUpdatedAge = executorService.submit(personUpdater);
// Now, back in our thread, ensure we read the original value
// (i.e. NOT the value that was committed in the separate thread)
assertNameAndAgeViaLookup(john.getId(), "John", 34, "John");
tx.success();
}
// But now, the lock has been released and we should be able to read the
// latest value after ensuring the update in the other thread finished.
try (Transaction tx = this.graphDatabaseService.beginTx()) {
assertEquals(personUpdater.newAge, confirmationOfUpdatedAge.get());
assertNameAndAgeViaLookup(john.getId(), "John", 44, "John");
}
}
@Test
public void deadlockScenarioAvoidedByOrderingUpdates() throws Exception {
DualPersonUpdater dru1 = new DualPersonUpdater("John", "Bob", 44, 46);
DualPersonUpdater dru2 = new DualPersonUpdater("John", "Bob", 54, 56);
Future<Boolean> dru1Done = executorService.submit(dru1);
sleepABit();
Future<Boolean> dru2Done = executorService.submit(dru2);
dru1Done.get();
dru2Done.get();
}
//Can't test this directly as the expected exception is nested
//@Test(expected = DeadlockDetectedException.class)
@Test
public void deadlockScenarioDetectedWithBadlyOrderedUpdates() throws Exception {
try {
DualPersonUpdater dru1 = new DualPersonUpdater("John", "Bob", 44, 46);
DualPersonUpdater dru2 = new DualPersonUpdater("Bob", "John", 56, 54);
Future<Boolean> dru1Done = executorService.submit(dru1);
sleepABit();
Future<Boolean> dru2Done = executorService.submit(dru2);
dru1Done.get();
dru2Done.get();
} catch (ExecutionException e) {
assertTrue(
"Expected Neo4j to detect this deadlock but rather issue was" + e.getMessage(),
(e.getCause() instanceof DeadlockDetectedException));
}
}
private void sleepABit() throws InterruptedException {
Thread.sleep(500);
}
private void doUpdateInSeparateThread(PersonUpdater personUpdater) throws Exception {
try (Transaction tx = this.graphDatabaseService.beginTx()) {
Future<Integer> confirmationOfUpdatedAge = executorService.submit(personUpdater);
assertEquals(personUpdater.newAge, confirmationOfUpdatedAge.get());
tx.success();
}
}
private void assertNameAndAgeViaLookup(long personId, String personName, Integer expectedAge, String expectedName) {
String lookedUpName = lookupNameForId(personId);
Integer lookedUpAge = lookupAgeForPerson(personName);
assertEquals(expectedAge, lookedUpAge);
assertEquals(expectedName, lookedUpName);
}
private int lookupAgeForPerson(String name) {
Node n = this.graphDatabaseService.index().forNodes("byName").get("name", name).getSingle();
int age = (Integer) n.getProperty("age");
return age;
}
private String lookupNameForId(long id) {
Node n = this.graphDatabaseService.getNodeById(id);
String name = (String) n.getProperty("name");
return name;
}
class DualPersonUpdater implements Callable<Boolean> {
String person1name;
String person2name;
Integer age1;
Integer age2;
DualPersonUpdater(String person1name, String person2name, Integer age1, Integer age2) {
this.person1name = person1name;
this.person2name = person2name;
this.age1 = age1;
this.age2 = age2;
}
private void updatePerson(String name, Integer age) {
try (Transaction tx = graphDatabaseService.beginTx()) {
Node n = graphDatabaseService.index().forNodes("byName").get("name", name).getSingle();
n.setProperty("age", age);
tx.success();
}
}
@Override
public Boolean call() throws Exception {
logger.info("Txt begun...");
try (Transaction tx = graphDatabaseService.beginTx()) {
logger.info("Starting Person1 update...");
updatePerson(person1name, age1);
logger.info("Finished Person1 update ...");
Thread.sleep(1000);
logger.info("Starting Person2 update...");
updatePerson(person2name, age2);
logger.info("Finished Person2 update ...");
tx.success();
return Boolean.TRUE;
}
}
}
class PersonUpdater implements Callable<Integer> {
private String personName;
private Integer newAge;
private Integer sleepTime;
PersonUpdater(String personName, Integer newAge) {
this(personName, newAge, null);
}
PersonUpdater(String personName, Integer newAge, Integer sleepTime) {
this.personName = personName;
this.newAge = newAge;
this.sleepTime = sleepTime;
}
@Override
public Integer call() throws Exception {
Transaction tx = graphDatabaseService.beginTx();
try {
Node n = graphDatabaseService.index().forNodes("byName").get("name", personName).getSingle();
tx.acquireWriteLock(n);
n.setProperty("age", newAge);
if (sleepTime != null) {
Thread.sleep(sleepTime);
}
tx.success();
return newAge;
} catch (InterruptedException e) {
logger.info("Caught InterruptedException " + e.getMessage());
throw e;
} finally {
tx.finish();
}
}
}
}
| 8,693 | 0.617278 | 0.60704 | 236 | 35.834747 | 30.392387 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.690678 | false | false | 10 |
668ea177046709e94f7b70f6238cc243e024e573 | 11,355,893,579,918 | 6b8dbdf63a208f8d703734ece99fdd8479ddf9a4 | /JNI_C/Exceptions/UnCaughtExceptionHandler.java~ | 62a51850cb4bd860b0df2a642219dcce13361033 | []
| no_license | workplay/JNI | https://github.com/workplay/JNI | c8b63098beb4e9bf1887fe719ddccd22fb5ee66b | d686ce7fbe170a015af64a9bd1607c7cf828a7ed | refs/heads/master | 2021-01-20T20:24:27.808000 | 2016-06-02T10:52:00 | 2016-06-02T10:52:00 | 60,256,364 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class UnCaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
int id = (int)t.getId();
e.printStackTrace();
}
}
| UTF-8 | Java | 207 | UnCaughtExceptionHandler.java~ | Java | []
| null | []
| public class UnCaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
int id = (int)t.getId();
e.printStackTrace();
}
}
| 207 | 0.758454 | 0.758454 | 7 | 28.571428 | 27.953314 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.714286 | false | false | 10 |
|
e783f2432c68ac81cb70cbebf3419d7e494b812c | 31,765,578,182,027 | 21e3b035ba6fd23f938e12336aae33d7a7cbd077 | /Demo/java/JDK8 Demo/HomeWork/src/day03/TrainTwo/Train4/HashSetTest.java | 39f227d866d3095c2d8b61488578169d19be7695 | []
| no_license | GriefSeed/Wheels | https://github.com/GriefSeed/Wheels | e22b8e5010d7f9a4dab257cda2b78a270be1bc85 | 41722f724f9ca43133f43a0bf0b262e59eadfda1 | refs/heads/master | 2021-01-19T20:30:09.543000 | 2018-09-29T12:03:32 | 2018-09-29T12:03:32 | 88,511,833 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day03.TrainTwo.Train4;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
public class HashSetTest {
public static void main(String[] args) {
int i = 0;
HashSet<Student> hs = new HashSet<>();
while(i < 10){
hs.add(Student.newBuilder().withName("学生" + i).withAge(i).withSex('男').build());
i++;
}
Iterator<Student> it = hs.iterator();
while(it.hasNext()){
System.out.println(it.next().toString());
}
System.out.println("=====================================");
for(Student s : hs){
System.out.println(s.toString());
}
}
}
| UTF-8 | Java | 703 | java | HashSetTest.java | Java | [
{
"context": " hs.add(Student.newBuilder().withName(\"学生\" + i).withAge(i).withSex('男').build());\n ",
"end": 324,
"score": 0.9289072155952454,
"start": 322,
"tag": "NAME",
"value": "学生"
}
]
| null | []
| package day03.TrainTwo.Train4;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
public class HashSetTest {
public static void main(String[] args) {
int i = 0;
HashSet<Student> hs = new HashSet<>();
while(i < 10){
hs.add(Student.newBuilder().withName("学生" + i).withAge(i).withSex('男').build());
i++;
}
Iterator<Student> it = hs.iterator();
while(it.hasNext()){
System.out.println(it.next().toString());
}
System.out.println("=====================================");
for(Student s : hs){
System.out.println(s.toString());
}
}
}
| 703 | 0.516499 | 0.507891 | 28 | 23.892857 | 22.653193 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 10 |
1935969386230eac95144692564f743cc451e68a | 3,461,743,683,656 | 06a46f5c173e8c95eefa46528039aac545d7f6a6 | /src/main/java/com/example/applicationcontext/annotation/MyService.java | 19ffeb93474a01ff93855f20226d73719c6993af | []
| no_license | yamstood/spring_src_study | https://github.com/yamstood/spring_src_study | 2d6772af6b6cbead142faa0ecb51fad7dee26813 | 8cff2dc36f1eb180783bf6e7de45bfc0ef7b5f10 | refs/heads/master | 2016-08-08T20:00:18.252000 | 2016-03-31T01:11:37 | 2016-03-31T01:11:37 | 54,005,983 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.applicationcontext.annotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Autowired
private SimpleObject simpleObject;
public SimpleObject getSimpleObject() {
return simpleObject;
}
}
| UTF-8 | Java | 338 | java | MyService.java | Java | []
| null | []
| package com.example.applicationcontext.annotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Autowired
private SimpleObject simpleObject;
public SimpleObject getSimpleObject() {
return simpleObject;
}
}
| 338 | 0.778107 | 0.778107 | 16 | 19.125 | 20.778219 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 10 |
aea8f72a140dd1643b0bd91e2f4a4809a6cad081 | 26,688,926,841,957 | 87b9ccf6c2485a51e16ce84854505ab82b8aed7b | /app/src/main/java/com/ww/administrator/demotest/adapter/D12HomeAdapter.java | e17a70e220da338e51c842d31e35cf57c9f3c641 | []
| no_license | wwfighting/demotest | https://github.com/wwfighting/demotest | 78623e5839a30e94e4680f591143b261ff2ae4aa | 39e4603f423ca9be2ab81001d19d898cd811654e | refs/heads/master | 2021-01-11T00:03:03.239000 | 2017-01-03T14:25:52 | 2017-01-03T14:25:52 | 70,766,370 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ww.administrator.demotest.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.ww.administrator.demotest.DetailActivity;
import com.ww.administrator.demotest.ProductListActivity;
import com.ww.administrator.demotest.R;
import com.ww.administrator.demotest.cityselect.utils.SharedPreUtil;
/**
* Created by Administrator on 2016/11/22.
*/
public class D12HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final static int VIEW_HEAD = 0;
private final static int VIEW_TYPE = 1;
private final static int[] PICURL= {R.drawable.nanjing_4, R.drawable.nanjing_5, R.drawable.quanguo_9,
R.drawable.quanguo_8, R.drawable.nanjing_6};
private final static int[] PICURL1= {R.drawable.nanjing_4, R.drawable.nanjing_5, R.drawable.nanjing_6,
R.drawable.nanjing_7};
private Context mConext;
String city = "";
public D12HomeAdapter(Context context) {
this.mConext = context;
city = (String) SharedPreUtil.getData(mConext, "locatCity", "南京");
}
@Override
public int getItemViewType(int position) {
return position == 0 ? VIEW_HEAD : VIEW_TYPE;
}
@Override
public int getItemCount() {
if (city.equals("南京")){
return 5;
}
return 6;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof D12HomeHeadViewHolder){
/*
"3550" => 小康美厨_雕刻时光A
"3551" => 尚品魅厨_地平线
"3552" => 精英悦厨_简爱
"3553" => 铂晶丽厨_穆萨
"3554" => 名家雅厨_雷尔诺
"3555" => 欧风御厨_普利亚
"3556" => 至尊典厨_圣艾米伦
*/
final Intent intent = new Intent();
((D12HomeHeadViewHolder) holder).mivXK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3527");
intent.putExtra("gid", "3572");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivQW.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (city.equals("南京")){
Toast.makeText(mConext, "抱歉,目前南京不参与全屋活动!", Toast.LENGTH_SHORT).show();
return;
}
intent.setClass(mConext, ProductListActivity.class);
intent.putExtra("keyName", "元全屋");
intent.putExtra("isRecom", "-1");
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivSP.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3528");
intent.putExtra("gid", "3573");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivJY.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3533");
intent.putExtra("gid", "3574");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivBJ.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3546");
intent.putExtra("gid", "3575");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivMJ.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3540");
intent.putExtra("gid", "3576");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivOF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3543");
intent.putExtra("gid", "3577");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivZZ.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "2888");
intent.putExtra("gid", "3578");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
}
if (holder instanceof D12HomeViewHolder){
if (city.equals("南京")){
Glide.with(mConext)
.load(PICURL1[position - 1])
.crossFade()
.into(((D12HomeViewHolder) holder).mivD12Show);
}else {
Glide.with(mConext)
.load(PICURL[position - 1])
.crossFade()
.into(((D12HomeViewHolder) holder).mivD12Show);
}
//((D12HomeViewHolder) holder).mivD12Show.setImageResource(PICURL[position - 1]);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return viewType == VIEW_TYPE ? new D12HomeViewHolder(LayoutInflater.from(mConext).inflate(R.layout.adapter_d12home_layout, parent, false))
: new D12HomeHeadViewHolder(LayoutInflater.from(mConext).inflate(R.layout.adapter_d12home_head_layout, parent, false));
}
private class D12HomeHeadViewHolder extends RecyclerView.ViewHolder{
ImageView mivXK, mivQW, mivSP, mivJY, mivBJ, mivMJ, mivOF, mivZZ;
public D12HomeHeadViewHolder(View itemView) {
super(itemView);
mivXK = (ImageView) itemView.findViewById(R.id.iv_d12_xiaokang);
mivQW = (ImageView) itemView.findViewById(R.id.iv_d12_quanwu);
mivSP = (ImageView) itemView.findViewById(R.id.iv_d12_shangpin);
mivJY = (ImageView) itemView.findViewById(R.id.iv_d12_jingying);
mivBJ = (ImageView) itemView.findViewById(R.id.iv_d12_bojing);
mivMJ = (ImageView) itemView.findViewById(R.id.iv_d12_mingjia);
mivOF = (ImageView) itemView.findViewById(R.id.iv_d12_oufeng);
mivZZ = (ImageView) itemView.findViewById(R.id.iv_d12_zhizun);
}
}
private class D12HomeViewHolder extends RecyclerView.ViewHolder{
ImageView mivD12Show;
public D12HomeViewHolder(View itemView) {
super(itemView);
mivD12Show = (ImageView) itemView.findViewById(R.id.iv_d12);
}
}
}
| UTF-8 | Java | 8,051 | java | D12HomeAdapter.java | Java | [
{
"context": "cityselect.utils.SharedPreUtil;\n\n/**\n * Created by Administrator on 2016/11/22.\n */\npublic class D12HomeAdapter ex",
"end": 599,
"score": 0.38563233613967896,
"start": 586,
"tag": "NAME",
"value": "Administrator"
},
{
"context": ";\n intent.putExtra(\"keyName\", \"元全屋\");\n intent.putExtra(\"isRecom\",",
"end": 3017,
"score": 0.9985129237174988,
"start": 3014,
"tag": "KEY",
"value": "元全屋"
}
]
| null | []
| package com.ww.administrator.demotest.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.ww.administrator.demotest.DetailActivity;
import com.ww.administrator.demotest.ProductListActivity;
import com.ww.administrator.demotest.R;
import com.ww.administrator.demotest.cityselect.utils.SharedPreUtil;
/**
* Created by Administrator on 2016/11/22.
*/
public class D12HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final static int VIEW_HEAD = 0;
private final static int VIEW_TYPE = 1;
private final static int[] PICURL= {R.drawable.nanjing_4, R.drawable.nanjing_5, R.drawable.quanguo_9,
R.drawable.quanguo_8, R.drawable.nanjing_6};
private final static int[] PICURL1= {R.drawable.nanjing_4, R.drawable.nanjing_5, R.drawable.nanjing_6,
R.drawable.nanjing_7};
private Context mConext;
String city = "";
public D12HomeAdapter(Context context) {
this.mConext = context;
city = (String) SharedPreUtil.getData(mConext, "locatCity", "南京");
}
@Override
public int getItemViewType(int position) {
return position == 0 ? VIEW_HEAD : VIEW_TYPE;
}
@Override
public int getItemCount() {
if (city.equals("南京")){
return 5;
}
return 6;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof D12HomeHeadViewHolder){
/*
"3550" => 小康美厨_雕刻时光A
"3551" => 尚品魅厨_地平线
"3552" => 精英悦厨_简爱
"3553" => 铂晶丽厨_穆萨
"3554" => 名家雅厨_雷尔诺
"3555" => 欧风御厨_普利亚
"3556" => 至尊典厨_圣艾米伦
*/
final Intent intent = new Intent();
((D12HomeHeadViewHolder) holder).mivXK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3527");
intent.putExtra("gid", "3572");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivQW.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (city.equals("南京")){
Toast.makeText(mConext, "抱歉,目前南京不参与全屋活动!", Toast.LENGTH_SHORT).show();
return;
}
intent.setClass(mConext, ProductListActivity.class);
intent.putExtra("keyName", "元全屋");
intent.putExtra("isRecom", "-1");
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivSP.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3528");
intent.putExtra("gid", "3573");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivJY.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3533");
intent.putExtra("gid", "3574");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivBJ.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3546");
intent.putExtra("gid", "3575");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivMJ.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3540");
intent.putExtra("gid", "3576");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivOF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "3543");
intent.putExtra("gid", "3577");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
((D12HomeHeadViewHolder) holder).mivZZ.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//intent.putExtra("gid", "2888");
intent.putExtra("gid", "3578");
intent.setClass(mConext, DetailActivity.class);
mConext.startActivity(intent);
}
});
}
if (holder instanceof D12HomeViewHolder){
if (city.equals("南京")){
Glide.with(mConext)
.load(PICURL1[position - 1])
.crossFade()
.into(((D12HomeViewHolder) holder).mivD12Show);
}else {
Glide.with(mConext)
.load(PICURL[position - 1])
.crossFade()
.into(((D12HomeViewHolder) holder).mivD12Show);
}
//((D12HomeViewHolder) holder).mivD12Show.setImageResource(PICURL[position - 1]);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return viewType == VIEW_TYPE ? new D12HomeViewHolder(LayoutInflater.from(mConext).inflate(R.layout.adapter_d12home_layout, parent, false))
: new D12HomeHeadViewHolder(LayoutInflater.from(mConext).inflate(R.layout.adapter_d12home_head_layout, parent, false));
}
private class D12HomeHeadViewHolder extends RecyclerView.ViewHolder{
ImageView mivXK, mivQW, mivSP, mivJY, mivBJ, mivMJ, mivOF, mivZZ;
public D12HomeHeadViewHolder(View itemView) {
super(itemView);
mivXK = (ImageView) itemView.findViewById(R.id.iv_d12_xiaokang);
mivQW = (ImageView) itemView.findViewById(R.id.iv_d12_quanwu);
mivSP = (ImageView) itemView.findViewById(R.id.iv_d12_shangpin);
mivJY = (ImageView) itemView.findViewById(R.id.iv_d12_jingying);
mivBJ = (ImageView) itemView.findViewById(R.id.iv_d12_bojing);
mivMJ = (ImageView) itemView.findViewById(R.id.iv_d12_mingjia);
mivOF = (ImageView) itemView.findViewById(R.id.iv_d12_oufeng);
mivZZ = (ImageView) itemView.findViewById(R.id.iv_d12_zhizun);
}
}
private class D12HomeViewHolder extends RecyclerView.ViewHolder{
ImageView mivD12Show;
public D12HomeViewHolder(View itemView) {
super(itemView);
mivD12Show = (ImageView) itemView.findViewById(R.id.iv_d12);
}
}
}
| 8,051 | 0.555499 | 0.531831 | 198 | 38.904041 | 29.783493 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.671717 | false | false | 10 |
e5f08df56ac552d5c9bb773278cbbc92c708bcd9 | 14,766,097,620,624 | 0dd059fbc5a44839747248197fce8bbc24bee57c | /src/eai/superivsion/historiqueIncidents/jpaControllers/IncGabExtJpaController.java | ba821ea3b1cce41f30229bac89e4c7d9b30aacb9 | [
"Apache-2.0"
]
| permissive | OumaimaHourrane/EurafricInformation | https://github.com/OumaimaHourrane/EurafricInformation | ec1ccf6929bc85b21461f5a72a15e89704a453b5 | 9d0d2f6075786eef18b1a25bb78f6b1f53e48316 | refs/heads/master | 2022-03-08T03:20:57.634000 | 2019-11-12T18:54:54 | 2019-11-12T18:54:54 | 113,740,048 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 eai.superivsion.historiqueIncidents.jpaControllers;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import eai.superivsion.historiqueIncidents.entities.IncGabExt;
import eai.superivsion.historiqueIncidents.jpaControllers.exceptions.NonexistentEntityException;
import eai.superivsion.historiqueIncidents.jpaControllers.exceptions.PreexistingEntityException;
/**
*
* @author Mohammed AGHOUI
*/
public class IncGabExtJpaController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public IncGabExtJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(IncGabExt incGabExt) throws PreexistingEntityException, Exception {
EntityManager em = null;
System.out.println("------- : "+incGabExt.getIdGab());
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(incGabExt);
em.getTransaction().commit();
System.out.println("------- : "+incGabExt.getIdGab());
} catch (Exception ex) {
if (findIncGabExt(incGabExt.getTicketGabExt()) != null) {
throw new PreexistingEntityException("IncGabExt " + incGabExt + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(IncGabExt incGabExt) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
incGabExt = em.merge(incGabExt);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = incGabExt.getTicketGabExt();
if (findIncGabExt(id) == null) {
throw new NonexistentEntityException("The incGabExt with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(IncGabExt incGabExt) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
if (!em.contains(incGabExt)) {
incGabExt = em.merge(incGabExt);
}
em.remove(incGabExt);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
@SuppressWarnings("unchecked")
public List<IncGabExt> findIncGabExt() {
EntityManager em = getEntityManager();
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT c.ville , c.idGab, c.duree, c.dateDebut, c.commentaire FROM IncGabExt c ");
Query query = em.createQuery(sb.toString());
List<IncGabExt> list = query.getResultList();
return list;
} finally {
em.close();
}
}
public List<IncGabExt> findIncGabExtEntities() {
return findIncGabExtEntities(true, 10, 10);
}
public List<IncGabExt> findIncGabExtEntities(int maxResults, int firstResult) {
return findIncGabExtEntities(false, maxResults, firstResult);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private List<IncGabExt> findIncGabExtEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
cq.select(cq.from(IncGabExt.class));
cq.orderBy(cb.desc(cq.from(IncGabExt.class).get("duree")));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public IncGabExt findIncGabExt(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(IncGabExt.class, id);
} finally {
em.close();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public int getIncGabExtCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<IncGabExt> rt = cq.from(IncGabExt.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
public IncGabExt findIncGabExtticket(int ticket) {
EntityManager em = getEntityManager();
IncGabExt resultat = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT u FROM IncGabExt u WHERE u.ticketGabExt = " + ticket);
Query query = em.createQuery(sb.toString());
// query.setParameter("ticketApp", ticket);
if (query.getResultList() != null && query.getResultList().size() > 0) {
resultat = (IncGabExt) query.getResultList().get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultat;
}
}
| UTF-8 | Java | 6,460 | java | IncGabExtJpaController.java | Java | [
{
"context": "PreexistingEntityException;\r\n\r\n/**\r\n *\r\n * @author Mohammed AGHOUI\r\n */\r\npublic class IncGabExtJpaController implement",
"end": 873,
"score": 0.9859141707420349,
"start": 858,
"tag": "NAME",
"value": "Mohammed AGHOUI"
}
]
| null | []
| /*
* 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 eai.superivsion.historiqueIncidents.jpaControllers;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import eai.superivsion.historiqueIncidents.entities.IncGabExt;
import eai.superivsion.historiqueIncidents.jpaControllers.exceptions.NonexistentEntityException;
import eai.superivsion.historiqueIncidents.jpaControllers.exceptions.PreexistingEntityException;
/**
*
* @author <NAME>
*/
public class IncGabExtJpaController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public IncGabExtJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(IncGabExt incGabExt) throws PreexistingEntityException, Exception {
EntityManager em = null;
System.out.println("------- : "+incGabExt.getIdGab());
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(incGabExt);
em.getTransaction().commit();
System.out.println("------- : "+incGabExt.getIdGab());
} catch (Exception ex) {
if (findIncGabExt(incGabExt.getTicketGabExt()) != null) {
throw new PreexistingEntityException("IncGabExt " + incGabExt + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(IncGabExt incGabExt) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
incGabExt = em.merge(incGabExt);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = incGabExt.getTicketGabExt();
if (findIncGabExt(id) == null) {
throw new NonexistentEntityException("The incGabExt with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(IncGabExt incGabExt) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
if (!em.contains(incGabExt)) {
incGabExt = em.merge(incGabExt);
}
em.remove(incGabExt);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
@SuppressWarnings("unchecked")
public List<IncGabExt> findIncGabExt() {
EntityManager em = getEntityManager();
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT c.ville , c.idGab, c.duree, c.dateDebut, c.commentaire FROM IncGabExt c ");
Query query = em.createQuery(sb.toString());
List<IncGabExt> list = query.getResultList();
return list;
} finally {
em.close();
}
}
public List<IncGabExt> findIncGabExtEntities() {
return findIncGabExtEntities(true, 10, 10);
}
public List<IncGabExt> findIncGabExtEntities(int maxResults, int firstResult) {
return findIncGabExtEntities(false, maxResults, firstResult);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private List<IncGabExt> findIncGabExtEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
cq.select(cq.from(IncGabExt.class));
cq.orderBy(cb.desc(cq.from(IncGabExt.class).get("duree")));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public IncGabExt findIncGabExt(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(IncGabExt.class, id);
} finally {
em.close();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public int getIncGabExtCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<IncGabExt> rt = cq.from(IncGabExt.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
public IncGabExt findIncGabExtticket(int ticket) {
EntityManager em = getEntityManager();
IncGabExt resultat = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT u FROM IncGabExt u WHERE u.ticketGabExt = " + ticket);
Query query = em.createQuery(sb.toString());
// query.setParameter("ticketApp", ticket);
if (query.getResultList() != null && query.getResultList().size() > 0) {
resultat = (IncGabExt) query.getResultList().get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultat;
}
}
| 6,451 | 0.562229 | 0.560991 | 197 | 30.791878 | 25.765682 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583756 | false | false | 10 |
206c694eaa1782b7facbb31d940e94712b3f520f | 11,613,591,620,680 | 4ba8efffdbea5686f087e755682378e9cfa02f7e | /vicsektamas-server/src/main/java/dev/borgod/vicsektamas/repo/TimeTableRepo.java | 4a95d3d6ee4e34771f99d227282546d1ca2c1707 | []
| no_license | godraadam/vicsek-tamas | https://github.com/godraadam/vicsek-tamas | 432f1f0ab240e924c91c242ca819e2522641d729 | 2d36ef97892f0f8c98ed2baa2676f71c595dd4a9 | refs/heads/master | 2023-04-28T12:52:16.688000 | 2021-05-24T14:32:22 | 2021-05-24T14:32:22 | 356,023,131 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dev.borgod.vicsektamas.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import dev.borgod.vicsektamas.model.TimeTable;
@Repository
public interface TimeTableRepo extends JpaRepository<TimeTable, Long> {
List<TimeTable> findByServiceId(Long id);
}
| UTF-8 | Java | 360 | java | TimeTableRepo.java | Java | []
| null | []
| package dev.borgod.vicsektamas.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import dev.borgod.vicsektamas.model.TimeTable;
@Repository
public interface TimeTableRepo extends JpaRepository<TimeTable, Long> {
List<TimeTable> findByServiceId(Long id);
}
| 360 | 0.811111 | 0.811111 | 14 | 24.714285 | 24.886683 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 10 |
b08f8d0f3a6f094ee409c4ce4a73ea2409d1efbd | 13,752,485,282,768 | bd5fa9bead6faddf2a72a0f6d03fcb80d2d29892 | /Armor.java | d26cd0154b889c8f3c75aca3c9e70ef946cb7f2c | []
| no_license | ironhandify/Inheritance- | https://github.com/ironhandify/Inheritance- | c5419df812d25e2813c9c49ea2227f2f88338c9d | 642ffd8b75328be33ff82eac3b7c193e061bbef8 | refs/heads/master | 2021-04-06T08:04:16.141000 | 2018-03-13T23:06:34 | 2018-03-13T23:06:34 | 125,111,564 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Write a description of class Armor here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.util.ArrayList;
public abstract class Armor extends Item implements DefenseCommands
{
int strength;
int agility;
int HealthPoints;
public Armor(String name, ArrayList stats){
super(name, stats);
stats.add(strength);
stats.add(agility);
stats.add(HealthPoints);
this.strength = strength;
this.agility = agility;
this.HealthPoints = HealthPoints;
}
public boolean blocked(){
int i = strength + (int)(Math.random() * (HealthPoints*2));
if(i > (strength/2)){
return true;
} else{
return false;
}
}
}
| UTF-8 | Java | 766 | java | Armor.java | Java | []
| null | []
|
/**
* Write a description of class Armor here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.util.ArrayList;
public abstract class Armor extends Item implements DefenseCommands
{
int strength;
int agility;
int HealthPoints;
public Armor(String name, ArrayList stats){
super(name, stats);
stats.add(strength);
stats.add(agility);
stats.add(HealthPoints);
this.strength = strength;
this.agility = agility;
this.HealthPoints = HealthPoints;
}
public boolean blocked(){
int i = strength + (int)(Math.random() * (HealthPoints*2));
if(i > (strength/2)){
return true;
} else{
return false;
}
}
}
| 766 | 0.593995 | 0.591384 | 32 | 22.90625 | 17.232527 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 10 |
b76aceb804e626504fce5590689ee905dbdb2767 | 13,752,485,282,904 | 7ff44556a09d370d447e2b8301e7a8e213591800 | /app/src/main/java/cn/jdzf/com/inspection/Act_NewInspectionHistory.java | 296c3500fcc796bb94122fdcae965d8f806a2d79 | []
| no_license | wpdabook/jgapp | https://github.com/wpdabook/jgapp | c2b3e82ed5f63b55ff7f22c92dfdf93fbd68d068 | b226a490eb58da18eb12c4a78409e17c972316e2 | refs/heads/master | 2021-06-28T07:47:58.635000 | 2021-06-21T08:36:04 | 2021-06-21T08:36:04 | 231,322,967 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.jdzf.com.inspection;
import android.app.Dialog;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.a21zhewang.lodindshowlibrary.WeiboDialogUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import cn.jdzf.com.R;
import cn.jdzf.com.adapter.ProceduralHostoryAdapter;
import cn.jdzf.com.bean.NineGridModel;
import cn.jdzf.com.bean.ObjBean;
import cn.jdzf.com.http.JsonUtils;
import cn.jdzf.com.http.MyCallBack;
import cn.jdzf.com.http.XUtil;
import cn.jdzf.com.util.Act_Base;
/**
* Created by WP-PC on 2020/3/11.
*/
public class Act_NewInspectionHistory extends Act_Base{
@BindView(R.id.rv_pic_list)
ListView mListView;
private int page = 0;
private int totalPage = 1;
private JSONArray dataArray = new JSONArray();
@BindView(R.id.placeholder)
LinearLayout placeHolder;
private String id;
private ProceduralHostoryAdapter mAdapter;
private List<NineGridModel> mList;
private String recordID;
private String sectionID;
private String itemID;
private Dialog loadingDialog;
@Override
public void beforesetContentView() {
}
@Override
public int getLayoutId() {
return R.layout.act_new_inspection_history;
}
@Override
public void initViews() {
loadingDialog = WeiboDialogUtils.createLoadingDialog(this, "提交中...");
recordID = getIntent().getStringExtra("recordId");
sectionID = getIntent().getStringExtra("sectionId");
itemID = getIntent().getStringExtra("itemID");
mAdapter = new ProceduralHostoryAdapter(this);
}
@Override
public void initListener() {
}
@Override
public void initData() {
loadData(true);
}
/**
* 1:近一周 2:近一月
* @param needDialog
*/
private void loadData(boolean needDialog) {
loadingDialog.show();
JSONObject object = JsonUtils.getjsonobj("{\"recordID\":\"" + recordID + "\"," +
"\"sectionID\":\"" + sectionID + "\",\"itemID\":\"" + itemID + "\"}");
XUtil.postjsondatasj(object, "GetBroadCastDetailCollection", new MyCallBack() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onResule(String res) {
try {
loadingDialog.dismiss();
JSONObject object = new JSONObject(res);
mList = new ArrayList<NineGridModel>();
if(object.length()>0){
dataArray = object.optJSONArray("recordList");
for (int i = 0; i < dataArray.length(); i++) {//
JSONObject tempobject = dataArray.optJSONObject(i);
NineGridModel model = new NineGridModel();
model.setContent(tempobject.optString("content"));
model.setCreateTime(tempobject.optString("createTime"));
model.setStatus(tempobject.optInt("type"));
// if(tempobject.optInt("type") == 1){
// model.setUser("安全记录");
// }else{
// model.setUser("有隐患记录");
// }
JSONArray array = tempobject.optJSONArray("files");
List<String> imglist = new ArrayList<String>();
for(int j=0;j<array.length();j++){
JSONObject tempobject2 = array.optJSONObject(j);
imglist.add(tempobject2.optString("url"));
model.setUrlList(imglist);
}
mList.add(model);
}
}
if (dataArray.length() == 0) {
placeHolder.setVisibility(View.VISIBLE);
} else {
placeHolder.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.setList(mList);
mListView.setAdapter(mAdapter);
if(mAdapter != null){
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onFail(ObjBean getbean) {
}
@Override
public void onWrong() {
}
});
}
@Override
public void processClick(View v) {
}
}
| UTF-8 | Java | 4,868 | java | Act_NewInspectionHistory.java | Java | [
{
"context": "port cn.jdzf.com.util.Act_Base;\n\n/**\n * Created by WP-PC on 2020/3/11.\n */\n\npublic class Act_NewInspection",
"end": 759,
"score": 0.998511791229248,
"start": 754,
"tag": "USERNAME",
"value": "WP-PC"
}
]
| null | []
| package cn.jdzf.com.inspection;
import android.app.Dialog;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.a21zhewang.lodindshowlibrary.WeiboDialogUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import cn.jdzf.com.R;
import cn.jdzf.com.adapter.ProceduralHostoryAdapter;
import cn.jdzf.com.bean.NineGridModel;
import cn.jdzf.com.bean.ObjBean;
import cn.jdzf.com.http.JsonUtils;
import cn.jdzf.com.http.MyCallBack;
import cn.jdzf.com.http.XUtil;
import cn.jdzf.com.util.Act_Base;
/**
* Created by WP-PC on 2020/3/11.
*/
public class Act_NewInspectionHistory extends Act_Base{
@BindView(R.id.rv_pic_list)
ListView mListView;
private int page = 0;
private int totalPage = 1;
private JSONArray dataArray = new JSONArray();
@BindView(R.id.placeholder)
LinearLayout placeHolder;
private String id;
private ProceduralHostoryAdapter mAdapter;
private List<NineGridModel> mList;
private String recordID;
private String sectionID;
private String itemID;
private Dialog loadingDialog;
@Override
public void beforesetContentView() {
}
@Override
public int getLayoutId() {
return R.layout.act_new_inspection_history;
}
@Override
public void initViews() {
loadingDialog = WeiboDialogUtils.createLoadingDialog(this, "提交中...");
recordID = getIntent().getStringExtra("recordId");
sectionID = getIntent().getStringExtra("sectionId");
itemID = getIntent().getStringExtra("itemID");
mAdapter = new ProceduralHostoryAdapter(this);
}
@Override
public void initListener() {
}
@Override
public void initData() {
loadData(true);
}
/**
* 1:近一周 2:近一月
* @param needDialog
*/
private void loadData(boolean needDialog) {
loadingDialog.show();
JSONObject object = JsonUtils.getjsonobj("{\"recordID\":\"" + recordID + "\"," +
"\"sectionID\":\"" + sectionID + "\",\"itemID\":\"" + itemID + "\"}");
XUtil.postjsondatasj(object, "GetBroadCastDetailCollection", new MyCallBack() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onResule(String res) {
try {
loadingDialog.dismiss();
JSONObject object = new JSONObject(res);
mList = new ArrayList<NineGridModel>();
if(object.length()>0){
dataArray = object.optJSONArray("recordList");
for (int i = 0; i < dataArray.length(); i++) {//
JSONObject tempobject = dataArray.optJSONObject(i);
NineGridModel model = new NineGridModel();
model.setContent(tempobject.optString("content"));
model.setCreateTime(tempobject.optString("createTime"));
model.setStatus(tempobject.optInt("type"));
// if(tempobject.optInt("type") == 1){
// model.setUser("安全记录");
// }else{
// model.setUser("有隐患记录");
// }
JSONArray array = tempobject.optJSONArray("files");
List<String> imglist = new ArrayList<String>();
for(int j=0;j<array.length();j++){
JSONObject tempobject2 = array.optJSONObject(j);
imglist.add(tempobject2.optString("url"));
model.setUrlList(imglist);
}
mList.add(model);
}
}
if (dataArray.length() == 0) {
placeHolder.setVisibility(View.VISIBLE);
} else {
placeHolder.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.setList(mList);
mListView.setAdapter(mAdapter);
if(mAdapter != null){
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onFail(ObjBean getbean) {
}
@Override
public void onWrong() {
}
});
}
@Override
public void processClick(View v) {
}
}
| 4,868 | 0.545963 | 0.541822 | 143 | 32.776222 | 23.53614 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531469 | false | false | 10 |
54206e574aa04540159fb330a08e5809a8b276de | 4,501,125,731,925 | bbb5fbaa5d714331cbbc610bd86881ca6b366175 | /src/com/lee/aafour/SmallestString.java | bb912b92631ec62d6783f553bc62c8507dcb1074 | []
| no_license | zhihzhang/leetcode | https://github.com/zhihzhang/leetcode | 9c99e9a9a12d6f5116c0db074beaa2b1cdd40675 | cfc92dd583e91bdc75556c112db1fcf51a8da03d | refs/heads/master | 2021-06-27T02:33:14.870000 | 2020-09-26T18:45:52 | 2020-09-26T18:45:52 | 138,515,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lee.aafour;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.lee.common.TreeNode;
public class SmallestString {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
// Set<String> set = new HashSet<>();
//
// public String smallestFromLeaf(TreeNode root) {
// dfs(root, "");
// String t = null;
// for (String s : list) {
// System.out.println(s);
// if (t == null) {
// t = s;
// }
// t = compare(t, s);
// }
// return t;
// }
//
// public String compare(String a, String b) {
// if (b.length() < a.length()) {
// String t = a;
// a = b;
// b = t;
// }
// for (int i = 0; i < a.length(); i++) {
// char x = a.charAt(i);
// char y = b.charAt(i);
// if (x < y) {
// return a;
// } else if (y < x) {
// return b;
// }
// }
// return a;
// }
//
// public void dfs(TreeNode root, String pre) {
// if(root==null){
// return;
// }
// if(root.left==null && root.right==null){
// StringBuilder sb = new StringBuilder(pre + (char)(root.val+'a'));
// set.add(sb.reverse().toString());
// }
// dfs(root.left, pre + (char)(root.val+'a'));
// dfs(root.right, pre + (char)(root.val+'a'));
// }
}
| UTF-8 | Java | 1,220 | java | SmallestString.java | Java | []
| null | []
| package com.lee.aafour;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.lee.common.TreeNode;
public class SmallestString {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
// Set<String> set = new HashSet<>();
//
// public String smallestFromLeaf(TreeNode root) {
// dfs(root, "");
// String t = null;
// for (String s : list) {
// System.out.println(s);
// if (t == null) {
// t = s;
// }
// t = compare(t, s);
// }
// return t;
// }
//
// public String compare(String a, String b) {
// if (b.length() < a.length()) {
// String t = a;
// a = b;
// b = t;
// }
// for (int i = 0; i < a.length(); i++) {
// char x = a.charAt(i);
// char y = b.charAt(i);
// if (x < y) {
// return a;
// } else if (y < x) {
// return b;
// }
// }
// return a;
// }
//
// public void dfs(TreeNode root, String pre) {
// if(root==null){
// return;
// }
// if(root.left==null && root.right==null){
// StringBuilder sb = new StringBuilder(pre + (char)(root.val+'a'));
// set.add(sb.reverse().toString());
// }
// dfs(root.left, pre + (char)(root.val+'a'));
// dfs(root.right, pre + (char)(root.val+'a'));
// }
}
| 1,220 | 0.539344 | 0.538525 | 61 | 19 | 16.437662 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.180328 | false | false | 10 |
620244d86a4f4324d282c3eaace7175ed53166ca | 9,045,201,194,113 | 93b8c5fa98056dfaac29f5f623e96b2de25439c0 | /src/main/java/com/denis/crudapplication/Users/UsersRepository.java | a46fc303e56e43d6a5ea184d845b1810a3266d55 | []
| no_license | denisrexhepi/SpringBoot-Application | https://github.com/denisrexhepi/SpringBoot-Application | b5abcd1767a30db088fe54e06722389a28379c0d | 305c3b8481d59b292d35e14f4b49d4ce755f634c | refs/heads/master | 2023-02-05T12:15:52.368000 | 2020-12-28T11:13:58 | 2020-12-28T11:13:58 | 324,991,691 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.denis.crudapplication.Users;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.stereotype.Repository;
@Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
}
| UTF-8 | Java | 411 | java | UsersRepository.java | Java | []
| null | []
| package com.denis.crudapplication.Users;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.stereotype.Repository;
@Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
}
| 411 | 0.849148 | 0.849148 | 12 | 33 | 27.172289 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 10 |
3697ba76f4d9ed1984f5def2abd3cf2f5c44cef1 | 5,712,306,518,836 | fac5d6126ab147e3197448d283f9a675733f3c34 | /src/main/java/dji/thirdparty/rx/internal/operators/BlockingOperatorLatest.java | 4a4b5c75eae75efaf1193fa6f5534bf39d631d06 | []
| no_license | KnzHz/fpv_live | https://github.com/KnzHz/fpv_live | 412e1dc8ab511b1a5889c8714352e3a373cdae2f | 7902f1a4834d581ee6afd0d17d87dc90424d3097 | refs/heads/master | 2022-12-18T18:15:39.101000 | 2020-09-24T19:42:03 | 2020-09-24T19:42:03 | 294,176,898 | 0 | 0 | null | true | 2020-09-09T17:03:58 | 2020-09-09T17:03:57 | 2020-07-13T03:26:16 | 2020-04-29T00:01:57 | 65,458 | 0 | 0 | 0 | null | false | false | package dji.thirdparty.rx.internal.operators;
import dji.thirdparty.rx.Notification;
import dji.thirdparty.rx.Observable;
import dji.thirdparty.rx.Subscriber;
import dji.thirdparty.rx.exceptions.Exceptions;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
public final class BlockingOperatorLatest {
private BlockingOperatorLatest() {
throw new IllegalStateException("No instances!");
}
public static <T> Iterable<T> latest(final Observable<? extends T> source) {
return new Iterable<T>() {
/* class dji.thirdparty.rx.internal.operators.BlockingOperatorLatest.AnonymousClass1 */
public Iterator<T> iterator() {
LatestObserverIterator<T> lio = new LatestObserverIterator<>();
source.materialize().subscribe((Subscriber) lio);
return lio;
}
};
}
static final class LatestObserverIterator<T> extends Subscriber<Notification<? extends T>> implements Iterator<T> {
Notification<? extends T> iNotif;
final Semaphore notify = new Semaphore(0);
final AtomicReference<Notification<? extends T>> value = new AtomicReference<>();
LatestObserverIterator() {
}
public /* bridge */ /* synthetic */ void onNext(Object x0) {
onNext((Notification) ((Notification) x0));
}
public void onNext(Notification<? extends T> args) {
if (this.value.getAndSet(args) == null) {
this.notify.release();
}
}
public void onError(Throwable e) {
}
public void onCompleted() {
}
public boolean hasNext() {
if (this.iNotif == null || !this.iNotif.isOnError()) {
if ((this.iNotif == null || !this.iNotif.isOnCompleted()) && this.iNotif == null) {
try {
this.notify.acquire();
this.iNotif = this.value.getAndSet(null);
if (this.iNotif.isOnError()) {
throw Exceptions.propagate(this.iNotif.getThrowable());
}
} catch (InterruptedException ex) {
unsubscribe();
Thread.currentThread().interrupt();
this.iNotif = Notification.createOnError(ex);
throw Exceptions.propagate(ex);
}
}
return !this.iNotif.isOnCompleted();
}
throw Exceptions.propagate(this.iNotif.getThrowable());
}
public T next() {
if (!hasNext() || !this.iNotif.isOnNext()) {
throw new NoSuchElementException();
}
T v = this.iNotif.getValue();
this.iNotif = null;
return v;
}
public void remove() {
throw new UnsupportedOperationException("Read-only iterator.");
}
}
}
| UTF-8 | Java | 3,103 | java | BlockingOperatorLatest.java | Java | []
| null | []
| package dji.thirdparty.rx.internal.operators;
import dji.thirdparty.rx.Notification;
import dji.thirdparty.rx.Observable;
import dji.thirdparty.rx.Subscriber;
import dji.thirdparty.rx.exceptions.Exceptions;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
public final class BlockingOperatorLatest {
private BlockingOperatorLatest() {
throw new IllegalStateException("No instances!");
}
public static <T> Iterable<T> latest(final Observable<? extends T> source) {
return new Iterable<T>() {
/* class dji.thirdparty.rx.internal.operators.BlockingOperatorLatest.AnonymousClass1 */
public Iterator<T> iterator() {
LatestObserverIterator<T> lio = new LatestObserverIterator<>();
source.materialize().subscribe((Subscriber) lio);
return lio;
}
};
}
static final class LatestObserverIterator<T> extends Subscriber<Notification<? extends T>> implements Iterator<T> {
Notification<? extends T> iNotif;
final Semaphore notify = new Semaphore(0);
final AtomicReference<Notification<? extends T>> value = new AtomicReference<>();
LatestObserverIterator() {
}
public /* bridge */ /* synthetic */ void onNext(Object x0) {
onNext((Notification) ((Notification) x0));
}
public void onNext(Notification<? extends T> args) {
if (this.value.getAndSet(args) == null) {
this.notify.release();
}
}
public void onError(Throwable e) {
}
public void onCompleted() {
}
public boolean hasNext() {
if (this.iNotif == null || !this.iNotif.isOnError()) {
if ((this.iNotif == null || !this.iNotif.isOnCompleted()) && this.iNotif == null) {
try {
this.notify.acquire();
this.iNotif = this.value.getAndSet(null);
if (this.iNotif.isOnError()) {
throw Exceptions.propagate(this.iNotif.getThrowable());
}
} catch (InterruptedException ex) {
unsubscribe();
Thread.currentThread().interrupt();
this.iNotif = Notification.createOnError(ex);
throw Exceptions.propagate(ex);
}
}
return !this.iNotif.isOnCompleted();
}
throw Exceptions.propagate(this.iNotif.getThrowable());
}
public T next() {
if (!hasNext() || !this.iNotif.isOnNext()) {
throw new NoSuchElementException();
}
T v = this.iNotif.getValue();
this.iNotif = null;
return v;
}
public void remove() {
throw new UnsupportedOperationException("Read-only iterator.");
}
}
}
| 3,103 | 0.56107 | 0.559781 | 87 | 34.666668 | 27.69442 | 119 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.448276 | false | false | 10 |
009114d0ca289ca7c84438c6e0814716d7cc9363 | 17,248,588,666,188 | 897cb1bbbbb9cd56a5e43f3f4ca2d9e6287bffb7 | /src/main/java/pac/repository/BrandRepo.java | 7f8fc0af8772d70523d83ca4b2473d6923955c7d | []
| no_license | BrandonIhor/JohnnyOnlineStore | https://github.com/BrandonIhor/JohnnyOnlineStore | 7c21e12c28e788ad45c39ea4f668120184ad640a | 18021f7d87b77ed39ab5a5586e921961b571d04e | refs/heads/master | 2018-03-20T20:17:08.279000 | 2016-08-31T09:16:35 | 2016-08-31T09:16:35 | 66,977,156 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pac.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import pac.entity.Brand;
import pac.entity.User;
/**
* Created by ІГОР on 02.08.2016.
*/
public interface BrandRepo extends JpaRepository<Brand, Integer> {
}
| UTF-8 | Java | 308 | java | BrandRepo.java | Java | [
{
"context": ".Brand;\nimport pac.entity.User;\n\n/**\n * Created by ІГОР on 02.08.2016.\n */\npublic interface BrandRepo ext",
"end": 213,
"score": 0.9955204129219055,
"start": 209,
"tag": "NAME",
"value": "ІГОР"
}
]
| null | []
| package pac.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import pac.entity.Brand;
import pac.entity.User;
/**
* Created by ІГОР on 02.08.2016.
*/
public interface BrandRepo extends JpaRepository<Brand, Integer> {
}
| 308 | 0.782895 | 0.756579 | 14 | 20.714285 | 23.331244 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 10 |
de08dde565948287a2a69cd98e73b4207f1e2482 | 31,842,887,590,673 | cabaa28e030af42b6bb5f739dc6939c3aa0e0b24 | /src/com/bvas/utils/ReportUtils.java | 0803406db81f0fce2452023084b71a9113f5f8ea | []
| no_license | infosynchron/bvaschicago | https://github.com/infosynchron/bvaschicago | fdc0331c718eeb86522a27b8877d89a9e6c6b364 | f170f80da4f144e05db1ba5473e3a7387b0a28e1 | refs/heads/master | 2021-01-15T14:43:02.783000 | 2015-02-27T17:35:20 | 2015-02-27T17:35:20 | 31,058,459 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bvas.utils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.bvas.beans.CustomerBean;
import com.bvas.beans.Driver;
import com.bvas.beans.InvoiceBean;
import com.bvas.beans.InvoiceDetailsBean;
import com.bvas.beans.InvoiceDetailsOurPrice;
import com.bvas.beans.LocalOrderBean;
import com.bvas.beans.PartsBean;
import com.bvas.beans.UserBean;
public class ReportUtils {
private static final Logger logger = Logger.getLogger(ReportUtils.class);
public static Hashtable showDaysSales(UserBean user, String fromDate, String toDate,
String salesPerson) throws UserException {
Hashtable toShowSales = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ResultSet rs1 = null;
try {
String fileName = "ShowSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[4][2];
con = DBInterfaceLocal.getSQLConnection();
stmt = con.createStatement();
boolean getReturn = false;
String sql =
"SELECT OrderDate, SUM(InvoiceTotal), SUM(Discount), SUM(Tax) FROM Invoice WHERE ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Medium")
&&
// !user.getRole().trim().equalsIgnoreCase("Acct") &&
!user.getUsername().trim().equalsIgnoreCase("CorrinaNY")
&& !user.getUsername().trim().equalsIgnoreCase("Nancy")
&& !user.getUsername().trim().equalsIgnoreCase("Joses")) {
sql += " SalesPerson='" + user.getUsername() + "' AND ";
getReturn = true;
} else if (salesPerson != null && !salesPerson.trim().equals("")) {
sql += " SalesPerson='" + salesPerson.trim() + "' AND ";
getReturn = true;
}
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sql += " Group BY OrderDate ";
// logger.error(sql);
rs = stmt.executeQuery(sql);
/*
* double totInvoiceTotal = 0.0; double totDiscount = 0.0; double totTax = 0.0;
*/
BigDecimal totInvoiceTotal = new BigDecimal("0.0");
BigDecimal totDiscount = new BigDecimal("0.0");
BigDecimal totTax = new BigDecimal("0.0");
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Order Date");
subHeadings.addElement("Invoice Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
while (rs.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
String orderDate = rs.getString(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
double tax = rs.getDouble(4);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
/*
* totInvoiceTotal += invoiceTotal; totDiscount += discount; totTax += tax;
*/
totInvoiceTotal = totInvoiceTotal.add(new BigDecimal(invoiceTotal));
totDiscount = totDiscount.add(new BigDecimal(discount));
totTax = totTax.add(new BigDecimal(tax));
Hashtable totData = new Hashtable();
totData.put("Order Date", DateUtils.convertMySQLToUSFormat(orderDate));
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
data.addElement(totData);
}
if (getReturn) {
String retSql =
"SELECT a.OrderDate, SUM(a.InvoiceTotal), SUM(a.Discount), SUM(a.Tax) FROM Invoice a, Invoice b WHERE a.ReturnedInvoice!=0 and a.ReturnedInvoice=b.InvoiceNumber and ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Medium")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Eddie")) {
retSql +=
" b.SalesPerson='" + user.getUsername() + "' AND a.SalesPerson!='"
+ user.getUsername() + "' AND ";
} else if (salesPerson != null && !salesPerson.trim().equals("")) {
retSql +=
" b.SalesPerson='" + salesPerson.trim() + "' AND a.SalesPerson!='"
+ user.getUsername() + "' AND ";
}
if (fromDate.trim().equals(toDate.trim())) {
retSql += " a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
retSql +=
" a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
retSql += " Group BY a.OrderDate ";
rs1 = stmt.executeQuery(retSql);
while (rs1.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
String orderDate = rs1.getString(1);
double invoiceTotal = rs1.getDouble(2);
double discount = rs1.getDouble(3);
double tax = rs1.getDouble(4);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
/*
* totInvoiceTotal += invoiceTotal; totDiscount += discount; totTax += tax;
*/
totInvoiceTotal = totInvoiceTotal.add(new BigDecimal(invoiceTotal));
totDiscount = totDiscount.add(new BigDecimal(discount));
totTax = totTax.add(new BigDecimal(tax));
Hashtable totData = new Hashtable();
totData.put("Order Date", DateUtils.convertMySQLToUSFormat(orderDate));
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
data.addElement(totData);
}
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
totInvoiceTotal = totInvoiceTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
totDiscount = totDiscount.setScale(2, BigDecimal.ROUND_HALF_UP);
totTax = totTax.setScale(2, BigDecimal.ROUND_HALF_UP);
String totInvoiceTotalStr = totInvoiceTotal.toString();
String totDiscountStr = totDiscount.toString();
String totTaxStr = totTax.toString();
BigDecimal grossTotal = totInvoiceTotal.add(totTax);
grossTotal = grossTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal netTotal = (grossTotal.subtract(totTax)).subtract(totDiscount);
netTotal = netTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
totals[0][0] = "Gross Total";
totals[0][1] = grossTotal.toString();
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Net Total";
totals[3][1] = netTotal.toString();
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
logger.error(e);;
// throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showSalesForPers(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[5][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX = "SELECT Count(Distinct OrderDate) FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsX = stmtX.executeQuery(sqlX);
int noOfDays = 0;
if (rsX.next()) {
noOfDays = rsX.getInt(1);
}
if (noOfDays == 0) {
noOfDays = 1;
}
Statement stmt = con.createStatement();
String sql =
"SELECT InvoiceNumber, SalesPerson, InvoiceTotal, Tax, Discount, ReturnedInvoice FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
/*
* double totInvoiceTotal = 0.0; double totDiscount = 0.0; double totTax = 0.0; double totAvg
* = 0.0;
*/
BigDecimal totInvoiceTotal = new BigDecimal("0.0");
BigDecimal totDiscount = new BigDecimal("0.0");
BigDecimal totTax = new BigDecimal("0.0");
BigDecimal totAvg = new BigDecimal("0.0");
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Sales Person");
subHeadings.addElement("Invoice Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
subHeadings.addElement("Average");
String[][] arrSales = new String[50][4];
for (int i = 0; i < 50; i++) {
arrSales[i][0] = "";
arrSales[i][1] = "0.0";
arrSales[i][2] = "0.0";
arrSales[i][3] = "0.0";
}
while (rs.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
int invNo = rs.getInt(1);
String salesPerson = rs.getString(2);
double invoiceTotal = rs.getDouble(3);
double discount = rs.getDouble(5);
double tax = rs.getDouble(4);
int retInv = rs.getInt(6);
salesPerson = salesPerson.trim();
int currCnt = -1;
String currPers = "";
if (retInv == 0) {
currPers = salesPerson;
} else {
Statement stmtXX = con.createStatement();
ResultSet rsXX =
stmtXX.executeQuery("Select SalesPerson From Invoice Where InvoiceNumber=" + retInv);
if (rsXX.next()) {
currPers = rsXX.getString(1);
}
/*
* InvoiceBean retBean = InvoiceBean.getInvoice(retInv); if (
* retBean.getSalesPerson().trim().equals(salesPerson.trim() )) { currPers = salesPerson;
* } else { currPers = retBean.getSalesPerson(); }
*/
// 10/12/2013 : Changes done as a part of review : Begin
stmtXX.close();
// 10/12/2013 : Changes done as a part of review : End
}
int alreadyIn = 0;
for (int i = 0; i < 50; i++) {
if (!arrSales[i][0].trim().equals("")) {
alreadyIn++;
}
if (arrSales[i][0].trim().equals(currPers)) {
currCnt = i;
}
}
if (currCnt == -1) {
arrSales[alreadyIn][0] = currPers;
arrSales[alreadyIn][1] = invoiceTotal + "";
arrSales[alreadyIn][2] = discount + "";
arrSales[alreadyIn][3] = tax + "";
// logger.error("First Time Adding For " + currPers);
} else {
arrSales[currCnt][1] = invoiceTotal + Double.parseDouble(arrSales[currCnt][1]) + "";
arrSales[currCnt][2] = discount + Double.parseDouble(arrSales[currCnt][2]) + "";
arrSales[currCnt][3] = tax + Double.parseDouble(arrSales[currCnt][3]) + "";
}
}
for (int i = 0; i < 50; i++) {
String salesPers = arrSales[i][0];
if (salesPers.trim().equals("")) {
break;
}
double avg = 0.0;
Statement stmtY = con.createStatement();
String sqlY =
"SELECT Count(Distinct OrderDate) FROM Invoice WHERE SalesPerson='" + salesPers
+ "' and ";
if (fromDate.trim().equals(toDate.trim())) {
sqlY += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlY +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsY = stmtY.executeQuery(sqlY);
int noOfIndDays = 0;
if (rsY.next()) {
noOfIndDays = rsY.getInt(1);
}
if (noOfIndDays == 0) {
noOfIndDays = 1;
}
avg = Double.parseDouble(arrSales[i][1]) / noOfIndDays;
String invoiceTotalStr = Double.parseDouble(arrSales[i][1]) + "";
String discountStr = Double.parseDouble(arrSales[i][2]) + "";
String taxStr = Double.parseDouble(arrSales[i][3]) + "";
String avgStr = avg + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
if (avgStr.indexOf(".") == avgStr.length() - 2) {
avgStr += "0";
}
invoiceTotalStr = NumberUtils.cutFractions(invoiceTotalStr);
discountStr = NumberUtils.cutFractions(discountStr);
taxStr = NumberUtils.cutFractions(taxStr);
avgStr = NumberUtils.cutFractions(avgStr);
/*
* totInvoiceTotal += Double.parseDouble(arrSales[i][1]); totDiscount +=
* Double.parseDouble(arrSales[i][2]); totTax += Double.parseDouble(arrSales[i][3]);
*/
totInvoiceTotal = totInvoiceTotal.add(new BigDecimal(Double.parseDouble(arrSales[i][1])));
totDiscount = totDiscount.add(new BigDecimal(Double.parseDouble(arrSales[i][2])));
totTax = totTax.add(new BigDecimal(Double.parseDouble(arrSales[i][3])));
Hashtable totData = new Hashtable();
totData.put("Sales Person", salesPers);
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
totData.put("Average", avgStr);
data.addElement(totData);
// 10/12/2013 : Changes done as a part of review : Begin
stmtY.close();
// 10/12/2013 : Changes done as a part of review : End
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
totInvoiceTotal = totInvoiceTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
totDiscount = totDiscount.setScale(2, BigDecimal.ROUND_HALF_UP);
totTax = totTax.setScale(2, BigDecimal.ROUND_HALF_UP);
/*
* String totInvoiceTotalStr = totInvoiceTotal+""; String totDiscountStr = totDiscount+"";
* String totTaxStr = totTax + ""; String netTotal = totInvoiceTotal - totDiscount + totTax +
* "";
*/
String totInvoiceTotalStr = totInvoiceTotal.add(totTax).toString();
String totDiscountStr = totDiscount.toString();
String totTaxStr = totTax.toString();
BigDecimal netTotal = totInvoiceTotal.subtract(totDiscount);
/*
* totAvg = totInvoiceTotal / noOfDays; String totAvgStr = totAvg + "";
*/
totAvg = totInvoiceTotal.divide(new BigDecimal(noOfDays), MathContext.DECIMAL32);
totAvg = totAvg.setScale(2, BigDecimal.ROUND_HALF_UP);
String totAvgStr = totAvg.toString();
netTotal = netTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
/*
* if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length()-2) { totInvoiceTotalStr
* += "0"; } if (totDiscountStr.indexOf(".") == totDiscountStr.length()-2) { totDiscountStr +=
* "0"; } if (totTaxStr.indexOf(".") == totTaxStr.length()-2) { totTaxStr += "0"; } if
* (netTotal.indexOf(".") == netTotal.length()-2) { netTotal += "0"; } if
* (totAvgStr.indexOf(".") == totAvgStr.length()-2) { totAvgStr += "0"; }
*/
/*
* totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr); totDiscountStr =
* NumberUtils.cutFractions(totDiscountStr); totTaxStr = NumberUtils.cutFractions(totTaxStr);
* netTotal = NumberUtils.cutFractions(netTotal); totAvgStr =
* NumberUtils.cutFractions(totAvgStr);
*/
totals[0][0] = "Gross Total";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Average";
totals[3][1] = totAvgStr;
totals[4][0] = "Net Total";
// totals[4][1] = netTotal;
totals[4][1] = netTotal.toString();
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rs.close();
stmt.close();
// 10/12/2013 : Changes done as a part of review : Begin
stmtX.close();
// 10/12/2013 : Changes done as a part of review : End
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showSalesForRt(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowRtSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
Connection con = DBInterfaceLocal.getSQLConnection();
double totalSalesRt = 0.0;
Statement stmt = con.createStatement();
String sql = "SELECT Region, Sum(InvoiceTotal) FROM Invoice a, Address b WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sql += " and a.CustomerId=b.Id and b.type='Standard' Group by Region ";
ResultSet rs = stmt.executeQuery(sql);
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report By Route " + toDate.trim();
} else {
mainHeading = "Sales Report By Route From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Route No");
subHeadings.addElement("Amount");
while (rs.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
String rtNo = rs.getString(1);
double amt = rs.getDouble(2);
totalSalesRt += amt;
Hashtable totData = new Hashtable();
totData.put("Route No", rtNo);
totData.put("Amount", amt + "");
data.addElement(totData);
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
String totalSalesRtStr = totalSalesRt + "";
if (totalSalesRtStr.indexOf(".") == totalSalesRtStr.length() - 2) {
totalSalesRtStr += "0";
}
totalSalesRtStr = NumberUtils.cutFractions(totalSalesRtStr);
totals[0][0] = "Total Sales";
totals[0][1] = totalSalesRtStr;
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
logger.error(e.getMessage());
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showReturns(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowReturns = null;
try {
String fileName = "ShowReturns" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[5][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX = "SELECT Count(Distinct OrderDate) FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsX = stmtX.executeQuery(sqlX);
int noOfDays = 0;
if (rsX.next()) {
noOfDays = rsX.getInt(1);
}
if (noOfDays == 0) {
noOfDays = 1;
}
Statement stmt = con.createStatement();
String sql =
"SELECT InvoiceNumber, SalesPerson, InvoiceTotal, Tax, Discount, ReturnedInvoice FROM Invoice WHERE ReturnedInvoice!=0 and ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rs = stmt.executeQuery(sql);
double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totTax = 0.0;
double totAvg = 0.0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Returns For The Date " + toDate.trim();
} else {
mainHeading = "Sales Returns For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Sales Person");
subHeadings.addElement("Invoice Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
subHeadings.addElement("Average");
String[][] arrSales = new String[50][4];
for (int i = 0; i < 50; i++) {
arrSales[i][0] = "";
arrSales[i][1] = "0.0";
arrSales[i][2] = "0.0";
arrSales[i][3] = "0.0";
}
while (rs.next()) {
if (toShowReturns == null) {
toShowReturns = new Hashtable();
}
int invNo = rs.getInt(1);
String salesPerson = rs.getString(2);
double invoiceTotal = rs.getDouble(3);
double discount = rs.getDouble(5);
double tax = rs.getDouble(4);
int retInv = rs.getInt(6);
salesPerson = salesPerson.trim();
int currCnt = -1;
String currPers = "";
if (retInv == 0) {
currPers = salesPerson;
} else {
Statement stmtXX = con.createStatement();
ResultSet rsXX =
stmtXX.executeQuery("Select SalesPerson From Invoice Where InvoiceNumber=" + retInv);
if (rsXX.next()) {
currPers = rsXX.getString(1);
}
/*
* InvoiceBean retBean = InvoiceBean.getInvoice(retInv); if (
* retBean.getSalesPerson().trim().equals(salesPerson.trim() )) { currPers = salesPerson;
* } else { currPers = retBean.getSalesPerson(); }
*/
// 10/12/2013 : Changes done as a part of review : Begin
stmtXX.close();
// 10/12/2013 : Changes done as a part of review : End
}
int alreadyIn = 0;
for (int i = 0; i < 50; i++) {
if (!arrSales[i][0].trim().equals("")) {
alreadyIn++;
}
if (arrSales[i][0].trim().equals(currPers)) {
currCnt = i;
}
}
if (currCnt == -1) {
arrSales[alreadyIn][0] = currPers;
arrSales[alreadyIn][1] = invoiceTotal + "";
arrSales[alreadyIn][2] = discount + "";
arrSales[alreadyIn][3] = tax + "";
// logger.error("First Time Adding For " + currPers);
} else {
arrSales[currCnt][1] = invoiceTotal + Double.parseDouble(arrSales[currCnt][1]) + "";
arrSales[currCnt][2] = discount + Double.parseDouble(arrSales[currCnt][2]) + "";
arrSales[currCnt][3] = tax + Double.parseDouble(arrSales[currCnt][3]) + "";
}
}
for (int i = 0; i < 50; i++) {
String salesPers = arrSales[i][0];
if (salesPers.trim().equals("")) {
break;
}
double avg = 0.0;
Statement stmtY = con.createStatement();
String sqlY =
"SELECT Count(Distinct OrderDate) FROM Invoice WHERE SalesPerson='" + salesPers
+ "' and ";
if (fromDate.trim().equals(toDate.trim())) {
sqlY += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlY +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsY = stmtY.executeQuery(sqlY);
int noOfIndDays = 0;
if (rsY.next()) {
noOfIndDays = rsY.getInt(1);
}
if (noOfIndDays == 0) {
noOfIndDays = 1;
}
avg = Double.parseDouble(arrSales[i][1]) / noOfIndDays;
String invoiceTotalStr = Double.parseDouble(arrSales[i][1]) + "";
String discountStr = Double.parseDouble(arrSales[i][2]) + "";
String taxStr = Double.parseDouble(arrSales[i][3]) + "";
String avgStr = avg + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
if (avgStr.indexOf(".") == avgStr.length() - 2) {
avgStr += "0";
}
invoiceTotalStr = NumberUtils.cutFractions(invoiceTotalStr);
discountStr = NumberUtils.cutFractions(discountStr);
taxStr = NumberUtils.cutFractions(taxStr);
avgStr = NumberUtils.cutFractions(avgStr);
totInvoiceTotal += Double.parseDouble(arrSales[i][1]);
totDiscount += Double.parseDouble(arrSales[i][2]);
totTax += Double.parseDouble(arrSales[i][3]);
Hashtable totData = new Hashtable();
totData.put("Sales Person", salesPers);
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
totData.put("Average", avgStr);
data.addElement(totData);
// 10/12/2013 : Changes done as a part of review : Begin
stmtY.close();
// 10/12/2013 : Changes done as a part of review : End
}
if (toShowReturns == null) {
throw new UserException(" No Sales For This Period ");
}
String totInvoiceTotalStr = totInvoiceTotal + "";
String totDiscountStr = totDiscount + "";
String totTaxStr = totTax + "";
String netTotal = totInvoiceTotal - totDiscount + totTax + "";
totAvg = totInvoiceTotal / noOfDays;
String totAvgStr = totAvg + "";
if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length() - 2) {
totInvoiceTotalStr += "0";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totTaxStr.indexOf(".") == totTaxStr.length() - 2) {
totTaxStr += "0";
}
if (netTotal.indexOf(".") == netTotal.length() - 2) {
netTotal += "0";
}
if (totAvgStr.indexOf(".") == totAvgStr.length() - 2) {
totAvgStr += "0";
}
totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totTaxStr = NumberUtils.cutFractions(totTaxStr);
netTotal = NumberUtils.cutFractions(netTotal);
totAvgStr = NumberUtils.cutFractions(totAvgStr);
totals[0][0] = "Gross Total";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Average";
totals[3][1] = totAvgStr;
totals[4][0] = "Net Total";
totals[4][1] = netTotal;
toShowReturns.put("FileName", fileName);
toShowReturns.put("BackScreen", "TodaysOrders");
toShowReturns.put("MainHeading", mainHeading);
toShowReturns.put("SubHeadings", subHeadings);
toShowReturns.put("Data", data);
toShowReturns.put("Totals", totals);
createReport(toShowReturns);
rs.close();
// 10/12/2013 : Changes done as a part of review : Begin
stmtX.close();
// 10/12/2013 : Changes done as a part of review : End
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowReturns;
}
public static Hashtable showSalesForOldPers(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[5][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX = "SELECT Count(Distinct OrderDate) FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsX = stmtX.executeQuery(sqlX);
int noOfDays = 0;
if (rsX.next()) {
noOfDays = rsX.getInt(1);
}
if (noOfDays == 0) {
noOfDays = 1;
}
Statement stmt = con.createStatement();
String sql =
"SELECT SalesPerson, SUM(InvoiceTotal), SUM(Discount), SUM(Tax) FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sql += " Group BY SalesPerson Order By SalesPerson ";
ResultSet rs = stmt.executeQuery(sql);
double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totTax = 0.0;
double totAvg = 0.0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Sales Person");
subHeadings.addElement("Invoice Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
subHeadings.addElement("Average");
while (rs.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
String salesPerson = rs.getString(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
double tax = rs.getDouble(4);
double avg = 0.0;
Statement stmtY = con.createStatement();
String sqlY =
"SELECT Count(Distinct OrderDate) FROM Invoice WHERE SalesPerson='" + salesPerson
+ "' and ";
if (fromDate.trim().equals(toDate.trim())) {
sqlY += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlY +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsY = stmtY.executeQuery(sqlY);
int noOfIndDays = 0;
if (rsY.next()) {
noOfIndDays = rsY.getInt(1);
}
if (noOfIndDays == 0) {
noOfIndDays = 1;
}
avg = invoiceTotal / noOfIndDays;
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
String avgStr = avg + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
if (avgStr.indexOf(".") == avgStr.length() - 2) {
avgStr += "0";
}
avgStr = NumberUtils.cutFractions(avgStr);
totInvoiceTotal += invoiceTotal;
totDiscount += discount;
totTax += tax;
Hashtable totData = new Hashtable();
totData.put("Sales Person", salesPerson);
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
totData.put("Average", avgStr);
data.addElement(totData);
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
String totInvoiceTotalStr = totInvoiceTotal + "";
String totDiscountStr = totDiscount + "";
String totTaxStr = totTax + "";
String netTotal = totInvoiceTotal - totDiscount + totTax + "";
totAvg = totInvoiceTotal / noOfDays;
String totAvgStr = totAvg + "";
if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length() - 2) {
totInvoiceTotalStr += "0";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totTaxStr.indexOf(".") == totTaxStr.length() - 2) {
totTaxStr += "0";
}
if (netTotal.indexOf(".") == netTotal.length() - 2) {
netTotal += "0";
}
if (totAvgStr.indexOf(".") == totAvgStr.length() - 2) {
totAvgStr += "0";
}
totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totTaxStr = NumberUtils.cutFractions(totTaxStr);
netTotal = NumberUtils.cutFractions(netTotal);
totAvgStr = NumberUtils.cutFractions(totAvgStr);
totals[0][0] = "Gross Total";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Average";
totals[3][1] = totAvgStr;
totals[4][0] = "Net Total";
totals[4][1] = netTotal;
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rs.close();
rsX.close();
stmt.close();
stmtX.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showSalesForCust(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowCustSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[3][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX =
"SELECT a.CustomerId, b.CompanyName, Sum(a.InvoiceTotal), b.CustomerLevel, Max(a.OrderDate) FROM Invoice a, Customer b WHERE a.CustomerId=b.CustomerId AND ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sqlX += " Group By a.CustomerId Order By 3 Desc ";
ResultSet rsX = stmtX.executeQuery(sqlX);
double totInvoiceTotal = 0.0;
int noOfCust = 0;
int totalLvlCust = 0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report By Customers For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report By Customers For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Customer Id");
subHeadings.addElement("Company Name");
subHeadings.addElement("Last Order");
subHeadings.addElement("Amount Bought");
subHeadings.addElement("Level");
while (rsX.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
noOfCust++;
String custId = rsX.getString(1);
String companyName = rsX.getString(2);
double invoiceTotal = rsX.getDouble(3);
int lvl = rsX.getInt(4);
String orderDate = DateUtils.convertMySQLToUSFormat(rsX.getString(5));
if (lvl != 0) {
totalLvlCust++;
}
String invoiceTotalStr = invoiceTotal + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
totInvoiceTotal += invoiceTotal;
Hashtable totData = new Hashtable();
totData.put("Customer Id", custId);
totData.put("Company Name", companyName);
totData.put("Last Order", orderDate);
totData.put("Amount Bought", invoiceTotalStr);
totData.put("Level", lvl + "");
data.addElement(totData);
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
String totInvoiceTotalStr = totInvoiceTotal + "";
if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length() - 2) {
totInvoiceTotalStr += "0";
}
totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr);
totals[0][0] = "Total Amount";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "No Of Customers";
totals[1][1] = noOfCust + "";
totals[2][0] = "No Of Leveled Customers";
totals[2][1] = totalLvlCust + "";
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rsX.close();
stmtX.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showPartsSold(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowPartsSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[8][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX =
"SELECT a.InvoiceNumber, a.PartNumber, a.Quantity, a.SoldPrice, a.ActualPrice, c.CostPrice, c.ActualPrice, c.UnitsInStock, c.UnitsOnOrder, c.ReorderLevel" +
// ", c.CompPrice1, c.CompPrice2" +
" FROM InvoiceDetails a, Invoice b, Parts c WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " b.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" b.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND b.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sqlX += " and b.InvoiceNumber=a.InvoiceNumber and a.PartNumber=c.PartNo Order By 1, 2 ";
ResultSet rsX = stmtX.executeQuery(sqlX);
int totalNoOfParts = 0;
int totalNoOfItems = 0;
double totalSoldPrice = 0.0;
double totalInvActual = 0.0;
double totalPartsCost = 0.0;
double totalPartsActual = 0.0;
double totalActualPerc = 0.0;
double partsPerc = 0.0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report By Parts For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report By Parts For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Part / Inv");
subHeadings.addElement("Qty/Sold/Act");
subHeadings.addElement("Cost/Act");
subHeadings.addElement("Units");
//subHeadings.addElement("Comp");
subHeadings.addElement("Perc");
subHeadings.addElement("Rmks");
while (rsX.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
int invNo = rsX.getInt(1);
String partNo = rsX.getString(2);
if ((partNo.startsWith("XX") || partNo.startsWith("xx")) && partNo.length() == 7) {
continue;
}
int qty = rsX.getInt(3);
double sold = rsX.getDouble(4);
double invAct = rsX.getDouble(5);
double partCost = rsX.getDouble(6);
double partAct = rsX.getDouble(7);
int units = rsX.getInt(8);
int onOrder = rsX.getInt(9);
int reorder = rsX.getInt(10);
// double comp1 = rsX.getDouble(11);
// double comp2 = rsX.getDouble(12);
double perc = 0.0;
double shouldBePerc = 0.0;
String remarks = " ";
if (partAct == 0 && invAct != 0) {
partAct = invAct;
}
if (sold > 0 && invAct > 0) {
perc = (sold - invAct) * 100 / sold;
perc = Math.rint(perc);
} else {
perc = 0;
}
if (invAct > 0) {
if (invAct < 1) {
shouldBePerc = 70;
} else if (invAct < 2) {
shouldBePerc = 67;
} else if (invAct < 3) {
shouldBePerc = 65;
} else if (invAct < 4) {
shouldBePerc = 63;
} else if (invAct < 5) {
shouldBePerc = 61;
} else if (invAct < 8) {
shouldBePerc = 59;
} else if (invAct < 11) {
shouldBePerc = 57;
} else if (invAct < 14) {
shouldBePerc = 55;
} else if (invAct < 18) {
shouldBePerc = 53;
} else if (invAct < 23) {
shouldBePerc = 51;
} else if (invAct < 28) {
shouldBePerc = 49;
} else if (invAct < 35) {
shouldBePerc = 47;
} else if (invAct < 42) {
shouldBePerc = 45;
} else if (invAct < 50) {
shouldBePerc = 43;
} else if (invAct < 60) {
shouldBePerc = 41;
} else if (invAct < 70) {
shouldBePerc = 39;
} else if (invAct < 80) {
shouldBePerc = 37;
} else if (invAct < 90) {
shouldBePerc = 35;
} else if (invAct < 125) {
shouldBePerc = 30;
} else if (invAct < 150) {
shouldBePerc = 25;
} else {
shouldBePerc = 20;
}
} else {
shouldBePerc = 0;
}
if (perc > shouldBePerc + 10) {
remarks = "High Price";
} else if (perc < shouldBePerc - 10) {
remarks = "Low Price";
}
totalNoOfParts++;
totalNoOfItems += qty;
totalSoldPrice += (sold * qty);
totalInvActual += (invAct * qty);
totalPartsCost += (partCost * qty);
totalPartsActual += (partAct * qty);
String partNoInvNo = partNo + " / " + invNo;
String qtySoldAct = qty + " / " + sold + " / " + invAct;
String costAct = partCost + " / " + partAct;
String unitsOrderReorder = units + " / " + onOrder + " / " + reorder;
// String comp1Comp2 = comp1 + " / " + comp2;
String percShouldBePerc = perc + " / " + shouldBePerc;
Hashtable totData = new Hashtable();
totData.put("Part / Inv", partNoInvNo);
totData.put("Qty/Sold/Act", qtySoldAct);
totData.put("Cost/Act", costAct);
totData.put("Units", unitsOrderReorder);
// totData.put("Comp", comp1Comp2);
totData.put("Perc", percShouldBePerc);
totData.put("Rmks", remarks);
data.addElement(totData);
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
double actualPerc = 0.0;
double shouldBePerc = 0.0;
String totalSoldPriceStr = totalSoldPrice + "";
if (totalSoldPriceStr.indexOf(".") == totalSoldPriceStr.length() - 2) {
totalSoldPriceStr += "0";
}
totalSoldPriceStr = NumberUtils.cutFractions(totalSoldPriceStr);
String totalInvActualStr = totalInvActual + "";
if (totalInvActualStr.indexOf(".") == totalInvActualStr.length() - 2) {
totalInvActualStr += "0";
}
totalInvActualStr = NumberUtils.cutFractions(totalInvActualStr);
String totalPartsCostStr = totalPartsCost + "";
if (totalPartsCostStr.indexOf(".") == totalPartsCostStr.length() - 2) {
totalPartsCostStr += "0";
}
totalPartsCostStr = NumberUtils.cutFractions(totalPartsCostStr);
String totalPartsActualStr = totalPartsActual + "";
if (totalPartsActualStr.indexOf(".") == totalPartsActualStr.length() - 2) {
totalPartsActualStr += "0";
}
totalPartsActualStr = NumberUtils.cutFractions(totalPartsActualStr);
totalActualPerc = (totalSoldPrice - totalInvActual) * 100 / totalSoldPrice;
totalActualPerc = Math.rint(totalActualPerc);
partsPerc = (totalPartsCost - totalPartsActual) * 100 / totalPartsCost;
partsPerc = Math.rint(partsPerc);
totals[0][0] = "Total No Of Parts";
totals[0][1] = totalNoOfParts + "";
totals[1][0] = "Total No Of Items";
totals[1][1] = totalNoOfItems + "";
totals[2][0] = "Total Sold Price";
totals[2][1] = totalSoldPriceStr;
totals[3][0] = "Total Invoice Actual";
totals[3][1] = totalInvActualStr;
totals[4][0] = "Total Parts Cost";
totals[4][1] = totalPartsCostStr;
totals[5][0] = "Total Parts Actual";
totals[5][1] = totalPartsActualStr;
totals[6][0] = "Actual Perc";
totals[6][1] = totalActualPerc + "";
totals[7][0] = "Perc On Parts";
totals[7][1] = partsPerc + "";
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rsX.close();
stmtX.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showInvoices(UserBean user, String invoiceFromDate, String invoiceToDate,
String salesPerson) throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowInvoices" + invoiceFromDate.trim() + invoiceToDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[4][2];
boolean getReturns = false;
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.SalesPerson, a.CustomerId, b.CompanyName, a.InvoiceTotal, a.Discount, a.Tax FROM Invoice a, Customer b WHERE ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Medium")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Marcie")
&& !user.getUsername().trim().equalsIgnoreCase("Nancy")
&& !user.getUsername().trim().equalsIgnoreCase("Eddie")) {
sql += " a.SalesPerson='" + user.getUsername() + "' AND ";
getReturns = true;
} else if (salesPerson != null && !salesPerson.trim().equals("")) {
sql += " a.SalesPerson='" + salesPerson.trim() + "' AND ";
getReturns = true;
}
if (invoiceFromDate.trim().equals(invoiceToDate)) {
sql += " a.OrderDate='" + DateUtils.convertUSToMySQLFormat(invoiceFromDate.trim()) + "'";
} else {
sql += " a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(invoiceFromDate.trim()) + "'";
sql += " AND a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(invoiceToDate.trim()) + "'";
}
sql += " AND a.CustomerId=b.CustomerId Order By 1 ";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totTax = 0.0;
if (invoiceFromDate.trim().equals(invoiceToDate)) {
mainHeading = "Invoice Orders For The Date " + invoiceFromDate.trim();
} else {
mainHeading =
"Invoice Orders From " + invoiceFromDate.trim() + " To " + invoiceToDate.trim();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Inv. Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
String invoiceNo = rs.getString(1);
String newSalesPerson = rs.getString(2);
String custId = rs.getString(3);
String custName = rs.getString(4);
double invoiceTotal = rs.getDouble(5);
double discount = rs.getDouble(6);
double tax = rs.getDouble(7);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
totInvoiceTotal += invoiceTotal;
totDiscount += discount;
totTax += tax;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Inv. Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
data.addElement(totData);
}
if (getReturns) {
String retSql =
"SELECT a.InvoiceNumber, a.ReturnedInvoice, a.CustomerId, b.CompanyName, a.InvoiceTotal, a.Discount, a.Tax FROM Invoice a, Customer b, Invoice c WHERE a.ReturnedInvoice!=0 and a.ReturnedInvoice=c.InvoiceNumber AND ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Medium")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Eddie")) {
retSql +=
" c.SalesPerson='" + user.getUsername() + "' AND a.SalesPerson!='"
+ user.getUsername() + "' AND ";
} else if (salesPerson != null && !salesPerson.trim().equals("")) {
retSql +=
" c.SalesPerson='" + salesPerson.trim() + "' AND a.SalesPerson!='"
+ user.getUsername() + "' AND ";
}
if (invoiceFromDate.trim().equals(invoiceToDate)) {
retSql +=
" a.OrderDate='" + DateUtils.convertUSToMySQLFormat(invoiceFromDate.trim()) + "'";
} else {
retSql +=
" a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(invoiceFromDate.trim()) + "'";
retSql +=
" AND a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(invoiceToDate.trim()) + "'";
}
retSql += " AND a.CustomerId=b.CustomerId Order By 1 ";
ResultSet rs1 = stmt.executeQuery(retSql);
while (rs1.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
String invoiceNo = rs1.getString(1);
String retInvNo = rs1.getString(2);
String custId = rs1.getString(3);
String custName = rs1.getString(4);
double invoiceTotal = rs1.getDouble(5);
double discount = rs1.getDouble(6);
double tax = rs1.getDouble(7);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
totInvoiceTotal += invoiceTotal;
totDiscount += discount;
totTax += tax;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Sales Person", retInvNo);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Inv. Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
data.addElement(totData);
}
}
if (toShowInvoices == null) {
throw new UserException(" No Sales For This Period ");
}
String totInvoiceTotalStr = totInvoiceTotal + "";
String totDiscountStr = totDiscount + "";
String totTaxStr = totTax + "";
String netTotal = totInvoiceTotal - totDiscount + totTax + "";
if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length() - 2) {
totInvoiceTotalStr += "0";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totTaxStr.indexOf(".") == totTaxStr.length() - 2) {
totTaxStr += "0";
}
if (netTotal.indexOf(".") == netTotal.length() - 2) {
netTotal += "0";
}
totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totTaxStr = NumberUtils.cutFractions(totTaxStr);
netTotal = NumberUtils.cutFractions(netTotal);
if (user.getRole().trim().equalsIgnoreCase("Acct")) {
totInvoiceTotalStr = "0.0";
totDiscountStr = "0.0";
totTaxStr = "0.0";
netTotal = "0.0";
}
totals[0][0] = "Gross Total";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Net Total";
totals[3][1] = netTotal;
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable analyseInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
if (!user.getRole().trim().equalsIgnoreCase("High")) {
throw new UserException("YOU ARE NOT AUTHORIZED TO VIEW THIS REPORT");
}
String fileName = "";
if (fromDate.trim().equals(toDate.trim())) {
fileName = "AI" + fromDate.trim() + ".html";
} else {
fileName = "AI" + fromDate.trim() + toDate.trim() + ".html";
}
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[23][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT InvoiceNumber, InvoiceTotal, Discount FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate = '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
} else {
sql +=
" OrderDate >= '" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate <= '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
}
sql += " Order By 1 ";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totOverseasPrice = 0;
double totOverseasSoldPrice = 0;
double totLocalPrice = 0;
double totLocalSoldPrice = 0;
double totTotalPrice = 0;
double totTotalSoldPrice = 0;
double totMargin = 0;
double totPercent = 0;
int totLocalItems = 0;
int totOverseasItems = 0;
int totNoPriceItems = 0;
double totNoPriceItemsSoldPrice = 0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Analyzing Invoices For The Date " + toDate.trim();
} else {
mainHeading =
"Analyzing Invoices For The Dates From " + fromDate.trim() + " To " + toDate.trim();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Overseas Price");
subHeadings.addElement("Overseas Sold Price");
subHeadings.addElement("Local Price");
subHeadings.addElement("Local Sold Price");
subHeadings.addElement("Percent");
subHeadings.addElement("Remarks");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
int invoiceNo = rs.getInt(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
double overseasPrice = 0;
double overseasSoldPrice = 0;
double localPrice = 0;
double localSoldPrice = 0;
double percent = 0;
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
String overseasPriceStr = "";
String overseasSoldPriceStr = "";
String localPriceStr = "";
String localSoldPriceStr = "";
String percentStr = "";
String remarks = "";
InvoiceBean invoice = InvoiceBean.getInvoice(invoiceNo, con);
Vector<InvoiceDetailsBean> invoiceDetails = invoice.getInvoiceDetails();
if (invoiceDetails.size() != 0) {
Enumeration<InvoiceDetailsBean> ennum = invoiceDetails.elements();
while (ennum.hasMoreElements()) {
InvoiceDetailsBean invoiceDetailsBean = ennum.nextElement();
String partNo = invoiceDetailsBean.getPartNumber();
int qty = invoiceDetailsBean.getQuantity();
int remainItems = 0;
double price = invoiceDetailsBean.getSoldPrice();
int supplierId = 0;
String vendorInvNo = "";
LocalOrderBean orderBean =
LocalOrderBean.getLocalOrder(supplierId, invoiceNo, partNo, vendorInvNo, con);
if (invoiceDetailsBean.getActualPrice() != 0) {
if (orderBean != null) {
totLocalItems += qty;
localPrice += (invoiceDetailsBean.getActualPrice() * qty);
localSoldPrice += (price * qty);
} else {
totOverseasItems += qty;
overseasPrice += (invoiceDetailsBean.getActualPrice() * qty);
overseasSoldPrice += (price * qty);
}
} else {
if (orderBean != null) {
// Got this Part From Local Vendor
if (qty <= orderBean.getQuantity()) {
remainItems = orderBean.getQuantity() - qty;
totLocalItems += qty;
localPrice += (orderBean.getPrice() * qty);
localSoldPrice += (price * qty);
} else {
remainItems = qty - orderBean.getQuantity();
}
} else {
remainItems = qty;
}
if (remainItems != 0) {
// Got This Part From Overseas
PartsBean part = PartsBean.getPart(partNo, con);
if (part != null) {
if (part.getActualPrice() != 0) {
totOverseasItems += remainItems;
overseasPrice += (part.getActualPrice() * remainItems);
overseasSoldPrice += (price * remainItems);
} else if (!part.getInterchangeNo().trim().equals("")
&& PartsBean.getPart(part.getInterchangeNo(), con).getActualPrice() != 0) {
totOverseasItems += remainItems;
overseasPrice +=
(PartsBean.getPart(part.getInterchangeNo(), con).getActualPrice() * remainItems);
overseasSoldPrice += (price * remainItems);
} else {
Statement stmt1 = con.createStatement();
ResultSet rs1 =
stmt1
.executeQuery("Select PartNo, ActualPrice From Parts Where InterchangeNo='"
+ part.getPartNo() + "'");
double actPrice = 0;
while (rs1.next()) {
actPrice = rs1.getDouble("ActualPrice");
if (actPrice != 0) {
break;
}
}
if (actPrice != 0) {
totOverseasItems += remainItems;
overseasPrice += (actPrice * remainItems);
overseasSoldPrice += (price * remainItems);
} else {
totNoPriceItemsSoldPrice += (price * remainItems);
totNoPriceItems += remainItems;
remarks += "No Price:" + partNo + "\n";
}
}
// logger.error(overseasSoldPrice);
part = null;
} else {
remarks += "No Part:" + partNo + "\n";
}
}
}
invoiceDetailsBean = null;
orderBean = null;
}
invoice = null;
} else {
overseasPriceStr = "";
overseasSoldPriceStr = "";
localPriceStr = "";
localSoldPriceStr = "";
percentStr = "";
remarks = "No Items";
}
double totPrice = overseasPrice + localPrice;
double totSoldPrice = overseasSoldPrice + localSoldPrice;
if (totPrice != 0) {
totPrice = Double.parseDouble(NumberUtils.cutFractions(totPrice + ""));
}
if (totSoldPrice != 0) {
totSoldPrice = Double.parseDouble(NumberUtils.cutFractions(totSoldPrice + ""));
}
// if (totSoldPrice != invoiceTotal) {
// remarks += "Not Matching\n";
// }
if (totSoldPrice != 0) {
percent = (totSoldPrice - totPrice - discount) * 100 / totSoldPrice;
} else {
percent = 0;
}
if (remarks.trim().equals("")) {
remarks = " ";
}
percent = Math.rint(percent);
totInvoiceTotal += invoiceTotal;
totDiscount += discount;
if (overseasPrice != 0) {
totOverseasPrice += overseasPrice;
overseasPriceStr = overseasPrice + "";
} else {
overseasPriceStr = " ";
}
if (overseasSoldPrice != 0) {
totOverseasSoldPrice += overseasSoldPrice;
overseasSoldPriceStr = overseasSoldPrice + "";
} else {
overseasSoldPriceStr = " ";
}
if (localPrice != 0) {
totLocalPrice += localPrice;
localPriceStr = localPrice + "";
} else {
localPriceStr = " ";
}
if (localSoldPrice != 0) {
totLocalSoldPrice += localSoldPrice;
localSoldPriceStr = localSoldPrice + "";
} else {
localSoldPriceStr = " ";
}
if (percent != 0) {
percentStr = percent + "";
} else {
percentStr = " ";
}
if (overseasPriceStr.indexOf(".") == overseasPriceStr.length() - 2) {
overseasPriceStr += "0";
}
if (overseasSoldPriceStr.indexOf(".") == overseasSoldPriceStr.length() - 2) {
overseasSoldPriceStr += "0";
}
if (localPriceStr.indexOf(".") == localPriceStr.length() - 2) {
localPriceStr += "0";
}
if (localSoldPriceStr.indexOf(".") == localSoldPriceStr.length() - 2) {
localSoldPriceStr += "0";
}
overseasPriceStr = NumberUtils.cutFractions(overseasPriceStr);
overseasSoldPriceStr = NumberUtils.cutFractions(overseasSoldPriceStr);
localPriceStr = NumberUtils.cutFractions(localPriceStr);
localSoldPriceStr = NumberUtils.cutFractions(localSoldPriceStr);
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo + "");
totData.put("Inv. Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Overseas Price", overseasPriceStr);
totData.put("Overseas Sold Price", overseasSoldPriceStr);
totData.put("Local Price", localPriceStr);
totData.put("Local Sold Price", localSoldPriceStr);
totData.put("Percent", percentStr);
totData.put("Remarks", remarks);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No Sales For This Period ");
}
// String totInvoiceTotalStr = totInvoiceTotal+"";
String totDiscountStr = totDiscount + "";
String netTotal = totInvoiceTotal - totDiscount + "";
// logger.error("TotOverseasPrice10: " + totOverseasPrice);
String totOverseasPriceStr = totOverseasPrice + "";
// logger.error("TotOverseasPriceStr10: " +
// totOverseasPriceStr);
String totOverseasSoldPriceStr = totOverseasSoldPrice + "";
String totLocalPriceStr = totLocalPrice + "";
String totLocalSoldPriceStr = totLocalSoldPrice + "";
String totPriceStr = "";
String totSoldPriceStr = "";
String overseasMarginStr = "";
String overseasPercentStr = "";
String localMarginStr = "";
String localPercentStr = "";
String totMarginStr = "";
String totPercentStr = "";
String totNoPriceItemsSoldPriceStr = "";
double overseasMargin = 0;
double overseasPercent = 0;
double localMargin = 0;
double localPercent = 0;
totTotalPrice = totOverseasPrice + totLocalPrice;
totTotalSoldPrice = totOverseasSoldPrice + totLocalSoldPrice + totNoPriceItemsSoldPrice;
overseasMargin = totOverseasSoldPrice - totOverseasPrice;
localMargin = totLocalSoldPrice - totLocalPrice;
if (totOverseasSoldPrice != 0) {
overseasPercent = overseasMargin * 100 / totOverseasSoldPrice;
} else {
overseasPercent = 0;
}
if (totLocalSoldPrice != 0) {
localPercent = localMargin * 100 / totLocalSoldPrice;
} else {
localPercent = 0;
}
overseasPercent = Math.rint(overseasPercent);
localPercent = Math.rint(localPercent);
totMargin = totTotalSoldPrice - totDiscount - totTotalPrice;
if (totOverseasSoldPrice + totLocalSoldPrice != 0) {
totPercent = (totMargin * 100) / (totOverseasSoldPrice + totLocalSoldPrice);
} else {
totPercent = 0;
}
totPercent = Math.rint(totPercent);
totPriceStr = totTotalPrice + "";
totSoldPriceStr = totTotalSoldPrice + "";
totNoPriceItemsSoldPriceStr = totNoPriceItemsSoldPrice + "";
overseasMarginStr = overseasMargin + "";
localMarginStr = localMargin + "";
if (overseasPercent != 0) {
overseasPercentStr = overseasPercent + "";
} else {
overseasPercentStr = " ";
}
if (localPercent != 0) {
localPercentStr = localPercent + "";
} else {
localPercentStr = " ";
}
totMarginStr = totMargin + "";
if (totPercent != 0) {
totPercentStr = totPercent + "";
} else {
totPercentStr = " ";
}
// if (totInvoiceTotalStr.indexOf(".") ==
// totInvoiceTotalStr.length()-2) {
// totInvoiceTotalStr += "0";
// }
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (netTotal.indexOf(".") == netTotal.length() - 2) {
netTotal += "0";
}
if (totLocalPriceStr.indexOf(".") == totLocalPriceStr.length() - 2) {
totLocalPriceStr += "0";
}
if (totLocalSoldPriceStr.indexOf(".") == totLocalSoldPriceStr.length() - 2) {
totLocalSoldPriceStr += "0";
}
if (localMarginStr.indexOf(".") == localMarginStr.length() - 2) {
localMarginStr += "0";
}
if (totOverseasPriceStr.indexOf(".") == totOverseasPriceStr.length() - 2) {
totOverseasPriceStr += "0";
}
if (totOverseasSoldPriceStr.indexOf(".") == totOverseasSoldPriceStr.length() - 2) {
totOverseasSoldPriceStr += "0";
}
if (overseasMarginStr.indexOf(".") == overseasMarginStr.length() - 2) {
overseasMarginStr += "0";
}
if (totPriceStr.indexOf(".") == totPriceStr.length() - 2) {
totPriceStr += "0";
}
if (totSoldPriceStr.indexOf(".") == totSoldPriceStr.length() - 2) {
totSoldPriceStr += "0";
}
if (totMarginStr.indexOf(".") == totMarginStr.length() - 2) {
totMarginStr += "0";
}
if (totNoPriceItemsSoldPriceStr.indexOf(".") == totNoPriceItemsSoldPriceStr.length() - 2) {
totNoPriceItemsSoldPriceStr += "0";
}
totLocalPriceStr = NumberUtils.cutFractions(totLocalPriceStr);
totLocalSoldPriceStr = NumberUtils.cutFractions(totLocalSoldPriceStr);
localMarginStr = NumberUtils.cutFractions(localMarginStr);
totOverseasPriceStr = NumberUtils.cutFractions(totOverseasPriceStr);
totOverseasSoldPriceStr = NumberUtils.cutFractions(totOverseasSoldPriceStr);
overseasMarginStr = NumberUtils.cutFractions(overseasMarginStr);
totPriceStr = NumberUtils.cutFractions(totPriceStr);
totSoldPriceStr = NumberUtils.cutFractions(totSoldPriceStr);
totMarginStr = NumberUtils.cutFractions(totMarginStr);
totNoPriceItemsSoldPriceStr = NumberUtils.cutFractions(totNoPriceItemsSoldPriceStr);
// totInvoiceTotalStr =
// NumberUtils.cutFractions(totInvoiceTotalStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
netTotal = NumberUtils.cutFractions(netTotal);
totals[0][0] = "Total No. Of Items Bought Locally";
totals[0][1] = totLocalItems + "";
totals[1][0] = "Local Price";
totals[1][1] = totLocalPriceStr;
totals[2][0] = "Our Sold Price";
totals[2][1] = totLocalSoldPriceStr;
totals[3][0] = "Margin On Local Items";
totals[3][1] = localMarginStr;
totals[4][0] = "Percentage of Margin";
totals[4][1] = localPercentStr + " %";
totals[5][0] = " ";
totals[5][1] = " ";
totals[6][0] = " ";
totals[6][1] = " ";
totals[7][0] = "Total No. Of Items Bought From Overseas";
totals[7][1] = totOverseasItems + "";
totals[8][0] = "Overseas Price";
totals[8][1] = totOverseasPriceStr;
totals[9][0] = "Our Sold Price";
totals[9][1] = totOverseasSoldPriceStr;
totals[10][0] = "Margin On Overseas Items";
totals[10][1] = overseasMarginStr;
totals[11][0] = "Percentage of Margin";
totals[11][1] = overseasPercentStr + " %";
totals[12][0] = " ";
totals[12][1] = " ";
totals[13][0] = " ";
totals[13][1] = " ";
totals[14][0] = "Items With No Price";
totals[14][1] = totNoPriceItems + "";
totals[15][0] = "No Price Items Sold Price";
totals[15][1] = totNoPriceItemsSoldPriceStr + "";
totals[16][0] = " ";
totals[16][1] = " ";
totals[17][0] = "Total No. Of Items";
totals[17][1] = totLocalItems + totOverseasItems + totNoPriceItems + "";
totals[18][0] = "Total Price";
totals[18][1] = totPriceStr;
totals[19][0] = "Total Sold Price";
totals[19][1] = totSoldPriceStr;
totals[20][0] = "Total Discount Given";
totals[20][1] = totDiscountStr;
totals[21][0] = "Margin On All Items";
totals[21][1] = totMarginStr;
totals[22][0] = "Percentage of Margin";
totals[22][1] = totPercentStr + " %";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
logger.error(e);
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable inventoryOnHand(UserBean user, boolean bySubCat) throws UserException {
Hashtable toShowInven = null;
try {
String fileName = "ShowInven" + DateUtils.getNewUSDate() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[4][2];
mainHeading = "Inventory On Hand On " + DateUtils.getNewUSDate();
subHeadings.addElement("CATEGORY");
subHeadings.addElement("No. Of Parts");
subHeadings.addElement("No. Of Items");
subHeadings.addElement("COST");
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql1 =
"SELECT c.CategoryName, COUNT(*), SUM(UnitsInStock), sum(UnitsInStock*ActualPrice) FROM Parts a, SubCategory b, Category c WHERE ";
sql1 +=
" UnitsInStock > 0 and a.SubCategory=b.SubCategoryCode and b.CategoryCode=c.CategoryCode Group By 1 Order By 1 ";
String sql2 =
"SELECT b.SubCategoryName, COUNT(*), SUM(UnitsInStock), sum(UnitsInStock*ActualPrice) FROM Parts a, SubCategory b WHERE ";
sql2 += " UnitsInStock > 0 and a.SubCategory=b.SubCategoryCode Group By 1 Order By 1 ";
// logger.error(sql);
ResultSet rs = null;
if (bySubCat) {
rs = stmt.executeQuery(sql2);
} else {
rs = stmt.executeQuery(sql1);
}
int cntCat = 0;
int totItems = 0;
int totUnits = 0;
double totCost = 0.0;
while (rs.next()) {
if (toShowInven == null) {
toShowInven = new Hashtable();
}
String cat = rs.getString(1);
int noItems = rs.getInt(2);
int noUnits = rs.getInt(3);
double cost = rs.getDouble(4);
cntCat++;
totItems += noItems;
totUnits += noUnits;
totCost += cost;
String totCostStr = cost + "";
if (totCostStr.indexOf(".") == totCostStr.length() - 2) {
totCostStr += "0";
}
totCostStr = NumberUtils.cutFractions(totCostStr);
Hashtable totData = new Hashtable();
totData.put("CATEGORY", cat);
totData.put("No. Of Parts", noItems + "");
totData.put("No. Of Items", noUnits + "");
totData.put("COST", totCostStr);
data.addElement(totData);
}
String totActualStr = totCost + "";
if (totActualStr.indexOf(".") == totActualStr.length() - 2) {
totActualStr += "0";
}
totActualStr = NumberUtils.cutFractions(totActualStr);
totals[0][0] = "No Of Categories";
totals[0][1] = cntCat + "";
totals[1][0] = "Total No. Of Parts";
totals[1][1] = totItems + "";
totals[2][0] = "total No. Of Units";
totals[2][1] = totUnits + "";
totals[3][0] = "Total Cost Of Inventory";
totals[3][1] = totActualStr;
toShowInven.put("FileName", fileName);
toShowInven.put("BackScreen", "TodaysOrders");
toShowInven.put("MainHeading", mainHeading);
toShowInven.put("SubHeadings", subHeadings);
toShowInven.put("Data", data);
toShowInven.put("Totals", totals);
createReport(toShowInven);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInven;
}
public static String findCOGIByOrderDate(UserBean user, String fromDate,
String toDate) throws UserException {
if (!user.getRole().trim().equalsIgnoreCase("High")) {
throw new UserException(
"YOU ARE NOT AUTHORIZED TO VIEW THIS REPORT");
}
List<InvoiceDetailsOurPrice> missingourpricelist =
UpdateOurPrice.getMissingOurPrice("");
if (missingourpricelist.size() > 0) {
UpdateOurPrice.updateOurPrices(missingourpricelist, "");
}
Connection conn = null;
Statement pstmt = null;
ResultSet rs = null;
StringBuilder totals = new StringBuilder();
try {
conn = DBInterfaceLocal.getSQLConnection();
String findcogiSql = "select i.InvoiceNumber,i.Discount, SUM(id.SoldPrice*Quantity) as invTotal,SUM(id.ActualPrice*Quantity) as ourPrice"
+ ",SUM(Quantity) as TotalItems from invoice i, invoicedetails id "
+ " WHERE i.InvoiceNumber = id.InvoiceNumber AND i.OrderDate BETWEEN '"
+ DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' "
+ "AND '"
+ DateUtils.convertUSToMySQLFormat(toDate.trim())
+ "'"
+ " and id.ActualPrice > 0 GROUP BY InvoiceNumber Having invTotal > 0 Order By i.InvoiceNumber DESC";
System.err.println("find sql----" + findcogiSql);
pstmt = conn.createStatement();
rs = pstmt.executeQuery(findcogiSql);
int totalItems = 0;
BigDecimal totalDiscount = new BigDecimal(0);
BigDecimal totalInvTotal = new BigDecimal(0);
BigDecimal totalOurPrice = new BigDecimal(0);
BigDecimal totalMargin = new BigDecimal(0);
totalMargin.setScale(2,RoundingMode.HALF_EVEN);
double discount = 0, invTotal = 0, ourPrice = 0, margin = 0;
StringBuilder sbOuter = new StringBuilder();
sbOuter.append("<TR><TD align='Center' ><TABLE border='1'><TBODY><TR>");
sbOuter.append("<TH width='100'>Inv. No.</TH><TH>Inv. Total</TH><TH>Discount</TH><TH>Our Cost</TH><TH>Margin</TH></TR>");
while (rs.next()) {
discount = rs.getDouble("Discount");
invTotal = rs.getDouble("invTotal");
ourPrice = rs.getDouble("ourPrice");
margin = new BigDecimal((invTotal - ourPrice - discount)).setScale(2,RoundingMode.HALF_EVEN).doubleValue();
StringBuilder sbInner = new StringBuilder();
sbInner.append("<TR>");
sbInner.append("<TD>");
sbInner.append(rs.getString("InvoiceNumber"));
sbInner.append("</TD>");
sbInner.append("<TD>");
sbInner.append( invTotal );
sbInner.append("</TD>");
sbInner.append("<TD>" );
sbInner.append( discount );
sbInner.append( "</TD>");
sbInner.append("<TD>" );
sbInner.append(ourPrice);
sbInner.append( "</TD>");
sbInner.append("<TD>");
sbInner.append( margin );
sbInner.append( "</TD>");
sbInner.append("</TR>");
sbOuter.append(sbInner);
totalItems += rs.getInt("TotalItems");
totalDiscount = totalDiscount.add(new BigDecimal(discount));
totalInvTotal = totalInvTotal.add(new BigDecimal(invTotal));
totalOurPrice = totalOurPrice.add(new BigDecimal(ourPrice));
totalMargin = totalMargin.add(new BigDecimal(margin));
}
double totPercent = (totalMargin.doubleValue()*100) /(totalInvTotal.doubleValue()) ;
totals.append("<TR><TD align='Right' ><TABLE>");
totals.append("<TR>");
totals.append("<TD><B>Total No. Of Items</B></TD>");
totals.append("<TD><B>" + totalItems + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Total Price</B></TD>");
totals.append("<TD><B>" + totalOurPrice.setScale(2,RoundingMode.HALF_EVEN).doubleValue() + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Total Sold Price</B></TD>");
totals.append("<TD><B>" + totalInvTotal.setScale(2,RoundingMode.HALF_EVEN).doubleValue() + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Total Discount Given</B></TD>");
totals.append("<TD><B>" + totalDiscount.setScale(2,RoundingMode.HALF_EVEN).doubleValue() + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Margin On All Items</B></TD>");
totals.append("<TD><B>" + totalMargin.setScale(2,RoundingMode.HALF_EVEN).doubleValue() + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Percentage of Margin</B></TD>");
totals.append("<TD><B>" +Math.rint( totPercent) + "%</B></TD>");
totals.append("</TR>");
totals.append("</TABLE></TD></TR>");
totals.append(sbOuter);
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
return totals.toString();
}
public static Hashtable costOfGoodsInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
if (!user.getRole().trim().equalsIgnoreCase("High")) {
throw new UserException("YOU ARE NOT AUTHORIZED TO VIEW THIS REPORT");
}
String fileName = "";
if (fromDate.trim().equals(toDate.trim())) {
fileName = "COGS" + fromDate.trim() + ".html";
} else {
fileName = "COGS" + fromDate.trim() + toDate.trim() + ".html";
}
//
String targetdDB = "CH";
List<InvoiceDetailsOurPrice> missingourpricelist = UpdateOurPrice.getMissingOurPrice(targetdDB);
System.err.println("****"+missingourpricelist.size());
if(missingourpricelist!=null && missingourpricelist.size() > 0)
UpdateOurPrice.updateOurPrices(missingourpricelist, targetdDB);
//
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[8][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT InvoiceNumber, InvoiceTotal, Discount FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate = '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
} else {
sql +=
" OrderDate >= '" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate <= '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
}
sql += " Order By 1 ";
logger.error(" Before calling query...");
ResultSet rs = stmt.executeQuery(sql);
logger.error(" After calling query..." + rs.getFetchSize());
//double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totInvoicePrice = 0;
double totInvoiceSoldPrice = 0;
double totTotalSoldPrice = 0;
double totMargin = 0;
double totPercent = 0;
int totItems = 0;
double invoicePrice = 0;
double invoiceSoldPrice = 0;
double margin = 0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Cost Of Goods Report For The Date " + toDate.trim();
} else {
mainHeading =
"Cost Of Goods Report For The Dates From " + fromDate.trim() + " To " + toDate.trim();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Our Cost");
subHeadings.addElement("Sold Price");
subHeadings.addElement("Margin");
subHeadings.addElement("Remarks");
logger.error(" Before processing of invoice...");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
int invoiceNo = rs.getInt(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
StringBuilder invoicePriceStr = new StringBuilder();
StringBuilder invoiceSoldPriceStr = new StringBuilder();
StringBuilder marginStr = new StringBuilder();
StringBuilder remarks = new StringBuilder();
// logger.error(" Before calling invoce bean ... ");
InvoiceBean invoice =new InvoiceBean();
invoice.setInvoiceNumber(rs.getInt("InvoiceNumber"));
invoice.setDiscount(rs.getDouble("Discount"));
invoice.setInvoiceTotal(rs.getDouble("InvoiceTotal"));
// logger.error(" After calling invoce bean ... ");
InvoiceDetailsBean invoiceDet=InvoiceDetailsBean.getInvoiceTotalDetails(con,invoiceNo);
totItems += invoiceDet.getTotalItems();
invoicePrice = invoiceDet.getTotalOurPrice();
invoiceSoldPrice = invoiceDet.getTotalSoldPrice();
if (invoicePrice != 0) {
invoicePrice = Double.parseDouble(NumberUtils.cutFractions(invoicePrice + ""));
}
if (invoiceSoldPrice != 0) {
invoiceSoldPrice = Double.parseDouble(NumberUtils.cutFractions(invoiceSoldPrice + ""));
}
if (invoiceSoldPrice != 0) {
margin = (invoiceSoldPrice - invoicePrice - discount);
} else {
margin = 0;
}
if (remarks.toString().equals("")) {
remarks.append( " ");
}
//if needed uncomment it
//totInvoiceTotal += invoiceTotal;
totDiscount += discount;
if (invoicePrice != 0) {
totInvoicePrice += invoicePrice;
invoicePriceStr.append( invoicePrice );
} else {
invoicePriceStr.append(" ");
}
if (invoiceSoldPrice != 0) {
totInvoiceSoldPrice += invoiceSoldPrice;
invoiceSoldPriceStr.append( invoiceSoldPrice );
} else {
invoiceSoldPriceStr.append( " ");
}
if (margin != 0) {
marginStr.append( margin );
} else {
marginStr.append( " ");
}
if (invoicePriceStr.indexOf(".") == invoicePriceStr.length() - 2) {
invoicePriceStr.append( "0");
}
if (invoiceSoldPriceStr.indexOf(".") == invoiceSoldPriceStr.length() - 2) {
invoiceSoldPriceStr.append( "0");
}
if (marginStr.indexOf(".") == marginStr.length() - 2) {
marginStr.append( "0");
}
invoicePriceStr = new StringBuilder( NumberUtils.cutFractions(invoicePriceStr.toString()));
invoiceSoldPriceStr = new StringBuilder( NumberUtils.cutFractions(invoiceSoldPriceStr.toString() ));
marginStr = new StringBuilder(NumberUtils.cutFractions(marginStr.toString()));
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo + "");
totData.put("Inv. Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Our Cost", invoicePriceStr.toString());
totData.put("Sold Price", invoiceSoldPriceStr.toString());
totData.put("Margin", marginStr.toString());
totData.put("Remarks", remarks.toString());
data.addElement(totData);
}
logger.error(" After processing of invoice...");
if (toShowInvoices == null) {
throw new UserException(" No Sales For This Period ");
}
String totDiscountStr = totDiscount + "";
String totPriceStr ;
String totSoldPriceStr ;
String totMarginStr ;
String totPercentStr ;
//totTotalPrice = totInvoicePrice;
totTotalSoldPrice = totInvoiceSoldPrice;
totMargin = totTotalSoldPrice - totDiscount - totInvoicePrice;
if (totTotalSoldPrice != 0) {
totPercent = (totMargin * 100) / (totTotalSoldPrice);
} else {
totPercent = 0;
}
totPercent = Math.rint(totPercent);
totPriceStr = totInvoicePrice + "";
totSoldPriceStr = totTotalSoldPrice + "";
totMarginStr = totMargin + "";
if (totPercent != 0) {
totPercentStr = totPercent + "";
} else {
totPercentStr = " ";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totPriceStr.indexOf(".") == totPriceStr.length() - 2) {
totPriceStr += "0";
}
if (totSoldPriceStr.indexOf(".") == totSoldPriceStr.length() - 2) {
totSoldPriceStr += "0";
}
if (totMarginStr.indexOf(".") == totMarginStr.length() - 2) {
totMarginStr += "0";
}
totPriceStr = NumberUtils.cutFractions(totPriceStr);
totSoldPriceStr = NumberUtils.cutFractions(totSoldPriceStr);
totMarginStr = NumberUtils.cutFractions(totMarginStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totals[0][0] = " ";
totals[0][1] = " ";
totals[1][0] = " ";
totals[1][1] = " ";
totals[2][0] = "Total No. Of Items";
totals[2][1] = totItems + "";
totals[3][0] = "Total Price";
totals[3][1] = totPriceStr;
totals[4][0] = "Total Sold Price";
totals[4][1] = totSoldPriceStr;
totals[5][0] = "Total Discount Given";
totals[5][1] = totDiscountStr;
totals[6][0] = "Margin On All Items";
totals[6][1] = totMarginStr;
totals[7][0] = "Percentage of Margin";
totals[7][1] = totPercentStr + " %";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
logger.error(e);
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
/*
public static int updateTotals(String sqlwhere){
int resultcount=0;
try{
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
resultcount= stmt.executeUpdate("update invoice v set " +
"sumSoldPrice=(select sum(SoldPrice*Quantity)from invoicedetails where InvoiceNumber=v.InvoiceNumber ) " +
" , sumQty=(select sum(Quantity) from invoicedetails where InvoiceNumber=v.InvoiceNumber ) ," +
" sumActualPrice=(select sum(ActualPrice*Quantity) from invoicedetails where InvoiceNumber=v.InvoiceNumber )" +
" "+sqlwhere);
}catch(SQLException ex){
ex.printStackTrace();
}
return resultcount;
}
public static Hashtable costOfGoodsInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
if (!user.getRole().trim().equalsIgnoreCase("High")) {
throw new UserException("YOU ARE NOT AUTHORIZED TO VIEW THIS REPORT");
}
String fileName = "";
if (fromDate.trim().equals(toDate.trim())) {
fileName = "COGS" + fromDate.trim() + ".html";
} else {
fileName = "COGS" + fromDate.trim() + toDate.trim() + ".html";
}
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[8][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT InvoiceNumber, InvoiceTotal, Discount,sumActualPrice,sumSoldPrice,sumQty FROM Invoice ";
String sqlWhere="";
if (fromDate.trim().equals(toDate.trim())) {
sqlWhere += " where OrderDate = '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
} else {
sqlWhere +=
" where OrderDate >= '" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate <= '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
}
sql = sql+sqlWhere+ " Order By 1 ";
updateTotals(sqlWhere);
logger.error(" Before calling query...");
ResultSet rs = stmt.executeQuery(sql);
logger.error(" After calling query..." + rs.getFetchSize());
//double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totInvoicePrice = 0;
double totInvoiceSoldPrice = 0;
double totTotalPrice = 0;
double totTotalSoldPrice = 0;
double totMargin = 0;
double totPercent = 0;
int totItems = 0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Cost Of Goods Report For The Date " + toDate.trim();
} else {
mainHeading =
"Cost Of Goods Report For The Dates From " + fromDate.trim() + " To " + toDate.trim();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Our Cost");
subHeadings.addElement("Sold Price");
subHeadings.addElement("Margin");
subHeadings.addElement("Remarks");
logger.error(" Before processing of invoice...");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
int invoiceNo = rs.getInt(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
double totSoldPrice =rs.getDouble("sumSoldPrice");
double totPrice = rs.getDouble("sumActualPrice");
double sumQty = rs.getDouble("sumQty");
totItems+=sumQty;
double margin = 0;
StringBuilder invoiceTotalStr = new StringBuilder();
invoiceTotalStr.append(invoiceTotal + "");
String discountStr = discount + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr.append("0");
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
StringBuilder invoicePriceStr = new StringBuilder();
StringBuilder invoiceSoldPriceStr = new StringBuilder();
StringBuilder marginStr = new StringBuilder();
StringBuilder remarks = new StringBuilder();
// logger.error(" Before calling invoce bean ... ");
// double totPrice = invoicePrice;
//double totSoldPrice = invoiceSoldPrice;
if (totPrice != 0) {
totPrice = Double.parseDouble(NumberUtils.cutFractions(totPrice + ""));
}
if (totSoldPrice != 0) {
totSoldPrice = Double.parseDouble(NumberUtils.cutFractions(totSoldPrice + ""));
}
if (totSoldPrice != 0) {
margin = totSoldPrice - totPrice - discount;
}
if (remarks.toString().equals("")) {
remarks = new StringBuilder(" ");
}
//totInvoiceTotal += invoiceTotal;
totDiscount += discount;
if (totPrice != 0) {
totInvoicePrice += totPrice;
invoicePriceStr.append( totPrice );
} else {
invoicePriceStr.append( " " );
}
if (totSoldPrice != 0) {
totInvoiceSoldPrice += totSoldPrice;
invoiceSoldPriceStr.append( totSoldPrice );
} else {
invoiceSoldPriceStr.append( " ");
}
if (margin != 0) {
marginStr.append( margin );
} else {
marginStr.append( " ");
}
if (invoicePriceStr.indexOf(".") == invoicePriceStr.length() - 2) {
invoicePriceStr.append( "0");
}
if (invoiceSoldPriceStr.indexOf(".") == invoiceSoldPriceStr.length() - 2) {
invoiceSoldPriceStr.append("0");
}
if (marginStr.indexOf(".") == marginStr.length() - 2) {
marginStr.append( "0" );
}
// invoicePriceStr = NumberUtils.cutFractions(invoicePriceStr);
// invoiceSoldPriceStr = NumberUtils.cutFractions(invoiceSoldPriceStr);
// marginStr = NumberUtils.cutFractions(marginStr);
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo + "");
totData.put("Inv. Total", invoiceTotalStr.toString());
totData.put("Discount", discountStr);
totData.put("Our Cost", invoicePriceStr.toString());
totData.put("Sold Price", invoiceSoldPriceStr.toString());
totData.put("Margin", marginStr.toString());
totData.put("Remarks", remarks.toString());
data.addElement(totData);
}
logger.error(" After processing of invoice...");
if (toShowInvoices == null) {
throw new UserException(" No Sales For This Period ");
}
String totDiscountStr = totDiscount + "";
String totPriceStr = "";
String totSoldPriceStr = "";
String totMarginStr = "";
String totPercentStr = "";
totTotalPrice = totInvoicePrice;
totTotalSoldPrice = totInvoiceSoldPrice;
totMargin = totTotalSoldPrice - totDiscount - totTotalPrice;
if (totTotalSoldPrice != 0) {
totPercent = (totMargin * 100) / (totTotalSoldPrice);
} else {
totPercent = 0;
}
totPercent = Math.rint(totPercent);
totPriceStr = totTotalPrice + "";
totSoldPriceStr = totTotalSoldPrice + "";
totMarginStr = totMargin + "";
if (totPercent != 0) {
totPercentStr = totPercent + "";
} else {
totPercentStr = " ";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totPriceStr.indexOf(".") == totPriceStr.length() - 2) {
totPriceStr += "0";
}
if (totSoldPriceStr.indexOf(".") == totSoldPriceStr.length() - 2) {
totSoldPriceStr += "0";
}
if (totMarginStr.indexOf(".") == totMarginStr.length() - 2) {
totMarginStr += "0";
}
totPriceStr = NumberUtils.cutFractions(totPriceStr);
totSoldPriceStr = NumberUtils.cutFractions(totSoldPriceStr);
totMarginStr = NumberUtils.cutFractions(totMarginStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totals[0][0] = " ";
totals[0][1] = " ";
totals[1][0] = " ";
totals[1][1] = " ";
totals[2][0] = "Total No. Of Items";
totals[2][1] = totItems + "";
totals[3][0] = "Total Price";
totals[3][1] = totPriceStr;
totals[4][0] = "Total Sold Price";
totals[4][1] = totSoldPriceStr;
totals[5][0] = "Total Discount Given";
totals[5][1] = totDiscountStr;
totals[6][0] = "Margin On All Items";
totals[6][1] = totMarginStr;
totals[7][0] = "Percentage of Margin";
totals[7][1] = totPercentStr + " %";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
logger.error(e);
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
*/
public static Hashtable<String, String> detailedReceivable() throws UserException {
long tt = System.currentTimeMillis();
Hashtable toShowAR = null;
try {
// select customerid, sum(balance) from invoice group by customerid
// order by 2 desc
String fileName = "DR" + DateUtils.getNewUSDate().trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[12][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"select a.customerid, b.companyname, sum(a.balance), b.PaymentTerms from invoice a, customer b where a.balance!=0 and a.Status!='C' and a.Status!='W' and a.customerid=b.customerid group by a.customerid order by 3 desc";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
int totCustPending = 0;
double totBalance = 0.0;
double totalSplitBalance = 0.0;
double totalCurrent = 0.0;
double total30Days = 0.0;
double total60Days = 0.0;
double total90Days = 0.0;
double totBCAmt = 0.0;
mainHeading = "Ageing Accounts Receivable As On " + DateUtils.getNewUSDate();
subHeadings.addElement("ID");
subHeadings.addElement("Customer");
subHeadings.addElement("Terms");
subHeadings.addElement("Total");
subHeadings.addElement("Current");
subHeadings.addElement("30 Days");
subHeadings.addElement("60 Days");
subHeadings.addElement("90 Days");
subHeadings.addElement("BC Chks");
Statement stmtXX = con.createStatement();
String sqlXX =
"Select CustomerId, Sum(Balance) From BouncedChecks Where Balance!=0 Group By CustomerId Order By 1 ";
Hashtable<String, String> bcChecks = null;
ResultSet rsXX = stmtXX.executeQuery(sqlXX);
while (rsXX.next()) {
if (bcChecks == null) {
bcChecks = new Hashtable<String, String>();
}
String cstId = rsXX.getString(1);
String bcAmt = rsXX.getString(2);
bcChecks.put(cstId, bcAmt);
}
while (rs.next()) {
if (toShowAR == null) {
toShowAR = new Hashtable();
}
String custId = rs.getString(1);
// logger.error("Detail:" + custId);
String companyName = rs.getString(2);
double pendingAmount = rs.getDouble(3);
String terms = rs.getString(4);
String bcAmtStr = "";
if (terms == null) {
terms = " ";
} else if (terms.trim().equals("")) {
terms = " ";
} else if (terms.trim().equalsIgnoreCase("C")) {
terms = "Cod";
} else if (terms.trim().equalsIgnoreCase("O")) {
terms = "Cash";
} else if (terms.trim().equalsIgnoreCase("W")) {
terms = "Wkly";
} else if (terms.trim().equalsIgnoreCase("B")) {
terms = "Bi-Wk";
} else if (terms.trim().equalsIgnoreCase("M")) {
terms = "Mthly";
}
/*
* Vector v = BouncedChecksBean.getAllBouncedChecks(custId); if (v != null) { Enumeration
* ennumX = v.elements(); while (ennumX.hasMoreElements()) { BouncedChecksBean bcBean =
* (BouncedChecksBean) ennumX.nextElement(); pendingAmount += bcBean.getBouncedAmount(); } }
*/
if (bcChecks != null && bcChecks.get(custId) != null) {
bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
pendingAmount += Double.parseDouble(bcAmtStr);
}
if (pendingAmount == 0) {
continue;
} else {
totBalance += pendingAmount;
totCustPending++;
}
double curr = 0.0;
double x30days = 0.0;
double x60days = 0.0;
double x90days = 0.0;
String sql1 =
"select InvoiceNumber, OrderDate, Balance from invoice where balance!=0 and Status!='C' and Status!='W' and customerid='"
+ custId + "' order by OrderDate ";
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery(sql1);
while (rs1.next()) {
String orderDate = DateUtils.convertMySQLToUSFormat(rs1.getString(2));
double noOfDays = 0;
try {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date dd = sdf.parse(orderDate);
long timeDiff = System.currentTimeMillis() - dd.getTime();
noOfDays = Math.rint(timeDiff / 86400000);
// java.util.Date ddX = new java.util.Date(dd.getTime()
// + (1000 * 60 * 60 * 24 * (long)terms));
} catch (Exception e) {
logger.error(e.getMessage());
}
double bal = rs1.getDouble(3);
// logger.error(orderDate + "--" + noOfDays + "--" +
// bal);
if (noOfDays <= 30) {
curr += bal;
} else if (noOfDays <= 60) {
x30days += bal;
} else if (noOfDays <= 90) {
x60days += bal;
} else {
x90days += bal;
}
}
if (rs1 != null) {
rs1.close();
}
if (stmt1 != null) {
stmt1.close();
}
totalCurrent += curr;
total30Days += x30days;
total60Days += x60days;
total90Days += x90days;
if (!bcAmtStr.trim().equals("")) {
totBCAmt += Double.parseDouble(bcAmtStr);
} else {
bcAmtStr = " ";
}
String pendingAmountStr = pendingAmount + "";
String currStr = "";
String x30daysStr = "";
String x60daysStr = "";
String x90daysStr = "";
if (curr == 0) {
currStr = " ";
} else {
currStr = curr + "";
if (currStr.indexOf(".") == currStr.length() - 2) {
currStr += "0";
}
currStr = NumberUtils.cutFractions(currStr);
}
if (x30days == 0) {
x30daysStr = " ";
} else {
x30daysStr = x30days + "";
if (x30daysStr.indexOf(".") == x30daysStr.length() - 2) {
x30daysStr += "0";
}
x30daysStr = NumberUtils.cutFractions(x30daysStr);
}
if (x60days == 0) {
x60daysStr = " ";
} else {
x60daysStr = x60days + "";
if (x60daysStr.indexOf(".") == x60daysStr.length() - 2) {
x60daysStr += "0";
}
x60daysStr = NumberUtils.cutFractions(x60daysStr);
}
if (x90days == 0) {
x90daysStr = " ";
} else {
x90daysStr = x90days + "";
if (x90daysStr.indexOf(".") == x90daysStr.length() - 2) {
x90daysStr += "0";
}
x90daysStr = NumberUtils.cutFractions(x90daysStr);
}
if (pendingAmountStr.indexOf(".") == pendingAmountStr.length() - 2) {
pendingAmountStr += "0";
}
pendingAmountStr = NumberUtils.cutFractions(pendingAmountStr);
Hashtable totData = new Hashtable();
totData.put("ID", custId);
totData.put("Customer", companyName);
totData.put("Terms", terms);
totData.put("Total", pendingAmountStr);
totData.put("Current", currStr);
totData.put("30 Days", x30daysStr);
totData.put("60 Days", x60daysStr);
totData.put("90 Days", x90daysStr);
totData.put("BC Chks", bcAmtStr);
data.addElement(totData);
}
if (bcChecks != null && bcChecks.size() > 0) {
// logger.error("BC Checks Left: " + bcChecks.size());
Enumeration<String> ennum = bcChecks.keys();
while (ennum.hasMoreElements()) {
String cstId = ennum.nextElement();
double amt = Double.parseDouble(bcChecks.get(cstId));
totBCAmt += amt;
totBalance += amt;
Hashtable totData = new Hashtable();
totData.put("ID", cstId);
totData.put("Customer", CustomerBean.getCompanyName(cstId));
totData.put("Terms", " ");
totData.put("Total", amt + "");
totData.put("Current", " ");
totData.put("30 Days", " ");
totData.put("60 Days", " ");
totData.put("90 Days", " ");
totData.put("BC Chks", amt + "");
data.addElement(totData);
totCustPending++;
}
}
if (toShowAR == null) {
throw new UserException(" No Customers have Pending Balances ");
}
totalSplitBalance = totalCurrent + total30Days + total60Days + total90Days + totBCAmt;
String totBalanceStr = totBalance + "";
String totalSplitBalanceStr = totalSplitBalance + "";
String totalCurrentStr = totalCurrent + "";
String total30DaysStr = total30Days + "";
String total60DaysStr = total60Days + "";
String total90DaysStr = total90Days + "";
String totBCAmtStr = totBCAmt + "";
String currPercStr =
Math.rint(100 - ((totalSplitBalance - totalCurrent) * 100 / totalSplitBalance)) + "";
String x30DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total30Days) * 100 / totalSplitBalance)) + "";
String x60DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total60Days) * 100 / totalSplitBalance)) + "";
String x90DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total90Days) * 100 / totalSplitBalance)) + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
if (totalSplitBalanceStr.indexOf(".") == totalSplitBalanceStr.length() - 2) {
totalSplitBalanceStr += "0";
}
if (totalCurrentStr.indexOf(".") == totalCurrentStr.length() - 2) {
totalCurrentStr += "0";
}
if (total30DaysStr.indexOf(".") == total30DaysStr.length() - 2) {
total30DaysStr += "0";
}
if (total60DaysStr.indexOf(".") == total60DaysStr.length() - 2) {
total60DaysStr += "0";
}
if (total90DaysStr.indexOf(".") == total90DaysStr.length() - 2) {
total90DaysStr += "0";
}
if (totBCAmtStr.indexOf(".") == totBCAmtStr.length() - 2) {
totBCAmtStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
totalSplitBalanceStr = NumberUtils.cutFractions(totalSplitBalanceStr);
totalCurrentStr = NumberUtils.cutFractions(totalCurrentStr);
total30DaysStr = NumberUtils.cutFractions(total30DaysStr);
total60DaysStr = NumberUtils.cutFractions(total60DaysStr);
total90DaysStr = NumberUtils.cutFractions(total90DaysStr);
totBCAmtStr = NumberUtils.cutFractions(totBCAmtStr);
totals[0][0] = "Total No. Of Customers Have Payments ";
totals[0][1] = totCustPending + "";
totals[1][0] = "Total Payments Receivable ";
totals[1][1] = totBalanceStr;
totals[2][0] = "Total Split Payments Receivable ";
totals[2][1] = totalSplitBalanceStr;
totals[3][0] = "Current Payments ";
totals[3][1] = totalCurrentStr;
totals[4][0] = "% of Current ";
totals[4][1] = currPercStr;
totals[5][0] = "Over 30 Days Payments ";
totals[5][1] = total30DaysStr;
totals[6][0] = "% of 30 Days ";
totals[6][1] = x30DaysPercStr;
totals[7][0] = "Over 60 Days Payments ";
totals[7][1] = total60DaysStr;
totals[8][0] = "% of 60 Days ";
totals[8][1] = x60DaysPercStr;
totals[9][0] = "Over 90 Days Payments ";
totals[9][1] = total90DaysStr;
totals[10][0] = "% of 90 Days ";
totals[10][1] = x90DaysPercStr;
totals[11][0] = "Total Bounced Checks Amount ";
totals[11][1] = totBCAmtStr;
toShowAR.put("FileName", fileName);
toShowAR.put("BackScreen", "AcctMenu");
toShowAR.put("MainHeading", mainHeading);
toShowAR.put("SubHeadings", subHeadings);
toShowAR.put("Data", data);
toShowAR.put("Totals", totals);
createReport(toShowAR);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
tt = System.currentTimeMillis() - tt;
double xx = tt / (1000 * 60);
logger.error("AGEING RECEIVABLES TIME - OLDER VERSION:::" + xx + " Min");
return toShowAR;
}
public static Hashtable<String, String> detailedReceivableNew() throws UserException {
long tt = System.currentTimeMillis();
Hashtable toShowAR = null;
try {
// select customerid, sum(balance) from invoice group by customerid
// order by 2 desc
String fileName = "DR" + DateUtils.getNewUSDate().trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[12][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtXX = con.createStatement();
String sqlXX =
"Select CustomerId, Sum(Balance) From BouncedChecks Where Balance!=0 Group By CustomerId Order By 1 ";
Hashtable<String, String> bcChecks = null;
ResultSet rsXX = stmtXX.executeQuery(sqlXX);
int noOfBCChecks = 0;
while (rsXX.next()) {
if (bcChecks == null) {
bcChecks = new Hashtable<String, String>();
}
String cstId = rsXX.getString(1);
String bcAmt = rsXX.getString(2);
bcChecks.put(cstId, bcAmt);
noOfBCChecks++;
}
Statement stmt = con.createStatement();
String sql =
"select count(distinct customerid) from invoice where balance!=0 and Status!='C' and Status!='W' ";
ResultSet rs = stmt.executeQuery(sql);
int noOfBalances = 0;
if (rs.next()) {
noOfBalances = rs.getInt(1);
}
String[][] list = new String[noOfBalances + noOfBCChecks][9];
double totBalance = 0.0;
double totalSplitBalance = 0.0;
double totalCurrent = 0.0;
double total30Days = 0.0;
double total60Days = 0.0;
double total90Days = 0.0;
double totBCAmt = 0.0;
mainHeading = "Ageing Accounts Receivable As On " + DateUtils.getNewUSDate();
subHeadings.addElement("ID");
subHeadings.addElement("Customer");
subHeadings.addElement("Terms");
subHeadings.addElement("Total");
subHeadings.addElement("Current");
subHeadings.addElement("30 Days");
subHeadings.addElement("60 Days");
subHeadings.addElement("90 Days");
subHeadings.addElement("BC Chks");
String sql1 =
"select a.CustomerId, b.CompanyName, b.PaymentTerms, a.OrderDate, a.Balance from invoice a, customer b where a.balance!=0 and a.Status!='C' and a.Status!='W' and a.customerid=b.customerId order by 1 ";
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery(sql1);
int cntBalances = 0;
double totalBalance = 0.0;
double curr = 0.0;
double x30days = 0.0;
double x60days = 0.0;
double x90days = 0.0;
String currCustId = "";
while (rs1.next()) {
String custId = rs1.getString(1);
String companyName = rs1.getString(2);
String terms = rs1.getString(3);
String orderDate = DateUtils.convertMySQLToUSFormat(rs1.getString(4));
// String orderDate = "2013-09-30";
double pendingAmount = rs1.getDouble(5);
double noOfDays = 0;
if (currCustId.trim().equals("")) {
currCustId = custId;
String bcAmtStr = "";
if (bcChecks != null && bcChecks.get(custId) != null) {
bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
double amt = Double.parseDouble(bcAmtStr);
totalBalance += amt;
totBCAmt += amt;
totBalance += amt;
}
list[cntBalances][0] = custId;
list[cntBalances][1] = companyName;
list[cntBalances][2] = terms;
list[cntBalances][8] = bcAmtStr;
} else if (currCustId.trim().equals(custId)) {
if (list[cntBalances][3] == null || list[cntBalances][3].trim().equals("")) {
totalBalance = 0.0;
} else {
totalBalance = Double.parseDouble(list[cntBalances][3]);
}
if (list[cntBalances][4] == null || list[cntBalances][4].trim().equals("")) {
curr = 0.0;
} else {
curr = Double.parseDouble(list[cntBalances][4]);
}
if (list[cntBalances][5] == null || list[cntBalances][5].trim().equals("")) {
x30days = 0.0;
} else {
x30days = Double.parseDouble(list[cntBalances][5]);
}
if (list[cntBalances][6] == null || list[cntBalances][6].trim().equals("")) {
x60days = 0.0;
} else {
x60days = Double.parseDouble(list[cntBalances][6]);
}
if (list[cntBalances][7] == null || list[cntBalances][7].trim().equals("")) {
x90days = 0.0;
} else {
x90days = Double.parseDouble(list[cntBalances][7]);
}
} else if (!currCustId.trim().equals(custId)) {
currCustId = custId;
cntBalances++;
totalBalance = 0;
curr = 0;
x30days = 0;
x60days = 0;
x90days = 0;
String bcAmtStr = "";
if (bcChecks != null && bcChecks.get(custId) != null) {
bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
double amt = Double.parseDouble(bcAmtStr);
totalBalance = amt;
totBCAmt += amt;
totBalance += amt;
}
list[cntBalances][0] = custId;
list[cntBalances][1] = companyName;
list[cntBalances][2] = terms;
list[cntBalances][8] = bcAmtStr;
}
try {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date dd = sdf.parse(orderDate);
long timeDiff = System.currentTimeMillis() - dd.getTime();
noOfDays = Math.rint(timeDiff / 86400000);
// java.util.Date ddX = new java.util.Date(dd.getTime() +
// (1000 * 60 * 60 * 24 * (long)terms));
} catch (Exception e) {
logger.error(e.getMessage());
}
double bal = pendingAmount;
// logger.error(orderDate + "--" + noOfDays + "--" + bal);
if (noOfDays <= 30) {
curr += bal;
totalCurrent += bal;
} else if (noOfDays <= 60) {
x30days += bal;
total30Days += bal;
} else if (noOfDays <= 90) {
x60days += bal;
total60Days += bal;
} else {
x90days += bal;
total90Days += bal;
}
totalBalance += bal;
totBalance += bal;
list[cntBalances][3] = totalBalance + "";
list[cntBalances][4] = curr + "";
list[cntBalances][5] = x30days + "";
list[cntBalances][6] = x60days + "";
list[cntBalances][7] = x90days + "";
}
if (bcChecks != null && bcChecks.size() > 0) {
// logger.error("BC Checks Left: " + bcChecks.size());
Enumeration<String> ennum = bcChecks.keys();
while (ennum.hasMoreElements()) {
String cstId = ennum.nextElement();
double amt = Double.parseDouble(bcChecks.get(cstId));
totBCAmt += amt;
totBalance += amt;
list[cntBalances][0] = cstId;
list[cntBalances][1] = CustomerBean.getCompanyName(cstId);
list[cntBalances][2] = " ";
list[cntBalances][3] = amt + "";
list[cntBalances][4] = "0";
list[cntBalances][5] = "0";
list[cntBalances][6] = "0";
list[cntBalances][7] = "0";
list[cntBalances][8] = amt + "";
cntBalances++;
}
}
int outCnt = 0;
int inCnt = 0;
for (outCnt = cntBalances - 1; outCnt > 1; outCnt--) {
for (inCnt = 0; inCnt < outCnt; inCnt++) {
if (Double.parseDouble(list[inCnt][3]) < Double.parseDouble(list[inCnt + 1][3])) {
String t0 = list[inCnt][0];
String t1 = list[inCnt][1];
String t2 = list[inCnt][2];
String t3 = list[inCnt][3];
String t4 = list[inCnt][4];
String t5 = list[inCnt][5];
String t6 = list[inCnt][6];
String t7 = list[inCnt][7];
String t8 = list[inCnt][8];
list[inCnt][0] = list[inCnt + 1][0];
list[inCnt][1] = list[inCnt + 1][1];
list[inCnt][2] = list[inCnt + 1][2];
list[inCnt][3] = list[inCnt + 1][3];
list[inCnt][4] = list[inCnt + 1][4];
list[inCnt][5] = list[inCnt + 1][5];
list[inCnt][6] = list[inCnt + 1][6];
list[inCnt][7] = list[inCnt + 1][7];
list[inCnt][8] = list[inCnt + 1][8];
list[inCnt + 1][0] = t0;
list[inCnt + 1][1] = t1;
list[inCnt + 1][2] = t2;
list[inCnt + 1][3] = t3;
list[inCnt + 1][4] = t4;
list[inCnt + 1][5] = t5;
list[inCnt + 1][6] = t6;
list[inCnt + 1][7] = t7;
list[inCnt + 1][8] = t8;
// swap(in, in+1);
// long temp = a[one];
// a[one] = a[two];
// a[two] = temp;
}
}
}
for (int i = 0; i < cntBalances; i++) {
if (toShowAR == null) {
toShowAR = new Hashtable();
}
String custId = list[i][0];
// logger.error("Detail:" + custId);
String companyName = list[i][1];
String terms = list[i][2];
double pendingAmount = Double.parseDouble(list[i][3]);
curr = Double.parseDouble(list[i][4]);
x30days = Double.parseDouble(list[i][5]);
x60days = Double.parseDouble(list[i][6]);
x90days = Double.parseDouble(list[i][7]);
String bcAmtStr = list[i][8];
if (terms == null) {
terms = " ";
} else if (terms.trim().equals("")) {
terms = " ";
} else if (terms.trim().equalsIgnoreCase("C")) {
terms = "Cod";
} else if (terms.trim().equalsIgnoreCase("O")) {
terms = "Cash";
} else if (terms.trim().equalsIgnoreCase("W")) {
terms = "Wkly";
} else if (terms.trim().equalsIgnoreCase("B")) {
terms = "Bi-Wk";
} else if (terms.trim().equalsIgnoreCase("M")) {
terms = "Mthly";
}
String pendingAmountStr = pendingAmount + "";
String currStr = "";
String x30daysStr = "";
String x60daysStr = "";
String x90daysStr = "";
if (curr == 0) {
currStr = " ";
} else {
currStr = curr + "";
if (currStr.indexOf(".") == currStr.length() - 2) {
currStr += "0";
}
currStr = NumberUtils.cutFractions(currStr);
}
if (x30days == 0) {
x30daysStr = " ";
} else {
x30daysStr = x30days + "";
if (x30daysStr.indexOf(".") == x30daysStr.length() - 2) {
x30daysStr += "0";
}
x30daysStr = NumberUtils.cutFractions(x30daysStr);
}
if (x60days == 0) {
x60daysStr = " ";
} else {
x60daysStr = x60days + "";
if (x60daysStr.indexOf(".") == x60daysStr.length() - 2) {
x60daysStr += "0";
}
x60daysStr = NumberUtils.cutFractions(x60daysStr);
}
if (x90days == 0) {
x90daysStr = " ";
} else {
x90daysStr = x90days + "";
if (x90daysStr.indexOf(".") == x90daysStr.length() - 2) {
x90daysStr += "0";
}
x90daysStr = NumberUtils.cutFractions(x90daysStr);
}
if (pendingAmountStr.indexOf(".") == pendingAmountStr.length() - 2) {
pendingAmountStr += "0";
}
pendingAmountStr = NumberUtils.cutFractions(pendingAmountStr);
if (bcAmtStr.trim().equals("")) {
bcAmtStr = " ";
}
Hashtable totData = new Hashtable();
totData.put("ID", custId);
totData.put("Customer", companyName);
totData.put("Terms", terms);
totData.put("Total", pendingAmountStr);
totData.put("Current", currStr);
totData.put("30 Days", x30daysStr);
totData.put("60 Days", x60daysStr);
totData.put("90 Days", x90daysStr);
totData.put("BC Chks", bcAmtStr);
data.addElement(totData);
}
// ---------------------------------------------------------------
// ---------------------------------------------------------------
if (toShowAR == null) {
throw new UserException(" No Customers have Pending Balances ");
}
totalSplitBalance = totalCurrent + total30Days + total60Days + total90Days + totBCAmt;
String totBalanceStr = totBalance + "";
String totalSplitBalanceStr = totalSplitBalance + "";
String totalCurrentStr = totalCurrent + "";
String total30DaysStr = total30Days + "";
String total60DaysStr = total60Days + "";
String total90DaysStr = total90Days + "";
String totBCAmtStr = totBCAmt + "";
String currPercStr =
Math.rint(100 - ((totalSplitBalance - totalCurrent) * 100 / totalSplitBalance)) + "";
String x30DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total30Days) * 100 / totalSplitBalance)) + "";
String x60DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total60Days) * 100 / totalSplitBalance)) + "";
String x90DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total90Days) * 100 / totalSplitBalance)) + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
if (totalSplitBalanceStr.indexOf(".") == totalSplitBalanceStr.length() - 2) {
totalSplitBalanceStr += "0";
}
if (totalCurrentStr.indexOf(".") == totalCurrentStr.length() - 2) {
totalCurrentStr += "0";
}
if (total30DaysStr.indexOf(".") == total30DaysStr.length() - 2) {
total30DaysStr += "0";
}
if (total60DaysStr.indexOf(".") == total60DaysStr.length() - 2) {
total60DaysStr += "0";
}
if (total90DaysStr.indexOf(".") == total90DaysStr.length() - 2) {
total90DaysStr += "0";
}
if (totBCAmtStr.indexOf(".") == totBCAmtStr.length() - 2) {
totBCAmtStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
totalSplitBalanceStr = NumberUtils.cutFractions(totalSplitBalanceStr);
totalCurrentStr = NumberUtils.cutFractions(totalCurrentStr);
total30DaysStr = NumberUtils.cutFractions(total30DaysStr);
total60DaysStr = NumberUtils.cutFractions(total60DaysStr);
total90DaysStr = NumberUtils.cutFractions(total90DaysStr);
totBCAmtStr = NumberUtils.cutFractions(totBCAmtStr);
totals[0][0] = "Total No. Of Customers Have Payments ";
totals[0][1] = cntBalances + "";
totals[1][0] = "Total Payments Receivable ";
totals[1][1] = totBalanceStr;
totals[2][0] = "Total Split Payments Receivable ";
totals[2][1] = totalSplitBalanceStr;
totals[3][0] = "Current Payments ";
totals[3][1] = totalCurrentStr;
totals[4][0] = "% of Current ";
totals[4][1] = currPercStr;
totals[5][0] = "Over 30 Days Payments ";
totals[5][1] = total30DaysStr;
totals[6][0] = "% of 30 Days ";
totals[6][1] = x30DaysPercStr;
totals[7][0] = "Over 60 Days Payments ";
totals[7][1] = total60DaysStr;
totals[8][0] = "% of 60 Days ";
totals[8][1] = x60DaysPercStr;
totals[9][0] = "Over 90 Days Payments ";
totals[9][1] = total90DaysStr;
totals[10][0] = "% of 90 Days ";
totals[10][1] = x90DaysPercStr;
totals[11][0] = "Total Bounced Checks Amount ";
totals[11][1] = totBCAmtStr;
toShowAR.put("FileName", fileName);
toShowAR.put("BackScreen", "AcctMenu");
toShowAR.put("MainHeading", mainHeading);
toShowAR.put("SubHeadings", subHeadings);
toShowAR.put("Data", data);
toShowAR.put("Totals", totals);
createReport(toShowAR);
rs.close();
stmt.close();
rs1.close();
stmt1.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
tt = System.currentTimeMillis() - tt;
double xx = tt / (1000 * 60);
logger.error("AGEING RECEIVABLES TIME - NEW VERSION:::" + xx + " Min");
return toShowAR;
}
public static Hashtable<String, String> accountsReceivable() throws UserException {
Hashtable toShowAR = null;
try {
// select customerid, sum(balance) from invoice group by customerid
// order by 2 desc
String fileName = "AR" + DateUtils.getNewUSDate().trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"select a.customerid, b.companyname, sum(a.balance) from invoice a, customer b where a.balance!=0 and a.Status!='C' and a.Status!='W' and a.customerid=b.customerid group by a.customerid order by 3 desc";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
int totCustPending = 0;
double totBalance = 0.0;
mainHeading = "Accounts Receivable As On " + DateUtils.getNewUSDate();
subHeadings.addElement("Customer Id");
subHeadings.addElement("Company Name");
subHeadings.addElement("Receivable Amount");
Statement stmtXX = con.createStatement();
String sqlXX =
"Select CustomerId, Sum(Balance) From BouncedChecks Where Balance!=0 Group By CustomerId Order By 1 ";
Hashtable<String, String> bcChecks = null;
ResultSet rsXX = stmtXX.executeQuery(sqlXX);
while (rsXX.next()) {
if (bcChecks == null) {
bcChecks = new Hashtable<String, String>();
}
String cstId = rsXX.getString(1);
String bcAmt = rsXX.getString(2);
bcChecks.put(cstId, bcAmt);
}
while (rs.next()) {
if (toShowAR == null) {
toShowAR = new Hashtable();
}
String custId = rs.getString(1);
String companyName = rs.getString(2);
double pendingAmount = rs.getDouble(3);
/*
* Vector v = BouncedChecksBean.getAllBouncedChecks(custId); if (v != null) { Enumeration
* ennumX = v.elements(); while (ennumX.hasMoreElements()) { BouncedChecksBean bcBean =
* (BouncedChecksBean) ennumX.nextElement(); pendingAmount += bcBean.getBalance(); } }
*/
if (bcChecks != null && bcChecks.get(custId) != null) {
String bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
pendingAmount += Double.parseDouble(bcAmtStr);
}
if (pendingAmount == 0) {
continue;
} else if (pendingAmount < 0) {
continue;
} else if (pendingAmount > 0) {
totBalance += pendingAmount;
totCustPending++;
}
String pendingAmountStr = pendingAmount + "";
if (pendingAmountStr.indexOf(".") == pendingAmountStr.length() - 2) {
pendingAmountStr += "0";
}
pendingAmountStr = NumberUtils.cutFractions(pendingAmountStr);
Hashtable totData = new Hashtable();
totData.put("Customer Id", custId);
totData.put("Company Name", companyName);
totData.put("Receivable Amount", pendingAmountStr);
data.addElement(totData);
}
if (bcChecks != null && bcChecks.size() > 0) {
// logger.error("BC Checks Left: " + bcChecks.size());
Enumeration<String> ennum = bcChecks.keys();
while (ennum.hasMoreElements()) {
String cstId = ennum.nextElement();
double amt = Double.parseDouble(bcChecks.get(cstId));
if (amt > 0) {
totBalance += amt;
} else {
continue;
}
Hashtable totData = new Hashtable();
totData.put("Customer Id", cstId);
totData.put("Company Name", CustomerBean.getCompanyName(cstId));
totData.put("Receivable Amount", amt + "");
data.addElement(totData);
totCustPending++;
}
}
if (toShowAR == null) {
throw new UserException(" No Customers have Pending Balances ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
totals[0][0] = "Total No. Of Customers Have Payments ";
totals[0][1] = totCustPending + "";
totals[1][0] = "Total Payments Receivable ";
totals[1][1] = totBalanceStr;
toShowAR.put("FileName", fileName);
toShowAR.put("BackScreen", "AcctMenu");
toShowAR.put("MainHeading", mainHeading);
toShowAR.put("SubHeadings", subHeadings);
toShowAR.put("Data", data);
toShowAR.put("Totals", totals);
createReport(toShowAR);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowAR;
}
public static Hashtable<String, String> accountsPayable() throws UserException {
Hashtable toShowAP = null;
try {
// select customerid, sum(balance) from invoice group by customerid
// order by 2 desc
String fileName = "AP" + DateUtils.getNewUSDate().trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"select a.customerid, b.companyname, sum(a.balance) from invoice a, customer b where a.balance!=0 and a.Status!='C' and a.Status!='W' and a.customerid=b.customerid group by a.customerid order by 3 desc";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
int totCreditCustPending = 0;
double totCreditBalance = 0.0;
mainHeading = "Accounts Payable As On " + DateUtils.getNewUSDate();
subHeadings.addElement("Customer Id");
subHeadings.addElement("Company Name");
subHeadings.addElement("Amount Payable");
Statement stmtXX = con.createStatement();
String sqlXX =
"Select CustomerId, Sum(Balance) From BouncedChecks Where Balance!=0 Group By CustomerId Order By 1 ";
Hashtable<String, String> bcChecks = null;
ResultSet rsXX = stmtXX.executeQuery(sqlXX);
while (rsXX.next()) {
if (bcChecks == null) {
bcChecks = new Hashtable<String, String>();
}
String cstId = rsXX.getString(1);
String bcAmt = rsXX.getString(2);
bcChecks.put(cstId, bcAmt);
}
while (rs.next()) {
if (toShowAP == null) {
toShowAP = new Hashtable();
}
String custId = rs.getString(1);
String companyName = rs.getString(2);
double pendingAmount = rs.getDouble(3);
/*
* Vector v = BouncedChecksBean.getAllBouncedChecks(custId); if (v != null) { Enumeration
* enumX = v.elements(); while (enumX.hasMoreElements()) { BouncedChecksBean bcBean =
* (BouncedChecksBean) enumX.nextElement(); pendingAmount += bcBean.getBalance(); } }
*/
if (bcChecks != null && bcChecks.get(custId) != null) {
String bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
pendingAmount += Double.parseDouble(bcAmtStr);
}
if (pendingAmount == 0) {
continue;
} else if (pendingAmount > 0) {
continue;
} else if (pendingAmount < 0) {
totCreditBalance += pendingAmount;
totCreditCustPending++;
}
String pendingAmountStr = pendingAmount + "";
if (pendingAmountStr.indexOf(".") == pendingAmountStr.length() - 2) {
pendingAmountStr += "0";
}
pendingAmountStr = NumberUtils.cutFractions(pendingAmountStr);
Hashtable totData = new Hashtable();
totData.put("Customer Id", custId);
totData.put("Company Name", companyName);
totData.put("Amount Payable", pendingAmountStr);
data.addElement(totData);
}
if (bcChecks != null && bcChecks.size() > 0) {
// logger.error("BC Checks Left: " + bcChecks.size());
Enumeration<String> ennum = bcChecks.keys();
while (ennum.hasMoreElements()) {
String cstId = ennum.nextElement();
double amt = Double.parseDouble(bcChecks.get(cstId));
if (amt < 0) {
totCreditBalance += amt;
} else {
continue;
}
Hashtable totData = new Hashtable();
totData.put("Customer Id", cstId);
totData.put("Company Name", CustomerBean.getCompanyName(cstId));
totData.put("Receivable Amount", amt + "");
data.addElement(totData);
totCreditCustPending++;
}
}
if (toShowAP == null) {
throw new UserException(" No Customers have Pending Balances ");
}
String totCreditBalanceStr = totCreditBalance + "";
if (totCreditBalanceStr.indexOf(".") == totCreditBalanceStr.length() - 2) {
totCreditBalanceStr += "0";
}
totCreditBalanceStr = NumberUtils.cutFractions(totCreditBalanceStr);
totals[0][0] = "Total No. Of Customers Have Credit ";
totals[0][1] = totCreditCustPending + "";
totals[1][0] = "Total Credits Payable ";
totals[1][1] = totCreditBalanceStr;
toShowAP.put("FileName", fileName);
toShowAP.put("BackScreen", "AcctMenu");
toShowAP.put("MainHeading", mainHeading);
toShowAP.put("SubHeadings", subHeadings);
toShowAP.put("Data", data);
toShowAP.put("Totals", totals);
createReport(toShowAP);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowAP;
}
public static Hashtable<String, String> showPendingInvoices() throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowPendInv" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance FROM Invoice a, Customer b WHERE ";
sql +=
" a.CustomerId=b.CustomerId and a.Balance!=0 and a.Status!='C' and a.Status!='W' Order by 1 ";
ResultSet rs = stmt.executeQuery(sql);
double totBalance = 0.0;
int totCnt = 0;
mainHeading = "PENDING INVOICES AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
String balanceStr = balance + "";
if (balanceStr.indexOf(".") == balanceStr.length() - 2) {
balanceStr += "0";
}
totBalance += balance;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balanceStr);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
totals[0][0] = "Total Balance";
totals[0][1] = totBalanceStr;
totals[1][0] = "Total No Of Invoices";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "AcctMenu");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable codPendingInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowCODPendInv" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance FROM Invoice a, Customer b WHERE ";
sql +=
" a.CustomerId=b.CustomerId and a.Balance!=0 and a.Status!='C' and a.Status!='W' and (b.PaymentTerms='C' or b.PaymentTerms='O') ";
if (toDate.trim().equals("")) {
sql +=
" and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(DateUtils.getNewUSDate()) + "'";
} else if (fromDate.trim().equals(toDate.trim())) {
sql += " and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
} else {
sql +=
" and a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate)
+ "' and a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
}
sql += " Order By 1 ";
ResultSet rs = stmt.executeQuery(sql);
double totBalance = 0.0;
int totCnt = 0;
mainHeading = "PENDING COD & CASH INVOICES AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
String balanceStr = balance + "";
if (balanceStr.indexOf(".") == balanceStr.length() - 2) {
balanceStr += "0";
}
totBalance += balance;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balanceStr);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
if (user.getRole().trim().equalsIgnoreCase("Acct")) {
totBalanceStr = "0.0";
}
totals[0][0] = "Total Balance";
totals[0][1] = totBalanceStr;
totals[1][0] = "Total No Of Invoices";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable otherPendingInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowOtherPendInv" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance FROM Invoice a, Customer b WHERE ";
sql +=
" a.CustomerId=b.CustomerId and a.Balance!=0 and a.Status!='C' and a.Status!='W' and b.PaymentTerms!='C' and b.PaymentTerms!='O' ";
if (toDate.trim().equals("")) {
sql +=
" and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(DateUtils.getNewUSDate()) + "'";
} else if (fromDate.trim().equals(toDate.trim())) {
sql += " and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
} else {
sql +=
" and a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate)
+ "' and a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
}
sql += " Order By 1 ";
ResultSet rs = stmt.executeQuery(sql);
double totBalance = 0.0;
int totCnt = 0;
mainHeading = "PENDING ACCOUNTS INVOICES AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
String balanceStr = balance + "";
if (balanceStr.indexOf(".") == balanceStr.length() - 2) {
balanceStr += "0";
}
totBalance += balance;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balanceStr);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
if (user.getRole().trim().equalsIgnoreCase("Acct")) {
totBalanceStr = "0.0";
}
totals[0][0] = "Total Balance";
totals[0][1] = totBalanceStr;
totals[1][0] = "Total No Of Invoices";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable allPendingInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowAllPendInv" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance, b.PaymentTerms FROM Invoice a, Customer b WHERE ";
sql += " a.CustomerId=b.CustomerId and a.Balance!=0 and a.Status!='C' and a.Status!='W' ";
if (toDate.trim().equals("")) {
sql +=
" and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(DateUtils.getNewUSDate()) + "'";
} else if (fromDate.trim().equals(toDate.trim())) {
sql += " and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
} else {
sql +=
" and a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate)
+ "' and a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
}
sql += " Order By 1 ";
ResultSet rs = stmt.executeQuery(sql);
double totBalance = 0.0;
int totCnt = 0;
mainHeading = "PENDING INVOICES AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
subHeadings.addElement("Terms");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
String terms = rs.getString(7);
String balanceStr = balance + "";
if (balanceStr.indexOf(".") == balanceStr.length() - 2) {
balanceStr += "0";
}
totBalance += balance;
if (terms == null || terms.trim().equals("")) {
terms = " ";
} else if (terms.trim().equalsIgnoreCase("C")) {
terms = "COD";
} else if (terms.trim().equalsIgnoreCase("O")) {
terms = "CASH";
} else if (terms.trim().equalsIgnoreCase("B")) {
terms = "BI-WK";
} else if (terms.trim().equalsIgnoreCase("W")) {
terms = "WKLY";
} else if (terms.trim().equalsIgnoreCase("M")) {
terms = "MTHLY";
}
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balanceStr);
totData.put("Terms", terms);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
if (user.getRole().trim().equalsIgnoreCase("Acct")) {
totBalanceStr = "0.0";
}
totals[0][0] = "Total Balance";
totals[0][1] = totBalanceStr;
totals[1][0] = "Total No Of Invoices";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable showDeposits(String fromDate, String toDate) throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowDepo" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT AppliedDate, sum(AppliedAmount) FROM AppliedAmounts WHERE ";
if (toDate.trim().equals("")) {
sql += " AppliedDate='" + DateUtils.convertUSToMySQLFormat(DateUtils.getNewUSDate()) + "'";
} else if (fromDate.trim().equals(toDate.trim())) {
sql += " AppliedDate='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
} else {
sql +=
" AppliedDate>='" + DateUtils.convertUSToMySQLFormat(fromDate) + "' and AppliedDate<='"
+ DateUtils.convertUSToMySQLFormat(toDate) + "'";
}
sql += " Group By AppliedDate Order By 1 ";
ResultSet rs = stmt.executeQuery(sql);
// double totDeposit = 0.0;
BigDecimal totDeposit = new BigDecimal("0.00");
totDeposit = totDeposit.setScale(2, BigDecimal.ROUND_CEILING);
int totCnt = 0;
mainHeading = "DEPOSITS FROM " + fromDate + " TO " + toDate;
subHeadings.addElement("Date");
subHeadings.addElement("Deposit");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String dd = DateUtils.convertMySQLToUSFormat(rs.getString(1));
BigDecimal depoAmount = rs.getBigDecimal(2);
totDeposit = totDeposit.add(depoAmount);
Hashtable totData = new Hashtable();
totData.put("Date", dd);
if (depoAmount != null) {
totData.put("Deposit", depoAmount.toString());
}
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totDepositStr = "";
// System.out.println("totDeposit.toString()..."+totDeposit.toString());
if (totDeposit != null) {
totDepositStr = totDeposit.toString();
// System.out.println("totDepositStr..."+totDepositStr);
}
/*
* String totDepositStr = totDeposit + ""; if (totDepositStr.indexOf(".") ==
* totDepositStr.length() - 2) { totDepositStr += "0"; } totDepositStr =
* NumberUtils.cutFractions(totDepositStr);
*/
totals[0][0] = "Total Deposit Amount";
totals[0][1] = totDepositStr;
totals[1][0] = "Total No Of Deposits";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable showInvoicesNotPrinted(UserBean user) throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowNonPrintInv" + user.getUsername() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName FROM Invoice a, Customer b WHERE ";
sql += " a.CustomerId=b.CustomerId and IsPrinted!='Y' and IsDelivered!='Y' and a.Balance!=0 ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Marcie")) {
sql += " AND a.SalesPerson='" + user.getUsername() + "' ";
}
ResultSet rs = stmt.executeQuery(sql);
int totCnt = 0;
mainHeading = "INVOICES NOT PRINTED AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Inovices ");
}
totals[0][0] = "Total No Of Invoices";
totals[0][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable showInvoicesNotPickedUp(UserBean user, boolean cods) throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowNonPrintInv" + user.getUsername() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance FROM Invoice a, Customer b WHERE ";
sql +=
" a.Status!='C' and a.Status!='W' and a.Balance>0 and a.ShipVia='Pick-Up' and a.CustomerId=b.CustomerId ";
if (cods) {
sql += " and b.PaymentTerms!='M' and b.PaymentTerms!='B' and b.PaymentTerms!='W' ";
} else {
sql += " and b.PaymentTerms!='C' and b.PaymentTerms!='O' ";
}
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Marcie")) {
sql += " AND a.SalesPerson='" + user.getUsername() + "' ";
}
sql += " Order by 1 desc ";
ResultSet rs = stmt.executeQuery(sql);
int totCnt = 0;
if (cods) {
mainHeading = "PENDING PICKUP COD & CASH INVOICES AS ON " + DateUtils.getNewUSDate();
} else {
mainHeading = "PENDING PICKUP ACCOUNTS INVOICES AS ON " + DateUtils.getNewUSDate();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balance + "");
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Inovices ");
}
totals[0][0] = "Total No Of Invoices";
totals[0][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable createHistoryReport(int invNo) throws UserException {
Hashtable invoiceHistory = null;
try {
String fileName = "Hist" + invNo + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT * From InvoiceHistory Where InvoiceNumber=" + invNo + " Order By ModifiedOrder ";
ResultSet rs = stmt.executeQuery(sql);
mainHeading = "History for the Invoice " + invNo;
subHeadings.addElement("Modified Date");
subHeadings.addElement("Modified By");
subHeadings.addElement("Remarks");
int totalChanges = 0;
while (rs.next()) {
if (invoiceHistory == null) {
invoiceHistory = new Hashtable();
}
totalChanges++;
String modifiedBy = rs.getString("ModifiedBy");
String modifiedDate = rs.getString("ModifiedDate");
String remarks =
rs.getString("Remarks1") + rs.getString("Remarks2") + rs.getString("Remarks3")
+ rs.getString("Remarks4") + rs.getString("Remarks5");
Hashtable totData = new Hashtable();
totData.put("Modified Date", DateUtils.convertMySQLToUSFormat(modifiedDate));
totData.put("Modified By", modifiedBy);
totData.put("Remarks", remarks);
data.addElement(totData);
}
if (invoiceHistory == null) {
throw new UserException(" No Changes On This Invoice ");
}
totals[0][0] = "Total No. Of Changes Found";
totals[0][1] = totalChanges + "";
invoiceHistory.put("FileName", fileName);
invoiceHistory.put("BackScreen", "CloseInvoices");
invoiceHistory.put("MainHeading", mainHeading);
invoiceHistory.put("SubHeadings", subHeadings);
invoiceHistory.put("Data", data);
invoiceHistory.put("Totals", totals);
createReport(invoiceHistory);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return invoiceHistory;
}
public static Hashtable createHistoryReport(String fromDate, String toDate) throws UserException {
Hashtable invoiceHistory = null;
try {
String fileName = "Hist" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
if (fromDate == null) {
fromDate = "";
}
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT * From InvoiceHistory Where ";
mainHeading = "Invoice History Report :";
if (fromDate.trim().equals("")) {
mainHeading += " For " + toDate.trim();
sql +=
" ModifiedDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim())
+ "' And Remarks1 Not like 'Printed%' Order By InvoiceNumber ";
} else if (fromDate.trim().equals(toDate.trim())) {
mainHeading += " For " + toDate.trim();
sql +=
" ModifiedDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim())
+ "' And Remarks1 Not like 'Printed%' Order By InvoiceNumber ";
} else {
mainHeading += " From " + fromDate.trim() + " To " + toDate.trim();
sql +=
" ModifiedDate >= '" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' and ModifiedDate <= '" + DateUtils.convertUSToMySQLFormat(toDate.trim())
+ "' And Remarks1 Not like 'Printed%' Order By ModifiedDate, InvoiceNumber ";
}
ResultSet rs = stmt.executeQuery(sql);
subHeadings.addElement("Inv. No");
subHeadings.addElement("Date");
subHeadings.addElement("Who");
subHeadings.addElement("Remarks");
int totalChanges = 0;
while (rs.next()) {
if (invoiceHistory == null) {
invoiceHistory = new Hashtable();
}
totalChanges++;
int invNo = rs.getInt("InvoiceNumber");
String modifiedBy = rs.getString("ModifiedBy");
String modifiedDate = rs.getString("ModifiedDate");
String remarks =
rs.getString("Remarks1") + rs.getString("Remarks2") + rs.getString("Remarks3")
+ rs.getString("Remarks4") + rs.getString("Remarks5");
Hashtable totData = new Hashtable();
totData.put("Inv. No", invNo + "");
totData.put("Date", DateUtils.convertMySQLToUSFormat(modifiedDate));
totData.put("Who", modifiedBy);
totData.put("Remarks", remarks);
data.addElement(totData);
}
if (invoiceHistory == null) {
throw new UserException(" No Changes On This Invoice ");
}
totals[0][0] = "Total No. Of Changes Found";
totals[0][1] = totalChanges + "";
invoiceHistory.put("FileName", fileName);
invoiceHistory.put("BackScreen", "TodaysOrders");
invoiceHistory.put("MainHeading", mainHeading);
invoiceHistory.put("SubHeadings", subHeadings);
invoiceHistory.put("Data", data);
invoiceHistory.put("Totals", totals);
createReport(invoiceHistory);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return invoiceHistory;
}
public static void createCOGReport(String fileName, String data) {
try {
File fileHtml = new File("c:/Tomcat/webapps/bvaschicago/html/reports/"
//"E:/projects/myeclipse/.metadata/.me_tcat/webapps/bvaschicago/html/reports/"
+ fileName);
FileWriter ft = new FileWriter(fileHtml);
// ft.write(getHeaders("General Reports Printer"));
ft.write(getHeaders(""));
ft.write("<table>");
ft.write("<tr>");
ft.write("<td colspan='4' align='center' style='font-size: 20pt '>");
ft.write("<B>Best Value Auto Body Supply Inc.</B><BR/>");
ft.write("</td>");
ft.write("<tr>");
ft.write("<td colspan='4' align='center' style='font-size: 16pt '>");
ft.write("<B>General Reports Viewer</B>");
ft.write("<BR/>");
ft.write("<hr align='center' noshade size='2px' width='500px'/><BR/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<TR><TD align='Center' colspan='4'><H2>Cost Of Goods Report</H2></TD></TR>");
ft.write("<tr style='border: thin;'>");
ft.write(data);
ft.write("</table>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<tr>");
ft.write("<td colspan='4'>");
ft.write("<hr align='center' noshade size='2px' width='700px'/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("</table>");
ft.write(getFooters());
ft.close();
} catch (IOException ioe) {
logger.error("Exception in PrintUtils.createInvoice: " + ioe);
} catch (Exception e) {
logger.error("Exception in PrintUtils.createInvoice: " + e);
}
}
public static void createReport(Hashtable toShowSales) {
try {
String fileName = (String) toShowSales.get("FileName");
String mainHeading = (String) toShowSales.get("MainHeading");
Vector subHeadings = (Vector) toShowSales.get("SubHeadings");
int arraySize = subHeadings.size();
String[] strSubHeads = new String[arraySize];
Vector data = (Vector) toShowSales.get("Data");
String[][] totals = (String[][]) toShowSales.get("Totals");
File fileHtml = new File("c:/Tomcat/webapps/bvaschicago/html/reports/" + fileName);
FileWriter ft = new FileWriter(fileHtml);
// ft.write(getHeaders("General Reports Printer"));
ft.write(getHeaders(""));
ft.write("<table>");
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "' align='center' style='font-size: 20pt '>");
ft.write("<B>Best Value Auto Body Supply Inc.</B><BR/>");
ft.write("</td>");
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "' align='center' style='font-size: 16pt '>");
ft.write("<B>" + mainHeading + "</B>");
ft.write("<BR/>");
ft.write("<hr align='center' noshade size='2px' width='500px'/><BR/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<tr style='border: thin;'>");
Enumeration enumSubHead = subHeadings.elements();
int cnt = 0;
while (enumSubHead.hasMoreElements()) {
String subH = (String) enumSubHead.nextElement();
strSubHeads[cnt] = subH;
cnt++;
ft.write("<td><B>");
ft.write(padSpaces(subH, 10));
ft.write("</B></td>");
}
ft.write("</tr>");
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "'>");
ft.write("<hr align='center' noshade size='2px' width='700px'/>");
ft.write("</td>");
ft.write("</tr>");
Enumeration enumData = data.elements();
while (enumData.hasMoreElements()) {
Hashtable innerData = (Hashtable) enumData.nextElement();
ft.write("<tr>");
for (int i = 0; i < strSubHeads.length; i++) {
ft.write("<td>");
ft.write(padSpaces((String) innerData.get(strSubHeads[i]), 10));
ft.write("</td>");
}
ft.write("</tr>");
}
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "'>");
ft.write("<hr align='center' noshade size='2px' width='700px'/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<tr>");
ft.write("<td align='right' colspan='" + arraySize + "'>");
ft.write("<table>");
for (int i = 0; i < totals.length; i++) {
ft.write("<tr>");
ft.write("<TD><B>" + totals[i][0] + "</B></TD>");
ft.write("<TD><B>" + totals[i][1] + "</B></TD>");
ft.write("</tr>");
}
ft.write("</table>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "'>");
ft.write("<hr align='center' noshade size='2px' width='700px'/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("</table>");
ft.write(getFooters());
ft.close();
} catch (IOException ioe) {
logger.error("Exception in PrintUtils.createInvoice: " + ioe);
} catch (Exception e) {
logger.error("Exception in PrintUtils.createInvoice: " + e);
}
}
public static String getHeaders() {
StringBuffer headers = new StringBuffer("");
headers
.append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>");
headers
.append("<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
// headers.append("<STYLE TYPE='text/css'> <!-- p { font-size: 13pt; } --> </STYLE> ");
headers.append("<TITLE>Print Invoice</TITLE></HEAD>");
headers
.append("<script language='JavaScript'> function PrintPage() { window.print(); window.close(); }</script>");
headers.append("<BODY onload='PrintPage()'>");
return headers.toString();
}
public static String getHeaders(String title) {
StringBuffer headers = new StringBuffer("");
headers
.append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>");
headers
.append("<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
// headers.append("<STYLE TYPE='text/css'> <!-- p { font-size: 13pt; } --> </STYLE> ");
headers.append("<TITLE>" + title + "</TITLE></HEAD>");
headers
.append("<script language='JavaScript'> function PrintPage() { window.print(); window.close(); }</script>");
headers.append("<BODY onload='PrintPage()'>");
return headers.toString();
}
public static String getFooters() {
StringBuffer footers = new StringBuffer("");
footers.append("</BODY></HTML>");
return footers.toString();
}
public static String padSpaces(String str, int len) {
if (str == null || str.trim().equals("null"))
str = "";
str = str.trim();
int len1 = str.length();
while (len1 < len) {
str += " ";
len1++;
}
str += " ";
return str;
}
public static String newLines(String str) {
int len = 0;
if (str != null && (len = str.indexOf("\n")) != -1) {
str = str.substring(0, len) + "<BR/>" + newLines(str.substring(len + 1));
}
return str;
}
public static String cutModel(String model) {
int len = 0;
if (model.length() > 15) {
model = model.substring(0, 15);
}
if ((len = model.indexOf("(")) != -1) {
model = model.substring(0, len);
}
return model;
}
public static int calLen(String str, int totSize) {
int len = str.length();
totSize = totSize - (len * 2);
for (int i = 0; i < 6; i++) {
if (str.indexOf(" ") != -1) {
totSize = totSize - 1;
str = str.substring(str.indexOf(" ") + 1);
}
}
return totSize;
}
public static void getVendorHeader(FileWriter ft, int supId, boolean woPrice) throws IOException {
ft.write("<table border='1' cellspacing='0' style='font-size: 10pt'>");
ft.write("<tr>");
ft.write("<td align='center'><B>");
ft.write("BV Part No");
ft.write("</B></td>");
ft.write("<td align='center'><B>");
ft.write("ITEM NO");
ft.write("</B></td>");
if (supId != 1 && supId != 4 && supId != 5 && supId != 6 && supId != 8) {
ft.write("<td align='center'><B>");
ft.write("Desc 1");
ft.write("</B></td>");
}
ft.write("<td align='center'><B>");
ft.write("Desc 2");
ft.write("</B></td>");
ft.write("<td align='center'><B>");
ft.write("P/L Number");
ft.write("</B></td>");
ft.write("<td align='center'><B>");
ft.write("OEM Number");
ft.write("</B></td>");
if (woPrice) {
ft.write("<td align='center'><B>");
ft.write("NR");
ft.write("</B></td>");
ft.write("<td align='center'><B>");
ft.write("CUFT");
ft.write("</B></td>");
}
ft.write("<td align='center'><B>");
ft.write("Order");
ft.write("</B></td>");
ft.write("</tr>");
}
public static List populateDrivers() {
List<Driver> drvrList = new ArrayList<Driver>();
Connection con = null;
Statement stmtDrvr = null;
ResultSet rsDrvr = null;
try {
con = DBInterfaceLocal.getSQLConnection();
stmtDrvr = con.createStatement();
rsDrvr = stmtDrvr.executeQuery("Select serial,drivername From driver Where active=1");
while (rsDrvr.next()) {
Driver drvr = new Driver();
drvr.setSerial(rsDrvr.getString("serial"));
drvr.setDriverName(rsDrvr.getString("drivername"));
drvrList.add(drvr);
}
stmtDrvr.close();
rsDrvr.close();
con.close();
} catch (SQLException e) {
logger.error(e);
} finally{
}
return drvrList;
}
}
| UTF-8 | Java | 183,400 | java | ReportUtils.java | Java | [
{
"context": " !user.getUsername().trim().equalsIgnoreCase(\"CorrinaNY\")\n && !user.getUsername().trim().equalsI",
"end": 1924,
"score": 0.9867752194404602,
"start": 1918,
"tag": "USERNAME",
"value": "rinaNY"
},
{
"context": " && !user.getUsername().trim().equalsIgnoreCase(\"Nancy\")\n && !user.getUsername().trim().equalsI",
"end": 1990,
"score": 0.8420950770378113,
"start": 1985,
"tag": "NAME",
"value": "Nancy"
},
{
"context": " && !user.getUsername().trim().equalsIgnoreCase(\"Joses\")) {\n sql += \" SalesPerson='\" + user.getUs",
"end": 2056,
"score": 0.8962674140930176,
"start": 2051,
"tag": "NAME",
"value": "Joses"
},
{
"context": " && !user.getUsername().trim().equalsIgnoreCase(\"Marcie\")\n && !user.getUsername().trim().equalsI",
"end": 51859,
"score": 0.9773849248886108,
"start": 51853,
"tag": "USERNAME",
"value": "Marcie"
},
{
"context": " && !user.getUsername().trim().equalsIgnoreCase(\"Nancy\")\n && !user.getUsername().trim().equalsI",
"end": 51925,
"score": 0.6047837734222412,
"start": 51920,
"tag": "USERNAME",
"value": "Nancy"
},
{
"context": " && !user.getUsername().trim().equalsIgnoreCase(\"Eddie\")) {\n sql += \" a.SalesPerson='\" + user",
"end": 51987,
"score": 0.6206109523773193,
"start": 51986,
"tag": "USERNAME",
"value": "E"
},
{
"context": " && !user.getUsername().trim().equalsIgnoreCase(\"Eddie\")) {\n sql += \" a.SalesPerson='\" + user.get",
"end": 51991,
"score": 0.6771457195281982,
"start": 51987,
"tag": "NAME",
"value": "ddie"
},
{
"context": "ust Id\", custId);\n totData.put(\"Cust Name\", custName);\n totData.put(\"Inv. Total\", invoiceTo",
"end": 54641,
"score": 0.5746815800666809,
"start": 54637,
"tag": "NAME",
"value": "cust"
},
{
"context": "ust Id\", custId);\n totData.put(\"Cust Name\", custName);\n totData.put(\"Balance\", balanceStr);\n ",
"end": 157640,
"score": 0.9938080310821533,
"start": 157632,
"tag": "NAME",
"value": "custName"
},
{
"context": " && !user.getUsername().trim().equalsIgnoreCase(\"Marcie\")) {\n sql += \" AND a.SalesPerson='\" + user",
"end": 163042,
"score": 0.996906042098999,
"start": 163036,
"tag": "USERNAME",
"value": "Marcie"
},
{
"context": " && !user.getUsername().trim().equalsIgnoreCase(\"Marcie\")) {\n sql += \" AND a.SalesPerson='\" + user",
"end": 166055,
"score": 0.9770635366439819,
"start": 166049,
"tag": "USERNAME",
"value": "Marcie"
}
]
| null | []
| package com.bvas.utils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.bvas.beans.CustomerBean;
import com.bvas.beans.Driver;
import com.bvas.beans.InvoiceBean;
import com.bvas.beans.InvoiceDetailsBean;
import com.bvas.beans.InvoiceDetailsOurPrice;
import com.bvas.beans.LocalOrderBean;
import com.bvas.beans.PartsBean;
import com.bvas.beans.UserBean;
public class ReportUtils {
private static final Logger logger = Logger.getLogger(ReportUtils.class);
public static Hashtable showDaysSales(UserBean user, String fromDate, String toDate,
String salesPerson) throws UserException {
Hashtable toShowSales = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ResultSet rs1 = null;
try {
String fileName = "ShowSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[4][2];
con = DBInterfaceLocal.getSQLConnection();
stmt = con.createStatement();
boolean getReturn = false;
String sql =
"SELECT OrderDate, SUM(InvoiceTotal), SUM(Discount), SUM(Tax) FROM Invoice WHERE ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Medium")
&&
// !user.getRole().trim().equalsIgnoreCase("Acct") &&
!user.getUsername().trim().equalsIgnoreCase("CorrinaNY")
&& !user.getUsername().trim().equalsIgnoreCase("Nancy")
&& !user.getUsername().trim().equalsIgnoreCase("Joses")) {
sql += " SalesPerson='" + user.getUsername() + "' AND ";
getReturn = true;
} else if (salesPerson != null && !salesPerson.trim().equals("")) {
sql += " SalesPerson='" + salesPerson.trim() + "' AND ";
getReturn = true;
}
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sql += " Group BY OrderDate ";
// logger.error(sql);
rs = stmt.executeQuery(sql);
/*
* double totInvoiceTotal = 0.0; double totDiscount = 0.0; double totTax = 0.0;
*/
BigDecimal totInvoiceTotal = new BigDecimal("0.0");
BigDecimal totDiscount = new BigDecimal("0.0");
BigDecimal totTax = new BigDecimal("0.0");
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Order Date");
subHeadings.addElement("Invoice Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
while (rs.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
String orderDate = rs.getString(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
double tax = rs.getDouble(4);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
/*
* totInvoiceTotal += invoiceTotal; totDiscount += discount; totTax += tax;
*/
totInvoiceTotal = totInvoiceTotal.add(new BigDecimal(invoiceTotal));
totDiscount = totDiscount.add(new BigDecimal(discount));
totTax = totTax.add(new BigDecimal(tax));
Hashtable totData = new Hashtable();
totData.put("Order Date", DateUtils.convertMySQLToUSFormat(orderDate));
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
data.addElement(totData);
}
if (getReturn) {
String retSql =
"SELECT a.OrderDate, SUM(a.InvoiceTotal), SUM(a.Discount), SUM(a.Tax) FROM Invoice a, Invoice b WHERE a.ReturnedInvoice!=0 and a.ReturnedInvoice=b.InvoiceNumber and ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Medium")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Eddie")) {
retSql +=
" b.SalesPerson='" + user.getUsername() + "' AND a.SalesPerson!='"
+ user.getUsername() + "' AND ";
} else if (salesPerson != null && !salesPerson.trim().equals("")) {
retSql +=
" b.SalesPerson='" + salesPerson.trim() + "' AND a.SalesPerson!='"
+ user.getUsername() + "' AND ";
}
if (fromDate.trim().equals(toDate.trim())) {
retSql += " a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
retSql +=
" a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
retSql += " Group BY a.OrderDate ";
rs1 = stmt.executeQuery(retSql);
while (rs1.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
String orderDate = rs1.getString(1);
double invoiceTotal = rs1.getDouble(2);
double discount = rs1.getDouble(3);
double tax = rs1.getDouble(4);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
/*
* totInvoiceTotal += invoiceTotal; totDiscount += discount; totTax += tax;
*/
totInvoiceTotal = totInvoiceTotal.add(new BigDecimal(invoiceTotal));
totDiscount = totDiscount.add(new BigDecimal(discount));
totTax = totTax.add(new BigDecimal(tax));
Hashtable totData = new Hashtable();
totData.put("Order Date", DateUtils.convertMySQLToUSFormat(orderDate));
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
data.addElement(totData);
}
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
totInvoiceTotal = totInvoiceTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
totDiscount = totDiscount.setScale(2, BigDecimal.ROUND_HALF_UP);
totTax = totTax.setScale(2, BigDecimal.ROUND_HALF_UP);
String totInvoiceTotalStr = totInvoiceTotal.toString();
String totDiscountStr = totDiscount.toString();
String totTaxStr = totTax.toString();
BigDecimal grossTotal = totInvoiceTotal.add(totTax);
grossTotal = grossTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal netTotal = (grossTotal.subtract(totTax)).subtract(totDiscount);
netTotal = netTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
totals[0][0] = "Gross Total";
totals[0][1] = grossTotal.toString();
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Net Total";
totals[3][1] = netTotal.toString();
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
logger.error(e);;
// throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showSalesForPers(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[5][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX = "SELECT Count(Distinct OrderDate) FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsX = stmtX.executeQuery(sqlX);
int noOfDays = 0;
if (rsX.next()) {
noOfDays = rsX.getInt(1);
}
if (noOfDays == 0) {
noOfDays = 1;
}
Statement stmt = con.createStatement();
String sql =
"SELECT InvoiceNumber, SalesPerson, InvoiceTotal, Tax, Discount, ReturnedInvoice FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
/*
* double totInvoiceTotal = 0.0; double totDiscount = 0.0; double totTax = 0.0; double totAvg
* = 0.0;
*/
BigDecimal totInvoiceTotal = new BigDecimal("0.0");
BigDecimal totDiscount = new BigDecimal("0.0");
BigDecimal totTax = new BigDecimal("0.0");
BigDecimal totAvg = new BigDecimal("0.0");
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Sales Person");
subHeadings.addElement("Invoice Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
subHeadings.addElement("Average");
String[][] arrSales = new String[50][4];
for (int i = 0; i < 50; i++) {
arrSales[i][0] = "";
arrSales[i][1] = "0.0";
arrSales[i][2] = "0.0";
arrSales[i][3] = "0.0";
}
while (rs.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
int invNo = rs.getInt(1);
String salesPerson = rs.getString(2);
double invoiceTotal = rs.getDouble(3);
double discount = rs.getDouble(5);
double tax = rs.getDouble(4);
int retInv = rs.getInt(6);
salesPerson = salesPerson.trim();
int currCnt = -1;
String currPers = "";
if (retInv == 0) {
currPers = salesPerson;
} else {
Statement stmtXX = con.createStatement();
ResultSet rsXX =
stmtXX.executeQuery("Select SalesPerson From Invoice Where InvoiceNumber=" + retInv);
if (rsXX.next()) {
currPers = rsXX.getString(1);
}
/*
* InvoiceBean retBean = InvoiceBean.getInvoice(retInv); if (
* retBean.getSalesPerson().trim().equals(salesPerson.trim() )) { currPers = salesPerson;
* } else { currPers = retBean.getSalesPerson(); }
*/
// 10/12/2013 : Changes done as a part of review : Begin
stmtXX.close();
// 10/12/2013 : Changes done as a part of review : End
}
int alreadyIn = 0;
for (int i = 0; i < 50; i++) {
if (!arrSales[i][0].trim().equals("")) {
alreadyIn++;
}
if (arrSales[i][0].trim().equals(currPers)) {
currCnt = i;
}
}
if (currCnt == -1) {
arrSales[alreadyIn][0] = currPers;
arrSales[alreadyIn][1] = invoiceTotal + "";
arrSales[alreadyIn][2] = discount + "";
arrSales[alreadyIn][3] = tax + "";
// logger.error("First Time Adding For " + currPers);
} else {
arrSales[currCnt][1] = invoiceTotal + Double.parseDouble(arrSales[currCnt][1]) + "";
arrSales[currCnt][2] = discount + Double.parseDouble(arrSales[currCnt][2]) + "";
arrSales[currCnt][3] = tax + Double.parseDouble(arrSales[currCnt][3]) + "";
}
}
for (int i = 0; i < 50; i++) {
String salesPers = arrSales[i][0];
if (salesPers.trim().equals("")) {
break;
}
double avg = 0.0;
Statement stmtY = con.createStatement();
String sqlY =
"SELECT Count(Distinct OrderDate) FROM Invoice WHERE SalesPerson='" + salesPers
+ "' and ";
if (fromDate.trim().equals(toDate.trim())) {
sqlY += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlY +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsY = stmtY.executeQuery(sqlY);
int noOfIndDays = 0;
if (rsY.next()) {
noOfIndDays = rsY.getInt(1);
}
if (noOfIndDays == 0) {
noOfIndDays = 1;
}
avg = Double.parseDouble(arrSales[i][1]) / noOfIndDays;
String invoiceTotalStr = Double.parseDouble(arrSales[i][1]) + "";
String discountStr = Double.parseDouble(arrSales[i][2]) + "";
String taxStr = Double.parseDouble(arrSales[i][3]) + "";
String avgStr = avg + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
if (avgStr.indexOf(".") == avgStr.length() - 2) {
avgStr += "0";
}
invoiceTotalStr = NumberUtils.cutFractions(invoiceTotalStr);
discountStr = NumberUtils.cutFractions(discountStr);
taxStr = NumberUtils.cutFractions(taxStr);
avgStr = NumberUtils.cutFractions(avgStr);
/*
* totInvoiceTotal += Double.parseDouble(arrSales[i][1]); totDiscount +=
* Double.parseDouble(arrSales[i][2]); totTax += Double.parseDouble(arrSales[i][3]);
*/
totInvoiceTotal = totInvoiceTotal.add(new BigDecimal(Double.parseDouble(arrSales[i][1])));
totDiscount = totDiscount.add(new BigDecimal(Double.parseDouble(arrSales[i][2])));
totTax = totTax.add(new BigDecimal(Double.parseDouble(arrSales[i][3])));
Hashtable totData = new Hashtable();
totData.put("Sales Person", salesPers);
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
totData.put("Average", avgStr);
data.addElement(totData);
// 10/12/2013 : Changes done as a part of review : Begin
stmtY.close();
// 10/12/2013 : Changes done as a part of review : End
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
totInvoiceTotal = totInvoiceTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
totDiscount = totDiscount.setScale(2, BigDecimal.ROUND_HALF_UP);
totTax = totTax.setScale(2, BigDecimal.ROUND_HALF_UP);
/*
* String totInvoiceTotalStr = totInvoiceTotal+""; String totDiscountStr = totDiscount+"";
* String totTaxStr = totTax + ""; String netTotal = totInvoiceTotal - totDiscount + totTax +
* "";
*/
String totInvoiceTotalStr = totInvoiceTotal.add(totTax).toString();
String totDiscountStr = totDiscount.toString();
String totTaxStr = totTax.toString();
BigDecimal netTotal = totInvoiceTotal.subtract(totDiscount);
/*
* totAvg = totInvoiceTotal / noOfDays; String totAvgStr = totAvg + "";
*/
totAvg = totInvoiceTotal.divide(new BigDecimal(noOfDays), MathContext.DECIMAL32);
totAvg = totAvg.setScale(2, BigDecimal.ROUND_HALF_UP);
String totAvgStr = totAvg.toString();
netTotal = netTotal.setScale(2, BigDecimal.ROUND_HALF_UP);
/*
* if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length()-2) { totInvoiceTotalStr
* += "0"; } if (totDiscountStr.indexOf(".") == totDiscountStr.length()-2) { totDiscountStr +=
* "0"; } if (totTaxStr.indexOf(".") == totTaxStr.length()-2) { totTaxStr += "0"; } if
* (netTotal.indexOf(".") == netTotal.length()-2) { netTotal += "0"; } if
* (totAvgStr.indexOf(".") == totAvgStr.length()-2) { totAvgStr += "0"; }
*/
/*
* totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr); totDiscountStr =
* NumberUtils.cutFractions(totDiscountStr); totTaxStr = NumberUtils.cutFractions(totTaxStr);
* netTotal = NumberUtils.cutFractions(netTotal); totAvgStr =
* NumberUtils.cutFractions(totAvgStr);
*/
totals[0][0] = "Gross Total";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Average";
totals[3][1] = totAvgStr;
totals[4][0] = "Net Total";
// totals[4][1] = netTotal;
totals[4][1] = netTotal.toString();
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rs.close();
stmt.close();
// 10/12/2013 : Changes done as a part of review : Begin
stmtX.close();
// 10/12/2013 : Changes done as a part of review : End
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showSalesForRt(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowRtSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
Connection con = DBInterfaceLocal.getSQLConnection();
double totalSalesRt = 0.0;
Statement stmt = con.createStatement();
String sql = "SELECT Region, Sum(InvoiceTotal) FROM Invoice a, Address b WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sql += " and a.CustomerId=b.Id and b.type='Standard' Group by Region ";
ResultSet rs = stmt.executeQuery(sql);
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report By Route " + toDate.trim();
} else {
mainHeading = "Sales Report By Route From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Route No");
subHeadings.addElement("Amount");
while (rs.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
String rtNo = rs.getString(1);
double amt = rs.getDouble(2);
totalSalesRt += amt;
Hashtable totData = new Hashtable();
totData.put("Route No", rtNo);
totData.put("Amount", amt + "");
data.addElement(totData);
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
String totalSalesRtStr = totalSalesRt + "";
if (totalSalesRtStr.indexOf(".") == totalSalesRtStr.length() - 2) {
totalSalesRtStr += "0";
}
totalSalesRtStr = NumberUtils.cutFractions(totalSalesRtStr);
totals[0][0] = "Total Sales";
totals[0][1] = totalSalesRtStr;
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
logger.error(e.getMessage());
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showReturns(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowReturns = null;
try {
String fileName = "ShowReturns" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[5][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX = "SELECT Count(Distinct OrderDate) FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsX = stmtX.executeQuery(sqlX);
int noOfDays = 0;
if (rsX.next()) {
noOfDays = rsX.getInt(1);
}
if (noOfDays == 0) {
noOfDays = 1;
}
Statement stmt = con.createStatement();
String sql =
"SELECT InvoiceNumber, SalesPerson, InvoiceTotal, Tax, Discount, ReturnedInvoice FROM Invoice WHERE ReturnedInvoice!=0 and ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rs = stmt.executeQuery(sql);
double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totTax = 0.0;
double totAvg = 0.0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Returns For The Date " + toDate.trim();
} else {
mainHeading = "Sales Returns For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Sales Person");
subHeadings.addElement("Invoice Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
subHeadings.addElement("Average");
String[][] arrSales = new String[50][4];
for (int i = 0; i < 50; i++) {
arrSales[i][0] = "";
arrSales[i][1] = "0.0";
arrSales[i][2] = "0.0";
arrSales[i][3] = "0.0";
}
while (rs.next()) {
if (toShowReturns == null) {
toShowReturns = new Hashtable();
}
int invNo = rs.getInt(1);
String salesPerson = rs.getString(2);
double invoiceTotal = rs.getDouble(3);
double discount = rs.getDouble(5);
double tax = rs.getDouble(4);
int retInv = rs.getInt(6);
salesPerson = salesPerson.trim();
int currCnt = -1;
String currPers = "";
if (retInv == 0) {
currPers = salesPerson;
} else {
Statement stmtXX = con.createStatement();
ResultSet rsXX =
stmtXX.executeQuery("Select SalesPerson From Invoice Where InvoiceNumber=" + retInv);
if (rsXX.next()) {
currPers = rsXX.getString(1);
}
/*
* InvoiceBean retBean = InvoiceBean.getInvoice(retInv); if (
* retBean.getSalesPerson().trim().equals(salesPerson.trim() )) { currPers = salesPerson;
* } else { currPers = retBean.getSalesPerson(); }
*/
// 10/12/2013 : Changes done as a part of review : Begin
stmtXX.close();
// 10/12/2013 : Changes done as a part of review : End
}
int alreadyIn = 0;
for (int i = 0; i < 50; i++) {
if (!arrSales[i][0].trim().equals("")) {
alreadyIn++;
}
if (arrSales[i][0].trim().equals(currPers)) {
currCnt = i;
}
}
if (currCnt == -1) {
arrSales[alreadyIn][0] = currPers;
arrSales[alreadyIn][1] = invoiceTotal + "";
arrSales[alreadyIn][2] = discount + "";
arrSales[alreadyIn][3] = tax + "";
// logger.error("First Time Adding For " + currPers);
} else {
arrSales[currCnt][1] = invoiceTotal + Double.parseDouble(arrSales[currCnt][1]) + "";
arrSales[currCnt][2] = discount + Double.parseDouble(arrSales[currCnt][2]) + "";
arrSales[currCnt][3] = tax + Double.parseDouble(arrSales[currCnt][3]) + "";
}
}
for (int i = 0; i < 50; i++) {
String salesPers = arrSales[i][0];
if (salesPers.trim().equals("")) {
break;
}
double avg = 0.0;
Statement stmtY = con.createStatement();
String sqlY =
"SELECT Count(Distinct OrderDate) FROM Invoice WHERE SalesPerson='" + salesPers
+ "' and ";
if (fromDate.trim().equals(toDate.trim())) {
sqlY += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlY +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsY = stmtY.executeQuery(sqlY);
int noOfIndDays = 0;
if (rsY.next()) {
noOfIndDays = rsY.getInt(1);
}
if (noOfIndDays == 0) {
noOfIndDays = 1;
}
avg = Double.parseDouble(arrSales[i][1]) / noOfIndDays;
String invoiceTotalStr = Double.parseDouble(arrSales[i][1]) + "";
String discountStr = Double.parseDouble(arrSales[i][2]) + "";
String taxStr = Double.parseDouble(arrSales[i][3]) + "";
String avgStr = avg + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
if (avgStr.indexOf(".") == avgStr.length() - 2) {
avgStr += "0";
}
invoiceTotalStr = NumberUtils.cutFractions(invoiceTotalStr);
discountStr = NumberUtils.cutFractions(discountStr);
taxStr = NumberUtils.cutFractions(taxStr);
avgStr = NumberUtils.cutFractions(avgStr);
totInvoiceTotal += Double.parseDouble(arrSales[i][1]);
totDiscount += Double.parseDouble(arrSales[i][2]);
totTax += Double.parseDouble(arrSales[i][3]);
Hashtable totData = new Hashtable();
totData.put("Sales Person", salesPers);
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
totData.put("Average", avgStr);
data.addElement(totData);
// 10/12/2013 : Changes done as a part of review : Begin
stmtY.close();
// 10/12/2013 : Changes done as a part of review : End
}
if (toShowReturns == null) {
throw new UserException(" No Sales For This Period ");
}
String totInvoiceTotalStr = totInvoiceTotal + "";
String totDiscountStr = totDiscount + "";
String totTaxStr = totTax + "";
String netTotal = totInvoiceTotal - totDiscount + totTax + "";
totAvg = totInvoiceTotal / noOfDays;
String totAvgStr = totAvg + "";
if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length() - 2) {
totInvoiceTotalStr += "0";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totTaxStr.indexOf(".") == totTaxStr.length() - 2) {
totTaxStr += "0";
}
if (netTotal.indexOf(".") == netTotal.length() - 2) {
netTotal += "0";
}
if (totAvgStr.indexOf(".") == totAvgStr.length() - 2) {
totAvgStr += "0";
}
totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totTaxStr = NumberUtils.cutFractions(totTaxStr);
netTotal = NumberUtils.cutFractions(netTotal);
totAvgStr = NumberUtils.cutFractions(totAvgStr);
totals[0][0] = "Gross Total";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Average";
totals[3][1] = totAvgStr;
totals[4][0] = "Net Total";
totals[4][1] = netTotal;
toShowReturns.put("FileName", fileName);
toShowReturns.put("BackScreen", "TodaysOrders");
toShowReturns.put("MainHeading", mainHeading);
toShowReturns.put("SubHeadings", subHeadings);
toShowReturns.put("Data", data);
toShowReturns.put("Totals", totals);
createReport(toShowReturns);
rs.close();
// 10/12/2013 : Changes done as a part of review : Begin
stmtX.close();
// 10/12/2013 : Changes done as a part of review : End
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowReturns;
}
public static Hashtable showSalesForOldPers(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[5][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX = "SELECT Count(Distinct OrderDate) FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsX = stmtX.executeQuery(sqlX);
int noOfDays = 0;
if (rsX.next()) {
noOfDays = rsX.getInt(1);
}
if (noOfDays == 0) {
noOfDays = 1;
}
Statement stmt = con.createStatement();
String sql =
"SELECT SalesPerson, SUM(InvoiceTotal), SUM(Discount), SUM(Tax) FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sql +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sql += " Group BY SalesPerson Order By SalesPerson ";
ResultSet rs = stmt.executeQuery(sql);
double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totTax = 0.0;
double totAvg = 0.0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Sales Person");
subHeadings.addElement("Invoice Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
subHeadings.addElement("Average");
while (rs.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
String salesPerson = rs.getString(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
double tax = rs.getDouble(4);
double avg = 0.0;
Statement stmtY = con.createStatement();
String sqlY =
"SELECT Count(Distinct OrderDate) FROM Invoice WHERE SalesPerson='" + salesPerson
+ "' and ";
if (fromDate.trim().equals(toDate.trim())) {
sqlY += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlY +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
ResultSet rsY = stmtY.executeQuery(sqlY);
int noOfIndDays = 0;
if (rsY.next()) {
noOfIndDays = rsY.getInt(1);
}
if (noOfIndDays == 0) {
noOfIndDays = 1;
}
avg = invoiceTotal / noOfIndDays;
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
String avgStr = avg + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
if (avgStr.indexOf(".") == avgStr.length() - 2) {
avgStr += "0";
}
avgStr = NumberUtils.cutFractions(avgStr);
totInvoiceTotal += invoiceTotal;
totDiscount += discount;
totTax += tax;
Hashtable totData = new Hashtable();
totData.put("Sales Person", salesPerson);
totData.put("Invoice Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
totData.put("Average", avgStr);
data.addElement(totData);
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
String totInvoiceTotalStr = totInvoiceTotal + "";
String totDiscountStr = totDiscount + "";
String totTaxStr = totTax + "";
String netTotal = totInvoiceTotal - totDiscount + totTax + "";
totAvg = totInvoiceTotal / noOfDays;
String totAvgStr = totAvg + "";
if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length() - 2) {
totInvoiceTotalStr += "0";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totTaxStr.indexOf(".") == totTaxStr.length() - 2) {
totTaxStr += "0";
}
if (netTotal.indexOf(".") == netTotal.length() - 2) {
netTotal += "0";
}
if (totAvgStr.indexOf(".") == totAvgStr.length() - 2) {
totAvgStr += "0";
}
totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totTaxStr = NumberUtils.cutFractions(totTaxStr);
netTotal = NumberUtils.cutFractions(netTotal);
totAvgStr = NumberUtils.cutFractions(totAvgStr);
totals[0][0] = "Gross Total";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Average";
totals[3][1] = totAvgStr;
totals[4][0] = "Net Total";
totals[4][1] = netTotal;
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rs.close();
rsX.close();
stmt.close();
stmtX.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showSalesForCust(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowCustSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[3][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX =
"SELECT a.CustomerId, b.CompanyName, Sum(a.InvoiceTotal), b.CustomerLevel, Max(a.OrderDate) FROM Invoice a, Customer b WHERE a.CustomerId=b.CustomerId AND ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sqlX += " Group By a.CustomerId Order By 3 Desc ";
ResultSet rsX = stmtX.executeQuery(sqlX);
double totInvoiceTotal = 0.0;
int noOfCust = 0;
int totalLvlCust = 0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report By Customers For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report By Customers For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Customer Id");
subHeadings.addElement("Company Name");
subHeadings.addElement("Last Order");
subHeadings.addElement("Amount Bought");
subHeadings.addElement("Level");
while (rsX.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
noOfCust++;
String custId = rsX.getString(1);
String companyName = rsX.getString(2);
double invoiceTotal = rsX.getDouble(3);
int lvl = rsX.getInt(4);
String orderDate = DateUtils.convertMySQLToUSFormat(rsX.getString(5));
if (lvl != 0) {
totalLvlCust++;
}
String invoiceTotalStr = invoiceTotal + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
totInvoiceTotal += invoiceTotal;
Hashtable totData = new Hashtable();
totData.put("Customer Id", custId);
totData.put("Company Name", companyName);
totData.put("Last Order", orderDate);
totData.put("Amount Bought", invoiceTotalStr);
totData.put("Level", lvl + "");
data.addElement(totData);
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
String totInvoiceTotalStr = totInvoiceTotal + "";
if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length() - 2) {
totInvoiceTotalStr += "0";
}
totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr);
totals[0][0] = "Total Amount";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "No Of Customers";
totals[1][1] = noOfCust + "";
totals[2][0] = "No Of Leveled Customers";
totals[2][1] = totalLvlCust + "";
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rsX.close();
stmtX.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showPartsSold(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowSales = null;
try {
String fileName = "ShowPartsSales" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[8][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtX = con.createStatement();
String sqlX =
"SELECT a.InvoiceNumber, a.PartNumber, a.Quantity, a.SoldPrice, a.ActualPrice, c.CostPrice, c.ActualPrice, c.UnitsInStock, c.UnitsOnOrder, c.ReorderLevel" +
// ", c.CompPrice1, c.CompPrice2" +
" FROM InvoiceDetails a, Invoice b, Parts c WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sqlX += " b.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
} else {
sqlX +=
" b.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND b.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "'";
}
sqlX += " and b.InvoiceNumber=a.InvoiceNumber and a.PartNumber=c.PartNo Order By 1, 2 ";
ResultSet rsX = stmtX.executeQuery(sqlX);
int totalNoOfParts = 0;
int totalNoOfItems = 0;
double totalSoldPrice = 0.0;
double totalInvActual = 0.0;
double totalPartsCost = 0.0;
double totalPartsActual = 0.0;
double totalActualPerc = 0.0;
double partsPerc = 0.0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Sales Report By Parts For The Date " + toDate.trim();
} else {
mainHeading = "Sales Report By Parts For The Period From " + fromDate + " To " + toDate;
}
subHeadings.addElement("Part / Inv");
subHeadings.addElement("Qty/Sold/Act");
subHeadings.addElement("Cost/Act");
subHeadings.addElement("Units");
//subHeadings.addElement("Comp");
subHeadings.addElement("Perc");
subHeadings.addElement("Rmks");
while (rsX.next()) {
if (toShowSales == null) {
toShowSales = new Hashtable();
}
int invNo = rsX.getInt(1);
String partNo = rsX.getString(2);
if ((partNo.startsWith("XX") || partNo.startsWith("xx")) && partNo.length() == 7) {
continue;
}
int qty = rsX.getInt(3);
double sold = rsX.getDouble(4);
double invAct = rsX.getDouble(5);
double partCost = rsX.getDouble(6);
double partAct = rsX.getDouble(7);
int units = rsX.getInt(8);
int onOrder = rsX.getInt(9);
int reorder = rsX.getInt(10);
// double comp1 = rsX.getDouble(11);
// double comp2 = rsX.getDouble(12);
double perc = 0.0;
double shouldBePerc = 0.0;
String remarks = " ";
if (partAct == 0 && invAct != 0) {
partAct = invAct;
}
if (sold > 0 && invAct > 0) {
perc = (sold - invAct) * 100 / sold;
perc = Math.rint(perc);
} else {
perc = 0;
}
if (invAct > 0) {
if (invAct < 1) {
shouldBePerc = 70;
} else if (invAct < 2) {
shouldBePerc = 67;
} else if (invAct < 3) {
shouldBePerc = 65;
} else if (invAct < 4) {
shouldBePerc = 63;
} else if (invAct < 5) {
shouldBePerc = 61;
} else if (invAct < 8) {
shouldBePerc = 59;
} else if (invAct < 11) {
shouldBePerc = 57;
} else if (invAct < 14) {
shouldBePerc = 55;
} else if (invAct < 18) {
shouldBePerc = 53;
} else if (invAct < 23) {
shouldBePerc = 51;
} else if (invAct < 28) {
shouldBePerc = 49;
} else if (invAct < 35) {
shouldBePerc = 47;
} else if (invAct < 42) {
shouldBePerc = 45;
} else if (invAct < 50) {
shouldBePerc = 43;
} else if (invAct < 60) {
shouldBePerc = 41;
} else if (invAct < 70) {
shouldBePerc = 39;
} else if (invAct < 80) {
shouldBePerc = 37;
} else if (invAct < 90) {
shouldBePerc = 35;
} else if (invAct < 125) {
shouldBePerc = 30;
} else if (invAct < 150) {
shouldBePerc = 25;
} else {
shouldBePerc = 20;
}
} else {
shouldBePerc = 0;
}
if (perc > shouldBePerc + 10) {
remarks = "High Price";
} else if (perc < shouldBePerc - 10) {
remarks = "Low Price";
}
totalNoOfParts++;
totalNoOfItems += qty;
totalSoldPrice += (sold * qty);
totalInvActual += (invAct * qty);
totalPartsCost += (partCost * qty);
totalPartsActual += (partAct * qty);
String partNoInvNo = partNo + " / " + invNo;
String qtySoldAct = qty + " / " + sold + " / " + invAct;
String costAct = partCost + " / " + partAct;
String unitsOrderReorder = units + " / " + onOrder + " / " + reorder;
// String comp1Comp2 = comp1 + " / " + comp2;
String percShouldBePerc = perc + " / " + shouldBePerc;
Hashtable totData = new Hashtable();
totData.put("Part / Inv", partNoInvNo);
totData.put("Qty/Sold/Act", qtySoldAct);
totData.put("Cost/Act", costAct);
totData.put("Units", unitsOrderReorder);
// totData.put("Comp", comp1Comp2);
totData.put("Perc", percShouldBePerc);
totData.put("Rmks", remarks);
data.addElement(totData);
}
if (toShowSales == null) {
throw new UserException(" No Sales For This Period ");
}
double actualPerc = 0.0;
double shouldBePerc = 0.0;
String totalSoldPriceStr = totalSoldPrice + "";
if (totalSoldPriceStr.indexOf(".") == totalSoldPriceStr.length() - 2) {
totalSoldPriceStr += "0";
}
totalSoldPriceStr = NumberUtils.cutFractions(totalSoldPriceStr);
String totalInvActualStr = totalInvActual + "";
if (totalInvActualStr.indexOf(".") == totalInvActualStr.length() - 2) {
totalInvActualStr += "0";
}
totalInvActualStr = NumberUtils.cutFractions(totalInvActualStr);
String totalPartsCostStr = totalPartsCost + "";
if (totalPartsCostStr.indexOf(".") == totalPartsCostStr.length() - 2) {
totalPartsCostStr += "0";
}
totalPartsCostStr = NumberUtils.cutFractions(totalPartsCostStr);
String totalPartsActualStr = totalPartsActual + "";
if (totalPartsActualStr.indexOf(".") == totalPartsActualStr.length() - 2) {
totalPartsActualStr += "0";
}
totalPartsActualStr = NumberUtils.cutFractions(totalPartsActualStr);
totalActualPerc = (totalSoldPrice - totalInvActual) * 100 / totalSoldPrice;
totalActualPerc = Math.rint(totalActualPerc);
partsPerc = (totalPartsCost - totalPartsActual) * 100 / totalPartsCost;
partsPerc = Math.rint(partsPerc);
totals[0][0] = "Total No Of Parts";
totals[0][1] = totalNoOfParts + "";
totals[1][0] = "Total No Of Items";
totals[1][1] = totalNoOfItems + "";
totals[2][0] = "Total Sold Price";
totals[2][1] = totalSoldPriceStr;
totals[3][0] = "Total Invoice Actual";
totals[3][1] = totalInvActualStr;
totals[4][0] = "Total Parts Cost";
totals[4][1] = totalPartsCostStr;
totals[5][0] = "Total Parts Actual";
totals[5][1] = totalPartsActualStr;
totals[6][0] = "Actual Perc";
totals[6][1] = totalActualPerc + "";
totals[7][0] = "Perc On Parts";
totals[7][1] = partsPerc + "";
toShowSales.put("FileName", fileName);
toShowSales.put("BackScreen", "TodaysOrders");
toShowSales.put("MainHeading", mainHeading);
toShowSales.put("SubHeadings", subHeadings);
toShowSales.put("Data", data);
toShowSales.put("Totals", totals);
createReport(toShowSales);
rsX.close();
stmtX.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowSales;
}
public static Hashtable showInvoices(UserBean user, String invoiceFromDate, String invoiceToDate,
String salesPerson) throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowInvoices" + invoiceFromDate.trim() + invoiceToDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[4][2];
boolean getReturns = false;
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.SalesPerson, a.CustomerId, b.CompanyName, a.InvoiceTotal, a.Discount, a.Tax FROM Invoice a, Customer b WHERE ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Medium")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Marcie")
&& !user.getUsername().trim().equalsIgnoreCase("Nancy")
&& !user.getUsername().trim().equalsIgnoreCase("Eddie")) {
sql += " a.SalesPerson='" + user.getUsername() + "' AND ";
getReturns = true;
} else if (salesPerson != null && !salesPerson.trim().equals("")) {
sql += " a.SalesPerson='" + salesPerson.trim() + "' AND ";
getReturns = true;
}
if (invoiceFromDate.trim().equals(invoiceToDate)) {
sql += " a.OrderDate='" + DateUtils.convertUSToMySQLFormat(invoiceFromDate.trim()) + "'";
} else {
sql += " a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(invoiceFromDate.trim()) + "'";
sql += " AND a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(invoiceToDate.trim()) + "'";
}
sql += " AND a.CustomerId=b.CustomerId Order By 1 ";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totTax = 0.0;
if (invoiceFromDate.trim().equals(invoiceToDate)) {
mainHeading = "Invoice Orders For The Date " + invoiceFromDate.trim();
} else {
mainHeading =
"Invoice Orders From " + invoiceFromDate.trim() + " To " + invoiceToDate.trim();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Inv. Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Tax");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
String invoiceNo = rs.getString(1);
String newSalesPerson = rs.getString(2);
String custId = rs.getString(3);
String custName = rs.getString(4);
double invoiceTotal = rs.getDouble(5);
double discount = rs.getDouble(6);
double tax = rs.getDouble(7);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
totInvoiceTotal += invoiceTotal;
totDiscount += discount;
totTax += tax;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Inv. Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
data.addElement(totData);
}
if (getReturns) {
String retSql =
"SELECT a.InvoiceNumber, a.ReturnedInvoice, a.CustomerId, b.CompanyName, a.InvoiceTotal, a.Discount, a.Tax FROM Invoice a, Customer b, Invoice c WHERE a.ReturnedInvoice!=0 and a.ReturnedInvoice=c.InvoiceNumber AND ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Medium")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Eddie")) {
retSql +=
" c.SalesPerson='" + user.getUsername() + "' AND a.SalesPerson!='"
+ user.getUsername() + "' AND ";
} else if (salesPerson != null && !salesPerson.trim().equals("")) {
retSql +=
" c.SalesPerson='" + salesPerson.trim() + "' AND a.SalesPerson!='"
+ user.getUsername() + "' AND ";
}
if (invoiceFromDate.trim().equals(invoiceToDate)) {
retSql +=
" a.OrderDate='" + DateUtils.convertUSToMySQLFormat(invoiceFromDate.trim()) + "'";
} else {
retSql +=
" a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(invoiceFromDate.trim()) + "'";
retSql +=
" AND a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(invoiceToDate.trim()) + "'";
}
retSql += " AND a.CustomerId=b.CustomerId Order By 1 ";
ResultSet rs1 = stmt.executeQuery(retSql);
while (rs1.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
String invoiceNo = rs1.getString(1);
String retInvNo = rs1.getString(2);
String custId = rs1.getString(3);
String custName = rs1.getString(4);
double invoiceTotal = rs1.getDouble(5);
double discount = rs1.getDouble(6);
double tax = rs1.getDouble(7);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
String taxStr = tax + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
if (taxStr.indexOf(".") == taxStr.length() - 2) {
taxStr += "0";
}
totInvoiceTotal += invoiceTotal;
totDiscount += discount;
totTax += tax;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Sales Person", retInvNo);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Inv. Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Tax", taxStr);
data.addElement(totData);
}
}
if (toShowInvoices == null) {
throw new UserException(" No Sales For This Period ");
}
String totInvoiceTotalStr = totInvoiceTotal + "";
String totDiscountStr = totDiscount + "";
String totTaxStr = totTax + "";
String netTotal = totInvoiceTotal - totDiscount + totTax + "";
if (totInvoiceTotalStr.indexOf(".") == totInvoiceTotalStr.length() - 2) {
totInvoiceTotalStr += "0";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totTaxStr.indexOf(".") == totTaxStr.length() - 2) {
totTaxStr += "0";
}
if (netTotal.indexOf(".") == netTotal.length() - 2) {
netTotal += "0";
}
totInvoiceTotalStr = NumberUtils.cutFractions(totInvoiceTotalStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totTaxStr = NumberUtils.cutFractions(totTaxStr);
netTotal = NumberUtils.cutFractions(netTotal);
if (user.getRole().trim().equalsIgnoreCase("Acct")) {
totInvoiceTotalStr = "0.0";
totDiscountStr = "0.0";
totTaxStr = "0.0";
netTotal = "0.0";
}
totals[0][0] = "Gross Total";
totals[0][1] = totInvoiceTotalStr;
totals[1][0] = "Discount";
totals[1][1] = totDiscountStr;
totals[2][0] = "Tax";
totals[2][1] = totTaxStr;
totals[3][0] = "Net Total";
totals[3][1] = netTotal;
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable analyseInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
if (!user.getRole().trim().equalsIgnoreCase("High")) {
throw new UserException("YOU ARE NOT AUTHORIZED TO VIEW THIS REPORT");
}
String fileName = "";
if (fromDate.trim().equals(toDate.trim())) {
fileName = "AI" + fromDate.trim() + ".html";
} else {
fileName = "AI" + fromDate.trim() + toDate.trim() + ".html";
}
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[23][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT InvoiceNumber, InvoiceTotal, Discount FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate = '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
} else {
sql +=
" OrderDate >= '" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate <= '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
}
sql += " Order By 1 ";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totOverseasPrice = 0;
double totOverseasSoldPrice = 0;
double totLocalPrice = 0;
double totLocalSoldPrice = 0;
double totTotalPrice = 0;
double totTotalSoldPrice = 0;
double totMargin = 0;
double totPercent = 0;
int totLocalItems = 0;
int totOverseasItems = 0;
int totNoPriceItems = 0;
double totNoPriceItemsSoldPrice = 0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Analyzing Invoices For The Date " + toDate.trim();
} else {
mainHeading =
"Analyzing Invoices For The Dates From " + fromDate.trim() + " To " + toDate.trim();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Overseas Price");
subHeadings.addElement("Overseas Sold Price");
subHeadings.addElement("Local Price");
subHeadings.addElement("Local Sold Price");
subHeadings.addElement("Percent");
subHeadings.addElement("Remarks");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
int invoiceNo = rs.getInt(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
double overseasPrice = 0;
double overseasSoldPrice = 0;
double localPrice = 0;
double localSoldPrice = 0;
double percent = 0;
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
String overseasPriceStr = "";
String overseasSoldPriceStr = "";
String localPriceStr = "";
String localSoldPriceStr = "";
String percentStr = "";
String remarks = "";
InvoiceBean invoice = InvoiceBean.getInvoice(invoiceNo, con);
Vector<InvoiceDetailsBean> invoiceDetails = invoice.getInvoiceDetails();
if (invoiceDetails.size() != 0) {
Enumeration<InvoiceDetailsBean> ennum = invoiceDetails.elements();
while (ennum.hasMoreElements()) {
InvoiceDetailsBean invoiceDetailsBean = ennum.nextElement();
String partNo = invoiceDetailsBean.getPartNumber();
int qty = invoiceDetailsBean.getQuantity();
int remainItems = 0;
double price = invoiceDetailsBean.getSoldPrice();
int supplierId = 0;
String vendorInvNo = "";
LocalOrderBean orderBean =
LocalOrderBean.getLocalOrder(supplierId, invoiceNo, partNo, vendorInvNo, con);
if (invoiceDetailsBean.getActualPrice() != 0) {
if (orderBean != null) {
totLocalItems += qty;
localPrice += (invoiceDetailsBean.getActualPrice() * qty);
localSoldPrice += (price * qty);
} else {
totOverseasItems += qty;
overseasPrice += (invoiceDetailsBean.getActualPrice() * qty);
overseasSoldPrice += (price * qty);
}
} else {
if (orderBean != null) {
// Got this Part From Local Vendor
if (qty <= orderBean.getQuantity()) {
remainItems = orderBean.getQuantity() - qty;
totLocalItems += qty;
localPrice += (orderBean.getPrice() * qty);
localSoldPrice += (price * qty);
} else {
remainItems = qty - orderBean.getQuantity();
}
} else {
remainItems = qty;
}
if (remainItems != 0) {
// Got This Part From Overseas
PartsBean part = PartsBean.getPart(partNo, con);
if (part != null) {
if (part.getActualPrice() != 0) {
totOverseasItems += remainItems;
overseasPrice += (part.getActualPrice() * remainItems);
overseasSoldPrice += (price * remainItems);
} else if (!part.getInterchangeNo().trim().equals("")
&& PartsBean.getPart(part.getInterchangeNo(), con).getActualPrice() != 0) {
totOverseasItems += remainItems;
overseasPrice +=
(PartsBean.getPart(part.getInterchangeNo(), con).getActualPrice() * remainItems);
overseasSoldPrice += (price * remainItems);
} else {
Statement stmt1 = con.createStatement();
ResultSet rs1 =
stmt1
.executeQuery("Select PartNo, ActualPrice From Parts Where InterchangeNo='"
+ part.getPartNo() + "'");
double actPrice = 0;
while (rs1.next()) {
actPrice = rs1.getDouble("ActualPrice");
if (actPrice != 0) {
break;
}
}
if (actPrice != 0) {
totOverseasItems += remainItems;
overseasPrice += (actPrice * remainItems);
overseasSoldPrice += (price * remainItems);
} else {
totNoPriceItemsSoldPrice += (price * remainItems);
totNoPriceItems += remainItems;
remarks += "No Price:" + partNo + "\n";
}
}
// logger.error(overseasSoldPrice);
part = null;
} else {
remarks += "No Part:" + partNo + "\n";
}
}
}
invoiceDetailsBean = null;
orderBean = null;
}
invoice = null;
} else {
overseasPriceStr = "";
overseasSoldPriceStr = "";
localPriceStr = "";
localSoldPriceStr = "";
percentStr = "";
remarks = "No Items";
}
double totPrice = overseasPrice + localPrice;
double totSoldPrice = overseasSoldPrice + localSoldPrice;
if (totPrice != 0) {
totPrice = Double.parseDouble(NumberUtils.cutFractions(totPrice + ""));
}
if (totSoldPrice != 0) {
totSoldPrice = Double.parseDouble(NumberUtils.cutFractions(totSoldPrice + ""));
}
// if (totSoldPrice != invoiceTotal) {
// remarks += "Not Matching\n";
// }
if (totSoldPrice != 0) {
percent = (totSoldPrice - totPrice - discount) * 100 / totSoldPrice;
} else {
percent = 0;
}
if (remarks.trim().equals("")) {
remarks = " ";
}
percent = Math.rint(percent);
totInvoiceTotal += invoiceTotal;
totDiscount += discount;
if (overseasPrice != 0) {
totOverseasPrice += overseasPrice;
overseasPriceStr = overseasPrice + "";
} else {
overseasPriceStr = " ";
}
if (overseasSoldPrice != 0) {
totOverseasSoldPrice += overseasSoldPrice;
overseasSoldPriceStr = overseasSoldPrice + "";
} else {
overseasSoldPriceStr = " ";
}
if (localPrice != 0) {
totLocalPrice += localPrice;
localPriceStr = localPrice + "";
} else {
localPriceStr = " ";
}
if (localSoldPrice != 0) {
totLocalSoldPrice += localSoldPrice;
localSoldPriceStr = localSoldPrice + "";
} else {
localSoldPriceStr = " ";
}
if (percent != 0) {
percentStr = percent + "";
} else {
percentStr = " ";
}
if (overseasPriceStr.indexOf(".") == overseasPriceStr.length() - 2) {
overseasPriceStr += "0";
}
if (overseasSoldPriceStr.indexOf(".") == overseasSoldPriceStr.length() - 2) {
overseasSoldPriceStr += "0";
}
if (localPriceStr.indexOf(".") == localPriceStr.length() - 2) {
localPriceStr += "0";
}
if (localSoldPriceStr.indexOf(".") == localSoldPriceStr.length() - 2) {
localSoldPriceStr += "0";
}
overseasPriceStr = NumberUtils.cutFractions(overseasPriceStr);
overseasSoldPriceStr = NumberUtils.cutFractions(overseasSoldPriceStr);
localPriceStr = NumberUtils.cutFractions(localPriceStr);
localSoldPriceStr = NumberUtils.cutFractions(localSoldPriceStr);
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo + "");
totData.put("Inv. Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Overseas Price", overseasPriceStr);
totData.put("Overseas Sold Price", overseasSoldPriceStr);
totData.put("Local Price", localPriceStr);
totData.put("Local Sold Price", localSoldPriceStr);
totData.put("Percent", percentStr);
totData.put("Remarks", remarks);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No Sales For This Period ");
}
// String totInvoiceTotalStr = totInvoiceTotal+"";
String totDiscountStr = totDiscount + "";
String netTotal = totInvoiceTotal - totDiscount + "";
// logger.error("TotOverseasPrice10: " + totOverseasPrice);
String totOverseasPriceStr = totOverseasPrice + "";
// logger.error("TotOverseasPriceStr10: " +
// totOverseasPriceStr);
String totOverseasSoldPriceStr = totOverseasSoldPrice + "";
String totLocalPriceStr = totLocalPrice + "";
String totLocalSoldPriceStr = totLocalSoldPrice + "";
String totPriceStr = "";
String totSoldPriceStr = "";
String overseasMarginStr = "";
String overseasPercentStr = "";
String localMarginStr = "";
String localPercentStr = "";
String totMarginStr = "";
String totPercentStr = "";
String totNoPriceItemsSoldPriceStr = "";
double overseasMargin = 0;
double overseasPercent = 0;
double localMargin = 0;
double localPercent = 0;
totTotalPrice = totOverseasPrice + totLocalPrice;
totTotalSoldPrice = totOverseasSoldPrice + totLocalSoldPrice + totNoPriceItemsSoldPrice;
overseasMargin = totOverseasSoldPrice - totOverseasPrice;
localMargin = totLocalSoldPrice - totLocalPrice;
if (totOverseasSoldPrice != 0) {
overseasPercent = overseasMargin * 100 / totOverseasSoldPrice;
} else {
overseasPercent = 0;
}
if (totLocalSoldPrice != 0) {
localPercent = localMargin * 100 / totLocalSoldPrice;
} else {
localPercent = 0;
}
overseasPercent = Math.rint(overseasPercent);
localPercent = Math.rint(localPercent);
totMargin = totTotalSoldPrice - totDiscount - totTotalPrice;
if (totOverseasSoldPrice + totLocalSoldPrice != 0) {
totPercent = (totMargin * 100) / (totOverseasSoldPrice + totLocalSoldPrice);
} else {
totPercent = 0;
}
totPercent = Math.rint(totPercent);
totPriceStr = totTotalPrice + "";
totSoldPriceStr = totTotalSoldPrice + "";
totNoPriceItemsSoldPriceStr = totNoPriceItemsSoldPrice + "";
overseasMarginStr = overseasMargin + "";
localMarginStr = localMargin + "";
if (overseasPercent != 0) {
overseasPercentStr = overseasPercent + "";
} else {
overseasPercentStr = " ";
}
if (localPercent != 0) {
localPercentStr = localPercent + "";
} else {
localPercentStr = " ";
}
totMarginStr = totMargin + "";
if (totPercent != 0) {
totPercentStr = totPercent + "";
} else {
totPercentStr = " ";
}
// if (totInvoiceTotalStr.indexOf(".") ==
// totInvoiceTotalStr.length()-2) {
// totInvoiceTotalStr += "0";
// }
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (netTotal.indexOf(".") == netTotal.length() - 2) {
netTotal += "0";
}
if (totLocalPriceStr.indexOf(".") == totLocalPriceStr.length() - 2) {
totLocalPriceStr += "0";
}
if (totLocalSoldPriceStr.indexOf(".") == totLocalSoldPriceStr.length() - 2) {
totLocalSoldPriceStr += "0";
}
if (localMarginStr.indexOf(".") == localMarginStr.length() - 2) {
localMarginStr += "0";
}
if (totOverseasPriceStr.indexOf(".") == totOverseasPriceStr.length() - 2) {
totOverseasPriceStr += "0";
}
if (totOverseasSoldPriceStr.indexOf(".") == totOverseasSoldPriceStr.length() - 2) {
totOverseasSoldPriceStr += "0";
}
if (overseasMarginStr.indexOf(".") == overseasMarginStr.length() - 2) {
overseasMarginStr += "0";
}
if (totPriceStr.indexOf(".") == totPriceStr.length() - 2) {
totPriceStr += "0";
}
if (totSoldPriceStr.indexOf(".") == totSoldPriceStr.length() - 2) {
totSoldPriceStr += "0";
}
if (totMarginStr.indexOf(".") == totMarginStr.length() - 2) {
totMarginStr += "0";
}
if (totNoPriceItemsSoldPriceStr.indexOf(".") == totNoPriceItemsSoldPriceStr.length() - 2) {
totNoPriceItemsSoldPriceStr += "0";
}
totLocalPriceStr = NumberUtils.cutFractions(totLocalPriceStr);
totLocalSoldPriceStr = NumberUtils.cutFractions(totLocalSoldPriceStr);
localMarginStr = NumberUtils.cutFractions(localMarginStr);
totOverseasPriceStr = NumberUtils.cutFractions(totOverseasPriceStr);
totOverseasSoldPriceStr = NumberUtils.cutFractions(totOverseasSoldPriceStr);
overseasMarginStr = NumberUtils.cutFractions(overseasMarginStr);
totPriceStr = NumberUtils.cutFractions(totPriceStr);
totSoldPriceStr = NumberUtils.cutFractions(totSoldPriceStr);
totMarginStr = NumberUtils.cutFractions(totMarginStr);
totNoPriceItemsSoldPriceStr = NumberUtils.cutFractions(totNoPriceItemsSoldPriceStr);
// totInvoiceTotalStr =
// NumberUtils.cutFractions(totInvoiceTotalStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
netTotal = NumberUtils.cutFractions(netTotal);
totals[0][0] = "Total No. Of Items Bought Locally";
totals[0][1] = totLocalItems + "";
totals[1][0] = "Local Price";
totals[1][1] = totLocalPriceStr;
totals[2][0] = "Our Sold Price";
totals[2][1] = totLocalSoldPriceStr;
totals[3][0] = "Margin On Local Items";
totals[3][1] = localMarginStr;
totals[4][0] = "Percentage of Margin";
totals[4][1] = localPercentStr + " %";
totals[5][0] = " ";
totals[5][1] = " ";
totals[6][0] = " ";
totals[6][1] = " ";
totals[7][0] = "Total No. Of Items Bought From Overseas";
totals[7][1] = totOverseasItems + "";
totals[8][0] = "Overseas Price";
totals[8][1] = totOverseasPriceStr;
totals[9][0] = "Our Sold Price";
totals[9][1] = totOverseasSoldPriceStr;
totals[10][0] = "Margin On Overseas Items";
totals[10][1] = overseasMarginStr;
totals[11][0] = "Percentage of Margin";
totals[11][1] = overseasPercentStr + " %";
totals[12][0] = " ";
totals[12][1] = " ";
totals[13][0] = " ";
totals[13][1] = " ";
totals[14][0] = "Items With No Price";
totals[14][1] = totNoPriceItems + "";
totals[15][0] = "No Price Items Sold Price";
totals[15][1] = totNoPriceItemsSoldPriceStr + "";
totals[16][0] = " ";
totals[16][1] = " ";
totals[17][0] = "Total No. Of Items";
totals[17][1] = totLocalItems + totOverseasItems + totNoPriceItems + "";
totals[18][0] = "Total Price";
totals[18][1] = totPriceStr;
totals[19][0] = "Total Sold Price";
totals[19][1] = totSoldPriceStr;
totals[20][0] = "Total Discount Given";
totals[20][1] = totDiscountStr;
totals[21][0] = "Margin On All Items";
totals[21][1] = totMarginStr;
totals[22][0] = "Percentage of Margin";
totals[22][1] = totPercentStr + " %";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
logger.error(e);
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable inventoryOnHand(UserBean user, boolean bySubCat) throws UserException {
Hashtable toShowInven = null;
try {
String fileName = "ShowInven" + DateUtils.getNewUSDate() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[4][2];
mainHeading = "Inventory On Hand On " + DateUtils.getNewUSDate();
subHeadings.addElement("CATEGORY");
subHeadings.addElement("No. Of Parts");
subHeadings.addElement("No. Of Items");
subHeadings.addElement("COST");
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql1 =
"SELECT c.CategoryName, COUNT(*), SUM(UnitsInStock), sum(UnitsInStock*ActualPrice) FROM Parts a, SubCategory b, Category c WHERE ";
sql1 +=
" UnitsInStock > 0 and a.SubCategory=b.SubCategoryCode and b.CategoryCode=c.CategoryCode Group By 1 Order By 1 ";
String sql2 =
"SELECT b.SubCategoryName, COUNT(*), SUM(UnitsInStock), sum(UnitsInStock*ActualPrice) FROM Parts a, SubCategory b WHERE ";
sql2 += " UnitsInStock > 0 and a.SubCategory=b.SubCategoryCode Group By 1 Order By 1 ";
// logger.error(sql);
ResultSet rs = null;
if (bySubCat) {
rs = stmt.executeQuery(sql2);
} else {
rs = stmt.executeQuery(sql1);
}
int cntCat = 0;
int totItems = 0;
int totUnits = 0;
double totCost = 0.0;
while (rs.next()) {
if (toShowInven == null) {
toShowInven = new Hashtable();
}
String cat = rs.getString(1);
int noItems = rs.getInt(2);
int noUnits = rs.getInt(3);
double cost = rs.getDouble(4);
cntCat++;
totItems += noItems;
totUnits += noUnits;
totCost += cost;
String totCostStr = cost + "";
if (totCostStr.indexOf(".") == totCostStr.length() - 2) {
totCostStr += "0";
}
totCostStr = NumberUtils.cutFractions(totCostStr);
Hashtable totData = new Hashtable();
totData.put("CATEGORY", cat);
totData.put("No. Of Parts", noItems + "");
totData.put("No. Of Items", noUnits + "");
totData.put("COST", totCostStr);
data.addElement(totData);
}
String totActualStr = totCost + "";
if (totActualStr.indexOf(".") == totActualStr.length() - 2) {
totActualStr += "0";
}
totActualStr = NumberUtils.cutFractions(totActualStr);
totals[0][0] = "No Of Categories";
totals[0][1] = cntCat + "";
totals[1][0] = "Total No. Of Parts";
totals[1][1] = totItems + "";
totals[2][0] = "total No. Of Units";
totals[2][1] = totUnits + "";
totals[3][0] = "Total Cost Of Inventory";
totals[3][1] = totActualStr;
toShowInven.put("FileName", fileName);
toShowInven.put("BackScreen", "TodaysOrders");
toShowInven.put("MainHeading", mainHeading);
toShowInven.put("SubHeadings", subHeadings);
toShowInven.put("Data", data);
toShowInven.put("Totals", totals);
createReport(toShowInven);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInven;
}
public static String findCOGIByOrderDate(UserBean user, String fromDate,
String toDate) throws UserException {
if (!user.getRole().trim().equalsIgnoreCase("High")) {
throw new UserException(
"YOU ARE NOT AUTHORIZED TO VIEW THIS REPORT");
}
List<InvoiceDetailsOurPrice> missingourpricelist =
UpdateOurPrice.getMissingOurPrice("");
if (missingourpricelist.size() > 0) {
UpdateOurPrice.updateOurPrices(missingourpricelist, "");
}
Connection conn = null;
Statement pstmt = null;
ResultSet rs = null;
StringBuilder totals = new StringBuilder();
try {
conn = DBInterfaceLocal.getSQLConnection();
String findcogiSql = "select i.InvoiceNumber,i.Discount, SUM(id.SoldPrice*Quantity) as invTotal,SUM(id.ActualPrice*Quantity) as ourPrice"
+ ",SUM(Quantity) as TotalItems from invoice i, invoicedetails id "
+ " WHERE i.InvoiceNumber = id.InvoiceNumber AND i.OrderDate BETWEEN '"
+ DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' "
+ "AND '"
+ DateUtils.convertUSToMySQLFormat(toDate.trim())
+ "'"
+ " and id.ActualPrice > 0 GROUP BY InvoiceNumber Having invTotal > 0 Order By i.InvoiceNumber DESC";
System.err.println("find sql----" + findcogiSql);
pstmt = conn.createStatement();
rs = pstmt.executeQuery(findcogiSql);
int totalItems = 0;
BigDecimal totalDiscount = new BigDecimal(0);
BigDecimal totalInvTotal = new BigDecimal(0);
BigDecimal totalOurPrice = new BigDecimal(0);
BigDecimal totalMargin = new BigDecimal(0);
totalMargin.setScale(2,RoundingMode.HALF_EVEN);
double discount = 0, invTotal = 0, ourPrice = 0, margin = 0;
StringBuilder sbOuter = new StringBuilder();
sbOuter.append("<TR><TD align='Center' ><TABLE border='1'><TBODY><TR>");
sbOuter.append("<TH width='100'>Inv. No.</TH><TH>Inv. Total</TH><TH>Discount</TH><TH>Our Cost</TH><TH>Margin</TH></TR>");
while (rs.next()) {
discount = rs.getDouble("Discount");
invTotal = rs.getDouble("invTotal");
ourPrice = rs.getDouble("ourPrice");
margin = new BigDecimal((invTotal - ourPrice - discount)).setScale(2,RoundingMode.HALF_EVEN).doubleValue();
StringBuilder sbInner = new StringBuilder();
sbInner.append("<TR>");
sbInner.append("<TD>");
sbInner.append(rs.getString("InvoiceNumber"));
sbInner.append("</TD>");
sbInner.append("<TD>");
sbInner.append( invTotal );
sbInner.append("</TD>");
sbInner.append("<TD>" );
sbInner.append( discount );
sbInner.append( "</TD>");
sbInner.append("<TD>" );
sbInner.append(ourPrice);
sbInner.append( "</TD>");
sbInner.append("<TD>");
sbInner.append( margin );
sbInner.append( "</TD>");
sbInner.append("</TR>");
sbOuter.append(sbInner);
totalItems += rs.getInt("TotalItems");
totalDiscount = totalDiscount.add(new BigDecimal(discount));
totalInvTotal = totalInvTotal.add(new BigDecimal(invTotal));
totalOurPrice = totalOurPrice.add(new BigDecimal(ourPrice));
totalMargin = totalMargin.add(new BigDecimal(margin));
}
double totPercent = (totalMargin.doubleValue()*100) /(totalInvTotal.doubleValue()) ;
totals.append("<TR><TD align='Right' ><TABLE>");
totals.append("<TR>");
totals.append("<TD><B>Total No. Of Items</B></TD>");
totals.append("<TD><B>" + totalItems + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Total Price</B></TD>");
totals.append("<TD><B>" + totalOurPrice.setScale(2,RoundingMode.HALF_EVEN).doubleValue() + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Total Sold Price</B></TD>");
totals.append("<TD><B>" + totalInvTotal.setScale(2,RoundingMode.HALF_EVEN).doubleValue() + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Total Discount Given</B></TD>");
totals.append("<TD><B>" + totalDiscount.setScale(2,RoundingMode.HALF_EVEN).doubleValue() + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Margin On All Items</B></TD>");
totals.append("<TD><B>" + totalMargin.setScale(2,RoundingMode.HALF_EVEN).doubleValue() + "</B></TD>");
totals.append("</TR><TR>");
totals.append("<TD><B>Percentage of Margin</B></TD>");
totals.append("<TD><B>" +Math.rint( totPercent) + "%</B></TD>");
totals.append("</TR>");
totals.append("</TABLE></TD></TR>");
totals.append(sbOuter);
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
return totals.toString();
}
public static Hashtable costOfGoodsInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
if (!user.getRole().trim().equalsIgnoreCase("High")) {
throw new UserException("YOU ARE NOT AUTHORIZED TO VIEW THIS REPORT");
}
String fileName = "";
if (fromDate.trim().equals(toDate.trim())) {
fileName = "COGS" + fromDate.trim() + ".html";
} else {
fileName = "COGS" + fromDate.trim() + toDate.trim() + ".html";
}
//
String targetdDB = "CH";
List<InvoiceDetailsOurPrice> missingourpricelist = UpdateOurPrice.getMissingOurPrice(targetdDB);
System.err.println("****"+missingourpricelist.size());
if(missingourpricelist!=null && missingourpricelist.size() > 0)
UpdateOurPrice.updateOurPrices(missingourpricelist, targetdDB);
//
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[8][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT InvoiceNumber, InvoiceTotal, Discount FROM Invoice WHERE ";
if (fromDate.trim().equals(toDate.trim())) {
sql += " OrderDate = '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
} else {
sql +=
" OrderDate >= '" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate <= '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
}
sql += " Order By 1 ";
logger.error(" Before calling query...");
ResultSet rs = stmt.executeQuery(sql);
logger.error(" After calling query..." + rs.getFetchSize());
//double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totInvoicePrice = 0;
double totInvoiceSoldPrice = 0;
double totTotalSoldPrice = 0;
double totMargin = 0;
double totPercent = 0;
int totItems = 0;
double invoicePrice = 0;
double invoiceSoldPrice = 0;
double margin = 0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Cost Of Goods Report For The Date " + toDate.trim();
} else {
mainHeading =
"Cost Of Goods Report For The Dates From " + fromDate.trim() + " To " + toDate.trim();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Our Cost");
subHeadings.addElement("Sold Price");
subHeadings.addElement("Margin");
subHeadings.addElement("Remarks");
logger.error(" Before processing of invoice...");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
int invoiceNo = rs.getInt(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
String invoiceTotalStr = invoiceTotal + "";
String discountStr = discount + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr += "0";
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
StringBuilder invoicePriceStr = new StringBuilder();
StringBuilder invoiceSoldPriceStr = new StringBuilder();
StringBuilder marginStr = new StringBuilder();
StringBuilder remarks = new StringBuilder();
// logger.error(" Before calling invoce bean ... ");
InvoiceBean invoice =new InvoiceBean();
invoice.setInvoiceNumber(rs.getInt("InvoiceNumber"));
invoice.setDiscount(rs.getDouble("Discount"));
invoice.setInvoiceTotal(rs.getDouble("InvoiceTotal"));
// logger.error(" After calling invoce bean ... ");
InvoiceDetailsBean invoiceDet=InvoiceDetailsBean.getInvoiceTotalDetails(con,invoiceNo);
totItems += invoiceDet.getTotalItems();
invoicePrice = invoiceDet.getTotalOurPrice();
invoiceSoldPrice = invoiceDet.getTotalSoldPrice();
if (invoicePrice != 0) {
invoicePrice = Double.parseDouble(NumberUtils.cutFractions(invoicePrice + ""));
}
if (invoiceSoldPrice != 0) {
invoiceSoldPrice = Double.parseDouble(NumberUtils.cutFractions(invoiceSoldPrice + ""));
}
if (invoiceSoldPrice != 0) {
margin = (invoiceSoldPrice - invoicePrice - discount);
} else {
margin = 0;
}
if (remarks.toString().equals("")) {
remarks.append( " ");
}
//if needed uncomment it
//totInvoiceTotal += invoiceTotal;
totDiscount += discount;
if (invoicePrice != 0) {
totInvoicePrice += invoicePrice;
invoicePriceStr.append( invoicePrice );
} else {
invoicePriceStr.append(" ");
}
if (invoiceSoldPrice != 0) {
totInvoiceSoldPrice += invoiceSoldPrice;
invoiceSoldPriceStr.append( invoiceSoldPrice );
} else {
invoiceSoldPriceStr.append( " ");
}
if (margin != 0) {
marginStr.append( margin );
} else {
marginStr.append( " ");
}
if (invoicePriceStr.indexOf(".") == invoicePriceStr.length() - 2) {
invoicePriceStr.append( "0");
}
if (invoiceSoldPriceStr.indexOf(".") == invoiceSoldPriceStr.length() - 2) {
invoiceSoldPriceStr.append( "0");
}
if (marginStr.indexOf(".") == marginStr.length() - 2) {
marginStr.append( "0");
}
invoicePriceStr = new StringBuilder( NumberUtils.cutFractions(invoicePriceStr.toString()));
invoiceSoldPriceStr = new StringBuilder( NumberUtils.cutFractions(invoiceSoldPriceStr.toString() ));
marginStr = new StringBuilder(NumberUtils.cutFractions(marginStr.toString()));
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo + "");
totData.put("Inv. Total", invoiceTotalStr);
totData.put("Discount", discountStr);
totData.put("Our Cost", invoicePriceStr.toString());
totData.put("Sold Price", invoiceSoldPriceStr.toString());
totData.put("Margin", marginStr.toString());
totData.put("Remarks", remarks.toString());
data.addElement(totData);
}
logger.error(" After processing of invoice...");
if (toShowInvoices == null) {
throw new UserException(" No Sales For This Period ");
}
String totDiscountStr = totDiscount + "";
String totPriceStr ;
String totSoldPriceStr ;
String totMarginStr ;
String totPercentStr ;
//totTotalPrice = totInvoicePrice;
totTotalSoldPrice = totInvoiceSoldPrice;
totMargin = totTotalSoldPrice - totDiscount - totInvoicePrice;
if (totTotalSoldPrice != 0) {
totPercent = (totMargin * 100) / (totTotalSoldPrice);
} else {
totPercent = 0;
}
totPercent = Math.rint(totPercent);
totPriceStr = totInvoicePrice + "";
totSoldPriceStr = totTotalSoldPrice + "";
totMarginStr = totMargin + "";
if (totPercent != 0) {
totPercentStr = totPercent + "";
} else {
totPercentStr = " ";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totPriceStr.indexOf(".") == totPriceStr.length() - 2) {
totPriceStr += "0";
}
if (totSoldPriceStr.indexOf(".") == totSoldPriceStr.length() - 2) {
totSoldPriceStr += "0";
}
if (totMarginStr.indexOf(".") == totMarginStr.length() - 2) {
totMarginStr += "0";
}
totPriceStr = NumberUtils.cutFractions(totPriceStr);
totSoldPriceStr = NumberUtils.cutFractions(totSoldPriceStr);
totMarginStr = NumberUtils.cutFractions(totMarginStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totals[0][0] = " ";
totals[0][1] = " ";
totals[1][0] = " ";
totals[1][1] = " ";
totals[2][0] = "Total No. Of Items";
totals[2][1] = totItems + "";
totals[3][0] = "Total Price";
totals[3][1] = totPriceStr;
totals[4][0] = "Total Sold Price";
totals[4][1] = totSoldPriceStr;
totals[5][0] = "Total Discount Given";
totals[5][1] = totDiscountStr;
totals[6][0] = "Margin On All Items";
totals[6][1] = totMarginStr;
totals[7][0] = "Percentage of Margin";
totals[7][1] = totPercentStr + " %";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
logger.error(e);
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
/*
public static int updateTotals(String sqlwhere){
int resultcount=0;
try{
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
resultcount= stmt.executeUpdate("update invoice v set " +
"sumSoldPrice=(select sum(SoldPrice*Quantity)from invoicedetails where InvoiceNumber=v.InvoiceNumber ) " +
" , sumQty=(select sum(Quantity) from invoicedetails where InvoiceNumber=v.InvoiceNumber ) ," +
" sumActualPrice=(select sum(ActualPrice*Quantity) from invoicedetails where InvoiceNumber=v.InvoiceNumber )" +
" "+sqlwhere);
}catch(SQLException ex){
ex.printStackTrace();
}
return resultcount;
}
public static Hashtable costOfGoodsInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
if (!user.getRole().trim().equalsIgnoreCase("High")) {
throw new UserException("YOU ARE NOT AUTHORIZED TO VIEW THIS REPORT");
}
String fileName = "";
if (fromDate.trim().equals(toDate.trim())) {
fileName = "COGS" + fromDate.trim() + ".html";
} else {
fileName = "COGS" + fromDate.trim() + toDate.trim() + ".html";
}
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[8][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT InvoiceNumber, InvoiceTotal, Discount,sumActualPrice,sumSoldPrice,sumQty FROM Invoice ";
String sqlWhere="";
if (fromDate.trim().equals(toDate.trim())) {
sqlWhere += " where OrderDate = '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
} else {
sqlWhere +=
" where OrderDate >= '" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' AND OrderDate <= '" + DateUtils.convertUSToMySQLFormat(toDate.trim()) + "' ";
}
sql = sql+sqlWhere+ " Order By 1 ";
updateTotals(sqlWhere);
logger.error(" Before calling query...");
ResultSet rs = stmt.executeQuery(sql);
logger.error(" After calling query..." + rs.getFetchSize());
//double totInvoiceTotal = 0.0;
double totDiscount = 0.0;
double totInvoicePrice = 0;
double totInvoiceSoldPrice = 0;
double totTotalPrice = 0;
double totTotalSoldPrice = 0;
double totMargin = 0;
double totPercent = 0;
int totItems = 0;
if (fromDate.trim().equals(toDate.trim())) {
mainHeading = "Cost Of Goods Report For The Date " + toDate.trim();
} else {
mainHeading =
"Cost Of Goods Report For The Dates From " + fromDate.trim() + " To " + toDate.trim();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Total");
subHeadings.addElement("Discount");
subHeadings.addElement("Our Cost");
subHeadings.addElement("Sold Price");
subHeadings.addElement("Margin");
subHeadings.addElement("Remarks");
logger.error(" Before processing of invoice...");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
int invoiceNo = rs.getInt(1);
double invoiceTotal = rs.getDouble(2);
double discount = rs.getDouble(3);
double totSoldPrice =rs.getDouble("sumSoldPrice");
double totPrice = rs.getDouble("sumActualPrice");
double sumQty = rs.getDouble("sumQty");
totItems+=sumQty;
double margin = 0;
StringBuilder invoiceTotalStr = new StringBuilder();
invoiceTotalStr.append(invoiceTotal + "");
String discountStr = discount + "";
if (invoiceTotalStr.indexOf(".") == invoiceTotalStr.length() - 2) {
invoiceTotalStr.append("0");
}
if (discountStr.indexOf(".") == discountStr.length() - 2) {
discountStr += "0";
}
StringBuilder invoicePriceStr = new StringBuilder();
StringBuilder invoiceSoldPriceStr = new StringBuilder();
StringBuilder marginStr = new StringBuilder();
StringBuilder remarks = new StringBuilder();
// logger.error(" Before calling invoce bean ... ");
// double totPrice = invoicePrice;
//double totSoldPrice = invoiceSoldPrice;
if (totPrice != 0) {
totPrice = Double.parseDouble(NumberUtils.cutFractions(totPrice + ""));
}
if (totSoldPrice != 0) {
totSoldPrice = Double.parseDouble(NumberUtils.cutFractions(totSoldPrice + ""));
}
if (totSoldPrice != 0) {
margin = totSoldPrice - totPrice - discount;
}
if (remarks.toString().equals("")) {
remarks = new StringBuilder(" ");
}
//totInvoiceTotal += invoiceTotal;
totDiscount += discount;
if (totPrice != 0) {
totInvoicePrice += totPrice;
invoicePriceStr.append( totPrice );
} else {
invoicePriceStr.append( " " );
}
if (totSoldPrice != 0) {
totInvoiceSoldPrice += totSoldPrice;
invoiceSoldPriceStr.append( totSoldPrice );
} else {
invoiceSoldPriceStr.append( " ");
}
if (margin != 0) {
marginStr.append( margin );
} else {
marginStr.append( " ");
}
if (invoicePriceStr.indexOf(".") == invoicePriceStr.length() - 2) {
invoicePriceStr.append( "0");
}
if (invoiceSoldPriceStr.indexOf(".") == invoiceSoldPriceStr.length() - 2) {
invoiceSoldPriceStr.append("0");
}
if (marginStr.indexOf(".") == marginStr.length() - 2) {
marginStr.append( "0" );
}
// invoicePriceStr = NumberUtils.cutFractions(invoicePriceStr);
// invoiceSoldPriceStr = NumberUtils.cutFractions(invoiceSoldPriceStr);
// marginStr = NumberUtils.cutFractions(marginStr);
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo + "");
totData.put("Inv. Total", invoiceTotalStr.toString());
totData.put("Discount", discountStr);
totData.put("Our Cost", invoicePriceStr.toString());
totData.put("Sold Price", invoiceSoldPriceStr.toString());
totData.put("Margin", marginStr.toString());
totData.put("Remarks", remarks.toString());
data.addElement(totData);
}
logger.error(" After processing of invoice...");
if (toShowInvoices == null) {
throw new UserException(" No Sales For This Period ");
}
String totDiscountStr = totDiscount + "";
String totPriceStr = "";
String totSoldPriceStr = "";
String totMarginStr = "";
String totPercentStr = "";
totTotalPrice = totInvoicePrice;
totTotalSoldPrice = totInvoiceSoldPrice;
totMargin = totTotalSoldPrice - totDiscount - totTotalPrice;
if (totTotalSoldPrice != 0) {
totPercent = (totMargin * 100) / (totTotalSoldPrice);
} else {
totPercent = 0;
}
totPercent = Math.rint(totPercent);
totPriceStr = totTotalPrice + "";
totSoldPriceStr = totTotalSoldPrice + "";
totMarginStr = totMargin + "";
if (totPercent != 0) {
totPercentStr = totPercent + "";
} else {
totPercentStr = " ";
}
if (totDiscountStr.indexOf(".") == totDiscountStr.length() - 2) {
totDiscountStr += "0";
}
if (totPriceStr.indexOf(".") == totPriceStr.length() - 2) {
totPriceStr += "0";
}
if (totSoldPriceStr.indexOf(".") == totSoldPriceStr.length() - 2) {
totSoldPriceStr += "0";
}
if (totMarginStr.indexOf(".") == totMarginStr.length() - 2) {
totMarginStr += "0";
}
totPriceStr = NumberUtils.cutFractions(totPriceStr);
totSoldPriceStr = NumberUtils.cutFractions(totSoldPriceStr);
totMarginStr = NumberUtils.cutFractions(totMarginStr);
totDiscountStr = NumberUtils.cutFractions(totDiscountStr);
totals[0][0] = " ";
totals[0][1] = " ";
totals[1][0] = " ";
totals[1][1] = " ";
totals[2][0] = "Total No. Of Items";
totals[2][1] = totItems + "";
totals[3][0] = "Total Price";
totals[3][1] = totPriceStr;
totals[4][0] = "Total Sold Price";
totals[4][1] = totSoldPriceStr;
totals[5][0] = "Total Discount Given";
totals[5][1] = totDiscountStr;
totals[6][0] = "Margin On All Items";
totals[6][1] = totMarginStr;
totals[7][0] = "Percentage of Margin";
totals[7][1] = totPercentStr + " %";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
logger.error(e);
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
*/
public static Hashtable<String, String> detailedReceivable() throws UserException {
long tt = System.currentTimeMillis();
Hashtable toShowAR = null;
try {
// select customerid, sum(balance) from invoice group by customerid
// order by 2 desc
String fileName = "DR" + DateUtils.getNewUSDate().trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[12][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"select a.customerid, b.companyname, sum(a.balance), b.PaymentTerms from invoice a, customer b where a.balance!=0 and a.Status!='C' and a.Status!='W' and a.customerid=b.customerid group by a.customerid order by 3 desc";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
int totCustPending = 0;
double totBalance = 0.0;
double totalSplitBalance = 0.0;
double totalCurrent = 0.0;
double total30Days = 0.0;
double total60Days = 0.0;
double total90Days = 0.0;
double totBCAmt = 0.0;
mainHeading = "Ageing Accounts Receivable As On " + DateUtils.getNewUSDate();
subHeadings.addElement("ID");
subHeadings.addElement("Customer");
subHeadings.addElement("Terms");
subHeadings.addElement("Total");
subHeadings.addElement("Current");
subHeadings.addElement("30 Days");
subHeadings.addElement("60 Days");
subHeadings.addElement("90 Days");
subHeadings.addElement("BC Chks");
Statement stmtXX = con.createStatement();
String sqlXX =
"Select CustomerId, Sum(Balance) From BouncedChecks Where Balance!=0 Group By CustomerId Order By 1 ";
Hashtable<String, String> bcChecks = null;
ResultSet rsXX = stmtXX.executeQuery(sqlXX);
while (rsXX.next()) {
if (bcChecks == null) {
bcChecks = new Hashtable<String, String>();
}
String cstId = rsXX.getString(1);
String bcAmt = rsXX.getString(2);
bcChecks.put(cstId, bcAmt);
}
while (rs.next()) {
if (toShowAR == null) {
toShowAR = new Hashtable();
}
String custId = rs.getString(1);
// logger.error("Detail:" + custId);
String companyName = rs.getString(2);
double pendingAmount = rs.getDouble(3);
String terms = rs.getString(4);
String bcAmtStr = "";
if (terms == null) {
terms = " ";
} else if (terms.trim().equals("")) {
terms = " ";
} else if (terms.trim().equalsIgnoreCase("C")) {
terms = "Cod";
} else if (terms.trim().equalsIgnoreCase("O")) {
terms = "Cash";
} else if (terms.trim().equalsIgnoreCase("W")) {
terms = "Wkly";
} else if (terms.trim().equalsIgnoreCase("B")) {
terms = "Bi-Wk";
} else if (terms.trim().equalsIgnoreCase("M")) {
terms = "Mthly";
}
/*
* Vector v = BouncedChecksBean.getAllBouncedChecks(custId); if (v != null) { Enumeration
* ennumX = v.elements(); while (ennumX.hasMoreElements()) { BouncedChecksBean bcBean =
* (BouncedChecksBean) ennumX.nextElement(); pendingAmount += bcBean.getBouncedAmount(); } }
*/
if (bcChecks != null && bcChecks.get(custId) != null) {
bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
pendingAmount += Double.parseDouble(bcAmtStr);
}
if (pendingAmount == 0) {
continue;
} else {
totBalance += pendingAmount;
totCustPending++;
}
double curr = 0.0;
double x30days = 0.0;
double x60days = 0.0;
double x90days = 0.0;
String sql1 =
"select InvoiceNumber, OrderDate, Balance from invoice where balance!=0 and Status!='C' and Status!='W' and customerid='"
+ custId + "' order by OrderDate ";
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery(sql1);
while (rs1.next()) {
String orderDate = DateUtils.convertMySQLToUSFormat(rs1.getString(2));
double noOfDays = 0;
try {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date dd = sdf.parse(orderDate);
long timeDiff = System.currentTimeMillis() - dd.getTime();
noOfDays = Math.rint(timeDiff / 86400000);
// java.util.Date ddX = new java.util.Date(dd.getTime()
// + (1000 * 60 * 60 * 24 * (long)terms));
} catch (Exception e) {
logger.error(e.getMessage());
}
double bal = rs1.getDouble(3);
// logger.error(orderDate + "--" + noOfDays + "--" +
// bal);
if (noOfDays <= 30) {
curr += bal;
} else if (noOfDays <= 60) {
x30days += bal;
} else if (noOfDays <= 90) {
x60days += bal;
} else {
x90days += bal;
}
}
if (rs1 != null) {
rs1.close();
}
if (stmt1 != null) {
stmt1.close();
}
totalCurrent += curr;
total30Days += x30days;
total60Days += x60days;
total90Days += x90days;
if (!bcAmtStr.trim().equals("")) {
totBCAmt += Double.parseDouble(bcAmtStr);
} else {
bcAmtStr = " ";
}
String pendingAmountStr = pendingAmount + "";
String currStr = "";
String x30daysStr = "";
String x60daysStr = "";
String x90daysStr = "";
if (curr == 0) {
currStr = " ";
} else {
currStr = curr + "";
if (currStr.indexOf(".") == currStr.length() - 2) {
currStr += "0";
}
currStr = NumberUtils.cutFractions(currStr);
}
if (x30days == 0) {
x30daysStr = " ";
} else {
x30daysStr = x30days + "";
if (x30daysStr.indexOf(".") == x30daysStr.length() - 2) {
x30daysStr += "0";
}
x30daysStr = NumberUtils.cutFractions(x30daysStr);
}
if (x60days == 0) {
x60daysStr = " ";
} else {
x60daysStr = x60days + "";
if (x60daysStr.indexOf(".") == x60daysStr.length() - 2) {
x60daysStr += "0";
}
x60daysStr = NumberUtils.cutFractions(x60daysStr);
}
if (x90days == 0) {
x90daysStr = " ";
} else {
x90daysStr = x90days + "";
if (x90daysStr.indexOf(".") == x90daysStr.length() - 2) {
x90daysStr += "0";
}
x90daysStr = NumberUtils.cutFractions(x90daysStr);
}
if (pendingAmountStr.indexOf(".") == pendingAmountStr.length() - 2) {
pendingAmountStr += "0";
}
pendingAmountStr = NumberUtils.cutFractions(pendingAmountStr);
Hashtable totData = new Hashtable();
totData.put("ID", custId);
totData.put("Customer", companyName);
totData.put("Terms", terms);
totData.put("Total", pendingAmountStr);
totData.put("Current", currStr);
totData.put("30 Days", x30daysStr);
totData.put("60 Days", x60daysStr);
totData.put("90 Days", x90daysStr);
totData.put("BC Chks", bcAmtStr);
data.addElement(totData);
}
if (bcChecks != null && bcChecks.size() > 0) {
// logger.error("BC Checks Left: " + bcChecks.size());
Enumeration<String> ennum = bcChecks.keys();
while (ennum.hasMoreElements()) {
String cstId = ennum.nextElement();
double amt = Double.parseDouble(bcChecks.get(cstId));
totBCAmt += amt;
totBalance += amt;
Hashtable totData = new Hashtable();
totData.put("ID", cstId);
totData.put("Customer", CustomerBean.getCompanyName(cstId));
totData.put("Terms", " ");
totData.put("Total", amt + "");
totData.put("Current", " ");
totData.put("30 Days", " ");
totData.put("60 Days", " ");
totData.put("90 Days", " ");
totData.put("BC Chks", amt + "");
data.addElement(totData);
totCustPending++;
}
}
if (toShowAR == null) {
throw new UserException(" No Customers have Pending Balances ");
}
totalSplitBalance = totalCurrent + total30Days + total60Days + total90Days + totBCAmt;
String totBalanceStr = totBalance + "";
String totalSplitBalanceStr = totalSplitBalance + "";
String totalCurrentStr = totalCurrent + "";
String total30DaysStr = total30Days + "";
String total60DaysStr = total60Days + "";
String total90DaysStr = total90Days + "";
String totBCAmtStr = totBCAmt + "";
String currPercStr =
Math.rint(100 - ((totalSplitBalance - totalCurrent) * 100 / totalSplitBalance)) + "";
String x30DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total30Days) * 100 / totalSplitBalance)) + "";
String x60DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total60Days) * 100 / totalSplitBalance)) + "";
String x90DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total90Days) * 100 / totalSplitBalance)) + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
if (totalSplitBalanceStr.indexOf(".") == totalSplitBalanceStr.length() - 2) {
totalSplitBalanceStr += "0";
}
if (totalCurrentStr.indexOf(".") == totalCurrentStr.length() - 2) {
totalCurrentStr += "0";
}
if (total30DaysStr.indexOf(".") == total30DaysStr.length() - 2) {
total30DaysStr += "0";
}
if (total60DaysStr.indexOf(".") == total60DaysStr.length() - 2) {
total60DaysStr += "0";
}
if (total90DaysStr.indexOf(".") == total90DaysStr.length() - 2) {
total90DaysStr += "0";
}
if (totBCAmtStr.indexOf(".") == totBCAmtStr.length() - 2) {
totBCAmtStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
totalSplitBalanceStr = NumberUtils.cutFractions(totalSplitBalanceStr);
totalCurrentStr = NumberUtils.cutFractions(totalCurrentStr);
total30DaysStr = NumberUtils.cutFractions(total30DaysStr);
total60DaysStr = NumberUtils.cutFractions(total60DaysStr);
total90DaysStr = NumberUtils.cutFractions(total90DaysStr);
totBCAmtStr = NumberUtils.cutFractions(totBCAmtStr);
totals[0][0] = "Total No. Of Customers Have Payments ";
totals[0][1] = totCustPending + "";
totals[1][0] = "Total Payments Receivable ";
totals[1][1] = totBalanceStr;
totals[2][0] = "Total Split Payments Receivable ";
totals[2][1] = totalSplitBalanceStr;
totals[3][0] = "Current Payments ";
totals[3][1] = totalCurrentStr;
totals[4][0] = "% of Current ";
totals[4][1] = currPercStr;
totals[5][0] = "Over 30 Days Payments ";
totals[5][1] = total30DaysStr;
totals[6][0] = "% of 30 Days ";
totals[6][1] = x30DaysPercStr;
totals[7][0] = "Over 60 Days Payments ";
totals[7][1] = total60DaysStr;
totals[8][0] = "% of 60 Days ";
totals[8][1] = x60DaysPercStr;
totals[9][0] = "Over 90 Days Payments ";
totals[9][1] = total90DaysStr;
totals[10][0] = "% of 90 Days ";
totals[10][1] = x90DaysPercStr;
totals[11][0] = "Total Bounced Checks Amount ";
totals[11][1] = totBCAmtStr;
toShowAR.put("FileName", fileName);
toShowAR.put("BackScreen", "AcctMenu");
toShowAR.put("MainHeading", mainHeading);
toShowAR.put("SubHeadings", subHeadings);
toShowAR.put("Data", data);
toShowAR.put("Totals", totals);
createReport(toShowAR);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
tt = System.currentTimeMillis() - tt;
double xx = tt / (1000 * 60);
logger.error("AGEING RECEIVABLES TIME - OLDER VERSION:::" + xx + " Min");
return toShowAR;
}
public static Hashtable<String, String> detailedReceivableNew() throws UserException {
long tt = System.currentTimeMillis();
Hashtable toShowAR = null;
try {
// select customerid, sum(balance) from invoice group by customerid
// order by 2 desc
String fileName = "DR" + DateUtils.getNewUSDate().trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[12][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmtXX = con.createStatement();
String sqlXX =
"Select CustomerId, Sum(Balance) From BouncedChecks Where Balance!=0 Group By CustomerId Order By 1 ";
Hashtable<String, String> bcChecks = null;
ResultSet rsXX = stmtXX.executeQuery(sqlXX);
int noOfBCChecks = 0;
while (rsXX.next()) {
if (bcChecks == null) {
bcChecks = new Hashtable<String, String>();
}
String cstId = rsXX.getString(1);
String bcAmt = rsXX.getString(2);
bcChecks.put(cstId, bcAmt);
noOfBCChecks++;
}
Statement stmt = con.createStatement();
String sql =
"select count(distinct customerid) from invoice where balance!=0 and Status!='C' and Status!='W' ";
ResultSet rs = stmt.executeQuery(sql);
int noOfBalances = 0;
if (rs.next()) {
noOfBalances = rs.getInt(1);
}
String[][] list = new String[noOfBalances + noOfBCChecks][9];
double totBalance = 0.0;
double totalSplitBalance = 0.0;
double totalCurrent = 0.0;
double total30Days = 0.0;
double total60Days = 0.0;
double total90Days = 0.0;
double totBCAmt = 0.0;
mainHeading = "Ageing Accounts Receivable As On " + DateUtils.getNewUSDate();
subHeadings.addElement("ID");
subHeadings.addElement("Customer");
subHeadings.addElement("Terms");
subHeadings.addElement("Total");
subHeadings.addElement("Current");
subHeadings.addElement("30 Days");
subHeadings.addElement("60 Days");
subHeadings.addElement("90 Days");
subHeadings.addElement("BC Chks");
String sql1 =
"select a.CustomerId, b.CompanyName, b.PaymentTerms, a.OrderDate, a.Balance from invoice a, customer b where a.balance!=0 and a.Status!='C' and a.Status!='W' and a.customerid=b.customerId order by 1 ";
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery(sql1);
int cntBalances = 0;
double totalBalance = 0.0;
double curr = 0.0;
double x30days = 0.0;
double x60days = 0.0;
double x90days = 0.0;
String currCustId = "";
while (rs1.next()) {
String custId = rs1.getString(1);
String companyName = rs1.getString(2);
String terms = rs1.getString(3);
String orderDate = DateUtils.convertMySQLToUSFormat(rs1.getString(4));
// String orderDate = "2013-09-30";
double pendingAmount = rs1.getDouble(5);
double noOfDays = 0;
if (currCustId.trim().equals("")) {
currCustId = custId;
String bcAmtStr = "";
if (bcChecks != null && bcChecks.get(custId) != null) {
bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
double amt = Double.parseDouble(bcAmtStr);
totalBalance += amt;
totBCAmt += amt;
totBalance += amt;
}
list[cntBalances][0] = custId;
list[cntBalances][1] = companyName;
list[cntBalances][2] = terms;
list[cntBalances][8] = bcAmtStr;
} else if (currCustId.trim().equals(custId)) {
if (list[cntBalances][3] == null || list[cntBalances][3].trim().equals("")) {
totalBalance = 0.0;
} else {
totalBalance = Double.parseDouble(list[cntBalances][3]);
}
if (list[cntBalances][4] == null || list[cntBalances][4].trim().equals("")) {
curr = 0.0;
} else {
curr = Double.parseDouble(list[cntBalances][4]);
}
if (list[cntBalances][5] == null || list[cntBalances][5].trim().equals("")) {
x30days = 0.0;
} else {
x30days = Double.parseDouble(list[cntBalances][5]);
}
if (list[cntBalances][6] == null || list[cntBalances][6].trim().equals("")) {
x60days = 0.0;
} else {
x60days = Double.parseDouble(list[cntBalances][6]);
}
if (list[cntBalances][7] == null || list[cntBalances][7].trim().equals("")) {
x90days = 0.0;
} else {
x90days = Double.parseDouble(list[cntBalances][7]);
}
} else if (!currCustId.trim().equals(custId)) {
currCustId = custId;
cntBalances++;
totalBalance = 0;
curr = 0;
x30days = 0;
x60days = 0;
x90days = 0;
String bcAmtStr = "";
if (bcChecks != null && bcChecks.get(custId) != null) {
bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
double amt = Double.parseDouble(bcAmtStr);
totalBalance = amt;
totBCAmt += amt;
totBalance += amt;
}
list[cntBalances][0] = custId;
list[cntBalances][1] = companyName;
list[cntBalances][2] = terms;
list[cntBalances][8] = bcAmtStr;
}
try {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM-dd-yyyy");
java.util.Date dd = sdf.parse(orderDate);
long timeDiff = System.currentTimeMillis() - dd.getTime();
noOfDays = Math.rint(timeDiff / 86400000);
// java.util.Date ddX = new java.util.Date(dd.getTime() +
// (1000 * 60 * 60 * 24 * (long)terms));
} catch (Exception e) {
logger.error(e.getMessage());
}
double bal = pendingAmount;
// logger.error(orderDate + "--" + noOfDays + "--" + bal);
if (noOfDays <= 30) {
curr += bal;
totalCurrent += bal;
} else if (noOfDays <= 60) {
x30days += bal;
total30Days += bal;
} else if (noOfDays <= 90) {
x60days += bal;
total60Days += bal;
} else {
x90days += bal;
total90Days += bal;
}
totalBalance += bal;
totBalance += bal;
list[cntBalances][3] = totalBalance + "";
list[cntBalances][4] = curr + "";
list[cntBalances][5] = x30days + "";
list[cntBalances][6] = x60days + "";
list[cntBalances][7] = x90days + "";
}
if (bcChecks != null && bcChecks.size() > 0) {
// logger.error("BC Checks Left: " + bcChecks.size());
Enumeration<String> ennum = bcChecks.keys();
while (ennum.hasMoreElements()) {
String cstId = ennum.nextElement();
double amt = Double.parseDouble(bcChecks.get(cstId));
totBCAmt += amt;
totBalance += amt;
list[cntBalances][0] = cstId;
list[cntBalances][1] = CustomerBean.getCompanyName(cstId);
list[cntBalances][2] = " ";
list[cntBalances][3] = amt + "";
list[cntBalances][4] = "0";
list[cntBalances][5] = "0";
list[cntBalances][6] = "0";
list[cntBalances][7] = "0";
list[cntBalances][8] = amt + "";
cntBalances++;
}
}
int outCnt = 0;
int inCnt = 0;
for (outCnt = cntBalances - 1; outCnt > 1; outCnt--) {
for (inCnt = 0; inCnt < outCnt; inCnt++) {
if (Double.parseDouble(list[inCnt][3]) < Double.parseDouble(list[inCnt + 1][3])) {
String t0 = list[inCnt][0];
String t1 = list[inCnt][1];
String t2 = list[inCnt][2];
String t3 = list[inCnt][3];
String t4 = list[inCnt][4];
String t5 = list[inCnt][5];
String t6 = list[inCnt][6];
String t7 = list[inCnt][7];
String t8 = list[inCnt][8];
list[inCnt][0] = list[inCnt + 1][0];
list[inCnt][1] = list[inCnt + 1][1];
list[inCnt][2] = list[inCnt + 1][2];
list[inCnt][3] = list[inCnt + 1][3];
list[inCnt][4] = list[inCnt + 1][4];
list[inCnt][5] = list[inCnt + 1][5];
list[inCnt][6] = list[inCnt + 1][6];
list[inCnt][7] = list[inCnt + 1][7];
list[inCnt][8] = list[inCnt + 1][8];
list[inCnt + 1][0] = t0;
list[inCnt + 1][1] = t1;
list[inCnt + 1][2] = t2;
list[inCnt + 1][3] = t3;
list[inCnt + 1][4] = t4;
list[inCnt + 1][5] = t5;
list[inCnt + 1][6] = t6;
list[inCnt + 1][7] = t7;
list[inCnt + 1][8] = t8;
// swap(in, in+1);
// long temp = a[one];
// a[one] = a[two];
// a[two] = temp;
}
}
}
for (int i = 0; i < cntBalances; i++) {
if (toShowAR == null) {
toShowAR = new Hashtable();
}
String custId = list[i][0];
// logger.error("Detail:" + custId);
String companyName = list[i][1];
String terms = list[i][2];
double pendingAmount = Double.parseDouble(list[i][3]);
curr = Double.parseDouble(list[i][4]);
x30days = Double.parseDouble(list[i][5]);
x60days = Double.parseDouble(list[i][6]);
x90days = Double.parseDouble(list[i][7]);
String bcAmtStr = list[i][8];
if (terms == null) {
terms = " ";
} else if (terms.trim().equals("")) {
terms = " ";
} else if (terms.trim().equalsIgnoreCase("C")) {
terms = "Cod";
} else if (terms.trim().equalsIgnoreCase("O")) {
terms = "Cash";
} else if (terms.trim().equalsIgnoreCase("W")) {
terms = "Wkly";
} else if (terms.trim().equalsIgnoreCase("B")) {
terms = "Bi-Wk";
} else if (terms.trim().equalsIgnoreCase("M")) {
terms = "Mthly";
}
String pendingAmountStr = pendingAmount + "";
String currStr = "";
String x30daysStr = "";
String x60daysStr = "";
String x90daysStr = "";
if (curr == 0) {
currStr = " ";
} else {
currStr = curr + "";
if (currStr.indexOf(".") == currStr.length() - 2) {
currStr += "0";
}
currStr = NumberUtils.cutFractions(currStr);
}
if (x30days == 0) {
x30daysStr = " ";
} else {
x30daysStr = x30days + "";
if (x30daysStr.indexOf(".") == x30daysStr.length() - 2) {
x30daysStr += "0";
}
x30daysStr = NumberUtils.cutFractions(x30daysStr);
}
if (x60days == 0) {
x60daysStr = " ";
} else {
x60daysStr = x60days + "";
if (x60daysStr.indexOf(".") == x60daysStr.length() - 2) {
x60daysStr += "0";
}
x60daysStr = NumberUtils.cutFractions(x60daysStr);
}
if (x90days == 0) {
x90daysStr = " ";
} else {
x90daysStr = x90days + "";
if (x90daysStr.indexOf(".") == x90daysStr.length() - 2) {
x90daysStr += "0";
}
x90daysStr = NumberUtils.cutFractions(x90daysStr);
}
if (pendingAmountStr.indexOf(".") == pendingAmountStr.length() - 2) {
pendingAmountStr += "0";
}
pendingAmountStr = NumberUtils.cutFractions(pendingAmountStr);
if (bcAmtStr.trim().equals("")) {
bcAmtStr = " ";
}
Hashtable totData = new Hashtable();
totData.put("ID", custId);
totData.put("Customer", companyName);
totData.put("Terms", terms);
totData.put("Total", pendingAmountStr);
totData.put("Current", currStr);
totData.put("30 Days", x30daysStr);
totData.put("60 Days", x60daysStr);
totData.put("90 Days", x90daysStr);
totData.put("BC Chks", bcAmtStr);
data.addElement(totData);
}
// ---------------------------------------------------------------
// ---------------------------------------------------------------
if (toShowAR == null) {
throw new UserException(" No Customers have Pending Balances ");
}
totalSplitBalance = totalCurrent + total30Days + total60Days + total90Days + totBCAmt;
String totBalanceStr = totBalance + "";
String totalSplitBalanceStr = totalSplitBalance + "";
String totalCurrentStr = totalCurrent + "";
String total30DaysStr = total30Days + "";
String total60DaysStr = total60Days + "";
String total90DaysStr = total90Days + "";
String totBCAmtStr = totBCAmt + "";
String currPercStr =
Math.rint(100 - ((totalSplitBalance - totalCurrent) * 100 / totalSplitBalance)) + "";
String x30DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total30Days) * 100 / totalSplitBalance)) + "";
String x60DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total60Days) * 100 / totalSplitBalance)) + "";
String x90DaysPercStr =
Math.rint(100 - ((totalSplitBalance - total90Days) * 100 / totalSplitBalance)) + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
if (totalSplitBalanceStr.indexOf(".") == totalSplitBalanceStr.length() - 2) {
totalSplitBalanceStr += "0";
}
if (totalCurrentStr.indexOf(".") == totalCurrentStr.length() - 2) {
totalCurrentStr += "0";
}
if (total30DaysStr.indexOf(".") == total30DaysStr.length() - 2) {
total30DaysStr += "0";
}
if (total60DaysStr.indexOf(".") == total60DaysStr.length() - 2) {
total60DaysStr += "0";
}
if (total90DaysStr.indexOf(".") == total90DaysStr.length() - 2) {
total90DaysStr += "0";
}
if (totBCAmtStr.indexOf(".") == totBCAmtStr.length() - 2) {
totBCAmtStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
totalSplitBalanceStr = NumberUtils.cutFractions(totalSplitBalanceStr);
totalCurrentStr = NumberUtils.cutFractions(totalCurrentStr);
total30DaysStr = NumberUtils.cutFractions(total30DaysStr);
total60DaysStr = NumberUtils.cutFractions(total60DaysStr);
total90DaysStr = NumberUtils.cutFractions(total90DaysStr);
totBCAmtStr = NumberUtils.cutFractions(totBCAmtStr);
totals[0][0] = "Total No. Of Customers Have Payments ";
totals[0][1] = cntBalances + "";
totals[1][0] = "Total Payments Receivable ";
totals[1][1] = totBalanceStr;
totals[2][0] = "Total Split Payments Receivable ";
totals[2][1] = totalSplitBalanceStr;
totals[3][0] = "Current Payments ";
totals[3][1] = totalCurrentStr;
totals[4][0] = "% of Current ";
totals[4][1] = currPercStr;
totals[5][0] = "Over 30 Days Payments ";
totals[5][1] = total30DaysStr;
totals[6][0] = "% of 30 Days ";
totals[6][1] = x30DaysPercStr;
totals[7][0] = "Over 60 Days Payments ";
totals[7][1] = total60DaysStr;
totals[8][0] = "% of 60 Days ";
totals[8][1] = x60DaysPercStr;
totals[9][0] = "Over 90 Days Payments ";
totals[9][1] = total90DaysStr;
totals[10][0] = "% of 90 Days ";
totals[10][1] = x90DaysPercStr;
totals[11][0] = "Total Bounced Checks Amount ";
totals[11][1] = totBCAmtStr;
toShowAR.put("FileName", fileName);
toShowAR.put("BackScreen", "AcctMenu");
toShowAR.put("MainHeading", mainHeading);
toShowAR.put("SubHeadings", subHeadings);
toShowAR.put("Data", data);
toShowAR.put("Totals", totals);
createReport(toShowAR);
rs.close();
stmt.close();
rs1.close();
stmt1.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
tt = System.currentTimeMillis() - tt;
double xx = tt / (1000 * 60);
logger.error("AGEING RECEIVABLES TIME - NEW VERSION:::" + xx + " Min");
return toShowAR;
}
public static Hashtable<String, String> accountsReceivable() throws UserException {
Hashtable toShowAR = null;
try {
// select customerid, sum(balance) from invoice group by customerid
// order by 2 desc
String fileName = "AR" + DateUtils.getNewUSDate().trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"select a.customerid, b.companyname, sum(a.balance) from invoice a, customer b where a.balance!=0 and a.Status!='C' and a.Status!='W' and a.customerid=b.customerid group by a.customerid order by 3 desc";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
int totCustPending = 0;
double totBalance = 0.0;
mainHeading = "Accounts Receivable As On " + DateUtils.getNewUSDate();
subHeadings.addElement("Customer Id");
subHeadings.addElement("Company Name");
subHeadings.addElement("Receivable Amount");
Statement stmtXX = con.createStatement();
String sqlXX =
"Select CustomerId, Sum(Balance) From BouncedChecks Where Balance!=0 Group By CustomerId Order By 1 ";
Hashtable<String, String> bcChecks = null;
ResultSet rsXX = stmtXX.executeQuery(sqlXX);
while (rsXX.next()) {
if (bcChecks == null) {
bcChecks = new Hashtable<String, String>();
}
String cstId = rsXX.getString(1);
String bcAmt = rsXX.getString(2);
bcChecks.put(cstId, bcAmt);
}
while (rs.next()) {
if (toShowAR == null) {
toShowAR = new Hashtable();
}
String custId = rs.getString(1);
String companyName = rs.getString(2);
double pendingAmount = rs.getDouble(3);
/*
* Vector v = BouncedChecksBean.getAllBouncedChecks(custId); if (v != null) { Enumeration
* ennumX = v.elements(); while (ennumX.hasMoreElements()) { BouncedChecksBean bcBean =
* (BouncedChecksBean) ennumX.nextElement(); pendingAmount += bcBean.getBalance(); } }
*/
if (bcChecks != null && bcChecks.get(custId) != null) {
String bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
pendingAmount += Double.parseDouble(bcAmtStr);
}
if (pendingAmount == 0) {
continue;
} else if (pendingAmount < 0) {
continue;
} else if (pendingAmount > 0) {
totBalance += pendingAmount;
totCustPending++;
}
String pendingAmountStr = pendingAmount + "";
if (pendingAmountStr.indexOf(".") == pendingAmountStr.length() - 2) {
pendingAmountStr += "0";
}
pendingAmountStr = NumberUtils.cutFractions(pendingAmountStr);
Hashtable totData = new Hashtable();
totData.put("Customer Id", custId);
totData.put("Company Name", companyName);
totData.put("Receivable Amount", pendingAmountStr);
data.addElement(totData);
}
if (bcChecks != null && bcChecks.size() > 0) {
// logger.error("BC Checks Left: " + bcChecks.size());
Enumeration<String> ennum = bcChecks.keys();
while (ennum.hasMoreElements()) {
String cstId = ennum.nextElement();
double amt = Double.parseDouble(bcChecks.get(cstId));
if (amt > 0) {
totBalance += amt;
} else {
continue;
}
Hashtable totData = new Hashtable();
totData.put("Customer Id", cstId);
totData.put("Company Name", CustomerBean.getCompanyName(cstId));
totData.put("Receivable Amount", amt + "");
data.addElement(totData);
totCustPending++;
}
}
if (toShowAR == null) {
throw new UserException(" No Customers have Pending Balances ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
totals[0][0] = "Total No. Of Customers Have Payments ";
totals[0][1] = totCustPending + "";
totals[1][0] = "Total Payments Receivable ";
totals[1][1] = totBalanceStr;
toShowAR.put("FileName", fileName);
toShowAR.put("BackScreen", "AcctMenu");
toShowAR.put("MainHeading", mainHeading);
toShowAR.put("SubHeadings", subHeadings);
toShowAR.put("Data", data);
toShowAR.put("Totals", totals);
createReport(toShowAR);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowAR;
}
public static Hashtable<String, String> accountsPayable() throws UserException {
Hashtable toShowAP = null;
try {
// select customerid, sum(balance) from invoice group by customerid
// order by 2 desc
String fileName = "AP" + DateUtils.getNewUSDate().trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"select a.customerid, b.companyname, sum(a.balance) from invoice a, customer b where a.balance!=0 and a.Status!='C' and a.Status!='W' and a.customerid=b.customerid group by a.customerid order by 3 desc";
// logger.error(sql);
ResultSet rs = stmt.executeQuery(sql);
int totCreditCustPending = 0;
double totCreditBalance = 0.0;
mainHeading = "Accounts Payable As On " + DateUtils.getNewUSDate();
subHeadings.addElement("Customer Id");
subHeadings.addElement("Company Name");
subHeadings.addElement("Amount Payable");
Statement stmtXX = con.createStatement();
String sqlXX =
"Select CustomerId, Sum(Balance) From BouncedChecks Where Balance!=0 Group By CustomerId Order By 1 ";
Hashtable<String, String> bcChecks = null;
ResultSet rsXX = stmtXX.executeQuery(sqlXX);
while (rsXX.next()) {
if (bcChecks == null) {
bcChecks = new Hashtable<String, String>();
}
String cstId = rsXX.getString(1);
String bcAmt = rsXX.getString(2);
bcChecks.put(cstId, bcAmt);
}
while (rs.next()) {
if (toShowAP == null) {
toShowAP = new Hashtable();
}
String custId = rs.getString(1);
String companyName = rs.getString(2);
double pendingAmount = rs.getDouble(3);
/*
* Vector v = BouncedChecksBean.getAllBouncedChecks(custId); if (v != null) { Enumeration
* enumX = v.elements(); while (enumX.hasMoreElements()) { BouncedChecksBean bcBean =
* (BouncedChecksBean) enumX.nextElement(); pendingAmount += bcBean.getBalance(); } }
*/
if (bcChecks != null && bcChecks.get(custId) != null) {
String bcAmtStr = bcChecks.get(custId);
bcChecks.remove(custId);
pendingAmount += Double.parseDouble(bcAmtStr);
}
if (pendingAmount == 0) {
continue;
} else if (pendingAmount > 0) {
continue;
} else if (pendingAmount < 0) {
totCreditBalance += pendingAmount;
totCreditCustPending++;
}
String pendingAmountStr = pendingAmount + "";
if (pendingAmountStr.indexOf(".") == pendingAmountStr.length() - 2) {
pendingAmountStr += "0";
}
pendingAmountStr = NumberUtils.cutFractions(pendingAmountStr);
Hashtable totData = new Hashtable();
totData.put("Customer Id", custId);
totData.put("Company Name", companyName);
totData.put("Amount Payable", pendingAmountStr);
data.addElement(totData);
}
if (bcChecks != null && bcChecks.size() > 0) {
// logger.error("BC Checks Left: " + bcChecks.size());
Enumeration<String> ennum = bcChecks.keys();
while (ennum.hasMoreElements()) {
String cstId = ennum.nextElement();
double amt = Double.parseDouble(bcChecks.get(cstId));
if (amt < 0) {
totCreditBalance += amt;
} else {
continue;
}
Hashtable totData = new Hashtable();
totData.put("Customer Id", cstId);
totData.put("Company Name", CustomerBean.getCompanyName(cstId));
totData.put("Receivable Amount", amt + "");
data.addElement(totData);
totCreditCustPending++;
}
}
if (toShowAP == null) {
throw new UserException(" No Customers have Pending Balances ");
}
String totCreditBalanceStr = totCreditBalance + "";
if (totCreditBalanceStr.indexOf(".") == totCreditBalanceStr.length() - 2) {
totCreditBalanceStr += "0";
}
totCreditBalanceStr = NumberUtils.cutFractions(totCreditBalanceStr);
totals[0][0] = "Total No. Of Customers Have Credit ";
totals[0][1] = totCreditCustPending + "";
totals[1][0] = "Total Credits Payable ";
totals[1][1] = totCreditBalanceStr;
toShowAP.put("FileName", fileName);
toShowAP.put("BackScreen", "AcctMenu");
toShowAP.put("MainHeading", mainHeading);
toShowAP.put("SubHeadings", subHeadings);
toShowAP.put("Data", data);
toShowAP.put("Totals", totals);
createReport(toShowAP);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowAP;
}
public static Hashtable<String, String> showPendingInvoices() throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowPendInv" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance FROM Invoice a, Customer b WHERE ";
sql +=
" a.CustomerId=b.CustomerId and a.Balance!=0 and a.Status!='C' and a.Status!='W' Order by 1 ";
ResultSet rs = stmt.executeQuery(sql);
double totBalance = 0.0;
int totCnt = 0;
mainHeading = "PENDING INVOICES AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
String balanceStr = balance + "";
if (balanceStr.indexOf(".") == balanceStr.length() - 2) {
balanceStr += "0";
}
totBalance += balance;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balanceStr);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
totals[0][0] = "Total Balance";
totals[0][1] = totBalanceStr;
totals[1][0] = "Total No Of Invoices";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "AcctMenu");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable codPendingInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowCODPendInv" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance FROM Invoice a, Customer b WHERE ";
sql +=
" a.CustomerId=b.CustomerId and a.Balance!=0 and a.Status!='C' and a.Status!='W' and (b.PaymentTerms='C' or b.PaymentTerms='O') ";
if (toDate.trim().equals("")) {
sql +=
" and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(DateUtils.getNewUSDate()) + "'";
} else if (fromDate.trim().equals(toDate.trim())) {
sql += " and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
} else {
sql +=
" and a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate)
+ "' and a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
}
sql += " Order By 1 ";
ResultSet rs = stmt.executeQuery(sql);
double totBalance = 0.0;
int totCnt = 0;
mainHeading = "PENDING COD & CASH INVOICES AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
String balanceStr = balance + "";
if (balanceStr.indexOf(".") == balanceStr.length() - 2) {
balanceStr += "0";
}
totBalance += balance;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balanceStr);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
if (user.getRole().trim().equalsIgnoreCase("Acct")) {
totBalanceStr = "0.0";
}
totals[0][0] = "Total Balance";
totals[0][1] = totBalanceStr;
totals[1][0] = "Total No Of Invoices";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable otherPendingInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowOtherPendInv" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance FROM Invoice a, Customer b WHERE ";
sql +=
" a.CustomerId=b.CustomerId and a.Balance!=0 and a.Status!='C' and a.Status!='W' and b.PaymentTerms!='C' and b.PaymentTerms!='O' ";
if (toDate.trim().equals("")) {
sql +=
" and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(DateUtils.getNewUSDate()) + "'";
} else if (fromDate.trim().equals(toDate.trim())) {
sql += " and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
} else {
sql +=
" and a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate)
+ "' and a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
}
sql += " Order By 1 ";
ResultSet rs = stmt.executeQuery(sql);
double totBalance = 0.0;
int totCnt = 0;
mainHeading = "PENDING ACCOUNTS INVOICES AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
String balanceStr = balance + "";
if (balanceStr.indexOf(".") == balanceStr.length() - 2) {
balanceStr += "0";
}
totBalance += balance;
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balanceStr);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
if (user.getRole().trim().equalsIgnoreCase("Acct")) {
totBalanceStr = "0.0";
}
totals[0][0] = "Total Balance";
totals[0][1] = totBalanceStr;
totals[1][0] = "Total No Of Invoices";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable allPendingInvoices(UserBean user, String fromDate, String toDate)
throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowAllPendInv" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance, b.PaymentTerms FROM Invoice a, Customer b WHERE ";
sql += " a.CustomerId=b.CustomerId and a.Balance!=0 and a.Status!='C' and a.Status!='W' ";
if (toDate.trim().equals("")) {
sql +=
" and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(DateUtils.getNewUSDate()) + "'";
} else if (fromDate.trim().equals(toDate.trim())) {
sql += " and a.OrderDate='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
} else {
sql +=
" and a.OrderDate>='" + DateUtils.convertUSToMySQLFormat(fromDate)
+ "' and a.OrderDate<='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
}
sql += " Order By 1 ";
ResultSet rs = stmt.executeQuery(sql);
double totBalance = 0.0;
int totCnt = 0;
mainHeading = "PENDING INVOICES AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
subHeadings.addElement("Terms");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
String terms = rs.getString(7);
String balanceStr = balance + "";
if (balanceStr.indexOf(".") == balanceStr.length() - 2) {
balanceStr += "0";
}
totBalance += balance;
if (terms == null || terms.trim().equals("")) {
terms = " ";
} else if (terms.trim().equalsIgnoreCase("C")) {
terms = "COD";
} else if (terms.trim().equalsIgnoreCase("O")) {
terms = "CASH";
} else if (terms.trim().equalsIgnoreCase("B")) {
terms = "BI-WK";
} else if (terms.trim().equalsIgnoreCase("W")) {
terms = "WKLY";
} else if (terms.trim().equalsIgnoreCase("M")) {
terms = "MTHLY";
}
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balanceStr);
totData.put("Terms", terms);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totBalanceStr = totBalance + "";
if (totBalanceStr.indexOf(".") == totBalanceStr.length() - 2) {
totBalanceStr += "0";
}
totBalanceStr = NumberUtils.cutFractions(totBalanceStr);
if (user.getRole().trim().equalsIgnoreCase("Acct")) {
totBalanceStr = "0.0";
}
totals[0][0] = "Total Balance";
totals[0][1] = totBalanceStr;
totals[1][0] = "Total No Of Invoices";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable showDeposits(String fromDate, String toDate) throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowDepo" + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[2][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT AppliedDate, sum(AppliedAmount) FROM AppliedAmounts WHERE ";
if (toDate.trim().equals("")) {
sql += " AppliedDate='" + DateUtils.convertUSToMySQLFormat(DateUtils.getNewUSDate()) + "'";
} else if (fromDate.trim().equals(toDate.trim())) {
sql += " AppliedDate='" + DateUtils.convertUSToMySQLFormat(toDate) + "'";
} else {
sql +=
" AppliedDate>='" + DateUtils.convertUSToMySQLFormat(fromDate) + "' and AppliedDate<='"
+ DateUtils.convertUSToMySQLFormat(toDate) + "'";
}
sql += " Group By AppliedDate Order By 1 ";
ResultSet rs = stmt.executeQuery(sql);
// double totDeposit = 0.0;
BigDecimal totDeposit = new BigDecimal("0.00");
totDeposit = totDeposit.setScale(2, BigDecimal.ROUND_CEILING);
int totCnt = 0;
mainHeading = "DEPOSITS FROM " + fromDate + " TO " + toDate;
subHeadings.addElement("Date");
subHeadings.addElement("Deposit");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String dd = DateUtils.convertMySQLToUSFormat(rs.getString(1));
BigDecimal depoAmount = rs.getBigDecimal(2);
totDeposit = totDeposit.add(depoAmount);
Hashtable totData = new Hashtable();
totData.put("Date", dd);
if (depoAmount != null) {
totData.put("Deposit", depoAmount.toString());
}
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Pending Inovices ");
}
String totDepositStr = "";
// System.out.println("totDeposit.toString()..."+totDeposit.toString());
if (totDeposit != null) {
totDepositStr = totDeposit.toString();
// System.out.println("totDepositStr..."+totDepositStr);
}
/*
* String totDepositStr = totDeposit + ""; if (totDepositStr.indexOf(".") ==
* totDepositStr.length() - 2) { totDepositStr += "0"; } totDepositStr =
* NumberUtils.cutFractions(totDepositStr);
*/
totals[0][0] = "Total Deposit Amount";
totals[0][1] = totDepositStr;
totals[1][0] = "Total No Of Deposits";
totals[1][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable showInvoicesNotPrinted(UserBean user) throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowNonPrintInv" + user.getUsername() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName FROM Invoice a, Customer b WHERE ";
sql += " a.CustomerId=b.CustomerId and IsPrinted!='Y' and IsDelivered!='Y' and a.Balance!=0 ";
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Marcie")) {
sql += " AND a.SalesPerson='" + user.getUsername() + "' ";
}
ResultSet rs = stmt.executeQuery(sql);
int totCnt = 0;
mainHeading = "INVOICES NOT PRINTED AS ON " + DateUtils.getNewUSDate();
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Inovices ");
}
totals[0][0] = "Total No Of Invoices";
totals[0][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable showInvoicesNotPickedUp(UserBean user, boolean cods) throws UserException {
Hashtable toShowInvoices = null;
try {
String fileName = "ShowNonPrintInv" + user.getUsername() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT a.InvoiceNumber, a.OrderDate, a.SalesPerson, a.CustomerId, b.CompanyName, a.Balance FROM Invoice a, Customer b WHERE ";
sql +=
" a.Status!='C' and a.Status!='W' and a.Balance>0 and a.ShipVia='Pick-Up' and a.CustomerId=b.CustomerId ";
if (cods) {
sql += " and b.PaymentTerms!='M' and b.PaymentTerms!='B' and b.PaymentTerms!='W' ";
} else {
sql += " and b.PaymentTerms!='C' and b.PaymentTerms!='O' ";
}
if (!user.getRole().trim().equalsIgnoreCase("High")
&& !user.getRole().trim().equalsIgnoreCase("Acct")
&& !user.getUsername().trim().equalsIgnoreCase("Marcie")) {
sql += " AND a.SalesPerson='" + user.getUsername() + "' ";
}
sql += " Order by 1 desc ";
ResultSet rs = stmt.executeQuery(sql);
int totCnt = 0;
if (cods) {
mainHeading = "PENDING PICKUP COD & CASH INVOICES AS ON " + DateUtils.getNewUSDate();
} else {
mainHeading = "PENDING PICKUP ACCOUNTS INVOICES AS ON " + DateUtils.getNewUSDate();
}
subHeadings.addElement("Inv. No.");
subHeadings.addElement("Inv. Date");
subHeadings.addElement("Sales Person");
subHeadings.addElement("Cust Id");
subHeadings.addElement("Cust Name");
subHeadings.addElement("Balance");
while (rs.next()) {
if (toShowInvoices == null) {
toShowInvoices = new Hashtable();
}
totCnt++;
String invoiceNo = rs.getString(1);
String orderDate = DateUtils.convertMySQLToUSFormat(rs.getString(2));
String newSalesPerson = rs.getString(3);
String custId = rs.getString(4);
String custName = rs.getString(5);
double balance = rs.getDouble(6);
Hashtable totData = new Hashtable();
totData.put("Inv. No.", invoiceNo);
totData.put("Inv. Date", orderDate);
totData.put("Sales Person", newSalesPerson);
totData.put("Cust Id", custId);
totData.put("Cust Name", custName);
totData.put("Balance", balance + "");
data.addElement(totData);
}
if (toShowInvoices == null) {
throw new UserException(" No More Inovices ");
}
totals[0][0] = "Total No Of Invoices";
totals[0][1] = totCnt + "";
toShowInvoices.put("FileName", fileName);
toShowInvoices.put("BackScreen", "TodaysOrders");
toShowInvoices.put("MainHeading", mainHeading);
toShowInvoices.put("SubHeadings", subHeadings);
toShowInvoices.put("Data", data);
toShowInvoices.put("Totals", totals);
createReport(toShowInvoices);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return toShowInvoices;
}
public static Hashtable createHistoryReport(int invNo) throws UserException {
Hashtable invoiceHistory = null;
try {
String fileName = "Hist" + invNo + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql =
"SELECT * From InvoiceHistory Where InvoiceNumber=" + invNo + " Order By ModifiedOrder ";
ResultSet rs = stmt.executeQuery(sql);
mainHeading = "History for the Invoice " + invNo;
subHeadings.addElement("Modified Date");
subHeadings.addElement("Modified By");
subHeadings.addElement("Remarks");
int totalChanges = 0;
while (rs.next()) {
if (invoiceHistory == null) {
invoiceHistory = new Hashtable();
}
totalChanges++;
String modifiedBy = rs.getString("ModifiedBy");
String modifiedDate = rs.getString("ModifiedDate");
String remarks =
rs.getString("Remarks1") + rs.getString("Remarks2") + rs.getString("Remarks3")
+ rs.getString("Remarks4") + rs.getString("Remarks5");
Hashtable totData = new Hashtable();
totData.put("Modified Date", DateUtils.convertMySQLToUSFormat(modifiedDate));
totData.put("Modified By", modifiedBy);
totData.put("Remarks", remarks);
data.addElement(totData);
}
if (invoiceHistory == null) {
throw new UserException(" No Changes On This Invoice ");
}
totals[0][0] = "Total No. Of Changes Found";
totals[0][1] = totalChanges + "";
invoiceHistory.put("FileName", fileName);
invoiceHistory.put("BackScreen", "CloseInvoices");
invoiceHistory.put("MainHeading", mainHeading);
invoiceHistory.put("SubHeadings", subHeadings);
invoiceHistory.put("Data", data);
invoiceHistory.put("Totals", totals);
createReport(invoiceHistory);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return invoiceHistory;
}
public static Hashtable createHistoryReport(String fromDate, String toDate) throws UserException {
Hashtable invoiceHistory = null;
try {
String fileName = "Hist" + fromDate.trim() + toDate.trim() + ".html";
String mainHeading = "";
Vector subHeadings = new Vector();
Vector<Hashtable> data = new Vector<Hashtable>();
String[][] totals = new String[1][2];
if (fromDate == null) {
fromDate = "";
}
Connection con = DBInterfaceLocal.getSQLConnection();
Statement stmt = con.createStatement();
String sql = "SELECT * From InvoiceHistory Where ";
mainHeading = "Invoice History Report :";
if (fromDate.trim().equals("")) {
mainHeading += " For " + toDate.trim();
sql +=
" ModifiedDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim())
+ "' And Remarks1 Not like 'Printed%' Order By InvoiceNumber ";
} else if (fromDate.trim().equals(toDate.trim())) {
mainHeading += " For " + toDate.trim();
sql +=
" ModifiedDate='" + DateUtils.convertUSToMySQLFormat(toDate.trim())
+ "' And Remarks1 Not like 'Printed%' Order By InvoiceNumber ";
} else {
mainHeading += " From " + fromDate.trim() + " To " + toDate.trim();
sql +=
" ModifiedDate >= '" + DateUtils.convertUSToMySQLFormat(fromDate.trim())
+ "' and ModifiedDate <= '" + DateUtils.convertUSToMySQLFormat(toDate.trim())
+ "' And Remarks1 Not like 'Printed%' Order By ModifiedDate, InvoiceNumber ";
}
ResultSet rs = stmt.executeQuery(sql);
subHeadings.addElement("Inv. No");
subHeadings.addElement("Date");
subHeadings.addElement("Who");
subHeadings.addElement("Remarks");
int totalChanges = 0;
while (rs.next()) {
if (invoiceHistory == null) {
invoiceHistory = new Hashtable();
}
totalChanges++;
int invNo = rs.getInt("InvoiceNumber");
String modifiedBy = rs.getString("ModifiedBy");
String modifiedDate = rs.getString("ModifiedDate");
String remarks =
rs.getString("Remarks1") + rs.getString("Remarks2") + rs.getString("Remarks3")
+ rs.getString("Remarks4") + rs.getString("Remarks5");
Hashtable totData = new Hashtable();
totData.put("Inv. No", invNo + "");
totData.put("Date", DateUtils.convertMySQLToUSFormat(modifiedDate));
totData.put("Who", modifiedBy);
totData.put("Remarks", remarks);
data.addElement(totData);
}
if (invoiceHistory == null) {
throw new UserException(" No Changes On This Invoice ");
}
totals[0][0] = "Total No. Of Changes Found";
totals[0][1] = totalChanges + "";
invoiceHistory.put("FileName", fileName);
invoiceHistory.put("BackScreen", "TodaysOrders");
invoiceHistory.put("MainHeading", mainHeading);
invoiceHistory.put("SubHeadings", subHeadings);
invoiceHistory.put("Data", data);
invoiceHistory.put("Totals", totals);
createReport(invoiceHistory);
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
throw new UserException(e.getMessage());
}
return invoiceHistory;
}
public static void createCOGReport(String fileName, String data) {
try {
File fileHtml = new File("c:/Tomcat/webapps/bvaschicago/html/reports/"
//"E:/projects/myeclipse/.metadata/.me_tcat/webapps/bvaschicago/html/reports/"
+ fileName);
FileWriter ft = new FileWriter(fileHtml);
// ft.write(getHeaders("General Reports Printer"));
ft.write(getHeaders(""));
ft.write("<table>");
ft.write("<tr>");
ft.write("<td colspan='4' align='center' style='font-size: 20pt '>");
ft.write("<B>Best Value Auto Body Supply Inc.</B><BR/>");
ft.write("</td>");
ft.write("<tr>");
ft.write("<td colspan='4' align='center' style='font-size: 16pt '>");
ft.write("<B>General Reports Viewer</B>");
ft.write("<BR/>");
ft.write("<hr align='center' noshade size='2px' width='500px'/><BR/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<TR><TD align='Center' colspan='4'><H2>Cost Of Goods Report</H2></TD></TR>");
ft.write("<tr style='border: thin;'>");
ft.write(data);
ft.write("</table>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<tr>");
ft.write("<td colspan='4'>");
ft.write("<hr align='center' noshade size='2px' width='700px'/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("</table>");
ft.write(getFooters());
ft.close();
} catch (IOException ioe) {
logger.error("Exception in PrintUtils.createInvoice: " + ioe);
} catch (Exception e) {
logger.error("Exception in PrintUtils.createInvoice: " + e);
}
}
public static void createReport(Hashtable toShowSales) {
try {
String fileName = (String) toShowSales.get("FileName");
String mainHeading = (String) toShowSales.get("MainHeading");
Vector subHeadings = (Vector) toShowSales.get("SubHeadings");
int arraySize = subHeadings.size();
String[] strSubHeads = new String[arraySize];
Vector data = (Vector) toShowSales.get("Data");
String[][] totals = (String[][]) toShowSales.get("Totals");
File fileHtml = new File("c:/Tomcat/webapps/bvaschicago/html/reports/" + fileName);
FileWriter ft = new FileWriter(fileHtml);
// ft.write(getHeaders("General Reports Printer"));
ft.write(getHeaders(""));
ft.write("<table>");
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "' align='center' style='font-size: 20pt '>");
ft.write("<B>Best Value Auto Body Supply Inc.</B><BR/>");
ft.write("</td>");
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "' align='center' style='font-size: 16pt '>");
ft.write("<B>" + mainHeading + "</B>");
ft.write("<BR/>");
ft.write("<hr align='center' noshade size='2px' width='500px'/><BR/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<tr style='border: thin;'>");
Enumeration enumSubHead = subHeadings.elements();
int cnt = 0;
while (enumSubHead.hasMoreElements()) {
String subH = (String) enumSubHead.nextElement();
strSubHeads[cnt] = subH;
cnt++;
ft.write("<td><B>");
ft.write(padSpaces(subH, 10));
ft.write("</B></td>");
}
ft.write("</tr>");
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "'>");
ft.write("<hr align='center' noshade size='2px' width='700px'/>");
ft.write("</td>");
ft.write("</tr>");
Enumeration enumData = data.elements();
while (enumData.hasMoreElements()) {
Hashtable innerData = (Hashtable) enumData.nextElement();
ft.write("<tr>");
for (int i = 0; i < strSubHeads.length; i++) {
ft.write("<td>");
ft.write(padSpaces((String) innerData.get(strSubHeads[i]), 10));
ft.write("</td>");
}
ft.write("</tr>");
}
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "'>");
ft.write("<hr align='center' noshade size='2px' width='700px'/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<tr>");
ft.write("<td align='right' colspan='" + arraySize + "'>");
ft.write("<table>");
for (int i = 0; i < totals.length; i++) {
ft.write("<tr>");
ft.write("<TD><B>" + totals[i][0] + "</B></TD>");
ft.write("<TD><B>" + totals[i][1] + "</B></TD>");
ft.write("</tr>");
}
ft.write("</table>");
ft.write("</td>");
ft.write("</tr>");
ft.write("<tr>");
ft.write("<td colspan='" + arraySize + "'>");
ft.write("<hr align='center' noshade size='2px' width='700px'/>");
ft.write("</td>");
ft.write("</tr>");
ft.write("</table>");
ft.write(getFooters());
ft.close();
} catch (IOException ioe) {
logger.error("Exception in PrintUtils.createInvoice: " + ioe);
} catch (Exception e) {
logger.error("Exception in PrintUtils.createInvoice: " + e);
}
}
public static String getHeaders() {
StringBuffer headers = new StringBuffer("");
headers
.append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>");
headers
.append("<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
// headers.append("<STYLE TYPE='text/css'> <!-- p { font-size: 13pt; } --> </STYLE> ");
headers.append("<TITLE>Print Invoice</TITLE></HEAD>");
headers
.append("<script language='JavaScript'> function PrintPage() { window.print(); window.close(); }</script>");
headers.append("<BODY onload='PrintPage()'>");
return headers.toString();
}
public static String getHeaders(String title) {
StringBuffer headers = new StringBuffer("");
headers
.append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>");
headers
.append("<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
// headers.append("<STYLE TYPE='text/css'> <!-- p { font-size: 13pt; } --> </STYLE> ");
headers.append("<TITLE>" + title + "</TITLE></HEAD>");
headers
.append("<script language='JavaScript'> function PrintPage() { window.print(); window.close(); }</script>");
headers.append("<BODY onload='PrintPage()'>");
return headers.toString();
}
public static String getFooters() {
StringBuffer footers = new StringBuffer("");
footers.append("</BODY></HTML>");
return footers.toString();
}
public static String padSpaces(String str, int len) {
if (str == null || str.trim().equals("null"))
str = "";
str = str.trim();
int len1 = str.length();
while (len1 < len) {
str += " ";
len1++;
}
str += " ";
return str;
}
public static String newLines(String str) {
int len = 0;
if (str != null && (len = str.indexOf("\n")) != -1) {
str = str.substring(0, len) + "<BR/>" + newLines(str.substring(len + 1));
}
return str;
}
public static String cutModel(String model) {
int len = 0;
if (model.length() > 15) {
model = model.substring(0, 15);
}
if ((len = model.indexOf("(")) != -1) {
model = model.substring(0, len);
}
return model;
}
public static int calLen(String str, int totSize) {
int len = str.length();
totSize = totSize - (len * 2);
for (int i = 0; i < 6; i++) {
if (str.indexOf(" ") != -1) {
totSize = totSize - 1;
str = str.substring(str.indexOf(" ") + 1);
}
}
return totSize;
}
public static void getVendorHeader(FileWriter ft, int supId, boolean woPrice) throws IOException {
ft.write("<table border='1' cellspacing='0' style='font-size: 10pt'>");
ft.write("<tr>");
ft.write("<td align='center'><B>");
ft.write("BV Part No");
ft.write("</B></td>");
ft.write("<td align='center'><B>");
ft.write("ITEM NO");
ft.write("</B></td>");
if (supId != 1 && supId != 4 && supId != 5 && supId != 6 && supId != 8) {
ft.write("<td align='center'><B>");
ft.write("Desc 1");
ft.write("</B></td>");
}
ft.write("<td align='center'><B>");
ft.write("Desc 2");
ft.write("</B></td>");
ft.write("<td align='center'><B>");
ft.write("P/L Number");
ft.write("</B></td>");
ft.write("<td align='center'><B>");
ft.write("OEM Number");
ft.write("</B></td>");
if (woPrice) {
ft.write("<td align='center'><B>");
ft.write("NR");
ft.write("</B></td>");
ft.write("<td align='center'><B>");
ft.write("CUFT");
ft.write("</B></td>");
}
ft.write("<td align='center'><B>");
ft.write("Order");
ft.write("</B></td>");
ft.write("</tr>");
}
public static List populateDrivers() {
List<Driver> drvrList = new ArrayList<Driver>();
Connection con = null;
Statement stmtDrvr = null;
ResultSet rsDrvr = null;
try {
con = DBInterfaceLocal.getSQLConnection();
stmtDrvr = con.createStatement();
rsDrvr = stmtDrvr.executeQuery("Select serial,drivername From driver Where active=1");
while (rsDrvr.next()) {
Driver drvr = new Driver();
drvr.setSerial(rsDrvr.getString("serial"));
drvr.setDriverName(rsDrvr.getString("drivername"));
drvrList.add(drvr);
}
stmtDrvr.close();
rsDrvr.close();
con.close();
} catch (SQLException e) {
logger.error(e);
} finally{
}
return drvrList;
}
}
| 183,400 | 0.581963 | 0.568108 | 5,218 | 34.147568 | 26.207586 | 229 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.823304 | false | false | 10 |
b29545fef5c2dbd396610eac9cf4b2ec0ac0b768 | 19,396,072,374,750 | dfafae202fd9a5bde7fa2d3ca266003f31a42d4a | /src/main/java/com/wizardsofcode/deckmanagerserver/service/usermanagement/UserEmailService.java | 438f1d64acfb807f670c1738aac2b7d0033b7e28 | []
| no_license | sanchezdale/deckmanagerapi | https://github.com/sanchezdale/deckmanagerapi | 0296fe40683b8eab70ae0668c5d58eba37aa6c0c | 7a51e0ed6a616958527357de81a839455f451d57 | refs/heads/master | 2021-07-25T12:26:05.371000 | 2017-11-06T03:26:33 | 2017-11-06T03:26:33 | 109,641,932 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* * * *
* * Created by: Daniel Alejandro Sanchez * *
* * Date: 9/16/17
*/
package com.wizardsofcode.deckmanagerserver.service.usermanagement;
import com.wizardsofcode.deckmanagerserver.model.usermanagement.User;
import com.wizardsofcode.deckmanagerserver.model.usermanagement.UserEmail;
public interface UserEmailService {
UserEmail getUserEmail(User user);
void saveUserEmail(UserEmail user);
}
| UTF-8 | Java | 486 | java | UserEmailService.java | Java | [
{
"context": " * *\n * * Created by: Daniel Alejandro Sanchez * *\n * * Date: 9/16/17 ",
"end": 90,
"score": 0.9998764395713806,
"start": 66,
"tag": "NAME",
"value": "Daniel Alejandro Sanchez"
}
]
| null | []
| /*
* * * *
* * Created by: <NAME> * *
* * Date: 9/16/17
*/
package com.wizardsofcode.deckmanagerserver.service.usermanagement;
import com.wizardsofcode.deckmanagerserver.model.usermanagement.User;
import com.wizardsofcode.deckmanagerserver.model.usermanagement.UserEmail;
public interface UserEmailService {
UserEmail getUserEmail(User user);
void saveUserEmail(UserEmail user);
}
| 468 | 0.658436 | 0.648148 | 17 | 27.588236 | 27.27002 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false | 10 |
d41611fcf4253f68b92bb6c815efcd986dafa9c4 | 24,232,205,487,864 | a7388786da8c66b1b5d48959f70c10a58c1dee23 | /src/wordSearchII/Test.java | edab09cb1ea6191acbb412a1a1c64323e3364af0 | []
| no_license | JohnnyHuo/leetcode-practise | https://github.com/JohnnyHuo/leetcode-practise | c3ef31d7c0e50b188aa7ff456f7a7094c106fb74 | 03039a4dd56ff1c9d638647b115eaf1a83fce48d | refs/heads/master | 2021-01-22T11:42:26.552000 | 2015-07-02T06:21:57 | 2015-07-02T06:21:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package wordSearchII;
import java.util.List;
public class Test {
public static void main(String[] args){
Solution sol = new Solution();
char[][] board = {{'a'}};
String[] words = {"ab"};
List<String> res = sol.findWords(board, words);
System.out.println(res.get(0));
}
}
| UTF-8 | Java | 285 | java | Test.java | Java | []
| null | []
| package wordSearchII;
import java.util.List;
public class Test {
public static void main(String[] args){
Solution sol = new Solution();
char[][] board = {{'a'}};
String[] words = {"ab"};
List<String> res = sol.findWords(board, words);
System.out.println(res.get(0));
}
}
| 285 | 0.649123 | 0.645614 | 13 | 20.923077 | 15.48926 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.538462 | false | false | 10 |
6c5fc749ca8ad3ab1221a4f494e9e9e9f643d932 | 6,451,040,890,988 | 2089e80014f289e0d632e2cc8ded1b820dc82b61 | /odata2-lib/odata-core/src/main/java/org/apache/olingo/odata2/core/ep/producer/JsonLinksEntityProducer.java | 7a19ed64d955b19b252f02e4c0b15abfebfe0a6e | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | apache/olingo-odata2 | https://github.com/apache/olingo-odata2 | a0e489101a6173734934eb9dd1b592f0ca284f49 | bed23e77f9735c0094b5784aa0d7e3ee972018be | refs/heads/master | 2023-08-25T06:05:34.246000 | 2022-10-23T06:54:29 | 2022-11-30T17:01:41 | 18,830,102 | 45 | 96 | Apache-2.0 | false | 2023-09-03T07:44:00 | 2014-04-16T07:00:07 | 2022-12-13T10:34:31 | 2023-09-03T07:43:58 | 6,956 | 38 | 75 | 9 | Java | false | false | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
******************************************************************************/
package org.apache.olingo.odata2.core.ep.producer;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import org.apache.olingo.odata2.api.commons.InlineCount;
import org.apache.olingo.odata2.api.ep.EntityProviderException;
import org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties;
import org.apache.olingo.odata2.core.ep.EntityProviderProducerException;
import org.apache.olingo.odata2.core.ep.aggregator.EntityInfoAggregator;
import org.apache.olingo.odata2.core.ep.util.FormatJson;
import org.apache.olingo.odata2.core.ep.util.JsonStreamWriter;
/**
* Producer for writing a link collection in JSON.
*
*/
public class JsonLinksEntityProducer {
private final EntityProviderWriteProperties properties;
public JsonLinksEntityProducer(final EntityProviderWriteProperties properties) throws EntityProviderException {
this.properties = properties == null ? EntityProviderWriteProperties.serviceRoot(null).build() : properties;
}
public void append(final Writer writer, final EntityInfoAggregator entityInfo, final List<Map<String, Object>> data)
throws EntityProviderException {
JsonStreamWriter jsonStreamWriter = new JsonStreamWriter(writer);
try {
if (!properties.isOmitJsonWrapper()) {
jsonStreamWriter.beginObject()
.name(FormatJson.D);
}
if (properties.getInlineCountType() == InlineCount.ALLPAGES) {
final int inlineCount = properties.getInlineCount() == null ? 0 : properties.getInlineCount();
jsonStreamWriter.beginObject()
.namedStringValueRaw(FormatJson.COUNT, String.valueOf(inlineCount)).separator()
.name(FormatJson.RESULTS);
}
jsonStreamWriter.beginArray();
final String serviceRoot = properties.getServiceRoot().toASCIIString();
boolean first = true;
for (final Map<String, Object> entryData : data) {
if (first) {
first = false;
} else {
jsonStreamWriter.separator();
}
JsonLinkEntityProducer.appendUri(jsonStreamWriter,
(serviceRoot == null ? "" : serviceRoot)
+ AtomEntryEntityProducer.createSelfLink(entityInfo, entryData, null));
}
jsonStreamWriter.endArray();
if (properties.getInlineCountType() == InlineCount.ALLPAGES) {
jsonStreamWriter.endObject();
}
if (!properties.isOmitJsonWrapper()) {
jsonStreamWriter.endObject();
}
} catch (final IOException e) {
throw new EntityProviderProducerException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass()
.getSimpleName()), e);
}
}
}
| UTF-8 | Java | 3,635 | java | JsonLinksEntityProducer.java | Java | []
| null | []
| /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
******************************************************************************/
package org.apache.olingo.odata2.core.ep.producer;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import org.apache.olingo.odata2.api.commons.InlineCount;
import org.apache.olingo.odata2.api.ep.EntityProviderException;
import org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties;
import org.apache.olingo.odata2.core.ep.EntityProviderProducerException;
import org.apache.olingo.odata2.core.ep.aggregator.EntityInfoAggregator;
import org.apache.olingo.odata2.core.ep.util.FormatJson;
import org.apache.olingo.odata2.core.ep.util.JsonStreamWriter;
/**
* Producer for writing a link collection in JSON.
*
*/
public class JsonLinksEntityProducer {
private final EntityProviderWriteProperties properties;
public JsonLinksEntityProducer(final EntityProviderWriteProperties properties) throws EntityProviderException {
this.properties = properties == null ? EntityProviderWriteProperties.serviceRoot(null).build() : properties;
}
public void append(final Writer writer, final EntityInfoAggregator entityInfo, final List<Map<String, Object>> data)
throws EntityProviderException {
JsonStreamWriter jsonStreamWriter = new JsonStreamWriter(writer);
try {
if (!properties.isOmitJsonWrapper()) {
jsonStreamWriter.beginObject()
.name(FormatJson.D);
}
if (properties.getInlineCountType() == InlineCount.ALLPAGES) {
final int inlineCount = properties.getInlineCount() == null ? 0 : properties.getInlineCount();
jsonStreamWriter.beginObject()
.namedStringValueRaw(FormatJson.COUNT, String.valueOf(inlineCount)).separator()
.name(FormatJson.RESULTS);
}
jsonStreamWriter.beginArray();
final String serviceRoot = properties.getServiceRoot().toASCIIString();
boolean first = true;
for (final Map<String, Object> entryData : data) {
if (first) {
first = false;
} else {
jsonStreamWriter.separator();
}
JsonLinkEntityProducer.appendUri(jsonStreamWriter,
(serviceRoot == null ? "" : serviceRoot)
+ AtomEntryEntityProducer.createSelfLink(entityInfo, entryData, null));
}
jsonStreamWriter.endArray();
if (properties.getInlineCountType() == InlineCount.ALLPAGES) {
jsonStreamWriter.endObject();
}
if (!properties.isOmitJsonWrapper()) {
jsonStreamWriter.endObject();
}
} catch (final IOException e) {
throw new EntityProviderProducerException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass()
.getSimpleName()), e);
}
}
}
| 3,635 | 0.694085 | 0.690509 | 89 | 39.842697 | 31.217216 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47191 | false | false | 10 |
5728453c930b230753526037de3590f0ea632729 | 10,264,971,844,105 | 97e2dac00d2a7a5e56262b871b743e5a195002dd | /src/main/java/com/smt/parent/code/filters/log/LogPersistenceHandler.java | 9b730a37de7663c2ca3f11eed418ad96bf62a306 | []
| no_license | DougLei/smt-parent-code | https://github.com/DougLei/smt-parent-code | 81c6c66068dbcd9f1af9431398f317856d168b80 | c7661cb01eed7bd6921309d9c6489ca4bb1251a3 | refs/heads/master | 2023-06-01T22:32:38.800000 | 2021-06-25T03:33:54 | 2021-06-25T03:33:54 | 365,377,315 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smt.parent.code.filters.log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import com.alibaba.fastjson.JSONObject;
import com.douglei.tools.ExceptionUtil;
import com.smt.parent.code.spring.eureka.cloud.feign.APIServer;
import com.smt.parent.code.spring.eureka.cloud.feign.RestTemplateWrapper;
/**
* 日志持久化处理器
* @author DougLei
*/
public class LogPersistenceHandler {
private static final Logger logger= LoggerFactory.getLogger(LogPersistenceHandler.class);
@Autowired
private RestTemplateWrapper restTemplate;
@Async
void save(LogOperation log) {
try {
restTemplate.exchange(new APIServer() {
@Override
public String getName() {
return "(异步)保存日志";
}
@Override
public String getUrl() {
return "http://smt-log/smt-log/log/add_";
}
}, JSONObject.toJSONString(log), null);
} catch (Exception e) {
logger.error("(异步)保存日志异常: {}", ExceptionUtil.getStackTrace(e));
}
}
}
| UTF-8 | Java | 1,170 | java | LogPersistenceHandler.java | Java | [
{
"context": "stTemplateWrapper;\r\n\r\n/**\r\n * 日志持久化处理器\r\n * @author DougLei\r\n */\r\npublic class LogPersistenceHandler {\r\n\tpriv",
"end": 486,
"score": 0.9970508813858032,
"start": 479,
"tag": "NAME",
"value": "DougLei"
}
]
| null | []
| package com.smt.parent.code.filters.log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import com.alibaba.fastjson.JSONObject;
import com.douglei.tools.ExceptionUtil;
import com.smt.parent.code.spring.eureka.cloud.feign.APIServer;
import com.smt.parent.code.spring.eureka.cloud.feign.RestTemplateWrapper;
/**
* 日志持久化处理器
* @author DougLei
*/
public class LogPersistenceHandler {
private static final Logger logger= LoggerFactory.getLogger(LogPersistenceHandler.class);
@Autowired
private RestTemplateWrapper restTemplate;
@Async
void save(LogOperation log) {
try {
restTemplate.exchange(new APIServer() {
@Override
public String getName() {
return "(异步)保存日志";
}
@Override
public String getUrl() {
return "http://smt-log/smt-log/log/add_";
}
}, JSONObject.toJSONString(log), null);
} catch (Exception e) {
logger.error("(异步)保存日志异常: {}", ExceptionUtil.getStackTrace(e));
}
}
}
| 1,170 | 0.703375 | 0.701599 | 43 | 24.186047 | 23.210117 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 10 |
ba839c369f670fd822bb66a8407b36f45a47ac88 | 31,430,570,708,646 | f9f63be5ff3114f01c2128dc42115a8f9b4ce76f | /src/LearnBasic/BaiHuongDoiTuong/Hinh.java | 50425fb82535b4a348b66a8733a61adb8ab5b396 | []
| no_license | thaidat01222/LearningCollection | https://github.com/thaidat01222/LearningCollection | 60d5dc889dc7935df480ccd347e76256bf5bfb5c | a5f7b479be9ad4fc5247acefce2affcd68d8b7a5 | refs/heads/master | 2022-09-09T06:05:21.817000 | 2020-06-03T16:18:01 | 2020-06-03T16:18:01 | 255,918,468 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package LearnBasic.BaiHuongDoiTuong;
import java.util.ArrayList;
public abstract class Hinh {
ArrayList<Hinh> list = new ArrayList<>();
public abstract double dientich();
public String toString(){
return "Dien tich : " + dientich();
}
public void addHinh(Hinh hinh){
list.add(hinh);
}
}
| UTF-8 | Java | 325 | java | Hinh.java | Java | []
| null | []
| package LearnBasic.BaiHuongDoiTuong;
import java.util.ArrayList;
public abstract class Hinh {
ArrayList<Hinh> list = new ArrayList<>();
public abstract double dientich();
public String toString(){
return "Dien tich : " + dientich();
}
public void addHinh(Hinh hinh){
list.add(hinh);
}
}
| 325 | 0.658462 | 0.658462 | 14 | 22.214285 | 16.040924 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 10 |
eaa39ae53ddc1f0a97c86add7fd11dc2352b2095 | 32,633,161,552,139 | a0830d48b180f3d49998a13e5f372b52c4f0afec | /Código/Sistema_de_Aluguel_de_Carros/src/main/java/com/example/sistema_de_aluguel_de_carros/Models/Usuario.java | a93ea0cb7d8aebcc2dd901f293ae1b8c82dd2341 | [
"MIT"
]
| permissive | marinisz/Projeto02-Lab-Desenvolvimento | https://github.com/marinisz/Projeto02-Lab-Desenvolvimento | 2503d3e05904dc3a2c3fe09b36489e0374443c2c | 8f97514fcd22cae634dedb11e5a83339c5af58f7 | refs/heads/main | 2023-08-31T12:02:29.142000 | 2021-10-04T02:49:28 | 2021-10-04T02:49:28 | 406,168,031 | 0 | 0 | MIT | false | 2021-10-02T20:47:51 | 2021-09-14T00:14:45 | 2021-09-26T21:51:33 | 2021-10-02T20:47:50 | 643 | 0 | 0 | 0 | Java | false | false | package com.example.sistema_de_aluguel_de_carros.Models;
public class Usuario {
private String nome;
private String endereco;
private String id;
public Usuario logar() {
return null;
}
public void cadastrar() {
}
}
| UTF-8 | Java | 232 | java | Usuario.java | Java | []
| null | []
| package com.example.sistema_de_aluguel_de_carros.Models;
public class Usuario {
private String nome;
private String endereco;
private String id;
public Usuario logar() {
return null;
}
public void cadastrar() {
}
}
| 232 | 0.711207 | 0.711207 | 19 | 11.210526 | 14.806041 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.736842 | false | false | 10 |
a6e89a001f7314194be2c81d6c39a34b582f1fc0 | 4,002,909,556,088 | 7494ee198e9c60d01fceb00a4808cf52f021364e | /src/main/java/edu/swri/swiftvis/plot/util/FontUser.java | f484bba2210f7a77c7c007d7afb5e8039abd64b5 | []
| no_license | MarkCLewis/SwiftVis | https://github.com/MarkCLewis/SwiftVis | acfb649988c03e41010ef7f2618ef7e793eac1d4 | 2147b26aeb47969027ea2c2e73d83e550b076971 | refs/heads/master | 2022-10-15T13:13:22.171000 | 2022-08-22T00:53:56 | 2022-08-22T00:53:56 | 54,576,592 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Generated by Together */
package edu.swri.swiftvis.plot.util;
public interface FontUser {
void applyFont(FontOptions options);
}
| UTF-8 | Java | 145 | java | FontUser.java | Java | []
| null | []
| /* Generated by Together */
package edu.swri.swiftvis.plot.util;
public interface FontUser {
void applyFont(FontOptions options);
}
| 145 | 0.710345 | 0.710345 | 7 | 18.714285 | 16.489948 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 10 |
8b0f91d1d4cacae9575745466576a3ab2523cca2 | 31,404,800,899,145 | db558c6a00423e616a79afb173ea95f0aec055f1 | /Chapter_12/Exercise12_19/Main.java | 36554655c8c1868c18d864bc8d28e1cd234a7a30 | []
| no_license | Zhandos-Hello-World/Introduction-to-Java | https://github.com/Zhandos-Hello-World/Introduction-to-Java | 79e455b86269e9cb6d1521de3f49dbddb980cc22 | 7ce2a220265cd48545dfb2d760c37e95acdffb88 | refs/heads/main | 2023-06-29T11:29:55.865000 | 2021-08-03T07:25:13 | 2021-08-03T07:25:13 | 350,361,967 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
(Linking two files) Write a program that prompts the user to enter the name of
an author and the title of one their books. It writes the author’s name to a file
by using the method written in Programming Exercise 12.15. Their book’s title
is written at the end of a file Books.txt with the line number of the author’s
name in Authors.txt inserted before the title. Assume that the title is not
already stored in Books.txt and the author name is already in Authors.txt.
*/
import java.util.Scanner;
import java.util.ArrayList;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Main{
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Write author's name: ");
String name = input.nextLine();
System.out.print("Author's name is written in the " + writeInFile(name, new File("Authors.txt")) + " index");
System.out.print("\nWrite author's book: ");
String book = input.nextLine();
System.out.print("Author's book is written in the " + writeInFile(book, new File("Book.txt")) + " index");
}
public static int writeInFile(String name, File file){
ArrayList<String> temp = new ArrayList<>();
if(file.exists()){
try{
Scanner input = new Scanner(file);
while(input.hasNext()){
temp.add(input.nextLine());
}
PrintWriter output = new PrintWriter(file);
for(int i = 0; i < temp.size(); i++){
output.println(temp.get(i));
}
output.println(name);
output.close();
input.close();
}
catch(FileNotFoundException ex){
System.out.print(ex.getMessage());
}
}
else{
try(PrintWriter output = new PrintWriter(file);){
output.println(name);
}catch(FileNotFoundException ex){
System.out.print(ex.getMessage());
}
}
return temp.size() + 1;
}
} | UTF-8 | Java | 1,833 | java | Main.java | Java | []
| null | []
| /*
(Linking two files) Write a program that prompts the user to enter the name of
an author and the title of one their books. It writes the author’s name to a file
by using the method written in Programming Exercise 12.15. Their book’s title
is written at the end of a file Books.txt with the line number of the author’s
name in Authors.txt inserted before the title. Assume that the title is not
already stored in Books.txt and the author name is already in Authors.txt.
*/
import java.util.Scanner;
import java.util.ArrayList;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Main{
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Write author's name: ");
String name = input.nextLine();
System.out.print("Author's name is written in the " + writeInFile(name, new File("Authors.txt")) + " index");
System.out.print("\nWrite author's book: ");
String book = input.nextLine();
System.out.print("Author's book is written in the " + writeInFile(book, new File("Book.txt")) + " index");
}
public static int writeInFile(String name, File file){
ArrayList<String> temp = new ArrayList<>();
if(file.exists()){
try{
Scanner input = new Scanner(file);
while(input.hasNext()){
temp.add(input.nextLine());
}
PrintWriter output = new PrintWriter(file);
for(int i = 0; i < temp.size(); i++){
output.println(temp.get(i));
}
output.println(name);
output.close();
input.close();
}
catch(FileNotFoundException ex){
System.out.print(ex.getMessage());
}
}
else{
try(PrintWriter output = new PrintWriter(file);){
output.println(name);
}catch(FileNotFoundException ex){
System.out.print(ex.getMessage());
}
}
return temp.size() + 1;
}
} | 1,833 | 0.691845 | 0.68856 | 56 | 31.642857 | 27.324392 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.482143 | false | false | 10 |
edb94dfd64ab553a6c2cac7f7014cb988a9901f8 | 9,603,546,911,313 | c0a79a12d5fc5c9f2521ed2b55f09389aca9a1ba | /dubbo-acid/dubbo-acid-facade/src/main/java/org/dubbo/acid/entity/AnalysisAnonymousEntity.java | 5fbb49e6b4cdf4d68e2d265b887d2027c92c4b7e | []
| no_license | boc1006/boc | https://github.com/boc1006/boc | 8362566442f0771e3fa13ddff878abca69c98c1b | a22e481401a20176bc02c55c7657b4052aa6e2f5 | refs/heads/master | 2021-05-11T13:00:44.498000 | 2018-01-16T10:39:53 | 2018-01-16T10:39:53 | 117,669,575 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.dubbo.acid.entity;
import java.io.Serializable;
public class AnalysisAnonymousEntity implements Serializable {
private static final long serialVersionUID = -307695598152779302L;
private long id;
private String clientid;
private String clientip;
private String pageid;
private String referer;
private String useragent;
private String userdata;
private long servtime;
private long clienttme;
private long dbtime;
private String terminal;
private String alldata;
private int residencetime;
private String siteid;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getClientid() {
return clientid;
}
public void setClientid(String clientid) {
this.clientid = clientid;
}
public String getClientip() {
return clientip;
}
public void setClientip(String clientip) {
this.clientip = clientip;
}
public String getPageid() {
return pageid;
}
public void setPageid(String pageid) {
this.pageid = pageid;
}
public String getReferer() {
return referer;
}
public void setReferer(String referer) {
this.referer = referer;
}
public String getUseragent() {
return useragent;
}
public void setUseragent(String useragent) {
this.useragent = useragent;
}
public String getUserdata() {
return userdata;
}
public void setUserdata(String userdata) {
this.userdata = userdata;
}
public long getServtime() {
return servtime;
}
public void setServtime(long servtime) {
this.servtime = servtime;
}
public long getClienttme() {
return clienttme;
}
public void setClienttme(long clienttme) {
this.clienttme = clienttme;
}
public long getDbtime() {
return dbtime;
}
public void setDbtime(long dbtime) {
this.dbtime = dbtime;
}
public String getTerminal() {
return terminal;
}
public void setTerminal(String terminal) {
this.terminal = terminal;
}
public String getAlldata() {
return alldata;
}
public void setAlldata(String alldata) {
this.alldata = alldata;
}
public int getResidencetime() {
return residencetime;
}
public void setResidencetime(int residencetime) {
this.residencetime = residencetime;
}
public String getSiteid() {
return siteid;
}
public void setSiteid(String siteid) {
this.siteid = siteid;
}
}
| UTF-8 | Java | 2,274 | java | AnalysisAnonymousEntity.java | Java | []
| null | []
| package org.dubbo.acid.entity;
import java.io.Serializable;
public class AnalysisAnonymousEntity implements Serializable {
private static final long serialVersionUID = -307695598152779302L;
private long id;
private String clientid;
private String clientip;
private String pageid;
private String referer;
private String useragent;
private String userdata;
private long servtime;
private long clienttme;
private long dbtime;
private String terminal;
private String alldata;
private int residencetime;
private String siteid;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getClientid() {
return clientid;
}
public void setClientid(String clientid) {
this.clientid = clientid;
}
public String getClientip() {
return clientip;
}
public void setClientip(String clientip) {
this.clientip = clientip;
}
public String getPageid() {
return pageid;
}
public void setPageid(String pageid) {
this.pageid = pageid;
}
public String getReferer() {
return referer;
}
public void setReferer(String referer) {
this.referer = referer;
}
public String getUseragent() {
return useragent;
}
public void setUseragent(String useragent) {
this.useragent = useragent;
}
public String getUserdata() {
return userdata;
}
public void setUserdata(String userdata) {
this.userdata = userdata;
}
public long getServtime() {
return servtime;
}
public void setServtime(long servtime) {
this.servtime = servtime;
}
public long getClienttme() {
return clienttme;
}
public void setClienttme(long clienttme) {
this.clienttme = clienttme;
}
public long getDbtime() {
return dbtime;
}
public void setDbtime(long dbtime) {
this.dbtime = dbtime;
}
public String getTerminal() {
return terminal;
}
public void setTerminal(String terminal) {
this.terminal = terminal;
}
public String getAlldata() {
return alldata;
}
public void setAlldata(String alldata) {
this.alldata = alldata;
}
public int getResidencetime() {
return residencetime;
}
public void setResidencetime(int residencetime) {
this.residencetime = residencetime;
}
public String getSiteid() {
return siteid;
}
public void setSiteid(String siteid) {
this.siteid = siteid;
}
}
| 2,274 | 0.730871 | 0.722955 | 108 | 20.055555 | 15.044891 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.611111 | false | false | 10 |
47d1b63ac158c12a23e028ff273bb722437dfa9a | 21,217,138,481,272 | 9e49c7bc59c8c3384545bf6497545690c9b912db | /Mathematical and String operations/Exercicio04.java | e1134b4e4f8214275ba4fc3c21e32aada030cc82 | []
| no_license | BrunoGino/Java | https://github.com/BrunoGino/Java | 99813cd23c01b51c5edc731d80fe97e3048820fb | 420a21b070ef6ae943ff3e53f2b1cad243f1b63a | refs/heads/master | 2018-12-08T15:07:14.901000 | 2018-11-13T13:26:46 | 2018-11-13T13:26:46 | 140,958,449 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cap04;
import javax.swing.JOptionPane;
public class Exercicio04 {
public static void main(String[] args) throws InterruptedException {
String frase = JOptionPane.showInputDialog("Insira uma frase qualquer: ");
String newFrase="";
for(int i=frase.length()-1;i>=0;i--){
char c = frase.charAt(i);
newFrase+=c;
}
JOptionPane.showMessageDialog(null,"Frase fornecida:\n"+frase+"\nFrase ao contrário:"+newFrase.replace(" "," "));
System.exit(0);
}
}
| UTF-8 | Java | 592 | java | Exercicio04.java | Java | []
| null | []
| package cap04;
import javax.swing.JOptionPane;
public class Exercicio04 {
public static void main(String[] args) throws InterruptedException {
String frase = JOptionPane.showInputDialog("Insira uma frase qualquer: ");
String newFrase="";
for(int i=frase.length()-1;i>=0;i--){
char c = frase.charAt(i);
newFrase+=c;
}
JOptionPane.showMessageDialog(null,"Frase fornecida:\n"+frase+"\nFrase ao contrário:"+newFrase.replace(" "," "));
System.exit(0);
}
}
| 592 | 0.563452 | 0.551607 | 14 | 41.214287 | 38.255119 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 10 |
ec07102ae71dec5053933c7c4e4f14e9d86a4850 | 15,109,694,984,678 | 5026a9cdd52c469d592b468e1de6c8cd2107d2b5 | /src/main/java/finskul/mr/WordCountPartitioner.java | 7ef5d593094ce38bb1b0b6c8ffe7ff8a640af018 | []
| no_license | FrederickPullen/hadoop-finskul | https://github.com/FrederickPullen/hadoop-finskul | dcdeae09068ecf2462ecd913273d86f390df64c6 | df3e7753eb6589829187af0bead56585e45ceead | refs/heads/master | 2018-03-31T14:52:17.750000 | 2017-04-13T12:05:09 | 2017-04-13T12:05:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package finskul.mr;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Partitioner;
import finskul.WordCountMRApp;
public class WordCountPartitioner extends Partitioner <Text, IntWritable>
{
@Override
public int getPartition(Text key, IntWritable value, int numReduceTasks)
{
return WordCountMRApp.evenOrOdd(key);
}
}
| UTF-8 | Java | 392 | java | WordCountPartitioner.java | Java | []
| null | []
| package finskul.mr;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Partitioner;
import finskul.WordCountMRApp;
public class WordCountPartitioner extends Partitioner <Text, IntWritable>
{
@Override
public int getPartition(Text key, IntWritable value, int numReduceTasks)
{
return WordCountMRApp.evenOrOdd(key);
}
}
| 392 | 0.790816 | 0.790816 | 20 | 18.6 | 24.162781 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 10 |
7f67fd5fbde17adfda73c145c048e575815561fa | 28,312,424,460,021 | 86c7c7a84e8e0c7f31b8dfccf17c11518f7cf446 | /AppAprendiendoIdiomas/app/src/main/java/com/example/appaprendiendoidiomas/ActivityNumeros.java | bc304f72b5bae9a31e3f4c380e9c00a8445e4345 | []
| no_license | gasparpd/Android | https://github.com/gasparpd/Android | 168191f2553de0a833f0c7c7934a3d61c6753888 | 2af386335c718a6f54049550d12d7a537f6b21a3 | refs/heads/master | 2020-12-11T15:41:14.300000 | 2020-03-18T13:38:50 | 2020-03-18T13:38:50 | 233,887,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.appaprendiendoidiomas;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class ActivityNumeros extends MainActivity {
Spinner spinner;
Button btn_0, btn_10, btn_20;
FloatingActionButton btn_practica;
int array_charged;
TextView tv_numbers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numeros);
spinner = findViewById(R.id.spinner_apr_num);
btn_0 = findViewById(R.id.btn_apr_num_0);
btn_10 = findViewById(R.id.btn_apr_num_10);
btn_20 = findViewById(R.id.btn_apr_num_20);
btn_practica = findViewById(R.id.apr_num_btn_practica);
tv_numbers = findViewById(R.id.tv_apr_num);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String string_num = comprobarNum(position);
tv_numbers.setText(string_num);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner.setEnabled(false);
}
public void practicaNumeros(View view) {
Intent i = new Intent(this, ActivityPractNumeros.class);
startActivity(i);
}
public void charge0 (View v){
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.array_0_9, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setEnabled(true);
array_charged = 0;
}
public void charge10 (View v){
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.array_10_19, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setEnabled(true);
array_charged = 10;
}
public void charge20 (View v){
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.array_20_100, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setEnabled(true);
array_charged = 20;
}
public String comprobarNum (int position){
String tv_num = "";
if(array_charged == 0){
switch (position){
case 0:
tv_num = "ZERO";
break;
case 1:
tv_num = "ONE";
break;
case 2:
tv_num = "TWO";
break;
case 3:
tv_num = "THREE";
break;
case 4:
tv_num = "FOUR";
break;
case 5:
tv_num = "FIVE";
break;
case 6:
tv_num = "SIX";
break;
case 7:
tv_num = "SEVEN";
break;
case 8:
tv_num = "EIGHT";
break;
case 9:
tv_num = "NINE";
break;
}
} else if (array_charged == 10){
switch (position){
case 0:
tv_num = "TEN";
break;
case 1:
tv_num = "ELEVEN";
break;
case 2:
tv_num = "TWELVE";
break;
case 3:
tv_num = "THIRTEEN";
break;
case 4:
tv_num = "FOURTEEN";
break;
case 5:
tv_num = "FIFTEEN";
break;
case 6:
tv_num = "SIXTEEN";
break;
case 7:
tv_num = "SEVENTEEN";
break;
case 8:
tv_num = "EIGHTEEN";
break;
case 9:
tv_num = "NINETEEN";
break;
}
}else if (array_charged == 20){
switch (position){
case 0:
tv_num = "TWENTY";
break;
case 1:
tv_num = "THIRTY";
break;
case 2:
tv_num = "FORTY";
break;
case 3:
tv_num = "FIFTY";
break;
case 4:
tv_num = "SIXTY";
break;
case 5:
tv_num = "SEVENTY";
break;
case 6:
tv_num = "EIGHTY";
break;
case 7:
tv_num = "NINETY";
break;
case 8:
tv_num = "ONE HUNDRED";
break;
}
}
return tv_num;
}
}
| UTF-8 | Java | 6,416 | java | ActivityNumeros.java | Java | []
| null | []
| package com.example.appaprendiendoidiomas;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class ActivityNumeros extends MainActivity {
Spinner spinner;
Button btn_0, btn_10, btn_20;
FloatingActionButton btn_practica;
int array_charged;
TextView tv_numbers;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numeros);
spinner = findViewById(R.id.spinner_apr_num);
btn_0 = findViewById(R.id.btn_apr_num_0);
btn_10 = findViewById(R.id.btn_apr_num_10);
btn_20 = findViewById(R.id.btn_apr_num_20);
btn_practica = findViewById(R.id.apr_num_btn_practica);
tv_numbers = findViewById(R.id.tv_apr_num);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String string_num = comprobarNum(position);
tv_numbers.setText(string_num);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner.setEnabled(false);
}
public void practicaNumeros(View view) {
Intent i = new Intent(this, ActivityPractNumeros.class);
startActivity(i);
}
public void charge0 (View v){
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.array_0_9, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setEnabled(true);
array_charged = 0;
}
public void charge10 (View v){
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.array_10_19, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setEnabled(true);
array_charged = 10;
}
public void charge20 (View v){
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.array_20_100, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setEnabled(true);
array_charged = 20;
}
public String comprobarNum (int position){
String tv_num = "";
if(array_charged == 0){
switch (position){
case 0:
tv_num = "ZERO";
break;
case 1:
tv_num = "ONE";
break;
case 2:
tv_num = "TWO";
break;
case 3:
tv_num = "THREE";
break;
case 4:
tv_num = "FOUR";
break;
case 5:
tv_num = "FIVE";
break;
case 6:
tv_num = "SIX";
break;
case 7:
tv_num = "SEVEN";
break;
case 8:
tv_num = "EIGHT";
break;
case 9:
tv_num = "NINE";
break;
}
} else if (array_charged == 10){
switch (position){
case 0:
tv_num = "TEN";
break;
case 1:
tv_num = "ELEVEN";
break;
case 2:
tv_num = "TWELVE";
break;
case 3:
tv_num = "THIRTEEN";
break;
case 4:
tv_num = "FOURTEEN";
break;
case 5:
tv_num = "FIFTEEN";
break;
case 6:
tv_num = "SIXTEEN";
break;
case 7:
tv_num = "SEVENTEEN";
break;
case 8:
tv_num = "EIGHTEEN";
break;
case 9:
tv_num = "NINETEEN";
break;
}
}else if (array_charged == 20){
switch (position){
case 0:
tv_num = "TWENTY";
break;
case 1:
tv_num = "THIRTY";
break;
case 2:
tv_num = "FORTY";
break;
case 3:
tv_num = "FIFTY";
break;
case 4:
tv_num = "SIXTY";
break;
case 5:
tv_num = "SEVENTY";
break;
case 6:
tv_num = "EIGHTY";
break;
case 7:
tv_num = "NINETY";
break;
case 8:
tv_num = "ONE HUNDRED";
break;
}
}
return tv_num;
}
}
| 6,416 | 0.481608 | 0.470698 | 194 | 32.072166 | 20.611151 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.597938 | false | false | 10 |
2f65ddea2703cc07a84f4a933ff9383750b888f4 | 8,194,797,653,588 | 70be890cc0cb89f28a05fb63fd7f17a9975587be | /ConstructorCall/src/com/saiprasanna/Test.java | 9dd48eaa9e616501f3119c9a74c0c9c26b8741ce | []
| no_license | dmovva/gitlearning | https://github.com/dmovva/gitlearning | 8ca9d3fbd91f7c2940e803dd981f4eb0af197773 | fed94c3b305a211f8df3ae3fbd9d814346749e6b | refs/heads/master | 2020-03-31T11:49:21.192000 | 2018-10-09T05:53:38 | 2018-10-09T05:53:38 | 152,192,528 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.saiprasanna;
/**
* Created by saipr on 6/2/2016.
*/
public class Test {
Test(){
this(10);
System.out.println("0 arg-constructor");
}
Test(int a){
this(10,20);
System.out.println("1-arg constructor: "+a);
}
Test(int a,int b){
System.out.println("2-arg constructors, "+ "first: "+a+", Second: "+b);
}
}
| UTF-8 | Java | 383 | java | Test.java | Java | [
{
"context": "package com.saiprasanna;\n\n/**\n * Created by saipr on 6/2/2016.\n */\npublic class Test {\n Test(){\n",
"end": 49,
"score": 0.999491810798645,
"start": 44,
"tag": "USERNAME",
"value": "saipr"
}
]
| null | []
| package com.saiprasanna;
/**
* Created by saipr on 6/2/2016.
*/
public class Test {
Test(){
this(10);
System.out.println("0 arg-constructor");
}
Test(int a){
this(10,20);
System.out.println("1-arg constructor: "+a);
}
Test(int a,int b){
System.out.println("2-arg constructors, "+ "first: "+a+", Second: "+b);
}
}
| 383 | 0.532637 | 0.493473 | 21 | 17.238094 | 20.252935 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false | 10 |
10b9fcf0192df6a869d977ce6afe85b4e65630f9 | 18,296,560,746,353 | c474b03758be154e43758220e47b3403eb7fc1fc | /apk/decompiled/com.tinder_2018-07-26_source_from_JADX/sources/com/tinder/utils/C15364o.java | d1e78bc801831b8fc8951f5d0bcb7e581314c619 | []
| no_license | EstebanDalelR/tinderAnalysis | https://github.com/EstebanDalelR/tinderAnalysis | f80fe1f43b3b9dba283b5db1781189a0dd592c24 | 941e2c634c40e5dbf5585c6876ef33f2a578b65c | refs/heads/master | 2020-04-04T09:03:32.659000 | 2018-11-23T20:41:28 | 2018-11-23T20:41:28 | 155,805,042 | 0 | 0 | null | false | 2018-11-18T16:02:45 | 2018-11-02T02:44:34 | 2018-11-18T15:58:25 | 2018-11-18T16:02:44 | 353,670 | 0 | 0 | 0 | null | false | null | package com.tinder.utils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import kotlin.Metadata;
import kotlin.jvm.internal.C2668g;
import org.jetbrains.annotations.NotNull;
@Metadata(bv = {1, 0, 2}, d1 = {"\u0000\f\n\u0000\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\u001a\n\u0010\u0000\u001a\u00020\u0001*\u00020\u0002¨\u0006\u0003"}, d2 = {"networkClass", "Lcom/tinder/utils/NetworkClass;", "Landroid/net/ConnectivityManager;", "Tinder_release"}, k = 2, mv = {1, 1, 10})
/* renamed from: com.tinder.utils.o */
public final class C15364o {
@NotNull
/* renamed from: a */
public static final NetworkClass m57673a(@NotNull ConnectivityManager connectivityManager) {
C2668g.b(connectivityManager, "$receiver");
if (connectivityManager.getActiveNetworkInfo() != null) {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
C2668g.a(activeNetworkInfo, "activeNetworkInfo");
if (activeNetworkInfo.isConnected()) {
activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
C2668g.a(activeNetworkInfo, "activeNetworkInfo");
if (activeNetworkInfo.getType() == 1) {
return NetworkClass.WIFI;
}
connectivityManager = connectivityManager.getActiveNetworkInfo();
C2668g.a(connectivityManager, "activeNetworkInfo");
switch (connectivityManager.getSubtype()) {
case 1:
case 2:
case 4:
case 7:
case 11:
connectivityManager = NetworkClass.NET_2G;
break;
case 3:
case 5:
case 6:
case 8:
case 9:
case 10:
case 12:
case 14:
case 15:
connectivityManager = NetworkClass.NET_3G;
break;
case 13:
connectivityManager = NetworkClass.NET_4G;
break;
default:
connectivityManager = NetworkClass.UNKNOWN;
break;
}
return connectivityManager;
}
}
return NetworkClass.NOT_CONNECTED;
}
}
| UTF-8 | Java | 2,490 | java | C15364o.java | Java | []
| null | []
| package com.tinder.utils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import kotlin.Metadata;
import kotlin.jvm.internal.C2668g;
import org.jetbrains.annotations.NotNull;
@Metadata(bv = {1, 0, 2}, d1 = {"\u0000\f\n\u0000\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\u001a\n\u0010\u0000\u001a\u00020\u0001*\u00020\u0002¨\u0006\u0003"}, d2 = {"networkClass", "Lcom/tinder/utils/NetworkClass;", "Landroid/net/ConnectivityManager;", "Tinder_release"}, k = 2, mv = {1, 1, 10})
/* renamed from: com.tinder.utils.o */
public final class C15364o {
@NotNull
/* renamed from: a */
public static final NetworkClass m57673a(@NotNull ConnectivityManager connectivityManager) {
C2668g.b(connectivityManager, "$receiver");
if (connectivityManager.getActiveNetworkInfo() != null) {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
C2668g.a(activeNetworkInfo, "activeNetworkInfo");
if (activeNetworkInfo.isConnected()) {
activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
C2668g.a(activeNetworkInfo, "activeNetworkInfo");
if (activeNetworkInfo.getType() == 1) {
return NetworkClass.WIFI;
}
connectivityManager = connectivityManager.getActiveNetworkInfo();
C2668g.a(connectivityManager, "activeNetworkInfo");
switch (connectivityManager.getSubtype()) {
case 1:
case 2:
case 4:
case 7:
case 11:
connectivityManager = NetworkClass.NET_2G;
break;
case 3:
case 5:
case 6:
case 8:
case 9:
case 10:
case 12:
case 14:
case 15:
connectivityManager = NetworkClass.NET_3G;
break;
case 13:
connectivityManager = NetworkClass.NET_4G;
break;
default:
connectivityManager = NetworkClass.UNKNOWN;
break;
}
return connectivityManager;
}
}
return NetworkClass.NOT_CONNECTED;
}
}
| 2,490 | 0.53636 | 0.479711 | 58 | 41.913792 | 40.882206 | 303 | false | false | 0 | 0 | 24 | 0.009642 | 0 | 0 | 0.706897 | false | false | 10 |
34b693d6db608ae4e52bf1fd918e84278a1841fb | 18,296,560,747,030 | ee8f76474c80cc89d0ba522d3f0ad24e9678e34b | /app/src/main/java/com/example/pocketclash/TopTenActivity.java | 25252efd90a48654723fc0aa7fc8431aca1d5a0d | []
| no_license | Vadix3/PocketClash | https://github.com/Vadix3/PocketClash | 14b51c7c76e5857c1a38b0c5db2c30fe47d49c61 | 6c5a7ce987a86f7bdd16713173170f11c4d32602 | refs/heads/master | 2022-12-22T15:23:28.392000 | 2020-09-24T14:12:36 | 2020-09-24T14:12:36 | 287,447,329 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.pocketclash;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class TopTenActivity extends AppCompatActivity implements View.OnLongClickListener, View.OnClickListener {
/**
* Views
*/
private RecyclerView recyclerView;
private TextView clearButton;
private RelativeLayout mainLayout;
private ImageView background;
private Toast toast;
MySP mySP;
RecyclerViewAdapter recyclerViewAdapter;
/**
* Variables
*/
private ArrayList<Score> scores;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mySP = new MySP(getApplicationContext());
setContentView(R.layout.activity_topten);
initViews();
initScores();
initRecyclerView();
}
/**
* A method to fill the RecyclerView
*/
private void initRecyclerView() {
recyclerViewAdapter = new RecyclerViewAdapter(this, scores);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
/**
* A method to initialize the widgets
*/
private void initViews() {
recyclerView = findViewById(R.id.top10_LST_recyclerView);
clearButton = findViewById(R.id.top10_LBL_clearList);
clearButton.setOnLongClickListener(this);
clearButton.setOnClickListener(this);
mainLayout = findViewById(R.id.top10_LAY_mainLayout);
background = findViewById(R.id.top10_IMG_background);
Glide.with(background).load(R.drawable.top_10_background).into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
mainLayout.setBackground(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
/**
* A method to save the top10Array to SP
*/
private void saveArrayToSP() {
Gson gson = new Gson();
String gradeJson = gson.toJson(scores);
mySP.putString(MySP.KEYS.TOP_10_ARRAY, gradeJson);
}
private void initScores() {
scores = new ArrayList<>();
Gson gson = new Gson();
String top10String = mySP.getString(MySP.KEYS.TOP_10_ARRAY, "");
Type scoreType = new TypeToken<ArrayList<Score>>() {
}.getType();
scores = gson.fromJson(top10String, scoreType); // get grades array from json
if (scores != null) { // If there is something to load
System.out.println("Scores array: " + scores.toString());
} else { // If there is nothing to load, init array
scores = new ArrayList<>();
}
}
@Override
public boolean onLongClick(View view) {
if (view.getId() == R.id.top10_LBL_clearList) {
displayToast("List Cleared");
scores.clear();
saveArrayToSP();
initRecyclerView();
}
return false;
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.top10_LBL_clearList) {
if (toast == null)
Toast.makeText(this, "Hold to clear list", Toast.LENGTH_SHORT).show();
}
}
/**
* A function to display Toast with given text
*/
private void displayToast(final String message) {
if (toast != null)
toast.cancel();
toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.show();
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
Intent intent = new Intent(TopTenActivity.this, WelcomeActivity.class);
startActivity(intent);
}
}
| UTF-8 | Java | 4,579 | java | TopTenActivity.java | Java | []
| null | []
| package com.example.pocketclash;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class TopTenActivity extends AppCompatActivity implements View.OnLongClickListener, View.OnClickListener {
/**
* Views
*/
private RecyclerView recyclerView;
private TextView clearButton;
private RelativeLayout mainLayout;
private ImageView background;
private Toast toast;
MySP mySP;
RecyclerViewAdapter recyclerViewAdapter;
/**
* Variables
*/
private ArrayList<Score> scores;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mySP = new MySP(getApplicationContext());
setContentView(R.layout.activity_topten);
initViews();
initScores();
initRecyclerView();
}
/**
* A method to fill the RecyclerView
*/
private void initRecyclerView() {
recyclerViewAdapter = new RecyclerViewAdapter(this, scores);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
/**
* A method to initialize the widgets
*/
private void initViews() {
recyclerView = findViewById(R.id.top10_LST_recyclerView);
clearButton = findViewById(R.id.top10_LBL_clearList);
clearButton.setOnLongClickListener(this);
clearButton.setOnClickListener(this);
mainLayout = findViewById(R.id.top10_LAY_mainLayout);
background = findViewById(R.id.top10_IMG_background);
Glide.with(background).load(R.drawable.top_10_background).into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
mainLayout.setBackground(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
/**
* A method to save the top10Array to SP
*/
private void saveArrayToSP() {
Gson gson = new Gson();
String gradeJson = gson.toJson(scores);
mySP.putString(MySP.KEYS.TOP_10_ARRAY, gradeJson);
}
private void initScores() {
scores = new ArrayList<>();
Gson gson = new Gson();
String top10String = mySP.getString(MySP.KEYS.TOP_10_ARRAY, "");
Type scoreType = new TypeToken<ArrayList<Score>>() {
}.getType();
scores = gson.fromJson(top10String, scoreType); // get grades array from json
if (scores != null) { // If there is something to load
System.out.println("Scores array: " + scores.toString());
} else { // If there is nothing to load, init array
scores = new ArrayList<>();
}
}
@Override
public boolean onLongClick(View view) {
if (view.getId() == R.id.top10_LBL_clearList) {
displayToast("List Cleared");
scores.clear();
saveArrayToSP();
initRecyclerView();
}
return false;
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.top10_LBL_clearList) {
if (toast == null)
Toast.makeText(this, "Hold to clear list", Toast.LENGTH_SHORT).show();
}
}
/**
* A function to display Toast with given text
*/
private void displayToast(final String message) {
if (toast != null)
toast.cancel();
toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.show();
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
Intent intent = new Intent(TopTenActivity.this, WelcomeActivity.class);
startActivity(intent);
}
}
| 4,579 | 0.652763 | 0.647521 | 147 | 30.14966 | 25.034765 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55102 | false | false | 10 |
a0f9906391b7ae9251195149d92d55e2aa1db3b1 | 35,828,617,198,200 | 0ce736857acafab8928a60a9749e1611aa1072f6 | /src/main/java/eu/socialsensor/framework/client/dao/MediaItemDAO.java | 6a92ee6a59e42f964c4035ed10ba5ed0c83cdb7c | [
"Apache-2.0"
]
| permissive | kandreadou/socialsensor-framework-client | https://github.com/kandreadou/socialsensor-framework-client | 01f9b258c3398f9032c9b94f4bdacc47e9c467fe | 4a9302fc61f4d899b58bb594e6c049bfd2aa8ed8 | refs/heads/master | 2020-12-26T02:31:53.421000 | 2014-01-09T11:00:28 | 2014-01-09T11:00:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eu.socialsensor.framework.client.dao;
import java.util.List;
import eu.socialsensor.framework.common.domain.MediaItem;
/**
*
* @author etzoannos
*/
public interface MediaItemDAO {
public void addMediaItem(MediaItem item);
public void updateMediaItem(String id, String name, Object value);
public void updateMediaItem(MediaItem item);
public void updateMediaItemPopularity(MediaItem item);
public boolean removeMediaItem(String mediaItemId);
public MediaItem getMediaItem(String mediaItemId);
public List<MediaItem> getLastMediaItems(int size);
public List<MediaItem> getLastMediaItems(long fromDate);
public List<MediaItem> getLastMediaItemsWithGeo(int size);
public List<MediaItem> getLastMediaItemsWithGeo(long fromDate);
public List<MediaItem> getLastNIndexedMediaItems(int size);
public List<MediaItem> getRecentIndexedMediaItems(long fromDate);
public boolean exists(MediaItem item);
public boolean exists(String id);
public void updateMediaItemDyscoId(String url, String dyscoId);
public List<MediaItem> getMediaItemsByDysco(String dyscoId, String mediaType, int size);
public List<MediaItem> getMediaItemsByUrls(List<String> url, String mediaType, int size);
public List<MediaItem> getMediaItemsByDyscos(List<String> dyscoIds, String mediaType, int size);
public List<MediaItem> getMediaItemsForItems(List<String> itemIds, String mediaType, int size);
public List<MediaItem> getMediaItemsForUrls(List<String> urls, String mediaType, int size);
List<MediaItem> getUnindexedItems(int max);
}
| UTF-8 | Java | 1,774 | java | MediaItemDAO.java | Java | [
{
"context": "rk.common.domain.MediaItem;\r\n\r\n/**\r\n *\r\n * @author etzoannos\r\n */\r\npublic interface MediaItemDAO {\r\n\r\n publ",
"end": 269,
"score": 0.9996178150177002,
"start": 260,
"tag": "USERNAME",
"value": "etzoannos"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eu.socialsensor.framework.client.dao;
import java.util.List;
import eu.socialsensor.framework.common.domain.MediaItem;
/**
*
* @author etzoannos
*/
public interface MediaItemDAO {
public void addMediaItem(MediaItem item);
public void updateMediaItem(String id, String name, Object value);
public void updateMediaItem(MediaItem item);
public void updateMediaItemPopularity(MediaItem item);
public boolean removeMediaItem(String mediaItemId);
public MediaItem getMediaItem(String mediaItemId);
public List<MediaItem> getLastMediaItems(int size);
public List<MediaItem> getLastMediaItems(long fromDate);
public List<MediaItem> getLastMediaItemsWithGeo(int size);
public List<MediaItem> getLastMediaItemsWithGeo(long fromDate);
public List<MediaItem> getLastNIndexedMediaItems(int size);
public List<MediaItem> getRecentIndexedMediaItems(long fromDate);
public boolean exists(MediaItem item);
public boolean exists(String id);
public void updateMediaItemDyscoId(String url, String dyscoId);
public List<MediaItem> getMediaItemsByDysco(String dyscoId, String mediaType, int size);
public List<MediaItem> getMediaItemsByUrls(List<String> url, String mediaType, int size);
public List<MediaItem> getMediaItemsByDyscos(List<String> dyscoIds, String mediaType, int size);
public List<MediaItem> getMediaItemsForItems(List<String> itemIds, String mediaType, int size);
public List<MediaItem> getMediaItemsForUrls(List<String> urls, String mediaType, int size);
List<MediaItem> getUnindexedItems(int max);
}
| 1,774 | 0.741826 | 0.741826 | 58 | 28.586206 | 32.688728 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672414 | false | false | 10 |
e660e5d356fa7126a4ea7f2c6bec58e8c06eb585 | 6,863,357,805,789 | 7a79a77dfbde361f3f23a02a9cb608a457daf385 | /test/src/main/java/io/github/privacystreams/test/MainActivity.java | 31ccda829beacf282ad736376c828b0df233090c | [
"Apache-2.0"
]
| permissive | MessageOnTap/PrivacyStreams | https://github.com/MessageOnTap/PrivacyStreams | 7e9f9bb6361992eb5c6ae841209dbe14e428f044 | c66f2cbc62add0a4a5c06f14432d3f6b4d7b282e | refs/heads/master | 2021-09-11T01:43:56.474000 | 2018-04-05T22:39:16 | 2018-04-05T22:39:16 | 91,588,268 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.github.privacystreams.test;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.multidex.MultiDex;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MultiDex.install(this);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new MyAsyncTask().execute();
}
});
}
private class MyAsyncTask extends AsyncTask<Object, Object, Object> {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected Object doInBackground(Object[] objects) {
TestCases testCases = new TestCases(MainActivity.this);
//testCases.testEmailList();;
// testCases.testsift();
// testCases.testContact(apiKey,apiSecret);
// testCases.testFlight(api_key,api_secret);
// testCases.testFood(apiKey,apiSecret);
// testCases.testParcel(api_key,api_secret);
//testCases.testImage();
//testCases.testInvoice(api_key,api_secret,"whatever");
// testCases.testOrder(api_key,api_secret);
// testCases.testDriveList();
// testCases.testEmailList();
// testCases.testCurrentLocation();
// testCases.testLocation();
// testCases.testImageUpdate();
//testCases.testImage();
//testCases.testBrowserSearchUpdates();
testCases.testBrowserHistoryUpdates();
// testCases.testLocalFileUpdate();
return null;
}
}
} | UTF-8 | Java | 2,057 | java | MainActivity.java | Java | []
| null | []
| package io.github.privacystreams.test;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.multidex.MultiDex;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MultiDex.install(this);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new MyAsyncTask().execute();
}
});
}
private class MyAsyncTask extends AsyncTask<Object, Object, Object> {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
protected Object doInBackground(Object[] objects) {
TestCases testCases = new TestCases(MainActivity.this);
//testCases.testEmailList();;
// testCases.testsift();
// testCases.testContact(apiKey,apiSecret);
// testCases.testFlight(api_key,api_secret);
// testCases.testFood(apiKey,apiSecret);
// testCases.testParcel(api_key,api_secret);
//testCases.testImage();
//testCases.testInvoice(api_key,api_secret,"whatever");
// testCases.testOrder(api_key,api_secret);
// testCases.testDriveList();
// testCases.testEmailList();
// testCases.testCurrentLocation();
// testCases.testLocation();
// testCases.testImageUpdate();
//testCases.testImage();
//testCases.testBrowserSearchUpdates();
testCases.testBrowserHistoryUpdates();
// testCases.testLocalFileUpdate();
return null;
}
}
} | 2,057 | 0.633933 | 0.632961 | 57 | 35.105263 | 20.618238 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.807018 | false | false | 10 |
25240d41d07d80cfbc5ce2213d09595ffb63d5f6 | 30,185,030,198,342 | 879c7e6a81aabe2ba746bc0f9857ffb3d067e6f6 | /CalcularConta/src/br/com/exercicio/back/dao/ClienteDAO.java | ebd466beeff37174ece4b9af39a404e40b6ebe8f | []
| no_license | leandro992/CalcularCorrida | https://github.com/leandro992/CalcularCorrida | af878e5b27cc832703334e6a4cc79f7817ae9386 | e3084aac7f2cd6d88df6b07b5c082beb0960e73d | refs/heads/master | 2020-03-16T05:32:51.102000 | 2018-05-08T01:48:07 | 2018-05-08T01:48:07 | 132,534,443 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.exercicio.back.dao;
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 br.com.exercicio.back.bean.Cliente;
import br.com.exercicio.conexaobanco.ConnectionManager;
/**
* Classe DAO da entidade <code>Cliente</code> no banco de dados
*
* @author Victor Leandro
*
*/
public class ClienteDAO {
public void incluirCliente(Cliente cliente) {
Connection conn = null;
try {
conn = ConnectionManager.getInstance().getConnection();
String sql = "INSERT INTO TB_CUSTOMER_ACCOUNT(cpf_cnpj, nm_customer, is_active, vl_total) VALUES (?,?,?,?)";
PreparedStatement stmtInsert = conn.prepareStatement(sql);
stmtInsert.setString(1, cliente.getCpf_cnpj());
stmtInsert.setString(2, cliente.getNome());
stmtInsert.setInt(3, cliente.getAtivo());
stmtInsert.setDouble(4, cliente.getValor());
stmtInsert.executeUpdate();
} catch (SQLException e) {
System.err.println("Erro ao inserir cliente.");
e.printStackTrace();
} finally {
if (conn != null) { // se ha uma conexao, fecha ela.
try {
// fechar a conexao com SGBDR.
conn.close();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
}
}
public List<Cliente> buscaClientesParaCalculoMedia() {
Connection conn = null; // conexao com o SGBDR
List<Cliente> listaClientes = new ArrayList<>();
try {
conn = ConnectionManager.getInstance().getConnection();
PreparedStatement stmtselect = conn.prepareStatement(
" Select * from tb_customer_account "+
" where ID_CUSTOMER BETWEEN 1 and 50 and vl_total > 240" +
" order by vl_total desc, nm_customer asc ");
ResultSet rs = stmtselect.executeQuery();
while (rs.next()) {
int id = rs.getInt("id_customer");
String cpf_cnpj = (String) rs.getString("cpf_cnpj");
String nome = rs.getString("nm_customer");
int ativo = rs.getInt("is_active");
double total = rs.getDouble("vl_total");
Cliente cliente = new Cliente(id, nome, cpf_cnpj, ativo, total);
listaClientes.add(cliente);
}
rs.close();
} catch (SQLException e) {
System.err.println("Erro ao executar query.");
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e2) {
System.err.println("Erro ao fechar o banco. " + e2.getMessage());
}
}
}
return listaClientes;
}
}
| UTF-8 | Java | 2,493 | java | ClienteDAO.java | Java | [
{
"context": "de>Cliente</code> no banco de dados\n * \n * @author Victor Leandro\n *\n */\npublic class ClienteDAO {\n\n\tpublic void in",
"end": 406,
"score": 0.9998377561569214,
"start": 392,
"tag": "NAME",
"value": "Victor Leandro"
}
]
| null | []
| package br.com.exercicio.back.dao;
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 br.com.exercicio.back.bean.Cliente;
import br.com.exercicio.conexaobanco.ConnectionManager;
/**
* Classe DAO da entidade <code>Cliente</code> no banco de dados
*
* @author <NAME>
*
*/
public class ClienteDAO {
public void incluirCliente(Cliente cliente) {
Connection conn = null;
try {
conn = ConnectionManager.getInstance().getConnection();
String sql = "INSERT INTO TB_CUSTOMER_ACCOUNT(cpf_cnpj, nm_customer, is_active, vl_total) VALUES (?,?,?,?)";
PreparedStatement stmtInsert = conn.prepareStatement(sql);
stmtInsert.setString(1, cliente.getCpf_cnpj());
stmtInsert.setString(2, cliente.getNome());
stmtInsert.setInt(3, cliente.getAtivo());
stmtInsert.setDouble(4, cliente.getValor());
stmtInsert.executeUpdate();
} catch (SQLException e) {
System.err.println("Erro ao inserir cliente.");
e.printStackTrace();
} finally {
if (conn != null) { // se ha uma conexao, fecha ela.
try {
// fechar a conexao com SGBDR.
conn.close();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
}
}
public List<Cliente> buscaClientesParaCalculoMedia() {
Connection conn = null; // conexao com o SGBDR
List<Cliente> listaClientes = new ArrayList<>();
try {
conn = ConnectionManager.getInstance().getConnection();
PreparedStatement stmtselect = conn.prepareStatement(
" Select * from tb_customer_account "+
" where ID_CUSTOMER BETWEEN 1 and 50 and vl_total > 240" +
" order by vl_total desc, nm_customer asc ");
ResultSet rs = stmtselect.executeQuery();
while (rs.next()) {
int id = rs.getInt("id_customer");
String cpf_cnpj = (String) rs.getString("cpf_cnpj");
String nome = rs.getString("nm_customer");
int ativo = rs.getInt("is_active");
double total = rs.getDouble("vl_total");
Cliente cliente = new Cliente(id, nome, cpf_cnpj, ativo, total);
listaClientes.add(cliente);
}
rs.close();
} catch (SQLException e) {
System.err.println("Erro ao executar query.");
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e2) {
System.err.println("Erro ao fechar o banco. " + e2.getMessage());
}
}
}
return listaClientes;
}
}
| 2,485 | 0.667068 | 0.661452 | 99 | 24.181818 | 23.000818 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.565657 | false | false | 10 |
9454a63490319ed529a0b735d66fcae806a8e7f3 | 37,941,741,096,260 | 011976b1e0df3a786459e37796d2aef24e92fb0d | /src/br/edu/ifce/ia/DecisionTree.java | e245a4d859ae8adee6f57a02d9eab0ac4c6d7777 | []
| no_license | likaiju/decisiontree | https://github.com/likaiju/decisiontree | d961fb0637c407855cfc819f215527c8234af732 | 6be0d491f6703a0070b2b7ee6a0fc3037471d0ea | refs/heads/master | 2020-06-11T22:25:37.689000 | 2014-10-22T02:48:54 | 2014-10-22T02:48:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.edu.ifce.ia;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DecisionTree {
private List<Map<String, String>> table;
private TreeNode rootTree;
public DecisionTree() {
this.table = new ArrayList<Map<String, String>>();
}
public void addRow(String[] fields, String[] data) {
Map<String, String> rowData = new HashMap<String, String>();
for (int i = fields.length - 1; i >= 0; i--) {
rowData.put(fields[i], data[i]);
}
this.table.add(rowData);
}
public void printTable() {
System.out.println();
int size = 12;
if (!this.table.isEmpty()) {
Set<String> fields = this.table.get(0).keySet();
for (String field : fields) {
System.out.print(" | " + field);
for (int i = 0; i < size - field.length(); i++)
System.out.print(" ");
}
System.out.println();
for (Map<String, String> row : this.table) {
Collection<String> data = row.values();
for (String string : data) {
System.out.print(" | " + string);
for (int i = 0; i < size - string.length(); i++)
System.out.print(" ");
}
System.out.println();
}
}
}
private double calculateGain(TreeNode node) {
double result = 0.0;
int allPositiveCount = 0, allNegativeCount = 0;
List<String> fieldValues = new ArrayList<String>();
Map<String, Integer> fieldFrequencyPos = new HashMap<String, Integer>();
Map<String, Integer> fieldFrequencyNeg = new HashMap<String, Integer>();
for (Map<String, String> map : table) {
String s = map.get(node.value);
if (!fieldValues.contains(s)) {
fieldValues.add(s);
fieldFrequencyPos.put(s, 0);
fieldFrequencyNeg.put(s, 0);
}
}
for (Map<String, String> map : table) {
String s = map.get(node.value);
String classe = map.get("classe");
Integer freqPos = fieldFrequencyPos.get(s);
Integer freqNeg = fieldFrequencyNeg.get(s);
if (node.parent != null) {
String parentValue = map.get(node.parent.value);
String action = node.action;
if (parentValue.equals(action)) {
if (classe.equalsIgnoreCase("sim")) {
fieldFrequencyPos.put(s, ++freqPos);
} else if (classe.equalsIgnoreCase("não")) {
fieldFrequencyNeg.put(s, ++freqNeg);
}
}
} else {
if (classe.equalsIgnoreCase("sim")) {
fieldFrequencyPos.put(s, ++freqPos);
} else if (classe.equalsIgnoreCase("não")) {
fieldFrequencyNeg.put(s, ++freqNeg);
}
}
}
double resto = 0.0;
for (String string : fieldValues) {
int fieldPos, fieldNeg;
double fieldTotal, total = 0.0;
fieldPos = fieldFrequencyPos.get(string);
fieldNeg = fieldFrequencyNeg.get(string);
fieldTotal = fieldPos + fieldNeg;
if (node.parent != null) {
for (Map<String, String> map : table) {
String parentValue = map.get(node.parent.value);
String action = node.action;
if (parentValue.equals(action)) {
total++;
}
}
} else {
total = table.size();
}
resto += (fieldTotal / total) * calculateEntropy(fieldPos, fieldNeg);
}
for (Map<String, String> map : table) {
String classe = map.get("classe");
if (node.parent != null) {
String parentValue = map.get(node.parent.value);
String action = node.action;
if (parentValue.equals(action)) {
if (classe.equalsIgnoreCase("sim")) {
allPositiveCount++;
} else if (classe.equalsIgnoreCase("não")) {
allNegativeCount++;
}
}
} else {
if (classe.equalsIgnoreCase("sim")) {
allPositiveCount++;
} else if (classe.equalsIgnoreCase("não")) {
allNegativeCount++;
}
}
}
result = calculateEntropy(allPositiveCount, allNegativeCount) - resto;
return result;
}
private double calculateEntropy(int pos, int neg) {
double posD, negD, total, fat1, fat2, log1, log2, result;
posD = pos;
negD = neg;
total = posD + negD;
if (neg == 0) {
fat1 = pos / total;
log1 = Math.log(fat1) / Math.log(2);
result = -fat1 * log1;
} else if (pos == 0) {
fat2 = neg / total;
log2 = Math.log(fat2) / Math.log(2);
result = -(fat2 * log2);
} else {
fat1 = posD / total;
fat2 = negD / total;
log1 = Math.log(fat1) / Math.log(2);
log2 = Math.log(fat2) / Math.log(2);
result = -fat1 * log1 - fat2 * log2;
}
return result;
}
private void printTree() {
System.out.println();
if (this.rootTree != null)
this.rootTree.print();
}
private void generateTree() {
this.rootTree = getNode();
this.generateTree(this.rootTree);
}
private TreeNode getNode() {
Set<String> fields = table.get(0).keySet();
double maxGain = 0.0;
TreeNode result = null;
for (String string : fields) {
if ("classe".equalsIgnoreCase(string)) {
continue;
}
TreeNode n = new TreeNode();
n.value = string;
n.action = "";
n.children = new ArrayList<TreeNode>();
n.parent = null;
n.gain = this.calculateGain(n);
if (n.gain > maxGain) {
maxGain = n.gain;
result = n;
}
}
return result;
}
private void generateTree(TreeNode node) {
if (node == null) {
return;
}
Set<String> nodeActions = new HashSet<String>();
for (Map<String, String> map : table) {
nodeActions.add(map.get(node.value));
}
for (String action : nodeActions) {
double maxGain = 0.0;
TreeNode maxGainNode = null;
Set<String> fields = table.get(0).keySet();
Set<String> classeValues = new HashSet<String>();
String value = "";
for (Map<String, String> map : table) {
if (node.parent == null) {
if (map.get(node.value).equals(action)) {
classeValues.add(map.get("classe"));
value = map.get("classe");
}
if (classeValues.size() > 1)
break;
} else {
if (map.get(node.value).equals(action) && map.get(node.parent.value).equals(node.action)) {
classeValues.add(map.get("classe"));
value = map.get("classe");
}
if (classeValues.size() > 1)
break;
}
}
if (classeValues.size() == 1) {
node.children.add(new TreeNode(node, action, value));
} else {
for (String string : fields) {
if ("classe".equalsIgnoreCase(string)) {
continue;
}
boolean visited = false;
for (TreeNode aux = node; aux != null; aux = aux.parent) {
visited = aux.value.equals(string);
}
if (visited) {
continue;
}
TreeNode n = new TreeNode(node, action, string);
n.gain = this.calculateGain(n);
if (n.gain > maxGain) {
maxGain = n.gain;
maxGainNode = n;
}
}
if (maxGainNode != null) {
node.children.add(maxGainNode);
}
generateTree(maxGainNode);
}
}
}
private void generateTable() {
String[] fields = new String[] { "tempo", "temperatura", "humidade", "ventando", "classe" };
addRow(fields, new String[] { "ensolarado", "quente", "alta", "não", "não" });
addRow(fields, new String[] { "ensolarado", "quente", "alta", "sim", "não" });
addRow(fields, new String[] { "nublado", "quente", "alta", "não", "sim" });
addRow(fields, new String[] { "chuva", "média", "alta", "não", "sim" });
addRow(fields, new String[] { "chuva", "fria", "normal", "não", "sim" });
addRow(fields, new String[] { "chuva", "fria", "normal", "sim", "não" });
addRow(fields, new String[] { "nublado", "fria", "normal", "sim", "sim" });
addRow(fields, new String[] { "ensolarado", "média", "alta", "não", "não" });
addRow(fields, new String[] { "ensolarado", "fria", "normal", "não", "sim" });
addRow(fields, new String[] { "chuva", "média", "normal", "não", "sim" });
addRow(fields, new String[] { "ensolarado", "média", "normal", "sim", "sim" });
addRow(fields, new String[] { "nublado", "média", "alta", "sim", "sim" });
addRow(fields, new String[] { "nublado", "quente", "normal", "não", "sim" });
addRow(fields, new String[] { "chuva", "média", "alta", "sim", "não" });
}
public static void main(String[] args) {
DecisionTree decisionTree = new DecisionTree();
decisionTree.generateTable();
decisionTree.generateTree();
decisionTree.printTable();
decisionTree.printTree();
}
}
| UTF-8 | Java | 8,248 | java | DecisionTree.java | Java | []
| null | []
| package br.edu.ifce.ia;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DecisionTree {
private List<Map<String, String>> table;
private TreeNode rootTree;
public DecisionTree() {
this.table = new ArrayList<Map<String, String>>();
}
public void addRow(String[] fields, String[] data) {
Map<String, String> rowData = new HashMap<String, String>();
for (int i = fields.length - 1; i >= 0; i--) {
rowData.put(fields[i], data[i]);
}
this.table.add(rowData);
}
public void printTable() {
System.out.println();
int size = 12;
if (!this.table.isEmpty()) {
Set<String> fields = this.table.get(0).keySet();
for (String field : fields) {
System.out.print(" | " + field);
for (int i = 0; i < size - field.length(); i++)
System.out.print(" ");
}
System.out.println();
for (Map<String, String> row : this.table) {
Collection<String> data = row.values();
for (String string : data) {
System.out.print(" | " + string);
for (int i = 0; i < size - string.length(); i++)
System.out.print(" ");
}
System.out.println();
}
}
}
private double calculateGain(TreeNode node) {
double result = 0.0;
int allPositiveCount = 0, allNegativeCount = 0;
List<String> fieldValues = new ArrayList<String>();
Map<String, Integer> fieldFrequencyPos = new HashMap<String, Integer>();
Map<String, Integer> fieldFrequencyNeg = new HashMap<String, Integer>();
for (Map<String, String> map : table) {
String s = map.get(node.value);
if (!fieldValues.contains(s)) {
fieldValues.add(s);
fieldFrequencyPos.put(s, 0);
fieldFrequencyNeg.put(s, 0);
}
}
for (Map<String, String> map : table) {
String s = map.get(node.value);
String classe = map.get("classe");
Integer freqPos = fieldFrequencyPos.get(s);
Integer freqNeg = fieldFrequencyNeg.get(s);
if (node.parent != null) {
String parentValue = map.get(node.parent.value);
String action = node.action;
if (parentValue.equals(action)) {
if (classe.equalsIgnoreCase("sim")) {
fieldFrequencyPos.put(s, ++freqPos);
} else if (classe.equalsIgnoreCase("não")) {
fieldFrequencyNeg.put(s, ++freqNeg);
}
}
} else {
if (classe.equalsIgnoreCase("sim")) {
fieldFrequencyPos.put(s, ++freqPos);
} else if (classe.equalsIgnoreCase("não")) {
fieldFrequencyNeg.put(s, ++freqNeg);
}
}
}
double resto = 0.0;
for (String string : fieldValues) {
int fieldPos, fieldNeg;
double fieldTotal, total = 0.0;
fieldPos = fieldFrequencyPos.get(string);
fieldNeg = fieldFrequencyNeg.get(string);
fieldTotal = fieldPos + fieldNeg;
if (node.parent != null) {
for (Map<String, String> map : table) {
String parentValue = map.get(node.parent.value);
String action = node.action;
if (parentValue.equals(action)) {
total++;
}
}
} else {
total = table.size();
}
resto += (fieldTotal / total) * calculateEntropy(fieldPos, fieldNeg);
}
for (Map<String, String> map : table) {
String classe = map.get("classe");
if (node.parent != null) {
String parentValue = map.get(node.parent.value);
String action = node.action;
if (parentValue.equals(action)) {
if (classe.equalsIgnoreCase("sim")) {
allPositiveCount++;
} else if (classe.equalsIgnoreCase("não")) {
allNegativeCount++;
}
}
} else {
if (classe.equalsIgnoreCase("sim")) {
allPositiveCount++;
} else if (classe.equalsIgnoreCase("não")) {
allNegativeCount++;
}
}
}
result = calculateEntropy(allPositiveCount, allNegativeCount) - resto;
return result;
}
private double calculateEntropy(int pos, int neg) {
double posD, negD, total, fat1, fat2, log1, log2, result;
posD = pos;
negD = neg;
total = posD + negD;
if (neg == 0) {
fat1 = pos / total;
log1 = Math.log(fat1) / Math.log(2);
result = -fat1 * log1;
} else if (pos == 0) {
fat2 = neg / total;
log2 = Math.log(fat2) / Math.log(2);
result = -(fat2 * log2);
} else {
fat1 = posD / total;
fat2 = negD / total;
log1 = Math.log(fat1) / Math.log(2);
log2 = Math.log(fat2) / Math.log(2);
result = -fat1 * log1 - fat2 * log2;
}
return result;
}
private void printTree() {
System.out.println();
if (this.rootTree != null)
this.rootTree.print();
}
private void generateTree() {
this.rootTree = getNode();
this.generateTree(this.rootTree);
}
private TreeNode getNode() {
Set<String> fields = table.get(0).keySet();
double maxGain = 0.0;
TreeNode result = null;
for (String string : fields) {
if ("classe".equalsIgnoreCase(string)) {
continue;
}
TreeNode n = new TreeNode();
n.value = string;
n.action = "";
n.children = new ArrayList<TreeNode>();
n.parent = null;
n.gain = this.calculateGain(n);
if (n.gain > maxGain) {
maxGain = n.gain;
result = n;
}
}
return result;
}
private void generateTree(TreeNode node) {
if (node == null) {
return;
}
Set<String> nodeActions = new HashSet<String>();
for (Map<String, String> map : table) {
nodeActions.add(map.get(node.value));
}
for (String action : nodeActions) {
double maxGain = 0.0;
TreeNode maxGainNode = null;
Set<String> fields = table.get(0).keySet();
Set<String> classeValues = new HashSet<String>();
String value = "";
for (Map<String, String> map : table) {
if (node.parent == null) {
if (map.get(node.value).equals(action)) {
classeValues.add(map.get("classe"));
value = map.get("classe");
}
if (classeValues.size() > 1)
break;
} else {
if (map.get(node.value).equals(action) && map.get(node.parent.value).equals(node.action)) {
classeValues.add(map.get("classe"));
value = map.get("classe");
}
if (classeValues.size() > 1)
break;
}
}
if (classeValues.size() == 1) {
node.children.add(new TreeNode(node, action, value));
} else {
for (String string : fields) {
if ("classe".equalsIgnoreCase(string)) {
continue;
}
boolean visited = false;
for (TreeNode aux = node; aux != null; aux = aux.parent) {
visited = aux.value.equals(string);
}
if (visited) {
continue;
}
TreeNode n = new TreeNode(node, action, string);
n.gain = this.calculateGain(n);
if (n.gain > maxGain) {
maxGain = n.gain;
maxGainNode = n;
}
}
if (maxGainNode != null) {
node.children.add(maxGainNode);
}
generateTree(maxGainNode);
}
}
}
private void generateTable() {
String[] fields = new String[] { "tempo", "temperatura", "humidade", "ventando", "classe" };
addRow(fields, new String[] { "ensolarado", "quente", "alta", "não", "não" });
addRow(fields, new String[] { "ensolarado", "quente", "alta", "sim", "não" });
addRow(fields, new String[] { "nublado", "quente", "alta", "não", "sim" });
addRow(fields, new String[] { "chuva", "média", "alta", "não", "sim" });
addRow(fields, new String[] { "chuva", "fria", "normal", "não", "sim" });
addRow(fields, new String[] { "chuva", "fria", "normal", "sim", "não" });
addRow(fields, new String[] { "nublado", "fria", "normal", "sim", "sim" });
addRow(fields, new String[] { "ensolarado", "média", "alta", "não", "não" });
addRow(fields, new String[] { "ensolarado", "fria", "normal", "não", "sim" });
addRow(fields, new String[] { "chuva", "média", "normal", "não", "sim" });
addRow(fields, new String[] { "ensolarado", "média", "normal", "sim", "sim" });
addRow(fields, new String[] { "nublado", "média", "alta", "sim", "sim" });
addRow(fields, new String[] { "nublado", "quente", "normal", "não", "sim" });
addRow(fields, new String[] { "chuva", "média", "alta", "sim", "não" });
}
public static void main(String[] args) {
DecisionTree decisionTree = new DecisionTree();
decisionTree.generateTable();
decisionTree.generateTree();
decisionTree.printTable();
decisionTree.printTree();
}
}
| 8,248 | 0.606079 | 0.599271 | 338 | 23.33432 | 22.142439 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.133136 | false | false | 10 |
d1ddb61a9fb7977796989d3d70c8f3274f3e8bb1 | 37,142,877,187,002 | 42b63263539a675a4557935a4f4829e474e18a91 | /src/test/java/com/github/blahord/lexiker/matcher/EmptyMatcherTest.java | 67736d0771743494c62ddd4477ef2f383e7f01d8 | [
"Apache-2.0"
]
| permissive | Blahord/Lexiker | https://github.com/Blahord/Lexiker | 52e4e05362392d8847f73f0b406f3c334aafd44c | 8bd00836028b9e19b1a9fc191a2b09c90c50cd73 | refs/heads/master | 2017-11-26T13:48:56.424000 | 2016-12-11T12:17:01 | 2016-12-11T12:17:01 | 51,608,681 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.blahord.lexiker.matcher;
import com.github.blahord.lexiker.charactersource.StringCharacterSource;
import org.testng.annotations.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;
@Test
public class EmptyMatcherTest {
public void testMatch() throws Exception {
final EmptyMatcher emptyMatcher = new EmptyMatcher("test");
checkSuccessResult(emptyMatcher, "fsdfdf", 0, "test", "", 0, 0);
checkSuccessResult(emptyMatcher, "fsdfdf", 3, "test", "", 3, 3);
checkSuccessResult(emptyMatcher, "fsdfdf", 6, "test", "", 6, 6);
final EmptyMatcher emptyMatcher2 = new EmptyMatcher();
checkSuccessResult(emptyMatcher2, "", 0, "Empty", "", 0, 0);
}
private void checkSuccessResult(Matcher matcher, String input, int startPosition, String label, String subText, int begin, int end) {
MatchReport report = matcher.match(new StringCharacterSource(input), startPosition, (long) input.length(), new RuleSet());
assertThat(report.getParseErrorStack()).isNull();
assertThat(report.getResultTree()).isNotNull();
assertThat(report.getResultTree().item().getLabel()).isEqualTo(label);
assertThat(report.getResultTree().item().getSubText()).isEqualTo(subText);
assertThat(report.getResultTree().item().getBegin()).isEqualTo(begin);
assertThat(report.getResultTree().item().getEnd()).isEqualTo(end);
assertThat(report.getResultTree().subTrees().isEmpty()).isTrue();
}
} | UTF-8 | Java | 1,512 | java | EmptyMatcherTest.java | Java | [
{
"context": "package com.github.blahord.lexiker.matcher;\n\nimport com.github.blahord.lexik",
"end": 26,
"score": 0.9073893427848816,
"start": 19,
"tag": "USERNAME",
"value": "blahord"
},
{
"context": "ithub.blahord.lexiker.matcher;\n\nimport com.github.blahord.lexiker.charactersource.StringCharacterSource;\nim",
"end": 70,
"score": 0.9445688724517822,
"start": 63,
"tag": "USERNAME",
"value": "blahord"
}
]
| null | []
| package com.github.blahord.lexiker.matcher;
import com.github.blahord.lexiker.charactersource.StringCharacterSource;
import org.testng.annotations.Test;
import static org.assertj.core.api.Java6Assertions.assertThat;
@Test
public class EmptyMatcherTest {
public void testMatch() throws Exception {
final EmptyMatcher emptyMatcher = new EmptyMatcher("test");
checkSuccessResult(emptyMatcher, "fsdfdf", 0, "test", "", 0, 0);
checkSuccessResult(emptyMatcher, "fsdfdf", 3, "test", "", 3, 3);
checkSuccessResult(emptyMatcher, "fsdfdf", 6, "test", "", 6, 6);
final EmptyMatcher emptyMatcher2 = new EmptyMatcher();
checkSuccessResult(emptyMatcher2, "", 0, "Empty", "", 0, 0);
}
private void checkSuccessResult(Matcher matcher, String input, int startPosition, String label, String subText, int begin, int end) {
MatchReport report = matcher.match(new StringCharacterSource(input), startPosition, (long) input.length(), new RuleSet());
assertThat(report.getParseErrorStack()).isNull();
assertThat(report.getResultTree()).isNotNull();
assertThat(report.getResultTree().item().getLabel()).isEqualTo(label);
assertThat(report.getResultTree().item().getSubText()).isEqualTo(subText);
assertThat(report.getResultTree().item().getBegin()).isEqualTo(begin);
assertThat(report.getResultTree().item().getEnd()).isEqualTo(end);
assertThat(report.getResultTree().subTrees().isEmpty()).isTrue();
}
} | 1,512 | 0.703704 | 0.693783 | 31 | 47.80645 | 37.911118 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.645161 | false | false | 10 |
7a052c067dfa6e72402aa18b7155ccf37639cbb6 | 15,522,011,863,729 | f1572d3a826ced3a778dd378ab52fa22d1ec3ec9 | /democode/xsd2javacreate/src/com/beyondbit/smartbox/request/ViewMagazineRequest.java | 509d5fe84a252c05007b5eae0bcfe1a843739a94 | []
| no_license | txc1223/helloworld | https://github.com/txc1223/helloworld | 0a3ae2cdf675e940816bcfba8a611de2b3aa4434 | c0db8c4a9eaa923c995e7aec239db35ef6ed498a | refs/heads/master | 2021-01-25T10:29:11.002000 | 2015-12-15T03:26:14 | 2015-12-15T03:26:14 | 31,292,917 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.beyondbit.smartbox.request;
public class ViewMagazineRequest extends Request {
private String magazineID;
public void setMagazineID(String magazineID){
this.magazineID=magazineID;
}
public String getMagazineID(){
return magazineID;
}
} | UTF-8 | Java | 263 | java | ViewMagazineRequest.java | Java | []
| null | []
| package com.beyondbit.smartbox.request;
public class ViewMagazineRequest extends Request {
private String magazineID;
public void setMagazineID(String magazineID){
this.magazineID=magazineID;
}
public String getMagazineID(){
return magazineID;
}
} | 263 | 0.779468 | 0.779468 | 11 | 22 | 18.120808 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 10 |
64e6fc95023b70d38d40ccec1f2adc28a1c5d6c6 | 26,843,545,649,090 | 3fae7512fbf441d7f15a502a0de26fc2a9db0c0e | /src/com/example/android_image_editing_filters/filter/SmoothingForExport.java | d85d8a100f1e5a4f159b03a80eb8d704f26fbd6b | [
"MIT"
]
| permissive | cgewdev/AndroidImageEditingFilters | https://github.com/cgewdev/AndroidImageEditingFilters | 52273578a5e3fa52ff8c3da1126b0aefc61d1b6d | 9dab2a98f83687af5f4f6f1e39f32b57bf8e11c6 | refs/heads/master | 2021-01-10T13:34:51.596000 | 2015-10-07T08:38:51 | 2015-10-07T08:38:51 | 43,802,576 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android_image_editing_filters.filter;
import android.graphics.Bitmap;
import com.example.android_image_editing_filters.model.ConvolutionMask;
/**
* Smoothes an image.
*/
public class SmoothingForExport extends Filter {
private Bitmap bitmapIn;
private int oldSizeOfMask, prevWidth, prevHeight, curWidth, curHeight;
private ConvolutionMask convolutionMask;
public SmoothingForExport(Bitmap bitmapIn, int oldSizeOfMask, int prevWidth, int prevHeight, int curWidth, int curHeight) {
this.bitmapIn = bitmapIn;
this.oldSizeOfMask = oldSizeOfMask;
this.prevWidth = prevWidth;
this.prevHeight = prevHeight;
this.curWidth = curWidth;
this.curHeight = curHeight;
this.convolutionMask = new ConvolutionMask(adjustSizeForMask(oldSizeOfMask, prevWidth, prevHeight, curWidth, curHeight));
}
/**
* Execute filter.
*
* @return the bitmap
*/
@Override
public Bitmap executeFilter() {
this.getConvolutionMask().setAll(1);
this.getConvolutionMask().Factor = convolutionMask.mask.length;
this.getConvolutionMask().Offset = 0;
return ConvolutionMask.calculateConvolutionMxM(this.getBitmapIn(),
this.getConvolutionMask());
}
/**
* Adjust size for mask.
*
* @param oldSizeOfMask the old size of mask
* @param prevWidth the prev width
* @param prevHeight the prev height
* @param curWidth the cur width
* @param curHeight the cur height
* @return the int
*/
private int adjustSizeForMask(int oldSizeOfMask, int prevWidth, int prevHeight, int curWidth, int curHeight) {
return Math.round((float) Math.sqrt(((curWidth * curHeight) / ((prevWidth * prevHeight) / (oldSizeOfMask * oldSizeOfMask)))));
}
public Bitmap getBitmapIn() {
return bitmapIn;
}
public void setBitmapIn(Bitmap bitmapIn) {
this.bitmapIn = bitmapIn;
}
public int getOldSizeOfMask() {
return oldSizeOfMask;
}
public void setOldSizeOfMask(int oldSizeOfMask) {
this.oldSizeOfMask = oldSizeOfMask;
}
public int getPrevWidth() {
return prevWidth;
}
public void setPrevWidth(int prevWidth) {
this.prevWidth = prevWidth;
}
public int getPrevHeight() {
return prevHeight;
}
public void setPrevHeight(int prevHeight) {
this.prevHeight = prevHeight;
}
public int getCurWidth() {
return curWidth;
}
public void setCurWidth(int curWidth) {
this.curWidth = curWidth;
}
public int getCurHeight() {
return curHeight;
}
public void setCurHeight(int curHeight) {
this.curHeight = curHeight;
}
public ConvolutionMask getConvolutionMask() {
return convolutionMask;
}
public void setConvolutionMask(ConvolutionMask convolutionMask) {
this.convolutionMask = convolutionMask;
}
}
| UTF-8 | Java | 3,012 | java | SmoothingForExport.java | Java | []
| null | []
| package com.example.android_image_editing_filters.filter;
import android.graphics.Bitmap;
import com.example.android_image_editing_filters.model.ConvolutionMask;
/**
* Smoothes an image.
*/
public class SmoothingForExport extends Filter {
private Bitmap bitmapIn;
private int oldSizeOfMask, prevWidth, prevHeight, curWidth, curHeight;
private ConvolutionMask convolutionMask;
public SmoothingForExport(Bitmap bitmapIn, int oldSizeOfMask, int prevWidth, int prevHeight, int curWidth, int curHeight) {
this.bitmapIn = bitmapIn;
this.oldSizeOfMask = oldSizeOfMask;
this.prevWidth = prevWidth;
this.prevHeight = prevHeight;
this.curWidth = curWidth;
this.curHeight = curHeight;
this.convolutionMask = new ConvolutionMask(adjustSizeForMask(oldSizeOfMask, prevWidth, prevHeight, curWidth, curHeight));
}
/**
* Execute filter.
*
* @return the bitmap
*/
@Override
public Bitmap executeFilter() {
this.getConvolutionMask().setAll(1);
this.getConvolutionMask().Factor = convolutionMask.mask.length;
this.getConvolutionMask().Offset = 0;
return ConvolutionMask.calculateConvolutionMxM(this.getBitmapIn(),
this.getConvolutionMask());
}
/**
* Adjust size for mask.
*
* @param oldSizeOfMask the old size of mask
* @param prevWidth the prev width
* @param prevHeight the prev height
* @param curWidth the cur width
* @param curHeight the cur height
* @return the int
*/
private int adjustSizeForMask(int oldSizeOfMask, int prevWidth, int prevHeight, int curWidth, int curHeight) {
return Math.round((float) Math.sqrt(((curWidth * curHeight) / ((prevWidth * prevHeight) / (oldSizeOfMask * oldSizeOfMask)))));
}
public Bitmap getBitmapIn() {
return bitmapIn;
}
public void setBitmapIn(Bitmap bitmapIn) {
this.bitmapIn = bitmapIn;
}
public int getOldSizeOfMask() {
return oldSizeOfMask;
}
public void setOldSizeOfMask(int oldSizeOfMask) {
this.oldSizeOfMask = oldSizeOfMask;
}
public int getPrevWidth() {
return prevWidth;
}
public void setPrevWidth(int prevWidth) {
this.prevWidth = prevWidth;
}
public int getPrevHeight() {
return prevHeight;
}
public void setPrevHeight(int prevHeight) {
this.prevHeight = prevHeight;
}
public int getCurWidth() {
return curWidth;
}
public void setCurWidth(int curWidth) {
this.curWidth = curWidth;
}
public int getCurHeight() {
return curHeight;
}
public void setCurHeight(int curHeight) {
this.curHeight = curHeight;
}
public ConvolutionMask getConvolutionMask() {
return convolutionMask;
}
public void setConvolutionMask(ConvolutionMask convolutionMask) {
this.convolutionMask = convolutionMask;
}
}
| 3,012 | 0.658699 | 0.658035 | 112 | 25.892857 | 28.051723 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446429 | false | false | 10 |
7c1c96d2544dc1c50cfc2b4f30f159a11cab20c2 | 32,719,060,915,567 | a7d60064a2e33188e0e286fe3ee69a5bfd1fa8ad | /src/main/java/com/cskaoyan/smzdm/utils/event/EventConsumer.java | dc0336e63ac2c756fe05773de29cf019e7616001 | []
| no_license | hlfvngr/smzdm | https://github.com/hlfvngr/smzdm | 34354705f4394542e633556e826ae24aa003ed34 | 2f0ef35a0a89bc42be12cadaf86b61cabbf1f0e3 | refs/heads/master | 2020-04-12T11:10:03.622000 | 2018-12-21T15:54:45 | 2018-12-21T15:54:45 | 162,451,167 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cskaoyan.smzdm.utils.event;
import com.alibaba.fastjson.JSON;
import com.cskaoyan.smzdm.bean.Event;
import com.cskaoyan.smzdm.bean.EventType;
import com.cskaoyan.smzdm.ehandler.EventHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.*;
@Component
public class EventConsumer implements ApplicationContextAware, InitializingBean {
private ApplicationContext applicationContext;
private Map<EventType, List<EventHandler>> map = new HashMap<>();
public void transfer(){
Jedis jedis = new JedisPool().getResource();
List<String> eventQueue = jedis.brpop(0, "EventQueue");
String jsonString = eventQueue.get(1);
Event event = JSON.parseObject(jsonString, Event.class);
List<EventHandler> eventHandlers = map.get(event.getEventType());
for (EventHandler e : eventHandlers) {
e.handlerEvent(event);
}
jedis.close();
}
@Override
public void afterPropertiesSet() throws Exception {
Map<String, EventHandler> handlerMap = applicationContext.getBeansOfType(EventHandler.class);
Collection<EventHandler> values = handlerMap.values();
for (EventHandler e : values){
List<EventType> list = e.registerCareEvent();
for(EventType eventType : list){
if(map.containsKey(eventType)){
map.get(eventType).add(e);
}else {
List<EventHandler> a = new ArrayList<>();
a.add(e);
map.put(eventType,a);
}
}
}
new Thread( new Runnable() {
@Override
public void run() {
while (true){
transfer();
}
}
}).start();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| UTF-8 | Java | 2,304 | java | EventConsumer.java | Java | []
| null | []
| package com.cskaoyan.smzdm.utils.event;
import com.alibaba.fastjson.JSON;
import com.cskaoyan.smzdm.bean.Event;
import com.cskaoyan.smzdm.bean.EventType;
import com.cskaoyan.smzdm.ehandler.EventHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.*;
@Component
public class EventConsumer implements ApplicationContextAware, InitializingBean {
private ApplicationContext applicationContext;
private Map<EventType, List<EventHandler>> map = new HashMap<>();
public void transfer(){
Jedis jedis = new JedisPool().getResource();
List<String> eventQueue = jedis.brpop(0, "EventQueue");
String jsonString = eventQueue.get(1);
Event event = JSON.parseObject(jsonString, Event.class);
List<EventHandler> eventHandlers = map.get(event.getEventType());
for (EventHandler e : eventHandlers) {
e.handlerEvent(event);
}
jedis.close();
}
@Override
public void afterPropertiesSet() throws Exception {
Map<String, EventHandler> handlerMap = applicationContext.getBeansOfType(EventHandler.class);
Collection<EventHandler> values = handlerMap.values();
for (EventHandler e : values){
List<EventType> list = e.registerCareEvent();
for(EventType eventType : list){
if(map.containsKey(eventType)){
map.get(eventType).add(e);
}else {
List<EventHandler> a = new ArrayList<>();
a.add(e);
map.put(eventType,a);
}
}
}
new Thread( new Runnable() {
@Override
public void run() {
while (true){
transfer();
}
}
}).start();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| 2,304 | 0.644965 | 0.644097 | 69 | 32.391304 | 25.061211 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.550725 | false | false | 10 |
f28ed0877e780e9b8dfe3f0445dfb015a7103afd | 4,148,938,478,291 | 29522bf433282bf11233aa65535dcc17856ac942 | /hackerrank/SherlockAndTheBeast.java | 41b059e09085132542a2c40d59ea20eedc87e415 | []
| no_license | naniroot/interview-prep | https://github.com/naniroot/interview-prep | 62b866899c2a4162fc35a5c038ad0f90f56d549a | 0cba269b95f5de5cc13396ea82624f736312f8f4 | refs/heads/master | 2021-01-10T06:59:36.143000 | 2016-03-16T06:29:55 | 2016-03-16T06:29:55 | 46,839,420 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hackerrank;
import java.util.Scanner;
public class SherlockAndTheBeast {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testCases = Integer.parseInt(scanner.nextLine());
for(int i=0; i<testCases; i++){
int n = Integer.parseInt(scanner.nextLine());
printDecent(n);
}
scanner.close();
}
public static void printDecent(int n){
if(0==n%3){
StringBuffer buffer = new StringBuffer();
for(int tada=0; tada<n; tada++){
buffer.append("5");
}
System.out.println(buffer);
return;
}
if(0==(n-5)%3 && n-5 >0){
StringBuffer buffer = new StringBuffer();
for(int tada=0; tada<n-5; tada++){
buffer.append("5");
}
for(int t=0; t<5; t++){
buffer.append("3");
}
System.out.println(buffer);
return;
}
if(0==(n-10)%3 && n-10 >0){
StringBuffer buffer = new StringBuffer();
for(int tada=0; tada<n-10; tada++){
buffer.append("5");
}
for(int t=0; t<10; t++){
buffer.append("3");
}
System.out.println(buffer);
return;
}
if(0==n%5){
StringBuffer buffer = new StringBuffer();
for(int tada=0; tada<n; tada++){
buffer.append("3");
}
System.out.println(buffer);
return;
}
System.out.println("-1");
}
}
| UTF-8 | Java | 1,709 | java | SherlockAndTheBeast.java | Java | []
| null | []
| package hackerrank;
import java.util.Scanner;
public class SherlockAndTheBeast {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testCases = Integer.parseInt(scanner.nextLine());
for(int i=0; i<testCases; i++){
int n = Integer.parseInt(scanner.nextLine());
printDecent(n);
}
scanner.close();
}
public static void printDecent(int n){
if(0==n%3){
StringBuffer buffer = new StringBuffer();
for(int tada=0; tada<n; tada++){
buffer.append("5");
}
System.out.println(buffer);
return;
}
if(0==(n-5)%3 && n-5 >0){
StringBuffer buffer = new StringBuffer();
for(int tada=0; tada<n-5; tada++){
buffer.append("5");
}
for(int t=0; t<5; t++){
buffer.append("3");
}
System.out.println(buffer);
return;
}
if(0==(n-10)%3 && n-10 >0){
StringBuffer buffer = new StringBuffer();
for(int tada=0; tada<n-10; tada++){
buffer.append("5");
}
for(int t=0; t<10; t++){
buffer.append("3");
}
System.out.println(buffer);
return;
}
if(0==n%5){
StringBuffer buffer = new StringBuffer();
for(int tada=0; tada<n; tada++){
buffer.append("3");
}
System.out.println(buffer);
return;
}
System.out.println("-1");
}
}
| 1,709 | 0.441779 | 0.420714 | 58 | 28.465517 | 16.861725 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.568966 | false | false | 3 |
0fe1db65da7f4c8db45117b0611709c9d020d66a | 37,598,143,729,746 | 69784a7cd71980e0df73fd008c75f0d394f91ada | /src/test/java/com/eitraz/tellstick/core/TellstickRule.java | c0a7f1ea30088406fe745b5e8903ed79047bc221 | []
| no_license | Eitraz/tellstick-core | https://github.com/Eitraz/tellstick-core | 7c5db3d137fb14cfffa62e625b238a8076fc5429 | 68e98b20388f944ac0a739c4a42b17fa3cf46552 | refs/heads/master | 2020-12-25T16:54:01.877000 | 2016-11-18T20:43:30 | 2016-11-18T20:43:30 | 42,671,295 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eitraz.tellstick.core;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class TellstickRule implements TestRule {
private Tellstick tellstick = new Tellstick();
private TellstickCoreMockLibrary library = new TellstickCoreMockLibrary();
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
tellstick.start(library);
try {
base.evaluate();
} finally {
tellstick.stop();
}
}
};
}
public TellstickCoreMockLibrary getLibrary() {
return library;
}
public Tellstick getTellstick() {
return tellstick;
}
}
| UTF-8 | Java | 894 | java | TellstickRule.java | Java | []
| null | []
| package com.eitraz.tellstick.core;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class TellstickRule implements TestRule {
private Tellstick tellstick = new Tellstick();
private TellstickCoreMockLibrary library = new TellstickCoreMockLibrary();
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
tellstick.start(library);
try {
base.evaluate();
} finally {
tellstick.stop();
}
}
};
}
public TellstickCoreMockLibrary getLibrary() {
return library;
}
public Tellstick getTellstick() {
return tellstick;
}
}
| 894 | 0.602908 | 0.602908 | 34 | 25.294117 | 20.771204 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.382353 | false | false | 3 |
dff2d9e3e379bb7ef8d39ff972a08bb1e09e5499 | 36,155,034,740,951 | 8017670eb55049d490e928c1964698afaa5a5e43 | /src/main/java/com/hackerrank/algorithm/string/CaesarCipher.java | 7e38a2fc880b0f6bcac25bb45876bd336e0d53aa | []
| no_license | Evg3n/problems | https://github.com/Evg3n/problems | 05877136f793dc6277198d82af9adcdfbc358ae5 | d2b1416af286abafcb1f05043c23330f5b54c2fa | refs/heads/master | 2021-01-16T00:47:01.723000 | 2020-04-05T21:20:25 | 2020-04-05T21:20:25 | 99,976,911 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hackerrank.algorithm.string;
import java.util.Scanner;
/**
* https://www.hackerrank.com/challenges/caesar-cipher-1
*/
public class CaesarCipher {
public static void main(String[] args) {
Scanner in = new Scanner(CaesarCipher.class.getClassLoader().getResourceAsStream(
"hackerrank/algorithm/string/caesar_cipher.txt"));
int length = in.nextInt();
String source = in.next();
int rotation = in.nextInt();
System.out.println(encode(source, rotation));
}
private static String encode(String source, int rotation) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < source.length(); i++) {
char currentChar = source.charAt(i);
if (currentChar >= 'A' && currentChar <= 'Z') {
sb.append((char) ((currentChar - 'A' + rotation) % 26 + 'A'));
} else if (currentChar >= 'a' && currentChar <= 'z') {
sb.append((char) ((currentChar - 'a' + rotation) % 26 + 'a'));
} else {
sb.append(currentChar);
}
}
return sb.toString();
}
} | UTF-8 | Java | 1,047 | java | CaesarCipher.java | Java | []
| null | []
| package com.hackerrank.algorithm.string;
import java.util.Scanner;
/**
* https://www.hackerrank.com/challenges/caesar-cipher-1
*/
public class CaesarCipher {
public static void main(String[] args) {
Scanner in = new Scanner(CaesarCipher.class.getClassLoader().getResourceAsStream(
"hackerrank/algorithm/string/caesar_cipher.txt"));
int length = in.nextInt();
String source = in.next();
int rotation = in.nextInt();
System.out.println(encode(source, rotation));
}
private static String encode(String source, int rotation) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < source.length(); i++) {
char currentChar = source.charAt(i);
if (currentChar >= 'A' && currentChar <= 'Z') {
sb.append((char) ((currentChar - 'A' + rotation) % 26 + 'A'));
} else if (currentChar >= 'a' && currentChar <= 'z') {
sb.append((char) ((currentChar - 'a' + rotation) % 26 + 'a'));
} else {
sb.append(currentChar);
}
}
return sb.toString();
}
} | 1,047 | 0.618911 | 0.613181 | 35 | 28.942858 | 24.937571 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.485714 | false | false | 3 |
3d5fbd4979774dd58e6dd62579230b2102269ec2 | 36,979,668,454,071 | 5e1ed588f861d3178ed59027ff1895d9e7392831 | /src/main/java/uk/ac/soton/ldanalytics/sparql2sql/model/BGPEngine.java | 0435a3ad0ddf439cfd1efdf06ce76bfbc9db89b7 | []
| no_license | ZuoMatthew/sparql2sql | https://github.com/ZuoMatthew/sparql2sql | 53e0b7bf1d40f0562a23469134e5e55da2749ebe | 00379e7e2501bbcd8c8c7bf50c1a3cf028f0dc98 | refs/heads/master | 2020-07-01T15:05:56.210000 | 2016-10-16T16:19:49 | 2016-10-16T16:19:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.ac.soton.ldanalytics.sparql2sql.model;
public enum BGPEngine {
JENA, SESAME
}
| UTF-8 | Java | 91 | java | BGPEngine.java | Java | []
| null | []
| package uk.ac.soton.ldanalytics.sparql2sql.model;
public enum BGPEngine {
JENA, SESAME
}
| 91 | 0.78022 | 0.769231 | 5 | 17.200001 | 18.004444 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
37a0d6c020060791af003f2560d5ac4dad63f4e4 | 34,102,040,385,170 | dcbd6a4633bfbfc9516e0cc351f17f815ac801e5 | /src/example14_lambda_expression/ConstructorRefDemo.java | 016e8b964a9f20607a01b8af715bbb6e06cb3bf7 | []
| no_license | HVLLOWeEn/Shild_Example | https://github.com/HVLLOWeEn/Shild_Example | f4c0fe1564a0602ab6e3517c6fd40b88bd2246fc | 85c6313b24739cd14ed4b2fcf830d0769fa9c3d7 | refs/heads/master | 2021-01-19T15:08:03.552000 | 2017-11-19T11:58:26 | 2017-11-19T11:58:26 | 88,199,087 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package example14_lambda_expression;
public class ConstructorRefDemo {
public static void main(String[] args) {
// Создать ссылку на конструктор MyClass
// Поскольку метод func() интерфеса MyFuncString принимает аргумент,
// new ссылается на параметризированный конструктор MyClass, а
// не на конструктор по-умолчанию
MyFuncString myClassCons = MyClass2::new;
// Создать экземпляр MyClass2 посредством ссылки на конструктор
MyClass2 myClass2 = myClassCons.func("Тестирование");
System.out.println("Строка str в myClass2: " + myClass2.getStr());
}
}
| UTF-8 | Java | 824 | java | ConstructorRefDemo.java | Java | []
| null | []
| package example14_lambda_expression;
public class ConstructorRefDemo {
public static void main(String[] args) {
// Создать ссылку на конструктор MyClass
// Поскольку метод func() интерфеса MyFuncString принимает аргумент,
// new ссылается на параметризированный конструктор MyClass, а
// не на конструктор по-умолчанию
MyFuncString myClassCons = MyClass2::new;
// Создать экземпляр MyClass2 посредством ссылки на конструктор
MyClass2 myClass2 = myClassCons.func("Тестирование");
System.out.println("Строка str в myClass2: " + myClass2.getStr());
}
}
| 824 | 0.6992 | 0.6864 | 16 | 38.0625 | 27.91386 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 3 |
94a795cfcd8de81b9e42a531ce6d5c176eebcf05 | 39,341,900,470,595 | 7fab8f68e5317d595b89d48e1b68c0df826e5031 | /src/main/java/com/bol/mancala/service/GameService.java | 61352b1268be7fd39350ddf888260c8d4b3594a4 | []
| no_license | hessam-shm/mancala | https://github.com/hessam-shm/mancala | 045e51abba459d0de1ee959552b773c5ba48996f | 8e747a7cdb52e250e6d686aaaa49952d9d5bee43 | refs/heads/master | 2023-05-05T18:18:37.927000 | 2021-05-16T11:00:15 | 2021-05-16T11:00:15 | 369,711,723 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bol.mancala.service;
import com.bol.mancala.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class GameService {
@Autowired
private BoardService boardService;
@Autowired
private MoveService moveService;
@Autowired
private GameState state;
public GameState startGame() {
boardService.initializeBoard();
state.setBoard(boardService.getBoard());
state.setTurn(boardService.getBoard().getPlayers().get(0));
state.setWinner(null);
state.setMessage("Game starts");
return state;
}
public GameState move(int pitIndex) {
if (state.getWinner() != null || !moveService.isLegalMove(pitIndex, state)) {
return state;
}
SeedHolder landingPit = boardService.updateBoard(pitIndex, state.getTurn());
state.setBoard(boardService.getBoard());
state.setMessage("");
Player previousPlayer = state.getTurn();
state.setTurn(takeTurn(state.getTurn()));
if (moveService.isEligibleToFreeTurn(landingPit.getIndex(), state)) {
state.setTurn(previousPlayer);
state.setMessage(landingPit.getPlayer() + " can move again");
//return state;
}
if (moveService.isEligibleToCapture(landingPit.getIndex(), previousPlayer, state)) {
capture(landingPit.getIndex(), previousPlayer);
state.setBoard(boardService.getBoard());
}
if (isGameEnded()) {
state.setMessage("Game over");
state.setWinner(defineWinner());
state.setTurn(null);
//return state;
}
return state;
}
//in two player games the pit opposite of your pit is captured
//in more than two players to avoid ambiguity the correspondent pits will be captured
private void capture(int pitIndex, Player player) {
boardService.capture(pitIndex, player);
if (boardService.getNumberOfPlayers() <= 2) {
boardService.capture(state.getBoard().getPits().size() - 2 - pitIndex, player);
} else {
int nextIndexToCapure = pitIndex + boardService.getnumberOfPits() + 1;
while (nextIndexToCapure < state.getBoard().getPits().size()) {
capture(nextIndexToCapure, player);
nextIndexToCapure += boardService.getnumberOfPits() + 1;
}
}
}
private String defineWinner() {
Map<Player, Integer> playerPoints = new HashMap<>();
state.getBoard().getPlayers().forEach(
p -> playerPoints.put(p, state.getBoard().getPits().stream()
.filter(pit -> pit.getPlayer().equals(p))
.mapToInt(SeedHolder::getSeeds).sum())
);
int maxPoints = playerPoints.entrySet().stream().max(Map.Entry.comparingByValue()).get().getValue();
String winners = "";
for (Map.Entry<Player, Integer> player : playerPoints.entrySet()) {
if (player.getValue().equals(maxPoints)) {
winners += player.getKey().getName() + " ";
}
}
return winners.trim();
}
public GameState getGameState() {
return state;
}
private boolean isGameEnded() {
return boardService.getBoard().getPits().stream()
.filter(p -> p instanceof Pit).map(p -> (Pit) p)
.filter(p -> p.getPlayer().equals(state.getTurn()))
.allMatch(Pit::emptySeed);
}
private Player takeTurn(Player player) {
int nextIndex = state.getBoard().getPlayers().indexOf(player) + 1;
if (nextIndex == state.getBoard().getPlayers().size())
nextIndex = 0;
return state.getBoard().getPlayers().get(nextIndex);
}
}
| UTF-8 | Java | 3,921 | java | GameService.java | Java | []
| null | []
| package com.bol.mancala.service;
import com.bol.mancala.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class GameService {
@Autowired
private BoardService boardService;
@Autowired
private MoveService moveService;
@Autowired
private GameState state;
public GameState startGame() {
boardService.initializeBoard();
state.setBoard(boardService.getBoard());
state.setTurn(boardService.getBoard().getPlayers().get(0));
state.setWinner(null);
state.setMessage("Game starts");
return state;
}
public GameState move(int pitIndex) {
if (state.getWinner() != null || !moveService.isLegalMove(pitIndex, state)) {
return state;
}
SeedHolder landingPit = boardService.updateBoard(pitIndex, state.getTurn());
state.setBoard(boardService.getBoard());
state.setMessage("");
Player previousPlayer = state.getTurn();
state.setTurn(takeTurn(state.getTurn()));
if (moveService.isEligibleToFreeTurn(landingPit.getIndex(), state)) {
state.setTurn(previousPlayer);
state.setMessage(landingPit.getPlayer() + " can move again");
//return state;
}
if (moveService.isEligibleToCapture(landingPit.getIndex(), previousPlayer, state)) {
capture(landingPit.getIndex(), previousPlayer);
state.setBoard(boardService.getBoard());
}
if (isGameEnded()) {
state.setMessage("Game over");
state.setWinner(defineWinner());
state.setTurn(null);
//return state;
}
return state;
}
//in two player games the pit opposite of your pit is captured
//in more than two players to avoid ambiguity the correspondent pits will be captured
private void capture(int pitIndex, Player player) {
boardService.capture(pitIndex, player);
if (boardService.getNumberOfPlayers() <= 2) {
boardService.capture(state.getBoard().getPits().size() - 2 - pitIndex, player);
} else {
int nextIndexToCapure = pitIndex + boardService.getnumberOfPits() + 1;
while (nextIndexToCapure < state.getBoard().getPits().size()) {
capture(nextIndexToCapure, player);
nextIndexToCapure += boardService.getnumberOfPits() + 1;
}
}
}
private String defineWinner() {
Map<Player, Integer> playerPoints = new HashMap<>();
state.getBoard().getPlayers().forEach(
p -> playerPoints.put(p, state.getBoard().getPits().stream()
.filter(pit -> pit.getPlayer().equals(p))
.mapToInt(SeedHolder::getSeeds).sum())
);
int maxPoints = playerPoints.entrySet().stream().max(Map.Entry.comparingByValue()).get().getValue();
String winners = "";
for (Map.Entry<Player, Integer> player : playerPoints.entrySet()) {
if (player.getValue().equals(maxPoints)) {
winners += player.getKey().getName() + " ";
}
}
return winners.trim();
}
public GameState getGameState() {
return state;
}
private boolean isGameEnded() {
return boardService.getBoard().getPits().stream()
.filter(p -> p instanceof Pit).map(p -> (Pit) p)
.filter(p -> p.getPlayer().equals(state.getTurn()))
.allMatch(Pit::emptySeed);
}
private Player takeTurn(Player player) {
int nextIndex = state.getBoard().getPlayers().indexOf(player) + 1;
if (nextIndex == state.getBoard().getPlayers().size())
nextIndex = 0;
return state.getBoard().getPlayers().get(nextIndex);
}
}
| 3,921 | 0.608263 | 0.606478 | 112 | 34.00893 | 27.493668 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553571 | false | false | 3 |
1ce459dc2e40f9c5ad67c38a3a560ca270d2d744 | 19,353,122,686,017 | 46d9a1102f5b81f5119b3f85b0ed0a51063fc090 | /app/src/main/java/com/am/my_feed/feed/FeedAdapter.java | 093b0dac930c2be51c04bad347ee5926a0c40d8e | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | Abed-Murad/ND_My-Feed | https://github.com/Abed-Murad/ND_My-Feed | 57ffce12ec93c534feb165ad817a345b96e1dde8 | 45283dc8b49d6ca7d9749b25b358413dfcf66398 | refs/heads/master | 2020-04-08T14:18:17.899000 | 2019-02-13T20:29:50 | 2019-02-13T20:29:50 | 159,431,088 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.am.my_feed.feed;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.am.my_feed.room.Article;
import com.am.my_feed.databinding.CardFeedArticleBinding;
import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import java.util.ArrayList;
import java.util.List;
public class FeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_ITEM = 1;
private Context mContext;
private List<Article> mArticleList;
private LayoutInflater mInflater;
private OnArticleClickListener mArticleClickListener;
public FeedAdapter(Context context, OnArticleClickListener articleClickListener) {
this.mContext = context;
this.mArticleList = new ArrayList<>();
this.mArticleClickListener = articleClickListener;
this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_ITEM: {
CardFeedArticleBinding cardBinding = CardFeedArticleBinding.inflate(mInflater, parent, false);
return new ViewHolder(cardBinding);
}
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder && mArticleList != null) {
if (mArticleList.size() != 0) {
final Article article = getItem(position);
ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.bindData(article);
}
}
}
@Override
public int getItemViewType(int position) {
return TYPE_ITEM;
}
@Override
public int getItemCount() {
return mArticleList == null ? 0 : mArticleList.size();
}
public void add(Article article) {
mArticleList.add(article);
notifyItemInserted(mArticleList.size());
}
public void addAll(List<Article> articleList) {
for (Article article : articleList) {
add(article);
Logger.d(article);
}
}
private Article getItem(int position) {
return mArticleList.get(position);
}
public void SetOnItemClickListener(final OnArticleClickListener mItemClickListener) {
this.mArticleClickListener = mItemClickListener;
}
public interface OnArticleClickListener {
//TODO: use this method in the real project data not the parameter-less onItemClick()
void onItemClick(View view, int position, Article model);
void onBookmarkButtonClick(Article model);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final CardFeedArticleBinding mBinding;
public ViewHolder(CardFeedArticleBinding itemView) {
super(itemView.getRoot());
this.mBinding = itemView;
mBinding.getRoot().setOnClickListener(view -> mArticleClickListener.onItemClick(mBinding.getRoot(), getAdapterPosition(), getItem(getAdapterPosition())));//TODO: Remove this Dummy Data
mBinding.addToFavoriteFab.setOnClickListener(view -> mArticleClickListener.onBookmarkButtonClick(getItem(getAdapterPosition())));//TODO: Remove this Dummy Data
}
private void bindData(Article article) {
mBinding.setArticle(article);
Glide.with(mContext).load(article.getUrlToImage()).into(mBinding.articleImage);
mBinding.executePendingBindings();
}
}
}
| UTF-8 | Java | 3,748 | java | FeedAdapter.java | Java | []
| null | []
| package com.am.my_feed.feed;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.am.my_feed.room.Article;
import com.am.my_feed.databinding.CardFeedArticleBinding;
import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import java.util.ArrayList;
import java.util.List;
public class FeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_ITEM = 1;
private Context mContext;
private List<Article> mArticleList;
private LayoutInflater mInflater;
private OnArticleClickListener mArticleClickListener;
public FeedAdapter(Context context, OnArticleClickListener articleClickListener) {
this.mContext = context;
this.mArticleList = new ArrayList<>();
this.mArticleClickListener = articleClickListener;
this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_ITEM: {
CardFeedArticleBinding cardBinding = CardFeedArticleBinding.inflate(mInflater, parent, false);
return new ViewHolder(cardBinding);
}
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder && mArticleList != null) {
if (mArticleList.size() != 0) {
final Article article = getItem(position);
ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.bindData(article);
}
}
}
@Override
public int getItemViewType(int position) {
return TYPE_ITEM;
}
@Override
public int getItemCount() {
return mArticleList == null ? 0 : mArticleList.size();
}
public void add(Article article) {
mArticleList.add(article);
notifyItemInserted(mArticleList.size());
}
public void addAll(List<Article> articleList) {
for (Article article : articleList) {
add(article);
Logger.d(article);
}
}
private Article getItem(int position) {
return mArticleList.get(position);
}
public void SetOnItemClickListener(final OnArticleClickListener mItemClickListener) {
this.mArticleClickListener = mItemClickListener;
}
public interface OnArticleClickListener {
//TODO: use this method in the real project data not the parameter-less onItemClick()
void onItemClick(View view, int position, Article model);
void onBookmarkButtonClick(Article model);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final CardFeedArticleBinding mBinding;
public ViewHolder(CardFeedArticleBinding itemView) {
super(itemView.getRoot());
this.mBinding = itemView;
mBinding.getRoot().setOnClickListener(view -> mArticleClickListener.onItemClick(mBinding.getRoot(), getAdapterPosition(), getItem(getAdapterPosition())));//TODO: Remove this Dummy Data
mBinding.addToFavoriteFab.setOnClickListener(view -> mArticleClickListener.onBookmarkButtonClick(getItem(getAdapterPosition())));//TODO: Remove this Dummy Data
}
private void bindData(Article article) {
mBinding.setArticle(article);
Glide.with(mContext).load(article.getUrlToImage()).into(mBinding.articleImage);
mBinding.executePendingBindings();
}
}
}
| 3,748 | 0.684365 | 0.683298 | 115 | 31.591305 | 34.048786 | 196 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.469565 | false | false | 3 |
27981eed8b122bc5ed62e37412f66bd18dc4ac2e | 33,998,961,175,122 | 41a534b1181e47d2bb199bcb4078582fdf3d533c | /src/main/java/com/reptile/analysis/CmbcCreditAnalysis.java | 9298394c3465d5170efbe3696a422d88f29a20f1 | []
| no_license | soldiers1989/ReptileBank | https://github.com/soldiers1989/ReptileBank | 2d0388bb502f33c3f12ecb4f6d533df0d7478227 | 0fc7cbaafbff4ce54e1c6a4f4064071b5bc117de | refs/heads/master | 2020-04-07T19:55:33.350000 | 2018-02-25T06:13:41 | 2018-02-25T06:13:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.reptile.analysis;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class CmbcCreditAnalysis {
/**
* 账单数据解析 按月
* @param banklist 每个月的账单数据
* @param creTLmit
* @return
*/
public static JSONArray getInfos(Map<String, String> banklist, String creTLmit){
JSONObject fromObject = JSONObject.fromObject(banklist.toString());
JSONArray yuemap = JSONArray.fromObject(fromObject.get("banklist"));
//循环 总月的数据
JSONArray payRecord=new JSONArray();
JSONObject bankList=new JSONObject();
JSONArray bankListarr=new JSONArray();
//请求3 每个月的汇总信息
String payRecordlist=JSONObject.fromObject(yuemap.get(0)).toString();
JSONObject payRecordlistobj = JSONObject.fromObject(payRecordlist);
JSONArray payRecordlistArr = JSONArray.fromObject(payRecordlistobj.get("payRecordlist"));
//每个月的汇总数据
String response3=JSONObject.fromObject(yuemap.get(0)).get("response3").toString();
JSONObject response3Object = JSONObject.fromObject(response3);
String RepayLimitDate = response3Object.get("RepayLimitDate").toString();
String CurrentperiodBillAmt = response3Object.get("CurrentperiodBillAmt").toString();
String BillDate = response3Object.get("BillDate").toString();
String MinRepayLimit = response3Object.get("MinRepayLimit").toString();
JSONObject AccountSummary=new JSONObject();
AccountSummary.put("PaymentDueDate", RepayLimitDate);
AccountSummary.put("RMBCurrentAmountDue", CurrentperiodBillAmt);
AccountSummary.put("StatementDate",BillDate);
AccountSummary.put("RMBMinimumAmountDue",MinRepayLimit);
//信用额度
AccountSummary.put("CreditLimit",creTLmit);
//每个月里的list
for (int i = 0; i < payRecordlistArr.size(); i++) {
JSONObject payRecordlistli = JSONObject.fromObject(payRecordlistArr.get(i));
JSONArray List = JSONArray.fromObject(payRecordlistli.get("List"));
JSONObject payRecordDateil=new JSONObject();
for (int j = 0; j < List.size(); j++) {
JSONObject payRecordlistArrlist = JSONObject.fromObject(List.get(j));
String LastPeriodBillAmts=payRecordlistArrlist.get("TransAmt").toString();
String TransDescribe1=payRecordlistArrlist.get("TransDescribe1").toString();
String TransDate=payRecordlistArrlist.get("TransDate").toString();
//每一条具体的记录信息
payRecordDateil.put("post_amt", LastPeriodBillAmts);
payRecordDateil.put("tran_desc", TransDescribe1);
payRecordDateil.put("tran_date",TransDate);
//每个月总的记录
payRecord.add(payRecordDateil);
}
}
//每个月总的数据
bankList.put("payRecord", payRecord);
bankList.put("AccountSummary", AccountSummary);
bankListarr.add(bankList);
return bankListarr;
}
}
| UTF-8 | Java | 2,957 | java | CmbcCreditAnalysis.java | Java | []
| null | []
| package com.reptile.analysis;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class CmbcCreditAnalysis {
/**
* 账单数据解析 按月
* @param banklist 每个月的账单数据
* @param creTLmit
* @return
*/
public static JSONArray getInfos(Map<String, String> banklist, String creTLmit){
JSONObject fromObject = JSONObject.fromObject(banklist.toString());
JSONArray yuemap = JSONArray.fromObject(fromObject.get("banklist"));
//循环 总月的数据
JSONArray payRecord=new JSONArray();
JSONObject bankList=new JSONObject();
JSONArray bankListarr=new JSONArray();
//请求3 每个月的汇总信息
String payRecordlist=JSONObject.fromObject(yuemap.get(0)).toString();
JSONObject payRecordlistobj = JSONObject.fromObject(payRecordlist);
JSONArray payRecordlistArr = JSONArray.fromObject(payRecordlistobj.get("payRecordlist"));
//每个月的汇总数据
String response3=JSONObject.fromObject(yuemap.get(0)).get("response3").toString();
JSONObject response3Object = JSONObject.fromObject(response3);
String RepayLimitDate = response3Object.get("RepayLimitDate").toString();
String CurrentperiodBillAmt = response3Object.get("CurrentperiodBillAmt").toString();
String BillDate = response3Object.get("BillDate").toString();
String MinRepayLimit = response3Object.get("MinRepayLimit").toString();
JSONObject AccountSummary=new JSONObject();
AccountSummary.put("PaymentDueDate", RepayLimitDate);
AccountSummary.put("RMBCurrentAmountDue", CurrentperiodBillAmt);
AccountSummary.put("StatementDate",BillDate);
AccountSummary.put("RMBMinimumAmountDue",MinRepayLimit);
//信用额度
AccountSummary.put("CreditLimit",creTLmit);
//每个月里的list
for (int i = 0; i < payRecordlistArr.size(); i++) {
JSONObject payRecordlistli = JSONObject.fromObject(payRecordlistArr.get(i));
JSONArray List = JSONArray.fromObject(payRecordlistli.get("List"));
JSONObject payRecordDateil=new JSONObject();
for (int j = 0; j < List.size(); j++) {
JSONObject payRecordlistArrlist = JSONObject.fromObject(List.get(j));
String LastPeriodBillAmts=payRecordlistArrlist.get("TransAmt").toString();
String TransDescribe1=payRecordlistArrlist.get("TransDescribe1").toString();
String TransDate=payRecordlistArrlist.get("TransDate").toString();
//每一条具体的记录信息
payRecordDateil.put("post_amt", LastPeriodBillAmts);
payRecordDateil.put("tran_desc", TransDescribe1);
payRecordDateil.put("tran_date",TransDate);
//每个月总的记录
payRecord.add(payRecordDateil);
}
}
//每个月总的数据
bankList.put("payRecord", payRecord);
bankList.put("AccountSummary", AccountSummary);
bankListarr.add(bankList);
return bankListarr;
}
}
| 2,957 | 0.715201 | 0.709505 | 71 | 37.563381 | 28.353271 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.253521 | false | false | 3 |
cc8d6c78a47bdadbefb6435b490cf71c4d878181 | 36,850,819,441,816 | ce07abd5dbd4d67ab7159adccd253f8248757be1 | /android/app/src/main/java/com/tuanhk/internal/UserConfigImpl.java | 11b5628b3e1f91b0123f2bc87a849ff1043a4d97 | []
| no_license | HoangKimTuan/Base | https://github.com/HoangKimTuan/Base | 87a51f499aa56b66fe6b86d835ba3f63beb8a962 | 667a4de6efa5d750faaa6b7ce78cb013601bfe68 | refs/heads/master | 2020-03-25T22:38:07.280000 | 2018-09-05T07:53:46 | 2018-09-05T07:53:46 | 144,227,770 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tuanhk.internal;
import android.content.SharedPreferences;
import com.tuanhk.data.cache.UserConfig;
public class UserConfigImpl implements UserConfig {
private final SharedPreferences preferences;
public UserConfigImpl(SharedPreferences pref) {
this.preferences = pref;
}
@Override
public boolean hasCurrentUser() {
return preferences.getBoolean(Constants.PREF_AUTO_LOGIN, false);
}
@Override
public void saveConfigLogin(boolean status) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(Constants.PREF_AUTO_LOGIN, status);
editor.apply();
}
}
| UTF-8 | Java | 663 | java | UserConfigImpl.java | Java | []
| null | []
| package com.tuanhk.internal;
import android.content.SharedPreferences;
import com.tuanhk.data.cache.UserConfig;
public class UserConfigImpl implements UserConfig {
private final SharedPreferences preferences;
public UserConfigImpl(SharedPreferences pref) {
this.preferences = pref;
}
@Override
public boolean hasCurrentUser() {
return preferences.getBoolean(Constants.PREF_AUTO_LOGIN, false);
}
@Override
public void saveConfigLogin(boolean status) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(Constants.PREF_AUTO_LOGIN, status);
editor.apply();
}
}
| 663 | 0.714932 | 0.714932 | 27 | 23.555555 | 23.533009 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false | 3 |
431cd95016e6f0d2ce4615d9718ff5e957af65b9 | 31,842,887,592,614 | 9b5ca743c5965db47b7956b8d078c91dd4400d1b | /branches/factnet-0.1/FactNet-Desk/src/main/java/uninove/factnet/datatypes/rh/Pessoa.java | 580db859e016556152cf87856465f3a5ac6af6b9 | []
| no_license | BGCX067/fact-net-svn-to-git | https://github.com/BGCX067/fact-net-svn-to-git | ef85260e3e7bb9e32c1f5fb994f43fee20a5e9e0 | abe9f4c0ef881bc2c6aa044b8b28e80835341749 | refs/heads/master | 2016-09-01T08:55:49.151000 | 2015-12-28T14:26:54 | 2015-12-28T14:26:54 | 48,758,349 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uninove.factnet.datatypes.rh;
import uninove.factnet.datatypes.autenticacao.Permissoes;
import uninove.factnet.datatypes.login.Login;
public class Pessoa {
private Long idPessoa;
private Boolean isAtivo;
private Boolean isFuncionario;
private Login login;
private String nome;
private Permissoes permissoes;
public Pessoa() {
// TODO Auto-generated constructor stub
}
public Pessoa(Long idPessoa) {
this.idPessoa = idPessoa;
}
public Pessoa(Login login) {
this.login = login;
}
public Long getIdPessoa() {
return idPessoa;
}
public void setIdPessoa(Long idPessoa) {
this.idPessoa = idPessoa;
}
public Boolean getIsAtivo() {
return isAtivo;
}
public void setIsAtivo(Boolean isAtivo) {
this.isAtivo = isAtivo;
}
public Boolean getIsFuncionario() {
return isFuncionario;
}
public void setIsFuncionario(Boolean isFuncionario) {
this.isFuncionario = isFuncionario;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Permissoes getPermissoes() {
return permissoes;
}
public void setPermissoes(Permissoes permissoes) {
this.permissoes = permissoes;
}
}
| UTF-8 | Java | 1,392 | java | Pessoa.java | Java | []
| null | []
| package uninove.factnet.datatypes.rh;
import uninove.factnet.datatypes.autenticacao.Permissoes;
import uninove.factnet.datatypes.login.Login;
public class Pessoa {
private Long idPessoa;
private Boolean isAtivo;
private Boolean isFuncionario;
private Login login;
private String nome;
private Permissoes permissoes;
public Pessoa() {
// TODO Auto-generated constructor stub
}
public Pessoa(Long idPessoa) {
this.idPessoa = idPessoa;
}
public Pessoa(Login login) {
this.login = login;
}
public Long getIdPessoa() {
return idPessoa;
}
public void setIdPessoa(Long idPessoa) {
this.idPessoa = idPessoa;
}
public Boolean getIsAtivo() {
return isAtivo;
}
public void setIsAtivo(Boolean isAtivo) {
this.isAtivo = isAtivo;
}
public Boolean getIsFuncionario() {
return isFuncionario;
}
public void setIsFuncionario(Boolean isFuncionario) {
this.isFuncionario = isFuncionario;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Permissoes getPermissoes() {
return permissoes;
}
public void setPermissoes(Permissoes permissoes) {
this.permissoes = permissoes;
}
}
| 1,392 | 0.677443 | 0.677443 | 78 | 15.846154 | 16.041674 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.371795 | false | false | 3 |
6b31943412e4a60810fba7ae56bd494be45c9396 | 12,300,786,362,795 | e7bf0bc458df19e6f168e009c3fb9295429e2bd1 | /src/main/java/ua/org/ostpc/ittools/entity/ProjectStages.java | fe7c3a36a678b09b2cec799d90e2b7ccc41a2c30 | [
"Apache-2.0"
]
| permissive | ostpc/ittools | https://github.com/ostpc/ittools | 8140183810e18cec6788fef5445ba51021b7c211 | 9a261d306003ca812affae46d459daa57844168c | refs/heads/master | 2020-04-21T01:31:04.526000 | 2019-03-19T13:14:51 | 2019-03-19T13:14:51 | 169,226,083 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.org.ostpc.ittools.entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class ProjectStages {
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "projectStages")
private Set<EmployeeRoles> employeeRoles = new HashSet<>();
@ManyToMany
@JoinTable(name="projectStages_tasks",
joinColumns = @JoinColumn(name="projectStages_id", referencedColumnName="id"),
inverseJoinColumns = @JoinColumn(name="tasks_id", referencedColumnName="id")
)
private Set<Tasks> tasks = new HashSet<>();
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String description;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<EmployeeRoles> getEmployeeRoles() {
return employeeRoles;
}
public void setEmployeeRoles(Set<EmployeeRoles> employeeRoles) {
this.employeeRoles = employeeRoles;
}
public Set<Tasks> getTasks() {
return tasks;
}
public void setTasks(Set<Tasks> tasks) {
this.tasks = tasks;
}
}
| UTF-8 | Java | 1,367 | java | ProjectStages.java | Java | []
| null | []
| package ua.org.ostpc.ittools.entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class ProjectStages {
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "projectStages")
private Set<EmployeeRoles> employeeRoles = new HashSet<>();
@ManyToMany
@JoinTable(name="projectStages_tasks",
joinColumns = @JoinColumn(name="projectStages_id", referencedColumnName="id"),
inverseJoinColumns = @JoinColumn(name="tasks_id", referencedColumnName="id")
)
private Set<Tasks> tasks = new HashSet<>();
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String description;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<EmployeeRoles> getEmployeeRoles() {
return employeeRoles;
}
public void setEmployeeRoles(Set<EmployeeRoles> employeeRoles) {
this.employeeRoles = employeeRoles;
}
public Set<Tasks> getTasks() {
return tasks;
}
public void setTasks(Set<Tasks> tasks) {
this.tasks = tasks;
}
}
| 1,367 | 0.651061 | 0.651061 | 60 | 21.783333 | 23.060133 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 3 |
f1a7443bb5b0f3564444e547085a80da1b6bae6e | 18,442,589,591,305 | 68ddffba63707d4686520aaa491026f18bf10234 | /src/main/java/com/lacoo/framework/db/persistence/JdbcPersistenceHandler.java | dbfecbbc82740f9b808673a939dff1a7c27be10f | []
| no_license | lacoolee/com.lacoo.framework.jdbc | https://github.com/lacoolee/com.lacoo.framework.jdbc | b98b86d3311eb8d1b23cc5c391c67406aeae0589 | 0f8df37752f2a196cbee5f607c94e14d83b49de2 | refs/heads/master | 2020-04-17T10:40:00.305000 | 2019-01-19T05:17:57 | 2019-01-19T05:17:57 | 166,509,117 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lacoo.framework.db.persistence;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
/**
* <p>
* 类注释
* </p>
* <p>
* Copyright (c) 2004 Drian. All rights reserved
* </p>
* <p>
*
* @(#) JdbcPersistenceManager.java 创建日期
* </p>
* <p>
* @author <a href="mailto:alf.1981@163.com">aden cheng </a>
* </p>
* <p>
* @version 1.0
* </p>
*/
public interface JdbcPersistenceHandler {
// 执行sql语句
public void executeSql(String sql);
public void executeSqlWithThrow(String sql) throws SQLException;
public String getDbInfo();
public void executeSqlClob(String sql, String content);// 需要测试
public void executeSqlClobWithThrow(String sql, String content) throws Exception;// 需要测试
public void executeSql(String sql, String[] params);
public void executeSqlWithThrow(String sql, String[] params) throws SQLException;
public void executeSql(String sql, Object[] params);
public void executeSqlWithThrow(String sql, Object[] params) throws SQLException;
public void executeSqls(String... sqls) throws SQLException;
// 执行多条sql语句
public void executeSql(List<String> sqls);
public void executeSqlWithThrow(List<String> sqls) throws SQLException;
// 批量执行sql语句
public void batchExecuteSql(String sql, List params);
public void batchExecuteSqlWithThrow(String sql, List params) throws SQLException;
// 批量执行带参数的sql语句
public void batchExecuteSqlWithParams(List<Pair<String, Object>> sqlsAndParams) throws SQLException;
}
// vim: ft=java
| UTF-8 | Java | 1,634 | java | JdbcPersistenceHandler.java | Java | [
{
"context": " * <p>\n * 类注释\n * </p>\n * <p>\n * Copyright (c) 2004 Drian. All rights reserved\n * </p>\n * <p>\n * \n * @(#) J",
"end": 204,
"score": 0.9995734691619873,
"start": 199,
"tag": "NAME",
"value": "Drian"
},
{
"context": " </p>\n * <p>\n * @author <a href=\"mailto:alf.1981@163.com\">aden cheng </a>\n * </p>\n * <p>\n ",
"end": 354,
"score": 0.9999170303344727,
"start": 338,
"tag": "EMAIL",
"value": "alf.1981@163.com"
},
{
"context": " <p>\n * @author <a href=\"mailto:alf.1981@163.com\">aden cheng </a>\n * </p>\n * <p>\n * @version 1",
"end": 366,
"score": 0.9997644424438477,
"start": 356,
"tag": "NAME",
"value": "aden cheng"
}
]
| null | []
| package com.lacoo.framework.db.persistence;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
/**
* <p>
* 类注释
* </p>
* <p>
* Copyright (c) 2004 Drian. All rights reserved
* </p>
* <p>
*
* @(#) JdbcPersistenceManager.java 创建日期
* </p>
* <p>
* @author <a href="mailto:<EMAIL>"><NAME> </a>
* </p>
* <p>
* @version 1.0
* </p>
*/
public interface JdbcPersistenceHandler {
// 执行sql语句
public void executeSql(String sql);
public void executeSqlWithThrow(String sql) throws SQLException;
public String getDbInfo();
public void executeSqlClob(String sql, String content);// 需要测试
public void executeSqlClobWithThrow(String sql, String content) throws Exception;// 需要测试
public void executeSql(String sql, String[] params);
public void executeSqlWithThrow(String sql, String[] params) throws SQLException;
public void executeSql(String sql, Object[] params);
public void executeSqlWithThrow(String sql, Object[] params) throws SQLException;
public void executeSqls(String... sqls) throws SQLException;
// 执行多条sql语句
public void executeSql(List<String> sqls);
public void executeSqlWithThrow(List<String> sqls) throws SQLException;
// 批量执行sql语句
public void batchExecuteSql(String sql, List params);
public void batchExecuteSqlWithThrow(String sql, List params) throws SQLException;
// 批量执行带参数的sql语句
public void batchExecuteSqlWithParams(List<Pair<String, Object>> sqlsAndParams) throws SQLException;
}
// vim: ft=java
| 1,621 | 0.722294 | 0.713273 | 62 | 24.032259 | 28.048326 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.758065 | false | false | 3 |
9a52c2ce5f2967523e41a69ead3064705d431fb4 | 27,513,560,561,719 | 817ac5e50e64eba54907a039a51def089414b34f | /whatever-boot/src/main/java/me/weix/whatever/entity/BaseEntity.java | a4068334b7c54ca7ea4d60ba31a892a5debb5138 | []
| no_license | wxpersonal/whatever-springboot | https://github.com/wxpersonal/whatever-springboot | 12d7731e14ff13afe5f13d353bf38eae075019d3 | 92e8eb67a221cfc2ed054f52e4334bdc370fe358 | refs/heads/master | 2022-10-28T21:01:14.448000 | 2019-05-17T01:13:59 | 2019-05-17T01:13:59 | 95,902,581 | 0 | 0 | null | false | 2022-10-12T20:26:47 | 2017-06-30T15:43:46 | 2019-05-17T01:14:29 | 2022-10-12T20:26:45 | 6,238 | 0 | 0 | 4 | Java | false | false | package me.weix.whatever.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableLogic;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author weix
*/
@Data
public class BaseEntity implements Serializable {
/**
* 创建人
*/
@TableField("create_by")
private Integer createBy;
/**
* 创建时间
*/
@TableField("create_time")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 修改人
*/
@TableField("update_by")
private Integer updateBy;
/**
* 修改时间
*/
@TableField("update_time")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/**
* 有效状态
*/
private Integer status;
/**
* 删除标记
*/
@TableLogic
private Integer deleted;
}
| UTF-8 | Java | 976 | java | BaseEntity.java | Java | [
{
"context": "rializable;\nimport java.util.Date;\n\n/**\n * @author weix\n */\n@Data\npublic class BaseEntity implements Seri",
"end": 291,
"score": 0.999508798122406,
"start": 287,
"tag": "USERNAME",
"value": "weix"
}
]
| null | []
| package me.weix.whatever.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableLogic;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author weix
*/
@Data
public class BaseEntity implements Serializable {
/**
* 创建人
*/
@TableField("create_by")
private Integer createBy;
/**
* 创建时间
*/
@TableField("create_time")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 修改人
*/
@TableField("update_by")
private Integer updateBy;
/**
* 修改时间
*/
@TableField("update_time")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/**
* 有效状态
*/
private Integer status;
/**
* 删除标记
*/
@TableLogic
private Integer deleted;
}
| 976 | 0.624463 | 0.624463 | 54 | 16.25926 | 15.845533 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.240741 | false | false | 3 |
4ba3e15f4669b618e8054bcac73d8eb3ce6d30d5 | 24,730,421,701,263 | 3e7a1180a9c382b292fe18fafed4538f70f090b6 | /src/test/java/ar/edu/unlam/tallerweb1/BuscarTest.java | 9f938918f304991ab111553a952a7b200a425907 | []
| no_license | DigruttolaGabriel/taller-web-1-proyecto | https://github.com/DigruttolaGabriel/taller-web-1-proyecto | 5c27df54f23bd119b567ae9c7da3f2e484d04375 | 102536eab31b9a1911bb08f0fd213d3d79eb89eb | refs/heads/master | 2023-02-03T00:49:52.558000 | 2020-12-17T20:50:23 | 2020-12-17T20:50:23 | 295,253,724 | 0 | 1 | null | false | 2020-12-17T20:50:24 | 2020-09-13T23:08:07 | 2020-12-17T19:35:31 | 2020-12-17T20:50:24 | 5,204 | 0 | 0 | 0 | Java | false | false | package ar.edu.unlam.tallerweb1;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
import javax.inject.Inject;
import org.junit.Test;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import ar.edu.unlam.tallerweb1.controladores.BusquedaController;
import ar.edu.unlam.tallerweb1.modelo.ClienteModel;
import ar.edu.unlam.tallerweb1.modelo.ComidaModel;
import ar.edu.unlam.tallerweb1.modelo.form.FormularioBusqueda;
import ar.edu.unlam.tallerweb1.modelo.form.FormularioRegistro;
import ar.edu.unlam.tallerweb1.servicios.BusquedaService;
import ar.edu.unlam.tallerweb1.servicios.ClienteService;
public class BuscarTest extends SpringTest {
@Inject
private BusquedaService busquedaService;
@Test
@Transactional
@Rollback
public void pruebaConexion() {
assertThat(session().isConnected()).isTrue();
}
/*
* @Test
*
* @Transactional
*
* @Rollback public void queElBuscadorTraigaComidas() { FormularioBusqueda
* formulario = new FormularioBusqueda(); ComidaModel comida = new
* ComidaModel(); String dato="COMIDA"; formulario.setDatoBuscado(dato);
*
*
* }
*
*
*
* @Test
*
* @Transactional
*
* @Rollback public void queElClienteSeGuardeCorrectamente() { ClienteModel
* cliente = new ClienteModel();
*
* cliente.setApellido("Apellido"); cliente.setDni("111111");
* cliente.setNombre("Nombre"); cliente.setTelefono("0303456");
*
* FormularioRegistro registro = new FormularioRegistro();
* registro.setClienteBuscado(cliente);
*
* servicioCliente.guardarClienteRegistrado(registro);
*
* assertEquals("Apellido", registro.getClienteBuscado().getApellido());
*
* }
*/
/*
* @Test
*
* @Transactional
*
* @Rollback public void
* queElClienteNoSeGuardeCorrectamenteSiNoSeCompletaronLosDatos() {
* FormularioRegistro registro = new FormularioRegistro();
* servicioCliente.guardarClienteRegistrado(registro);
*
* assertThat(registro);
*
* }
*/
} | UTF-8 | Java | 2,065 | java | BuscarTest.java | Java | [
{
"context": " cliente.setDni(\"111111\");\n\t * cliente.setNombre(\"Nombre\"); cliente.setTelefono(\"0303456\");\n\t * \n\t * Formu",
"end": 1464,
"score": 0.9068447947502136,
"start": 1458,
"tag": "NAME",
"value": "Nombre"
}
]
| null | []
| package ar.edu.unlam.tallerweb1;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
import javax.inject.Inject;
import org.junit.Test;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import ar.edu.unlam.tallerweb1.controladores.BusquedaController;
import ar.edu.unlam.tallerweb1.modelo.ClienteModel;
import ar.edu.unlam.tallerweb1.modelo.ComidaModel;
import ar.edu.unlam.tallerweb1.modelo.form.FormularioBusqueda;
import ar.edu.unlam.tallerweb1.modelo.form.FormularioRegistro;
import ar.edu.unlam.tallerweb1.servicios.BusquedaService;
import ar.edu.unlam.tallerweb1.servicios.ClienteService;
public class BuscarTest extends SpringTest {
@Inject
private BusquedaService busquedaService;
@Test
@Transactional
@Rollback
public void pruebaConexion() {
assertThat(session().isConnected()).isTrue();
}
/*
* @Test
*
* @Transactional
*
* @Rollback public void queElBuscadorTraigaComidas() { FormularioBusqueda
* formulario = new FormularioBusqueda(); ComidaModel comida = new
* ComidaModel(); String dato="COMIDA"; formulario.setDatoBuscado(dato);
*
*
* }
*
*
*
* @Test
*
* @Transactional
*
* @Rollback public void queElClienteSeGuardeCorrectamente() { ClienteModel
* cliente = new ClienteModel();
*
* cliente.setApellido("Apellido"); cliente.setDni("111111");
* cliente.setNombre("Nombre"); cliente.setTelefono("0303456");
*
* FormularioRegistro registro = new FormularioRegistro();
* registro.setClienteBuscado(cliente);
*
* servicioCliente.guardarClienteRegistrado(registro);
*
* assertEquals("Apellido", registro.getClienteBuscado().getApellido());
*
* }
*/
/*
* @Test
*
* @Transactional
*
* @Rollback public void
* queElClienteNoSeGuardeCorrectamenteSiNoSeCompletaronLosDatos() {
* FormularioRegistro registro = new FormularioRegistro();
* servicioCliente.guardarClienteRegistrado(registro);
*
* assertThat(registro);
*
* }
*/
} | 2,065 | 0.74092 | 0.730751 | 81 | 24.506172 | 25.557547 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.098765 | false | false | 3 |
818d2717b0e5b2624329628755d9d1b9163e7492 | 3,659,312,152,613 | d0af17144cff316536a2a6b33de6494dc263ccb3 | /app/src/main/java/com/example/moviesapp/FavouriteMoviesActivity.java | 3d135827d767f2fbc2f3fd7b3fd7ac186bd5de22 | []
| no_license | mohammedsalmeen/MovieApp | https://github.com/mohammedsalmeen/MovieApp | 06ca0527cfb2c3063ee3025bc55e1a316025a27a | f06396b79710c72ee2b0b98fa1c5c506b115f112 | refs/heads/master | 2020-09-03T01:05:21.956000 | 2019-11-06T21:45:17 | 2019-11-06T21:45:17 | 219,347,029 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.moviesapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.moviesapp.Model.Movies;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
public class FavouriteMoviesActivity extends AppCompatActivity {
// variable definition
ArrayList<Movies> list = new ArrayList<>();
MoviesAdapter adapter;
RecyclerView recyclerView;
ImageView favIsEmpty;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite_movies);
favIsEmpty = findViewById(R.id.favIsEmpty);
recyclerView = findViewById(R.id.recyclerView);
list = getData();
// if the favourite is empty
if (list.size() == 0) {
Toast.makeText(this, getString(R.string.no_favs), Toast.LENGTH_SHORT).show();
}
// to handel the adapter and recyclerView
adapter = new MoviesAdapter(list, this, recyclerView);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
// to get the favourite data from movies page
private ArrayList<Movies> getData() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String jsonFavs = prefs.getString("favourites", null);
Log.e("Khaled", "JSON is " + jsonFavs);
Movies movie = new Movies();
ArrayList<Movies> result = new ArrayList<>();
if (jsonFavs != null) {
try {
JSONArray favList = new JSONArray(jsonFavs);
for (int i = 0; i < favList.length(); i++) {
Log.e("Khaled", "" + i);
JSONObject movieJson = favList.getJSONObject(i);
movie.movieTitle = movieJson.getString("title");
Log.e("Khaled", movie.movieTitle);
movie.imdbRating = movieJson.getDouble("ImdbRating");
movie.year = movieJson.getString("Year");
movie.released_date = movieJson.getString("Released_date");
movie.moviePoster = movieJson.getString("MoviePoster");
result.add(movie);
favIsEmpty.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return result;
}
}
| UTF-8 | Java | 2,913 | java | FavouriteMoviesActivity.java | Java | []
| null | []
| package com.example.moviesapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.moviesapp.Model.Movies;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
public class FavouriteMoviesActivity extends AppCompatActivity {
// variable definition
ArrayList<Movies> list = new ArrayList<>();
MoviesAdapter adapter;
RecyclerView recyclerView;
ImageView favIsEmpty;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite_movies);
favIsEmpty = findViewById(R.id.favIsEmpty);
recyclerView = findViewById(R.id.recyclerView);
list = getData();
// if the favourite is empty
if (list.size() == 0) {
Toast.makeText(this, getString(R.string.no_favs), Toast.LENGTH_SHORT).show();
}
// to handel the adapter and recyclerView
adapter = new MoviesAdapter(list, this, recyclerView);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
// to get the favourite data from movies page
private ArrayList<Movies> getData() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String jsonFavs = prefs.getString("favourites", null);
Log.e("Khaled", "JSON is " + jsonFavs);
Movies movie = new Movies();
ArrayList<Movies> result = new ArrayList<>();
if (jsonFavs != null) {
try {
JSONArray favList = new JSONArray(jsonFavs);
for (int i = 0; i < favList.length(); i++) {
Log.e("Khaled", "" + i);
JSONObject movieJson = favList.getJSONObject(i);
movie.movieTitle = movieJson.getString("title");
Log.e("Khaled", movie.movieTitle);
movie.imdbRating = movieJson.getDouble("ImdbRating");
movie.year = movieJson.getString("Year");
movie.released_date = movieJson.getString("Released_date");
movie.moviePoster = movieJson.getString("MoviePoster");
result.add(movie);
favIsEmpty.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return result;
}
}
| 2,913 | 0.640577 | 0.63989 | 84 | 33.67857 | 23.978245 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.702381 | false | false | 3 |
e08187f20151063dfccf28b12bfaa5d973215be8 | 14,345,190,786,827 | b6aab7ba6bc50e02dd1f4856a0b4241f9dc5041e | /A1.java | 7119506f87aa7ba93c975e4f87f1aa453e782f9f | []
| no_license | Pushpam-iitd/Conference-Scheduling-using-Local-Search | https://github.com/Pushpam-iitd/Conference-Scheduling-using-Local-Search | 33b4f58113b0007132b0e7284005021b1279ec22 | c7f20bde2af540a16a46e30cde1eb8d437745374 | refs/heads/master | 2020-03-27T09:17:45.495000 | 2018-08-27T17:09:04 | 2018-08-27T17:09:04 | 146,328,577 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
import java.io.*;
public class A1 {
// public static int[][] generate_neighbours(int[][] curr_state){
// int[][] temp=curr_state;
// }
double[][] dis_bw_papers;
public static double getgoodness(int[][][] schedule){
return(null);
}
// private static saveState(...){
// }
private static getDistance(int i,int j){
}
public static double get_p_goodness(int[][] schedule_in_a_timeSlot,int c_trade_off){
double goodness=0;
for (int i=0;i<schedule_in_a_timeSlot.length;i++) {
for(int j=0;j<schedule_in_a_timeSlot[0].length-1;j++){
goodness+=getDistance(schedule_in_a_timeSlot[i][j],schedule_in_a_timeSlot[i][j+1]);
}
}
double term2=0;
for (int i=0;i<schedule_in_a_timeSlot.length;i++) {
for(int j=0;j<schedule_in_a_timeSlot[0].length;j++){
for (int k=i+1;k<schedule_in_a_timeSlot.length ;k++ ) {
for (int l=0;l<schedule_in_a_timeSlot[0].length ;l++) {
term2+=getDistance(schedule_in_a_timeSlot[i][j],schedule_in_a_timeSlot[k][l]);
}
}
}
}
}
public static int[][][] randomState(int p,int k,int t){
int[][][] a=new int[t][p][k];
Random rand=new Random();
int r_int=0;
int[] random_arr=new int[t*p*k];
for (int i=0;i<t*p*k;i++){
random_arr[i]=(i+1);
}
for(int i=0;i<t*p*k;i++){
int f=rand.nextInt(p*t*k);
int s=rand.nextInt(p*t*k);
int temp=random_arr[f];
random_arr[f]=random_arr[s];
random_arr[s]=temp;
}
int count=0;
for(int i=0;i<t;i++){
for (int j=0;j<p;j++) {
for (int z=0;z<k;z++) {
a[i][j][z]=random_arr[count];
count++;
}
}
}
return(a);
}
public static void printState(int[][][] a){
for (int i=0;i<a.length ;i++ ) {
for (int j=0;j<a[0].length;j++) {
for (int k=0;k<a[0][0].length;k++) {
System.out.print(a[i][j][k]+" ");
}
if(j!=a[0].length-1)
System.out.print("|");
}
System.out.println();
}
}
public static int[][] partial_local_search(int[][] initial_state,int c_trade_off){
return null;
}
public static localSearch(int t,int p, int k,int c_trade_off){
int[][][] initial_state=randomState(p,t,k);
int[][][] result=new int[t][p][k];
double max_goodness=-100000;
while(true){//terminate when time's up
initial_state=randomState(p,t,k);
for(int i=0;i<initial_state.length;i++){
result[i]=partial_local_search(initial_state[i]);
}
double temp=getgoodness(result);
if(temp>max_goodness)
max_goodness=temp;
//restarting
}
}
public static void main(String[] args) {
Scanner scn =new Scanner(System.in);
int max_time=scn.nextInt();
int paper_per_sess=scn.nextInt();
int no_of_sess=scn.nextInt();
int time_slots=scn.nextInt();
int c_trade_off=scn.nextInt();
int n=paper_per_sess*time_slots*no_of_sess;
dis_bw_papers=new double[n+1][n+1];
for(int i=1;i<n+1;i++){
for(int j=1;j<n+1;j++){
dis_bw_papers[i][j]=scn.nextDouble();
}
}
int[][][] goal=localSearch(t,p,k,c_trade_off);
printState(goal);
}
} | UTF-8 | Java | 2,982 | java | A1.java | Java | []
| null | []
| import java.util.*;
import java.io.*;
public class A1 {
// public static int[][] generate_neighbours(int[][] curr_state){
// int[][] temp=curr_state;
// }
double[][] dis_bw_papers;
public static double getgoodness(int[][][] schedule){
return(null);
}
// private static saveState(...){
// }
private static getDistance(int i,int j){
}
public static double get_p_goodness(int[][] schedule_in_a_timeSlot,int c_trade_off){
double goodness=0;
for (int i=0;i<schedule_in_a_timeSlot.length;i++) {
for(int j=0;j<schedule_in_a_timeSlot[0].length-1;j++){
goodness+=getDistance(schedule_in_a_timeSlot[i][j],schedule_in_a_timeSlot[i][j+1]);
}
}
double term2=0;
for (int i=0;i<schedule_in_a_timeSlot.length;i++) {
for(int j=0;j<schedule_in_a_timeSlot[0].length;j++){
for (int k=i+1;k<schedule_in_a_timeSlot.length ;k++ ) {
for (int l=0;l<schedule_in_a_timeSlot[0].length ;l++) {
term2+=getDistance(schedule_in_a_timeSlot[i][j],schedule_in_a_timeSlot[k][l]);
}
}
}
}
}
public static int[][][] randomState(int p,int k,int t){
int[][][] a=new int[t][p][k];
Random rand=new Random();
int r_int=0;
int[] random_arr=new int[t*p*k];
for (int i=0;i<t*p*k;i++){
random_arr[i]=(i+1);
}
for(int i=0;i<t*p*k;i++){
int f=rand.nextInt(p*t*k);
int s=rand.nextInt(p*t*k);
int temp=random_arr[f];
random_arr[f]=random_arr[s];
random_arr[s]=temp;
}
int count=0;
for(int i=0;i<t;i++){
for (int j=0;j<p;j++) {
for (int z=0;z<k;z++) {
a[i][j][z]=random_arr[count];
count++;
}
}
}
return(a);
}
public static void printState(int[][][] a){
for (int i=0;i<a.length ;i++ ) {
for (int j=0;j<a[0].length;j++) {
for (int k=0;k<a[0][0].length;k++) {
System.out.print(a[i][j][k]+" ");
}
if(j!=a[0].length-1)
System.out.print("|");
}
System.out.println();
}
}
public static int[][] partial_local_search(int[][] initial_state,int c_trade_off){
return null;
}
public static localSearch(int t,int p, int k,int c_trade_off){
int[][][] initial_state=randomState(p,t,k);
int[][][] result=new int[t][p][k];
double max_goodness=-100000;
while(true){//terminate when time's up
initial_state=randomState(p,t,k);
for(int i=0;i<initial_state.length;i++){
result[i]=partial_local_search(initial_state[i]);
}
double temp=getgoodness(result);
if(temp>max_goodness)
max_goodness=temp;
//restarting
}
}
public static void main(String[] args) {
Scanner scn =new Scanner(System.in);
int max_time=scn.nextInt();
int paper_per_sess=scn.nextInt();
int no_of_sess=scn.nextInt();
int time_slots=scn.nextInt();
int c_trade_off=scn.nextInt();
int n=paper_per_sess*time_slots*no_of_sess;
dis_bw_papers=new double[n+1][n+1];
for(int i=1;i<n+1;i++){
for(int j=1;j<n+1;j++){
dis_bw_papers[i][j]=scn.nextDouble();
}
}
int[][][] goal=localSearch(t,p,k,c_trade_off);
printState(goal);
}
} | 2,982 | 0.597921 | 0.58283 | 116 | 24.715517 | 21.031096 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.103448 | false | false | 3 |
321616668e174e50d0fa3c5e03ec1005edb16ee9 | 25,701,084,314,124 | 1afdeb4d55e8754a3d1d41c6226d847b5bb9f9e4 | /src/com/servlet/PurchaseConfirmation.java | f8bf7f84548b4268cd0b17e3d52084e84f308e25 | []
| no_license | machin3head/CLAIM_CarSalesWebApp | https://github.com/machin3head/CLAIM_CarSalesWebApp | 30b94b72a52f00172d2bd7918c6e886ea9594fd4 | d06991e93bd7481e1012bc0ceea6263f63a73178 | refs/heads/master | 2021-09-16T06:00:45.987000 | 2018-06-17T16:41:17 | 2018-06-17T16:41:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.servlet;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import webApp.Vehicle;
@WebServlet("/PurchaseConfirmation")
public class PurchaseConfirmation extends HttpServlet {
private static final long serialVersionUID = 1L;
public PurchaseConfirmation() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String vin = request.getParameter("vin");
Vehicle purchaseCar = new Vehicle();
Set<Vehicle> vehicles = new HashSet<>();
vehicles.addAll(purchaseCar.getVehicles());
for (Vehicle v : vehicles) {
if (v.getVin().equals(vin)) {
purchaseCar = v;
break; }}
session.setAttribute("purchaseCar", purchaseCar);
RequestDispatcher rd = request.getRequestDispatcher("purchaseConfirmation.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| UTF-8 | Java | 1,413 | java | PurchaseConfirmation.java | Java | []
| null | []
| package com.servlet;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import webApp.Vehicle;
@WebServlet("/PurchaseConfirmation")
public class PurchaseConfirmation extends HttpServlet {
private static final long serialVersionUID = 1L;
public PurchaseConfirmation() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String vin = request.getParameter("vin");
Vehicle purchaseCar = new Vehicle();
Set<Vehicle> vehicles = new HashSet<>();
vehicles.addAll(purchaseCar.getVehicles());
for (Vehicle v : vehicles) {
if (v.getVin().equals(vin)) {
purchaseCar = v;
break; }}
session.setAttribute("purchaseCar", purchaseCar);
RequestDispatcher rd = request.getRequestDispatcher("purchaseConfirmation.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| 1,413 | 0.760085 | 0.759377 | 51 | 26.705883 | 27.019451 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.54902 | false | false | 3 |
86f5ccd76b304f31d8b272fea005d677267954b3 | 6,133,213,315,382 | 7c9f02d557b4acf5d61667d89c4d371dcd1ef208 | /src/main/java/com/lunzi/camry/domain/Seller.java | 67ae8cc90fb5c36c586d114acd32d69b62f0ebd6 | []
| no_license | wushengtao/camry | https://github.com/wushengtao/camry | d7846f079511fb326ce5fc9ec9cc40cded433551 | 1fea2c8b4c942f688b7965740fd3007bc1e48c39 | refs/heads/master | 2022-06-27T16:37:20.238000 | 2019-07-04T01:18:35 | 2019-07-04T01:18:35 | 147,057,826 | 1 | 0 | null | false | 2022-06-22T18:37:54 | 2018-09-02T05:40:28 | 2019-07-04T01:19:02 | 2022-06-22T18:37:54 | 406 | 1 | 0 | 7 | JavaScript | false | false | package com.lunzi.camry.domain;
import com.google.gson.Gson;
import lombok.Builder;
import lombok.Data;
/**
* Created by lunzi on 2018/8/30 下午11:02
*/
@Data
@Builder
public class Seller {
private Long carId;
private Long contractAmount; // 合同金额
private Long earnest; // 定金
private Long balance; // 尾款
private Long speedReturnApplyFee; // 速回款(申请)金额
private Long speedReturnActualFee; // 速回款(借贷实际)金额
private Long expectedInterests; // 预估利息
private Long actualInterests; // 实际利息
private Long expectedWmsFee; // 预估仓储费
private Long expectedTmsFee; // 预估物流费用
private Long earnestFrozenFee; // 定金冻结预估费用
private Long balanceFrozenFee; // 尾款冻结预估费用
public static void main(String args[]){
Seller seller=Seller.builder()
.carId(1L)
.contractAmount(1L)
.earnest(1L)
.balance(1L)
.speedReturnApplyFee(1L)
.speedReturnActualFee(1L)
.expectedInterests(1L)
.actualInterests(1L)
.expectedWmsFee(1L)
.expectedTmsFee(1L)
.earnestFrozenFee(1L)
.balanceFrozenFee(1L)
.build();
System.out.println(new Gson().toJson(seller));
}
}
| UTF-8 | Java | 1,413 | java | Seller.java | Java | [
{
"context": "ok.Builder;\nimport lombok.Data;\n\n/**\n * Created by lunzi on 2018/8/30 下午11:02\n */\n@Data\n@Builder\npublic cl",
"end": 129,
"score": 0.9995539784431458,
"start": 124,
"tag": "USERNAME",
"value": "lunzi"
}
]
| null | []
| package com.lunzi.camry.domain;
import com.google.gson.Gson;
import lombok.Builder;
import lombok.Data;
/**
* Created by lunzi on 2018/8/30 下午11:02
*/
@Data
@Builder
public class Seller {
private Long carId;
private Long contractAmount; // 合同金额
private Long earnest; // 定金
private Long balance; // 尾款
private Long speedReturnApplyFee; // 速回款(申请)金额
private Long speedReturnActualFee; // 速回款(借贷实际)金额
private Long expectedInterests; // 预估利息
private Long actualInterests; // 实际利息
private Long expectedWmsFee; // 预估仓储费
private Long expectedTmsFee; // 预估物流费用
private Long earnestFrozenFee; // 定金冻结预估费用
private Long balanceFrozenFee; // 尾款冻结预估费用
public static void main(String args[]){
Seller seller=Seller.builder()
.carId(1L)
.contractAmount(1L)
.earnest(1L)
.balance(1L)
.speedReturnApplyFee(1L)
.speedReturnActualFee(1L)
.expectedInterests(1L)
.actualInterests(1L)
.expectedWmsFee(1L)
.expectedTmsFee(1L)
.earnestFrozenFee(1L)
.balanceFrozenFee(1L)
.build();
System.out.println(new Gson().toJson(seller));
}
}
| 1,413 | 0.603408 | 0.585593 | 42 | 29.738094 | 15.19721 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 3 |
1b20eb5d13a6fe93ebece7b5b6e7c2e1588209be | 13,228,499,286,407 | 2d2d64c1be2f6614983b84f794e0b680f5b0c509 | /src/main/java/br/com/bank/onlybank/enums/AccountType.java | 27da9683c71f8a2f6b164ea11b80e5eb545c90dd | []
| no_license | audicarmo/one-bank-service-old-project | https://github.com/audicarmo/one-bank-service-old-project | 7d9f09de26ae66073832be52d814de6aa726e61d | 078ed8a6b9590de4ef84e1b3b0beb95d2ae78de2 | refs/heads/main | 2023-04-27T10:06:27.107000 | 2021-05-13T05:11:13 | 2021-05-13T05:11:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.bank.onlybank.enums;
public enum AccountType {
}
| UTF-8 | Java | 65 | java | AccountType.java | Java | []
| null | []
| package br.com.bank.onlybank.enums;
public enum AccountType {
}
| 65 | 0.769231 | 0.769231 | 4 | 15.25 | 15.171931 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 3 |
9819929f27f450cf4d0f0a595da76b0d4d538c06 | 807,453,877,892 | 735775b647f91b740b20fd80ab7327116c784efa | /javaVersionSourceCode/WumpusGame/src/WumpusGame/buildTree.java | 75601b8b1706df1ae6d449d8b5c2b512b4c9eb20 | []
| no_license | kir-a11y/WumpusGame | https://github.com/kir-a11y/WumpusGame | 8b73ce5806a77b947dac72d23b526fcf1ca2be87 | e3749c41b6e31e15e9c3805b1affc40e89a24945 | refs/heads/master | 2023-01-19T01:55:53.212000 | 2020-11-28T06:07:50 | 2020-11-28T06:07:50 | 316,653,329 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package WumpusGame;
import java.util.ArrayList;
public class buildTree {
public void buildthreelayer(Board board){
buildTree(board);
ArrayList<Board>firstSetOfChildren=board.getChildren();
int i=0;
while(i<firstSetOfChildren.size()){
firstSetOfChildren.get(i).setIsRed(!firstSetOfChildren.get(i).getIsRed());
buildTree(firstSetOfChildren.get(i));
ArrayList<Board>secondSetOfChildren=firstSetOfChildren.get(i).getChildren();
int j=0;
while(j<secondSetOfChildren.size()){
buildTree(secondSetOfChildren.get(j));
j++;
}
i++;
}
}
public void buildTree(Board board) { //only going to build one layer
board.calculateValue();
int depth = 0;
//depth of the tree
int count = 0;
int[][] getredlocation = new int[board.getBoardLength()][2];
if (board.getIsRed()) {
int num = board.getBoardLength();
//finding all possible pieces
for (int i = 0; i < board.getBoardLength(); i++) {
for (int j = 0; j < board.getBoardLength(); j++) {
if (board.getPiece(i, j)!=null&&board.getPiece(i, j).getTeam() == 0) {
getredlocation[count][0] = i;
getredlocation[count][1] = j;
count++;
}
}
}
//get all possible next step
} else {
int num = board.getBoardLength();
//finding all possible pieces
for (int i = 0; i < board.getBoardLength(); i++) {
for (int j = 0; j < board.getBoardLength(); j++) {
if (board.getPiece(i, j)!=null&&board.getPiece(i, j).getTeam() == 1) {
getredlocation[count][0] = i;
getredlocation[count][1] = j;
count++;
}
}
}
}
for (int i = 0; i < count; i++) {
Board possiblechild = board.duplicate();
int x1 = getredlocation[i][0];
int y1 = getredlocation[i][1];
if (possiblechild.movePiece(x1, y1, x1, y1 - 1)) {
possiblechild.setFather(board);
possiblechild.calculateValue();
board.setChildren(possiblechild);
}
Board possiblechild2 = board.duplicate();
if (possiblechild2.movePiece(x1, y1, x1, y1 + 1)) {
possiblechild2.setFather(board);
possiblechild2.calculateValue();
board.setChildren(possiblechild2);
}
Board possiblechild3 = board.duplicate();
if (possiblechild3.movePiece(x1, y1, x1 - 1, y1)) {
possiblechild3.setFather(board);
possiblechild3.calculateValue();
board.setChildren(possiblechild3);
}
Board possiblechild4 = board.duplicate();
if (possiblechild4.movePiece(x1, y1, x1 + 1, y1)) {
possiblechild4.setFather(board);
possiblechild4.calculateValue();
board.setChildren(possiblechild4);
}
Board possiblechild5 = board.duplicate();
if (possiblechild5.movePiece(x1, y1, x1 - 1, y1 - 1)) {
possiblechild5.setFather(board);
possiblechild5.calculateValue();
board.setChildren(possiblechild5);
}
Board possiblechild6 = board.duplicate();
if (possiblechild6.movePiece(x1, y1, x1 - 1, y1 + 1)) {
possiblechild6.setFather(board);
possiblechild6.calculateValue();
board.setChildren(possiblechild6);
}
Board possiblechild7 = board.duplicate();
if (possiblechild7.movePiece(x1, y1, x1 + 1, y1 + 1)) {
possiblechild7.setFather(board);
possiblechild7.calculateValue();
board.setChildren(possiblechild7);
}
Board possiblechild8 = board.duplicate();
if (possiblechild8.movePiece(x1, y1, x1 + 1, y1 - 1)) {
possiblechild8.setFather(board);
possiblechild8.calculateValue();
board.setChildren(possiblechild8);
}
// board.setFather = null; // set up the original board
}
}
public static void main(String[] args){
Board board=new Board(1);
buildTree buildTree=new buildTree();
board.printBoard();
buildTree.buildthreelayer(board);
}
} | UTF-8 | Java | 4,735 | java | buildTree.java | Java | []
| null | []
| package WumpusGame;
import java.util.ArrayList;
public class buildTree {
public void buildthreelayer(Board board){
buildTree(board);
ArrayList<Board>firstSetOfChildren=board.getChildren();
int i=0;
while(i<firstSetOfChildren.size()){
firstSetOfChildren.get(i).setIsRed(!firstSetOfChildren.get(i).getIsRed());
buildTree(firstSetOfChildren.get(i));
ArrayList<Board>secondSetOfChildren=firstSetOfChildren.get(i).getChildren();
int j=0;
while(j<secondSetOfChildren.size()){
buildTree(secondSetOfChildren.get(j));
j++;
}
i++;
}
}
public void buildTree(Board board) { //only going to build one layer
board.calculateValue();
int depth = 0;
//depth of the tree
int count = 0;
int[][] getredlocation = new int[board.getBoardLength()][2];
if (board.getIsRed()) {
int num = board.getBoardLength();
//finding all possible pieces
for (int i = 0; i < board.getBoardLength(); i++) {
for (int j = 0; j < board.getBoardLength(); j++) {
if (board.getPiece(i, j)!=null&&board.getPiece(i, j).getTeam() == 0) {
getredlocation[count][0] = i;
getredlocation[count][1] = j;
count++;
}
}
}
//get all possible next step
} else {
int num = board.getBoardLength();
//finding all possible pieces
for (int i = 0; i < board.getBoardLength(); i++) {
for (int j = 0; j < board.getBoardLength(); j++) {
if (board.getPiece(i, j)!=null&&board.getPiece(i, j).getTeam() == 1) {
getredlocation[count][0] = i;
getredlocation[count][1] = j;
count++;
}
}
}
}
for (int i = 0; i < count; i++) {
Board possiblechild = board.duplicate();
int x1 = getredlocation[i][0];
int y1 = getredlocation[i][1];
if (possiblechild.movePiece(x1, y1, x1, y1 - 1)) {
possiblechild.setFather(board);
possiblechild.calculateValue();
board.setChildren(possiblechild);
}
Board possiblechild2 = board.duplicate();
if (possiblechild2.movePiece(x1, y1, x1, y1 + 1)) {
possiblechild2.setFather(board);
possiblechild2.calculateValue();
board.setChildren(possiblechild2);
}
Board possiblechild3 = board.duplicate();
if (possiblechild3.movePiece(x1, y1, x1 - 1, y1)) {
possiblechild3.setFather(board);
possiblechild3.calculateValue();
board.setChildren(possiblechild3);
}
Board possiblechild4 = board.duplicate();
if (possiblechild4.movePiece(x1, y1, x1 + 1, y1)) {
possiblechild4.setFather(board);
possiblechild4.calculateValue();
board.setChildren(possiblechild4);
}
Board possiblechild5 = board.duplicate();
if (possiblechild5.movePiece(x1, y1, x1 - 1, y1 - 1)) {
possiblechild5.setFather(board);
possiblechild5.calculateValue();
board.setChildren(possiblechild5);
}
Board possiblechild6 = board.duplicate();
if (possiblechild6.movePiece(x1, y1, x1 - 1, y1 + 1)) {
possiblechild6.setFather(board);
possiblechild6.calculateValue();
board.setChildren(possiblechild6);
}
Board possiblechild7 = board.duplicate();
if (possiblechild7.movePiece(x1, y1, x1 + 1, y1 + 1)) {
possiblechild7.setFather(board);
possiblechild7.calculateValue();
board.setChildren(possiblechild7);
}
Board possiblechild8 = board.duplicate();
if (possiblechild8.movePiece(x1, y1, x1 + 1, y1 - 1)) {
possiblechild8.setFather(board);
possiblechild8.calculateValue();
board.setChildren(possiblechild8);
}
// board.setFather = null; // set up the original board
}
}
public static void main(String[] args){
Board board=new Board(1);
buildTree buildTree=new buildTree();
board.printBoard();
buildTree.buildthreelayer(board);
}
} | 4,735 | 0.515523 | 0.494403 | 130 | 35.430771 | 23.697756 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.784615 | false | false | 3 |
a0c3c7bd099a32b12c46a9527abb82a267be8528 | 30,691,836,314,250 | aa0352c80caebf6d53c30e7b4f71f87a60810fe4 | /pixplorer-web/src/test/java/at/ac/uibk/sepm/pixplorer/rest/FoundTest.java | b523066864d58bbda31a70c87d86ada62944ceb0 | []
| no_license | cboehler/pixplorer | https://github.com/cboehler/pixplorer | 063280865f097e076683589eed4416e3a1596381 | e36080b513423490ce1ae22fe9a7e223b1115680 | refs/heads/master | 2021-01-02T09:53:45.252000 | 2015-06-15T12:25:42 | 2015-06-15T12:25:42 | 32,873,475 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package at.ac.uibk.sepm.pixplorer.rest;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import at.ac.uibk.sepm.pixplorer.db.PersistenceManager;
import at.ac.uibk.sepm.pixplorer.db.Place;
import at.ac.uibk.sepm.pixplorer.db.User;
import at.ac.uibk.sepm.pixplorer.rest.msg.AbstractReply;
import at.ac.uibk.sepm.pixplorer.rest.msg.AppInitReply;
import at.ac.uibk.sepm.pixplorer.rest.msg.AppInitRequest;
import at.ac.uibk.sepm.pixplorer.rest.msg.FoundReply;
import at.ac.uibk.sepm.pixplorer.rest.msg.FoundRequest;
import at.ac.uibk.sepm.pixplorer.rest.msg.ReplyException;
import com.google.gson.Gson;
public class FoundTest {
private static final Gson gson = new Gson();
@Test
public void testFound() {
AppInitRequest initRequest = new AppInitRequest();
initRequest.setGoogleId("max.mustermann@google.com");
initRequest.setOption(User.TYPE_LOCAL);
String json = gson.toJson(initRequest);
AppInit initCall = new AppInit();
String jsonReply = initCall.init(json);
AppInitReply initReply = gson.fromJson(jsonReply, AppInitReply.class);
FoundRequest request = new FoundRequest();
request.setGoogleId("max.mustermann@google.com");
Place p = initReply.getPlaces().get(0);
long oldCount = p.getCount();
request.setFoundPlace(p.getId());
request.setLatitude(p.getGpsData().getLatitude());
request.setLongitude(p.getGpsData().getLongitude());
json = gson.toJson(request);
Found call = new Found();
jsonReply = call.found(json);
FoundReply reply = gson.fromJson(jsonReply, FoundReply.class);
try {
reply.checkReturnCode();
Assert.assertFalse(reply.getPlaces().isEmpty());
// read place from db and check if count has been incremented
List<Place> places = PersistenceManager.get(Place.class, "where x.id = " + p.getId());
Assert.assertFalse(places.isEmpty());
Place newPlace = places.get(0);
Assert.assertEquals(oldCount + 1, newPlace.getCount());
} catch (ReplyException e) {
Assert.fail();
}
}
@Test
public void testFoundInvalidCoordinates() {
AppInitRequest initRequest = new AppInitRequest();
initRequest.setGoogleId("max.mustermann@google.com");
initRequest.setOption(User.TYPE_LOCAL);
String json = gson.toJson(initRequest);
AppInit initCall = new AppInit();
String jsonReply = initCall.init(json);
AppInitReply initReply = gson.fromJson(jsonReply, AppInitReply.class);
FoundRequest request = new FoundRequest();
request.setGoogleId("max.mustermann@google.com");
Place p = initReply.getPlaces().get(0);
request.setFoundPlace(p.getId());
request.setLatitude(-1.0d);
request.setLongitude(-2.0d);
json = gson.toJson(request);
Found call = new Found();
jsonReply = call.found(json);
FoundReply reply = gson.fromJson(jsonReply, FoundReply.class);
try {
reply.checkReturnCode();
Assert.fail();
} catch (ReplyException e) {
Assert.assertEquals(AbstractReply.RET_INVALUD_COORDINATES, reply.getReturnCode());
}
}
@Test
public void testInvalidPlace() {
FoundRequest request = new FoundRequest();
request.setGoogleId("max.mustermann@google.com");
request.setFoundPlace(-1);
String json = gson.toJson(request);
Found call = new Found();
String jsonReply = call.found(json);
FoundReply reply = gson.fromJson(jsonReply, FoundReply.class);
try {
reply.checkReturnCode();
Assert.fail();
} catch (ReplyException e) {
Assert.assertEquals(AbstractReply.RET_PLACE_NOT_FOUND, reply.getReturnCode());
}
}
@Test
public void testInvalidUser() {
FoundRequest request = new FoundRequest();
request.setGoogleId("invalid@google.com");
request.setFoundPlace(-1);
String json = gson.toJson(request);
Found call = new Found();
String jsonReply = call.found(json);
FoundReply reply = gson.fromJson(jsonReply, FoundReply.class);
try {
reply.checkReturnCode();
Assert.fail();
} catch (ReplyException e) {
Assert.assertEquals(AbstractReply.RET_USER_NOT_FOUND, reply.getReturnCode());
}
}
}
| UTF-8 | Java | 4,049 | java | FoundTest.java | Java | [
{
"context": " new AppInitRequest();\n\t\tinitRequest.setGoogleId(\"max.mustermann@google.com\");\n\t\tinitRequest.setOption(User.TYPE_LOCAL);\n\t\t\n\t",
"end": 837,
"score": 0.9999175667762756,
"start": 812,
"tag": "EMAIL",
"value": "max.mustermann@google.com"
},
{
"context": "uest = new FoundRequest();\n\t\trequest.setGoogleId(\"max.mustermann@google.com\");\n\t\t\n\t\tPlace p = initReply.getPlaces().get(0);\n\t",
"end": 1181,
"score": 0.9999164938926697,
"start": 1156,
"tag": "EMAIL",
"value": "max.mustermann@google.com"
},
{
"context": " new AppInitRequest();\n\t\tinitRequest.setGoogleId(\"max.mustermann@google.com\");\n\t\tinitRequest.setOption(User.TYPE_LOCAL);\n\t\t\n\t",
"end": 2176,
"score": 0.9999133348464966,
"start": 2151,
"tag": "EMAIL",
"value": "max.mustermann@google.com"
},
{
"context": "uest = new FoundRequest();\n\t\trequest.setGoogleId(\"max.mustermann@google.com\");\n\t\t\n\t\tPlace p = initReply.getPlaces().get(0);\n\t",
"end": 2520,
"score": 0.999913215637207,
"start": 2495,
"tag": "EMAIL",
"value": "max.mustermann@google.com"
},
{
"context": "uest = new FoundRequest();\n\t\trequest.setGoogleId(\"max.mustermann@google.com\");\n\t\trequest.setFoundPlace(-1);\n\t\t\n\t\tString json ",
"end": 3146,
"score": 0.9999193549156189,
"start": 3121,
"tag": "EMAIL",
"value": "max.mustermann@google.com"
},
{
"context": "uest = new FoundRequest();\n\t\trequest.setGoogleId(\"invalid@google.com\");\n\t\trequest.setFoundPlace(-1);\n\t\t\n\t\tString json ",
"end": 3661,
"score": 0.9999249577522278,
"start": 3643,
"tag": "EMAIL",
"value": "invalid@google.com"
}
]
| null | []
| package at.ac.uibk.sepm.pixplorer.rest;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import at.ac.uibk.sepm.pixplorer.db.PersistenceManager;
import at.ac.uibk.sepm.pixplorer.db.Place;
import at.ac.uibk.sepm.pixplorer.db.User;
import at.ac.uibk.sepm.pixplorer.rest.msg.AbstractReply;
import at.ac.uibk.sepm.pixplorer.rest.msg.AppInitReply;
import at.ac.uibk.sepm.pixplorer.rest.msg.AppInitRequest;
import at.ac.uibk.sepm.pixplorer.rest.msg.FoundReply;
import at.ac.uibk.sepm.pixplorer.rest.msg.FoundRequest;
import at.ac.uibk.sepm.pixplorer.rest.msg.ReplyException;
import com.google.gson.Gson;
public class FoundTest {
private static final Gson gson = new Gson();
@Test
public void testFound() {
AppInitRequest initRequest = new AppInitRequest();
initRequest.setGoogleId("<EMAIL>");
initRequest.setOption(User.TYPE_LOCAL);
String json = gson.toJson(initRequest);
AppInit initCall = new AppInit();
String jsonReply = initCall.init(json);
AppInitReply initReply = gson.fromJson(jsonReply, AppInitReply.class);
FoundRequest request = new FoundRequest();
request.setGoogleId("<EMAIL>");
Place p = initReply.getPlaces().get(0);
long oldCount = p.getCount();
request.setFoundPlace(p.getId());
request.setLatitude(p.getGpsData().getLatitude());
request.setLongitude(p.getGpsData().getLongitude());
json = gson.toJson(request);
Found call = new Found();
jsonReply = call.found(json);
FoundReply reply = gson.fromJson(jsonReply, FoundReply.class);
try {
reply.checkReturnCode();
Assert.assertFalse(reply.getPlaces().isEmpty());
// read place from db and check if count has been incremented
List<Place> places = PersistenceManager.get(Place.class, "where x.id = " + p.getId());
Assert.assertFalse(places.isEmpty());
Place newPlace = places.get(0);
Assert.assertEquals(oldCount + 1, newPlace.getCount());
} catch (ReplyException e) {
Assert.fail();
}
}
@Test
public void testFoundInvalidCoordinates() {
AppInitRequest initRequest = new AppInitRequest();
initRequest.setGoogleId("<EMAIL>");
initRequest.setOption(User.TYPE_LOCAL);
String json = gson.toJson(initRequest);
AppInit initCall = new AppInit();
String jsonReply = initCall.init(json);
AppInitReply initReply = gson.fromJson(jsonReply, AppInitReply.class);
FoundRequest request = new FoundRequest();
request.setGoogleId("<EMAIL>");
Place p = initReply.getPlaces().get(0);
request.setFoundPlace(p.getId());
request.setLatitude(-1.0d);
request.setLongitude(-2.0d);
json = gson.toJson(request);
Found call = new Found();
jsonReply = call.found(json);
FoundReply reply = gson.fromJson(jsonReply, FoundReply.class);
try {
reply.checkReturnCode();
Assert.fail();
} catch (ReplyException e) {
Assert.assertEquals(AbstractReply.RET_INVALUD_COORDINATES, reply.getReturnCode());
}
}
@Test
public void testInvalidPlace() {
FoundRequest request = new FoundRequest();
request.setGoogleId("<EMAIL>");
request.setFoundPlace(-1);
String json = gson.toJson(request);
Found call = new Found();
String jsonReply = call.found(json);
FoundReply reply = gson.fromJson(jsonReply, FoundReply.class);
try {
reply.checkReturnCode();
Assert.fail();
} catch (ReplyException e) {
Assert.assertEquals(AbstractReply.RET_PLACE_NOT_FOUND, reply.getReturnCode());
}
}
@Test
public void testInvalidUser() {
FoundRequest request = new FoundRequest();
request.setGoogleId("<EMAIL>");
request.setFoundPlace(-1);
String json = gson.toJson(request);
Found call = new Found();
String jsonReply = call.found(json);
FoundReply reply = gson.fromJson(jsonReply, FoundReply.class);
try {
reply.checkReturnCode();
Assert.fail();
} catch (ReplyException e) {
Assert.assertEquals(AbstractReply.RET_USER_NOT_FOUND, reply.getReturnCode());
}
}
}
| 3,948 | 0.720425 | 0.717955 | 142 | 27.514084 | 22.848162 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.359155 | false | false | 3 |
63112932800e4fafbe7bd12d9fffbd648589d65b | 14,525,579,415,769 | 607aa9fe8b56019d35299e3915e2bb505dea8203 | /src/main/java/com/yanghui/auth/biz/service/impl/RoleServiceImpl.java | 91b108a375cbbaeee56d0008d9fd4c8b1420d3bd | []
| no_license | yanghuijava/video | https://github.com/yanghuijava/video | d30c89f05193fc104e5626ea75d6ac0c06f85f50 | ee1550b5bb0583fc47260a8f7da9b3c24633a182 | refs/heads/master | 2016-08-08T20:01:20.808000 | 2015-09-25T09:24:52 | 2015-09-25T09:24:52 | 43,104,047 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yanghui.auth.biz.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yanghui.auth.biz.model.Role;
import com.yanghui.auth.biz.model.RoleResource;
import com.yanghui.auth.biz.service.RoleService;
import com.yanghui.auth.integration.dao.RoleMapper;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Override
public List<Role> query(Map<String, Object> param) {
return this.roleMapper.getAll(param);
}
@Override
public int save(Role role) {
if(role == null) {
return 0;
}
if(role.getId() == null){
Map<String, Object> param = new HashMap<String, Object>();
param.put("name", role.getName());
List<Role> findRoleList = this.roleMapper.getAll(param);
if(findRoleList != null && findRoleList.size() > 0){
throw new RuntimeException("角色名称不能重复!");
}
param.clear();
param.put("code", role.getCode());
findRoleList = this.roleMapper.getAll(param);
if(findRoleList != null && findRoleList.size() > 0){
throw new RuntimeException("角色编码不能重复!");
}
return this.roleMapper.insert(role);
}else {
role.setCode(null);
return this.roleMapper.update(role);
}
}
@Override
public int delete(int id) {
return this.roleMapper.delete(id);
}
@Override
public Role queryById(int id) {
return this.roleMapper.selectByKey(id);
}
@Override
@Transactional(rollbackFor=Exception.class)
public void saveRoleResource(Integer roleId, String resIds) throws Exception{
if(roleId != null){
this.roleMapper.deleteRoleResource(roleId);
if(resIds != null) {
String[] resIdArr = resIds.split(",");
this.roleMapper.deleteRoleResource(roleId);
for(String resId : resIdArr){
if(Integer.valueOf(resId) == 0) {
continue;
}
RoleResource rr = new RoleResource();
rr.setRoleId(roleId);
rr.setResId(Integer.valueOf(resId));
this.roleMapper.insertRoleResource(rr);
}
}
}else {
throw new RuntimeException("角色ID不能为空!");
}
}
}
| UTF-8 | Java | 2,273 | java | RoleServiceImpl.java | Java | []
| null | []
| package com.yanghui.auth.biz.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yanghui.auth.biz.model.Role;
import com.yanghui.auth.biz.model.RoleResource;
import com.yanghui.auth.biz.service.RoleService;
import com.yanghui.auth.integration.dao.RoleMapper;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Override
public List<Role> query(Map<String, Object> param) {
return this.roleMapper.getAll(param);
}
@Override
public int save(Role role) {
if(role == null) {
return 0;
}
if(role.getId() == null){
Map<String, Object> param = new HashMap<String, Object>();
param.put("name", role.getName());
List<Role> findRoleList = this.roleMapper.getAll(param);
if(findRoleList != null && findRoleList.size() > 0){
throw new RuntimeException("角色名称不能重复!");
}
param.clear();
param.put("code", role.getCode());
findRoleList = this.roleMapper.getAll(param);
if(findRoleList != null && findRoleList.size() > 0){
throw new RuntimeException("角色编码不能重复!");
}
return this.roleMapper.insert(role);
}else {
role.setCode(null);
return this.roleMapper.update(role);
}
}
@Override
public int delete(int id) {
return this.roleMapper.delete(id);
}
@Override
public Role queryById(int id) {
return this.roleMapper.selectByKey(id);
}
@Override
@Transactional(rollbackFor=Exception.class)
public void saveRoleResource(Integer roleId, String resIds) throws Exception{
if(roleId != null){
this.roleMapper.deleteRoleResource(roleId);
if(resIds != null) {
String[] resIdArr = resIds.split(",");
this.roleMapper.deleteRoleResource(roleId);
for(String resId : resIdArr){
if(Integer.valueOf(resId) == 0) {
continue;
}
RoleResource rr = new RoleResource();
rr.setRoleId(roleId);
rr.setResId(Integer.valueOf(resId));
this.roleMapper.insertRoleResource(rr);
}
}
}else {
throw new RuntimeException("角色ID不能为空!");
}
}
}
| 2,273 | 0.710301 | 0.708502 | 84 | 25.464285 | 20.489513 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.357143 | false | false | 3 |
fd9334158b0834b8b7cb64f8a10ed8de79d12dfd | 12,824,772,364,797 | 8b8ea960d643b0290b67921aba989ae0a29747a6 | /src/test/java/com/m3u8/basetool/GetSegList.java | a80bc58fb532052163e054922bfcae7da391ee13 | []
| no_license | Siiyoung/M3U8 | https://github.com/Siiyoung/M3U8 | b348facbe09b1f31975510958f721ed1629abb36 | 242fed7ac753b5facdeec240bc2d8c2196e27fb4 | refs/heads/master | 2021-01-10T15:39:29.592000 | 2016-03-29T10:42:43 | 2016-03-29T10:42:43 | 54,106,857 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.m3u8.basetool;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GetSegList {
String url="http://pl.youku.com/playlist/m3u8?vid=373787369&type=mp4&ts=1458296769&keyframe=0&ep=cyaREkuEUMkG7CvagT8bZCqzdCJeXP0N9RiNhtFkCdQkQey2&sid=14582967698591236a0ea&token=0949&ctype=12&ev=1&oip=3702858343";
//String url = "http://pl.youku.com/playlist/m3u8?vid=21324343243543543534&ts=1458891649&ep=cSaREkGEV8gE5yrcjT8bZC3qJ3NdXP0M8xeDhtJjALgjT%2By8nD%2FUxZ62SfxLHv4RciEAGeLwq9nmaEMTePdGq2kP3SGpPuXp&sid=345889164293512318c4b&token=1729&ctype=12&ev=1&oip=3702858339";
getResponse getResponse = new getResponse();
/**
* 验证各标签唯一性
* @throws Exception
* */
public boolean isonlyvalue() throws Exception{
String response = getResponse.getResponseByGet(url);
String M3u="#EXTM3U";//标识播放列表文件扩展名的格式
String MAXtime="#EXT-X-TARGETDURATION";//指定媒体段文件最大持续的时间
String VERSION="#EXT-X-VERSION";//指定播放列表兼容性版本。相关的媒体文件和服务器都必须全部支持该标签指定的版本。
String M3uEND="#EXT-X-ENDLIST";//该标签指示其后没有媒体文件段了
int n=0;
String s="";
List<Integer> list=new ArrayList<Integer>();
String [] sts={"#EXTM3U","#EXT-X-TARGETDURATION","#EXT-X-VERSION","#EXT-X-ENDLIST"};
List<Integer> t_m3u=new ArrayList<Integer>();
List<Integer> t_max=new ArrayList<Integer>();
List<Integer> t_ver=new ArrayList<Integer>();
List<Integer> t_mend=new ArrayList<Integer>();
GetSegList l=new GetSegList();
t_m3u=l.getindexof(response, M3u);
t_max=l.getindexof(response, MAXtime);
t_ver=l.getindexof(response, VERSION);
t_mend=l.getindexof(response, M3uEND);
list.add(t_m3u.size());
list.add(t_max.size());
list.add(t_ver.size());
list.add(t_mend.size());
for(int m=0;m<list.size();m++){
int num=list.get(m);
if(num==1){
n++;
//s=s+sts[m]+"标签正常\r\n";
}
else{
s=s+sts[m]+"参数数量异常,为"+num+"个,请检查!"+"\r\n";
}
}
if(n==4){
s=s+M3u+","+MAXtime+","+VERSION+","+M3uEND+"标签唯一性验证通过。";
System.out.println(s);
return true;
}
else{
s=s+"有错误!";
System.out.println(s);
throw new IOException(s+"有错误!");
}
}
/**
* 获取playservice的时长
* aim取值从:flvhd,mp4hd,mp4hd2中选取,标、高、超
* 目前不支持mp4hd3 1080p格式
* @throws Exception
* */
public List<Double> GetPstime() throws Exception{
GetSegList gsl = new GetSegList();
String definition = gsl.getDefinition();//获取视频清晰度
int vnum;
String vid="";
vnum = url.indexOf("vid=");
if(vnum == -1){
vnum = url.indexOf("%22v%22");
if(vnum == -1){
//return
throw new IOException("URL参数有问题,缺失vid参数!");
}
int n = url.indexOf("_", vnum);
vid = url.substring(vnum+11, n);
}
else{
int n = url.indexOf("&", vnum);
vid = url.substring(vnum+4, n);
}
String v =vid.toString();
String psurl = "http://play.youku.com/play/get.json?vid="+v+"&ct=10&ran=7106";
String response = Httpunit.getResponseByGet(psurl);
//String response = (String) getResponse.getResponseByGet(psurl);
GetSegList l=new GetSegList();
List<Double> result = new ArrayList<Double>();
String mvideo = "total_milliseconds_video\":\"";
List<String> time = new ArrayList<String>();//各分片时长
List<Integer> liststream = new ArrayList<Integer>();//各清晰度所在位置
List<Integer> listaim = new ArrayList<Integer>();//获取目标清晰度各分片位置
String aimstr = "";//获取目标清晰度的seg内容
int aimpos = response.indexOf(definition)-14;//获取目标清晰度stream_type节点所在位置
liststream = l.getindexof(response, "stream_type");
for(int n=0;n<liststream.size();n++){
if(liststream.get(n)==aimpos){
if(n==0)
aimstr = response.substring(0,liststream.get(n));
else
aimstr = response.substring(liststream.get(n-1), liststream.get(n));
}
}
if(aimstr.equals(""))
result.add((double) 0);//-1代表未找到该格式
else{
listaim = l.getindexof(aimstr, mvideo);
for(int n:listaim){
int m = n+mvideo.length();
int i=0;
while(i<aimstr.length()){
if(aimstr.charAt(m+i)!='\"'){
i++;
}
else{
time.add(aimstr.substring(m,m+i));
i=0;
break;
}
}
}
}
double d = 0;
double count = 0;
for(String s:time){
d=Double.valueOf(s).doubleValue()/1000;
BigDecimal big = new BigDecimal(d);
count = big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
result.add(count);
d = 0;
}
return result;
}
/**
* 获取m3u8视频流时长
* @throws Exception
* */
public List<Double> Getm3u8Time() throws Exception{
GetSegList gid=new GetSegList();
String response = getResponse.getResponseByGet(url+"&ykss=faacf356010c2b5c133c029a");
List<Integer> L_EXD=new ArrayList<Integer>();//EXT-X-DISCONTINUITY参数位置链表
L_EXD=gid.getindexof(response,"#EXT-X-DISCONTINUITY");
double doubl=0;//ts流实际时长
double doublm=0;//ts分片情况下总时长
List<Double> result = new ArrayList<Double>();
int size=L_EXD.size();//#EXT-X-DISCONTINUITY标签个数
/**
* 获取ts时长*/
/*1没有分片*/
if(size==0){
doublm = gid.gettsendtime(response);
BigDecimal big = new BigDecimal(doublm);
double count = big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
result.add(count);
}
/*1有分片*/
else{
int i=0;
for(int n=0;n<=size;n++){
String rsps1="";
if(n!=size){
rsps1=response.substring(i,L_EXD.get(n));//第n分片字符串
i=L_EXD.get(n);
}
else{
rsps1=response.substring(i);
}
doubl=gid.gettsendtime(rsps1);
BigDecimal big = new BigDecimal(doubl);
double count = big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
result.add(count);
}
/*判断是否有广告*/
int nu=gid.getAdnum();
if(nu!=0){
for(int n=0;n<nu;n++){
result.remove(0);//移除广告部分
}
}
}
return result;
}
/**
* 获取视频清晰度
* @throws Exception
* */
public String getDefinition() throws Exception{
String response = getResponse.getResponseByGet(url);
String result= "";
GetSegList g=new GetSegList();
List<Integer> l1 = new ArrayList<Integer>();
List<Integer> l2 = new ArrayList<Integer>();
l1=g.getindexof(response, "http://");
l2=g.getindexof(response, "ts_start");
if(l1.size()!=l2.size()||l1.size()==0||l2.size()==0)
return "error";
//throw new IOException("TS流信息出现异常!"+"ts流数量为:"+l1.size());
else{
int n=l1.size()-1;
String str=response.substring(l1.get(n), l2.get(n));
String [] st = str.split("/");
String sd = st[st.length-1];
String s = sd.substring(2,6);
if(s.equals("0001"))
result="mp4hd2";
if(s.equals("0002"))
result="flvhd";
if(s.equals("0008"))
result="mp4hd";
else
result="error";
}
return result;
}
/**
* 获取广告个数
* */
public Integer getAdnum() throws Exception{
GetSegList g = new GetSegList();
List<Integer> l=new ArrayList<Integer>();
for(int n=1;n<8;n++){
String str = "%22a"+n+"%22";
l=g.getindexof(url, str);
}
return l.size();
}
/**
* 获取去广告后的数据
* @throws Exception
* */
public String getDeteAdInfo() throws Exception{
GetSegList g = new GetSegList();
String response = getResponse.getResponseByGet(url);
int adnum = g.getAdnum();
if(adnum==0)
return response;
else{
List<Integer> l = g.getindexof(response, "#EXT-X-DISCONTINUITY");
int n = l.get(adnum-1);
return response.substring(n);
}
}
/**
* 获取最后一个ts_end的值
* @throws Exception
* */
public double gettsendtime(String st) throws Exception{
//String response = getResponse.getResponseByGet(url);
double d;
String s;
GetSegList get=new GetSegList();
// String [] resp = get.geteveryurl();
// String str = resp[resp.length-1];
List<String> l=get.getvalue(st,"ts_end=", "&ts_seg_no=");
if(l.size()==0){
return 0;
}
s=l.get(l.size()-1);
d=Double.valueOf(s).doubleValue();
return d;
}
/**
* 从str中获取str2的值,str3为目标值之后的字符串
* @throws Exception
* */
public List<String> getvalue(String str,String str2,String str3) throws Exception {
List<Integer> ts1=new ArrayList<Integer>();
List<Integer> ts2=new ArrayList<Integer>();
List<String> value=new ArrayList<String>();
int m=str2.length();
GetSegList l=new GetSegList();
ts1=l.getindexof(str, str2);
ts2=l.getindexof(str, str3);
for(int n=0;n<ts1.size();n++){
int n1=ts1.get(n);
int n2=ts2.get(n);
value.add(str.substring(n1+m, n2));
}
return value;
}
/**
* 获取各分片的单独返回链表
* @throws Exception
* */
public String[] geteveryurl() throws Exception{
GetSegList get=new GetSegList();
String response = get.getDeteAdInfo();
return response.split("#EXT-X-DISCONTINUITY");
}
public List<Integer> getindexof(String rep,String aim){
List<Integer> list=new ArrayList<Integer>();
int m=0;
for(int n=0;n<=(rep.length()-aim.length());n++){
while(m<aim.length()){
if(rep.charAt(n+m)!=aim.charAt(m))
break;
m++;
}
if(m==aim.length()){
list.add(n);
m=0;
}
}
return list;
}
public void checkResponse() throws Exception{
String response = getResponse.getResponseByGet(url);
String respCode = getResponse.getResponseByGet(url);
if((response!=null)&(respCode=="200")){
System.out.println("接口请求成功!");
}
}
public List<String> solveTs_Seg_No(String[] strs){ //正则匹配ts_seg_no=: 获取其值
Pattern pattern=Pattern.compile("(?<=ts_seg_no=)\\d+");
List<String> results=new ArrayList<String>();
for(String segList:strs){
Matcher matcher=pattern.matcher(segList);
if(matcher.find()){
results.add(matcher.group());
}
}
return results;
}
public List<String> solveDuration(String[] strs){ //正则匹配EXT-X-TARGETDURATION: 获取其值
Pattern pattern=Pattern.compile("(?<=EXT-X-TARGETDURATION:)(\\-|\\+?)\\d+");
List<String> results=new ArrayList<String>();
for(String segList:strs){
Matcher matcher=pattern.matcher(segList);
if(matcher.find()){
results.add(matcher.group());
}
}
return results;
}
public List<String> solveExtinf(String[] strs) throws IOException{ //正则匹配EXTINF: 获取其值
Pattern pattern=Pattern.compile("(?<=EXTINF:)[\\d\\.]+");
List<String> results=new ArrayList<String>();
int i = 0;
for(String segList:strs){
Matcher matcher=pattern.matcher(segList);
if(matcher.find()){
results.add(matcher.group());
i++;
}
}
System.out.println("#EXTINF的数目:"+i+"#EXTINF的集合是:"+results);
return results;
}
public List<String> solveExtVersion(String[] strs){ //正则匹配#EXT-X-TARGETDURATION: 获取其值
Pattern pattern=Pattern.compile("(?<=EXT-X-VERSION:)\\d+");
List<String> results=new ArrayList<String>();
for(String segList:strs){
Matcher matcher=pattern.matcher(segList);
if(matcher.find()){
results.add(matcher.group());
}
}
return results;
}
public ArrayList<String> getExtDuration() throws Exception{ //获取duration的值
String response = getResponse.getResponseByGet(url);
ArrayList<String> extVersion = new ArrayList<String>();
String[] resp = response.split("\n");
List<String> strs=solveDuration(resp);
for(String s:strs){
extVersion.add(s);
//System.out.print(s+",");
}
return extVersion;
}
public ArrayList<Integer> getSegNoList() throws Exception{ // 获取ts_seg_no
String response = getResponse.getResponseByGet(url);
ArrayList<Integer> segNoList = new ArrayList<Integer>();
String[] resp = response.split("\n");
List<String> strs=solveTs_Seg_No(resp);
int i = 0;
for(String s:strs){
segNoList.add(Integer.parseInt(s));
i++;
//System.out.print(s+",");
}
System.out.println("ts_sg_no标签数目有:"+i+"ts_seg_no标签的所有的值是:"+segNoList);
return segNoList;
}
public ArrayList<String> getExtinf() throws Exception{ //获取extinf的值
String response = getResponse.getResponseByGet(url);
ArrayList<String> extinf = new ArrayList<String>();
String[] resp = response.split("\n");
List<String> strs=solveExtinf(resp);
for(String s:strs){
extinf.add(s);
//extinf.add(new BigDecimal(s).setScale(3,BigDecimal.ROUND_DOWN));
//System.out.print(s+",");
}
return extinf;
}
public ArrayList<String> getExtVersion() throws Exception{
String response = getResponse.getResponseByGet(url);
ArrayList<String> extVersion = new ArrayList<String>();
String[] resp = response.split("\n");
List<String> strs=solveExtVersion(resp);
for(String s:strs){
extVersion.add(s);
}
return extVersion;
}
}
| UTF-8 | Java | 13,992 | java | GetSegList.java | Java | [
{
"context": "N9RiNhtFkCdQkQey2&sid=14582967698591236a0ea&token=0949&ctype=12&ev=1&oip=3702858343\";\r\n\t//String url = \"",
"end": 422,
"score": 0.9915534257888794,
"start": 418,
"tag": "PASSWORD",
"value": "0949"
},
{
"context": "TePdGq2kP3SGpPuXp&sid=345889164293512318c4b&token=1729&ctype=12&ev=1&oip=3702858339\";\r\n\r\n getResponse",
"end": 685,
"score": 0.9912635087966919,
"start": 681,
"tag": "PASSWORD",
"value": "1729"
}
]
| null | []
| package com.m3u8.basetool;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GetSegList {
String url="http://pl.youku.com/playlist/m3u8?vid=373787369&type=mp4&ts=1458296769&keyframe=0&ep=cyaREkuEUMkG7CvagT8bZCqzdCJeXP0N9RiNhtFkCdQkQey2&sid=14582967698591236a0ea&token=<PASSWORD>&ctype=12&ev=1&oip=3702858343";
//String url = "http://pl.youku.com/playlist/m3u8?vid=21324343243543543534&ts=1458891649&ep=cSaREkGEV8gE5yrcjT8bZC3qJ3NdXP0M8xeDhtJjALgjT%2By8nD%2FUxZ62SfxLHv4RciEAGeLwq9nmaEMTePdGq2kP3SGpPuXp&sid=345889164293512318c4b&token=<PASSWORD>&ctype=12&ev=1&oip=3702858339";
getResponse getResponse = new getResponse();
/**
* 验证各标签唯一性
* @throws Exception
* */
public boolean isonlyvalue() throws Exception{
String response = getResponse.getResponseByGet(url);
String M3u="#EXTM3U";//标识播放列表文件扩展名的格式
String MAXtime="#EXT-X-TARGETDURATION";//指定媒体段文件最大持续的时间
String VERSION="#EXT-X-VERSION";//指定播放列表兼容性版本。相关的媒体文件和服务器都必须全部支持该标签指定的版本。
String M3uEND="#EXT-X-ENDLIST";//该标签指示其后没有媒体文件段了
int n=0;
String s="";
List<Integer> list=new ArrayList<Integer>();
String [] sts={"#EXTM3U","#EXT-X-TARGETDURATION","#EXT-X-VERSION","#EXT-X-ENDLIST"};
List<Integer> t_m3u=new ArrayList<Integer>();
List<Integer> t_max=new ArrayList<Integer>();
List<Integer> t_ver=new ArrayList<Integer>();
List<Integer> t_mend=new ArrayList<Integer>();
GetSegList l=new GetSegList();
t_m3u=l.getindexof(response, M3u);
t_max=l.getindexof(response, MAXtime);
t_ver=l.getindexof(response, VERSION);
t_mend=l.getindexof(response, M3uEND);
list.add(t_m3u.size());
list.add(t_max.size());
list.add(t_ver.size());
list.add(t_mend.size());
for(int m=0;m<list.size();m++){
int num=list.get(m);
if(num==1){
n++;
//s=s+sts[m]+"标签正常\r\n";
}
else{
s=s+sts[m]+"参数数量异常,为"+num+"个,请检查!"+"\r\n";
}
}
if(n==4){
s=s+M3u+","+MAXtime+","+VERSION+","+M3uEND+"标签唯一性验证通过。";
System.out.println(s);
return true;
}
else{
s=s+"有错误!";
System.out.println(s);
throw new IOException(s+"有错误!");
}
}
/**
* 获取playservice的时长
* aim取值从:flvhd,mp4hd,mp4hd2中选取,标、高、超
* 目前不支持mp4hd3 1080p格式
* @throws Exception
* */
public List<Double> GetPstime() throws Exception{
GetSegList gsl = new GetSegList();
String definition = gsl.getDefinition();//获取视频清晰度
int vnum;
String vid="";
vnum = url.indexOf("vid=");
if(vnum == -1){
vnum = url.indexOf("%22v%22");
if(vnum == -1){
//return
throw new IOException("URL参数有问题,缺失vid参数!");
}
int n = url.indexOf("_", vnum);
vid = url.substring(vnum+11, n);
}
else{
int n = url.indexOf("&", vnum);
vid = url.substring(vnum+4, n);
}
String v =vid.toString();
String psurl = "http://play.youku.com/play/get.json?vid="+v+"&ct=10&ran=7106";
String response = Httpunit.getResponseByGet(psurl);
//String response = (String) getResponse.getResponseByGet(psurl);
GetSegList l=new GetSegList();
List<Double> result = new ArrayList<Double>();
String mvideo = "total_milliseconds_video\":\"";
List<String> time = new ArrayList<String>();//各分片时长
List<Integer> liststream = new ArrayList<Integer>();//各清晰度所在位置
List<Integer> listaim = new ArrayList<Integer>();//获取目标清晰度各分片位置
String aimstr = "";//获取目标清晰度的seg内容
int aimpos = response.indexOf(definition)-14;//获取目标清晰度stream_type节点所在位置
liststream = l.getindexof(response, "stream_type");
for(int n=0;n<liststream.size();n++){
if(liststream.get(n)==aimpos){
if(n==0)
aimstr = response.substring(0,liststream.get(n));
else
aimstr = response.substring(liststream.get(n-1), liststream.get(n));
}
}
if(aimstr.equals(""))
result.add((double) 0);//-1代表未找到该格式
else{
listaim = l.getindexof(aimstr, mvideo);
for(int n:listaim){
int m = n+mvideo.length();
int i=0;
while(i<aimstr.length()){
if(aimstr.charAt(m+i)!='\"'){
i++;
}
else{
time.add(aimstr.substring(m,m+i));
i=0;
break;
}
}
}
}
double d = 0;
double count = 0;
for(String s:time){
d=Double.valueOf(s).doubleValue()/1000;
BigDecimal big = new BigDecimal(d);
count = big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
result.add(count);
d = 0;
}
return result;
}
/**
* 获取m3u8视频流时长
* @throws Exception
* */
public List<Double> Getm3u8Time() throws Exception{
GetSegList gid=new GetSegList();
String response = getResponse.getResponseByGet(url+"&ykss=faacf356010c2b5c133c029a");
List<Integer> L_EXD=new ArrayList<Integer>();//EXT-X-DISCONTINUITY参数位置链表
L_EXD=gid.getindexof(response,"#EXT-X-DISCONTINUITY");
double doubl=0;//ts流实际时长
double doublm=0;//ts分片情况下总时长
List<Double> result = new ArrayList<Double>();
int size=L_EXD.size();//#EXT-X-DISCONTINUITY标签个数
/**
* 获取ts时长*/
/*1没有分片*/
if(size==0){
doublm = gid.gettsendtime(response);
BigDecimal big = new BigDecimal(doublm);
double count = big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
result.add(count);
}
/*1有分片*/
else{
int i=0;
for(int n=0;n<=size;n++){
String rsps1="";
if(n!=size){
rsps1=response.substring(i,L_EXD.get(n));//第n分片字符串
i=L_EXD.get(n);
}
else{
rsps1=response.substring(i);
}
doubl=gid.gettsendtime(rsps1);
BigDecimal big = new BigDecimal(doubl);
double count = big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
result.add(count);
}
/*判断是否有广告*/
int nu=gid.getAdnum();
if(nu!=0){
for(int n=0;n<nu;n++){
result.remove(0);//移除广告部分
}
}
}
return result;
}
/**
* 获取视频清晰度
* @throws Exception
* */
public String getDefinition() throws Exception{
String response = getResponse.getResponseByGet(url);
String result= "";
GetSegList g=new GetSegList();
List<Integer> l1 = new ArrayList<Integer>();
List<Integer> l2 = new ArrayList<Integer>();
l1=g.getindexof(response, "http://");
l2=g.getindexof(response, "ts_start");
if(l1.size()!=l2.size()||l1.size()==0||l2.size()==0)
return "error";
//throw new IOException("TS流信息出现异常!"+"ts流数量为:"+l1.size());
else{
int n=l1.size()-1;
String str=response.substring(l1.get(n), l2.get(n));
String [] st = str.split("/");
String sd = st[st.length-1];
String s = sd.substring(2,6);
if(s.equals("0001"))
result="mp4hd2";
if(s.equals("0002"))
result="flvhd";
if(s.equals("0008"))
result="mp4hd";
else
result="error";
}
return result;
}
/**
* 获取广告个数
* */
public Integer getAdnum() throws Exception{
GetSegList g = new GetSegList();
List<Integer> l=new ArrayList<Integer>();
for(int n=1;n<8;n++){
String str = "%22a"+n+"%22";
l=g.getindexof(url, str);
}
return l.size();
}
/**
* 获取去广告后的数据
* @throws Exception
* */
public String getDeteAdInfo() throws Exception{
GetSegList g = new GetSegList();
String response = getResponse.getResponseByGet(url);
int adnum = g.getAdnum();
if(adnum==0)
return response;
else{
List<Integer> l = g.getindexof(response, "#EXT-X-DISCONTINUITY");
int n = l.get(adnum-1);
return response.substring(n);
}
}
/**
* 获取最后一个ts_end的值
* @throws Exception
* */
public double gettsendtime(String st) throws Exception{
//String response = getResponse.getResponseByGet(url);
double d;
String s;
GetSegList get=new GetSegList();
// String [] resp = get.geteveryurl();
// String str = resp[resp.length-1];
List<String> l=get.getvalue(st,"ts_end=", "&ts_seg_no=");
if(l.size()==0){
return 0;
}
s=l.get(l.size()-1);
d=Double.valueOf(s).doubleValue();
return d;
}
/**
* 从str中获取str2的值,str3为目标值之后的字符串
* @throws Exception
* */
public List<String> getvalue(String str,String str2,String str3) throws Exception {
List<Integer> ts1=new ArrayList<Integer>();
List<Integer> ts2=new ArrayList<Integer>();
List<String> value=new ArrayList<String>();
int m=str2.length();
GetSegList l=new GetSegList();
ts1=l.getindexof(str, str2);
ts2=l.getindexof(str, str3);
for(int n=0;n<ts1.size();n++){
int n1=ts1.get(n);
int n2=ts2.get(n);
value.add(str.substring(n1+m, n2));
}
return value;
}
/**
* 获取各分片的单独返回链表
* @throws Exception
* */
public String[] geteveryurl() throws Exception{
GetSegList get=new GetSegList();
String response = get.getDeteAdInfo();
return response.split("#EXT-X-DISCONTINUITY");
}
public List<Integer> getindexof(String rep,String aim){
List<Integer> list=new ArrayList<Integer>();
int m=0;
for(int n=0;n<=(rep.length()-aim.length());n++){
while(m<aim.length()){
if(rep.charAt(n+m)!=aim.charAt(m))
break;
m++;
}
if(m==aim.length()){
list.add(n);
m=0;
}
}
return list;
}
public void checkResponse() throws Exception{
String response = getResponse.getResponseByGet(url);
String respCode = getResponse.getResponseByGet(url);
if((response!=null)&(respCode=="200")){
System.out.println("接口请求成功!");
}
}
public List<String> solveTs_Seg_No(String[] strs){ //正则匹配ts_seg_no=: 获取其值
Pattern pattern=Pattern.compile("(?<=ts_seg_no=)\\d+");
List<String> results=new ArrayList<String>();
for(String segList:strs){
Matcher matcher=pattern.matcher(segList);
if(matcher.find()){
results.add(matcher.group());
}
}
return results;
}
public List<String> solveDuration(String[] strs){ //正则匹配EXT-X-TARGETDURATION: 获取其值
Pattern pattern=Pattern.compile("(?<=EXT-X-TARGETDURATION:)(\\-|\\+?)\\d+");
List<String> results=new ArrayList<String>();
for(String segList:strs){
Matcher matcher=pattern.matcher(segList);
if(matcher.find()){
results.add(matcher.group());
}
}
return results;
}
public List<String> solveExtinf(String[] strs) throws IOException{ //正则匹配EXTINF: 获取其值
Pattern pattern=Pattern.compile("(?<=EXTINF:)[\\d\\.]+");
List<String> results=new ArrayList<String>();
int i = 0;
for(String segList:strs){
Matcher matcher=pattern.matcher(segList);
if(matcher.find()){
results.add(matcher.group());
i++;
}
}
System.out.println("#EXTINF的数目:"+i+"#EXTINF的集合是:"+results);
return results;
}
public List<String> solveExtVersion(String[] strs){ //正则匹配#EXT-X-TARGETDURATION: 获取其值
Pattern pattern=Pattern.compile("(?<=EXT-X-VERSION:)\\d+");
List<String> results=new ArrayList<String>();
for(String segList:strs){
Matcher matcher=pattern.matcher(segList);
if(matcher.find()){
results.add(matcher.group());
}
}
return results;
}
public ArrayList<String> getExtDuration() throws Exception{ //获取duration的值
String response = getResponse.getResponseByGet(url);
ArrayList<String> extVersion = new ArrayList<String>();
String[] resp = response.split("\n");
List<String> strs=solveDuration(resp);
for(String s:strs){
extVersion.add(s);
//System.out.print(s+",");
}
return extVersion;
}
public ArrayList<Integer> getSegNoList() throws Exception{ // 获取ts_seg_no
String response = getResponse.getResponseByGet(url);
ArrayList<Integer> segNoList = new ArrayList<Integer>();
String[] resp = response.split("\n");
List<String> strs=solveTs_Seg_No(resp);
int i = 0;
for(String s:strs){
segNoList.add(Integer.parseInt(s));
i++;
//System.out.print(s+",");
}
System.out.println("ts_sg_no标签数目有:"+i+"ts_seg_no标签的所有的值是:"+segNoList);
return segNoList;
}
public ArrayList<String> getExtinf() throws Exception{ //获取extinf的值
String response = getResponse.getResponseByGet(url);
ArrayList<String> extinf = new ArrayList<String>();
String[] resp = response.split("\n");
List<String> strs=solveExtinf(resp);
for(String s:strs){
extinf.add(s);
//extinf.add(new BigDecimal(s).setScale(3,BigDecimal.ROUND_DOWN));
//System.out.print(s+",");
}
return extinf;
}
public ArrayList<String> getExtVersion() throws Exception{
String response = getResponse.getResponseByGet(url);
ArrayList<String> extVersion = new ArrayList<String>();
String[] resp = response.split("\n");
List<String> strs=solveExtVersion(resp);
for(String s:strs){
extVersion.add(s);
}
return extVersion;
}
}
| 14,004 | 0.611339 | 0.587519 | 460 | 26.549999 | 25.445332 | 261 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.813044 | false | false | 3 |
938e446af89fcd9258f54fea451d469f2a84d988 | 7,911,329,781,130 | d8e311867938caf76ef4a031ff6a5576983a2edd | /webapp/racing/racingDomain/src/test/java/be/tiwi/vop/racing/domain/test/TournamentDaoTest.java | d86df9d44df94014074290898eef3faaf4553678 | []
| no_license | t0tec/racing-2D | https://github.com/t0tec/racing-2D | 21d2682383f6dd224dce1a874abe02d39008cc62 | abe7dc0182857871762c10a07df20677e1b54460 | refs/heads/master | 2021-01-13T01:29:59.045000 | 2015-01-21T12:21:06 | 2015-01-21T12:21:06 | 28,816,834 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package be.tiwi.vop.racing.domain.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import be.tiwi.vop.racing.core.model.Tournament;
import be.tiwi.vop.racing.core.model.User;
import be.tiwi.vop.racing.domain.BaseSetupTest;
public class TournamentDaoTest extends BaseSetupTest {
private static final Logger logger = LoggerFactory.getLogger(TournamentDaoTest.class);
@Test
public void getAllTournaments() {
logger.info("Getting all tournaments");
List<Tournament> tournaments = daoManager.getTournamentDao().getAllTournaments();
Assert.assertTrue(tournaments.size() > 0);
}
@Test
public void getLimitedNumberOfTournaments() {
int number1 = 5;
int number2 = 9;
List<Tournament> tournaments =
daoManager.getTournamentDao().getUpcomingTournaments(number1, number2);
Assert.assertTrue(tournaments.size() > 0);
Assert.assertEquals(number2 - number1, tournaments.size());
}
@Test
public void getTournamentById() {
logger.info("Get a tournament by id");
Tournament tournament = daoManager.getTournamentDao().getTournamentById(1);
Assert.assertNotNull(tournament);
}
@Test
public void getTournamentByName() {
logger.info("Get a tournament by name");
Tournament tournament = daoManager.getTournamentDao().getTournamentByName("tournament1");
Assert.assertNotNull(tournament);
}
@Test
public void insertDummyTournament() {
logger.info("Insert a dummy tournament");
Tournament dummyTournament = new Tournament();
dummyTournament.setName("dummy tournament");
dummyTournament.setUserId(2);
dummyTournament.setMaxPlayers(4);
dummyTournament.setFormule(Tournament.Formule.FASTEST);
String strDate = "04/26/2014 12:00";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
Date date = null;
try {
date = sdf.parse(strDate);
} catch (ParseException pEx) {
logger.error("Parse Exception: " + pEx.getMessage());
}
dummyTournament.setDate(date);
daoManager.getTournamentDao().insertTournament(dummyTournament);
Assert.assertNotNull(dummyTournament.getId());
}
@Test
@Ignore
public void updateTournament() {
logger.info("Updating a tournament");
Tournament tournament = daoManager.getTournamentDao().getTournamentById(1);
tournament.setMaxPlayers(10);
daoManager.getTournamentDao().updateTournament(tournament);
Assert.assertEquals(10, tournament.getMaxPlayers());
}
@Test
public void getTournamentsByUser() {
logger.info("Getting tournaments created by one user");
List<Tournament> tournaments = daoManager.getTournamentDao().getTournamentsByUserId(3);
Assert.assertTrue(tournaments.size() > 0);
}
@Test
public void getTournamentsByParticipantId() {
logger.info("Getting tournaments where a user is participating in");
List<Tournament> tournaments = daoManager.getTournamentDao().getTournamentsByParticipantId(4);
Assert.assertTrue(tournaments.size() > 0);
}
@Test
public void getParticipantsByTournamentId() {
logger.info("Getting all particpating users who are playing in the same tournament");
List<User> participants = daoManager.getTournamentDao().getParticipantsByTournamentId(1);
Assert.assertTrue(participants.size() > 0);
}
}
| UTF-8 | Java | 3,493 | java | TournamentDaoTest.java | Java | []
| null | []
| package be.tiwi.vop.racing.domain.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import be.tiwi.vop.racing.core.model.Tournament;
import be.tiwi.vop.racing.core.model.User;
import be.tiwi.vop.racing.domain.BaseSetupTest;
public class TournamentDaoTest extends BaseSetupTest {
private static final Logger logger = LoggerFactory.getLogger(TournamentDaoTest.class);
@Test
public void getAllTournaments() {
logger.info("Getting all tournaments");
List<Tournament> tournaments = daoManager.getTournamentDao().getAllTournaments();
Assert.assertTrue(tournaments.size() > 0);
}
@Test
public void getLimitedNumberOfTournaments() {
int number1 = 5;
int number2 = 9;
List<Tournament> tournaments =
daoManager.getTournamentDao().getUpcomingTournaments(number1, number2);
Assert.assertTrue(tournaments.size() > 0);
Assert.assertEquals(number2 - number1, tournaments.size());
}
@Test
public void getTournamentById() {
logger.info("Get a tournament by id");
Tournament tournament = daoManager.getTournamentDao().getTournamentById(1);
Assert.assertNotNull(tournament);
}
@Test
public void getTournamentByName() {
logger.info("Get a tournament by name");
Tournament tournament = daoManager.getTournamentDao().getTournamentByName("tournament1");
Assert.assertNotNull(tournament);
}
@Test
public void insertDummyTournament() {
logger.info("Insert a dummy tournament");
Tournament dummyTournament = new Tournament();
dummyTournament.setName("dummy tournament");
dummyTournament.setUserId(2);
dummyTournament.setMaxPlayers(4);
dummyTournament.setFormule(Tournament.Formule.FASTEST);
String strDate = "04/26/2014 12:00";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
Date date = null;
try {
date = sdf.parse(strDate);
} catch (ParseException pEx) {
logger.error("Parse Exception: " + pEx.getMessage());
}
dummyTournament.setDate(date);
daoManager.getTournamentDao().insertTournament(dummyTournament);
Assert.assertNotNull(dummyTournament.getId());
}
@Test
@Ignore
public void updateTournament() {
logger.info("Updating a tournament");
Tournament tournament = daoManager.getTournamentDao().getTournamentById(1);
tournament.setMaxPlayers(10);
daoManager.getTournamentDao().updateTournament(tournament);
Assert.assertEquals(10, tournament.getMaxPlayers());
}
@Test
public void getTournamentsByUser() {
logger.info("Getting tournaments created by one user");
List<Tournament> tournaments = daoManager.getTournamentDao().getTournamentsByUserId(3);
Assert.assertTrue(tournaments.size() > 0);
}
@Test
public void getTournamentsByParticipantId() {
logger.info("Getting tournaments where a user is participating in");
List<Tournament> tournaments = daoManager.getTournamentDao().getTournamentsByParticipantId(4);
Assert.assertTrue(tournaments.size() > 0);
}
@Test
public void getParticipantsByTournamentId() {
logger.info("Getting all particpating users who are playing in the same tournament");
List<User> participants = daoManager.getTournamentDao().getParticipantsByTournamentId(1);
Assert.assertTrue(participants.size() > 0);
}
}
| 3,493 | 0.738906 | 0.727741 | 108 | 31.342592 | 27.18461 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.546296 | false | false | 3 |
998d31f171a57c40097cea7e50f2f9715daea052 | 28,484,223,128,890 | 3f89e01a48d1859ece8f5c827285d5d0cad23368 | /src/aha/jingdong2.java | df8d6ae28861f92e0f1ee138f0f17036b87cdc58 | []
| no_license | royal007a/algorithm | https://github.com/royal007a/algorithm | cb0e6baf41d0ecf1a56c290fe27a93044400896b | fc03eeb13194f702bc5490b115f3d6b033facab5 | refs/heads/master | 2017-10-07T14:27:14.740000 | 2017-08-17T15:22:08 | 2017-08-17T15:22:08 | 81,203,960 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aha;
import java.util.Scanner;
public class jingdong2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int k1,k2,k3,k4;
k1 = sc.nextInt();
k2 = sc.nextInt();
k3 = sc.nextInt();
k4 = sc.nextInt();
int count;
count=getNum(k1)+getNum(k2)+getNum(k3)+getNum(k4);
System.out.println(count);
}
public static int getNum(int k){
int count = 0;
while(k>0){
count +=(k+k/2);
k=k/2;
}
return count;
}
}
| UTF-8 | Java | 592 | java | jingdong2.java | Java | []
| null | []
| package aha;
import java.util.Scanner;
public class jingdong2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int k1,k2,k3,k4;
k1 = sc.nextInt();
k2 = sc.nextInt();
k3 = sc.nextInt();
k4 = sc.nextInt();
int count;
count=getNum(k1)+getNum(k2)+getNum(k3)+getNum(k4);
System.out.println(count);
}
public static int getNum(int k){
int count = 0;
while(k>0){
count +=(k+k/2);
k=k/2;
}
return count;
}
}
| 592 | 0.554054 | 0.525338 | 32 | 17.5 | 14.893371 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.375 | false | false | 3 |
04d5fa53baa6bb84135d5e67dfba4cfd66f9b13a | 22,771,916,626,936 | 6e6db7db5aa823c77d9858d2182d901684faaa24 | /sample/webservice/eBayDemoApp/src/com/ebay/trading/api/CombinedPaymentPreferencesType.java | ddb982712f0e88709b0b8e32b9991f3c21cf89e3 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
]
| permissive | 4everalone/nano | https://github.com/4everalone/nano | 68a480d07d80f0f50d73ec593443bfb362d646aa | 71779b1ad546663ee90a29f1c2d4236a6948a621 | refs/heads/master | 2020-12-25T14:08:08.303000 | 2013-07-25T13:28:41 | 2013-07-25T13:28:41 | 10,792,684 | 0 | 1 | Apache-2.0 | true | 2019-04-24T20:12:27 | 2013-06-19T13:14:26 | 2014-01-22T13:50:48 | 2014-12-18T17:18:08 | 8,049 | 0 | 1 | 1 | Java | false | false | // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;
/**
*
* Type used to define all Combined Payment preferences, including preferences and
* rules for Calculated and Flat Rate shipping, a flag to allow or disallow Combined
* Payment orders, and the time period in which to allow buyers to combine multiple
* purchases from the seller into a Combined Payment order.
*
*/
public class CombinedPaymentPreferencesType implements Serializable {
private static final long serialVersionUID = -1L;
@Element(name = "CalculatedShippingPreferences")
@Order(value=0)
public CalculatedShippingPreferencesType calculatedShippingPreferences;
@Element(name = "CombinedPaymentOption")
@Order(value=1)
public CombinedPaymentOptionCodeType combinedPaymentOption;
@Element(name = "CombinedPaymentPeriod")
@Order(value=2)
public CombinedPaymentPeriodCodeType combinedPaymentPeriod;
@Element(name = "FlatShippingPreferences")
@Order(value=3)
public FlatShippingPreferencesType flatShippingPreferences;
@AnyElement
@Order(value=4)
public List<Object> any;
} | UTF-8 | Java | 1,220 | java | CombinedPaymentPreferencesType.java | Java | []
| null | []
| // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;
/**
*
* Type used to define all Combined Payment preferences, including preferences and
* rules for Calculated and Flat Rate shipping, a flag to allow or disallow Combined
* Payment orders, and the time period in which to allow buyers to combine multiple
* purchases from the seller into a Combined Payment order.
*
*/
public class CombinedPaymentPreferencesType implements Serializable {
private static final long serialVersionUID = -1L;
@Element(name = "CalculatedShippingPreferences")
@Order(value=0)
public CalculatedShippingPreferencesType calculatedShippingPreferences;
@Element(name = "CombinedPaymentOption")
@Order(value=1)
public CombinedPaymentOptionCodeType combinedPaymentOption;
@Element(name = "CombinedPaymentPeriod")
@Order(value=2)
public CombinedPaymentPeriodCodeType combinedPaymentPeriod;
@Element(name = "FlatShippingPreferences")
@Order(value=3)
public FlatShippingPreferencesType flatShippingPreferences;
@AnyElement
@Order(value=4)
public List<Object> any;
} | 1,220 | 0.781148 | 0.77623 | 42 | 28.071428 | 27.059364 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.904762 | false | false | 3 |
7249543417cd71ceaf55b62d3bbffba24b3d09cd | 2,010,044,724,844 | 771ec5da7f9ff1eb04795a762cf8e79161af0553 | /app/src/main/java/com/w3engineers/core/util/helper/CheckNetworkAvailabilityAndPermission.java | a6003a3de4e1ebb11ddfb2ddc3f9a9d930114fbb | []
| no_license | netsmartdo/appmobilemusic | https://github.com/netsmartdo/appmobilemusic | 8268248b9a6267783240791b67e32a74086a8ddf | 579a5121a2b5ab04e14d4d5a917f24e87a774792 | refs/heads/master | 2020-07-25T05:25:41.274000 | 2019-09-13T02:22:34 | 2019-09-13T02:22:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.w3engineers.core.util.helper;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class CheckNetworkAvailabilityAndPermission {
String[] permissions = new String[]{
Manifest.permission.ACCESS_NETWORK_STATE
};
///Checking network availability
public boolean checkIfHasNetwork(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
boolean b = networkInfo != null && networkInfo.isConnected();
if (!b)
Toast.makeText(context, "Please turn on your Wifi or Mobile data .", Toast.LENGTH_LONG).show();
return b;
}
///Checking permission
public boolean checkPermissions(Context context) {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(context, p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions((Activity) context, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100);
return false;
}
return true;
}
}
| UTF-8 | Java | 1,776 | java | CheckNetworkAvailabilityAndPermission.java | Java | []
| null | []
| package com.w3engineers.core.util.helper;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class CheckNetworkAvailabilityAndPermission {
String[] permissions = new String[]{
Manifest.permission.ACCESS_NETWORK_STATE
};
///Checking network availability
public boolean checkIfHasNetwork(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
boolean b = networkInfo != null && networkInfo.isConnected();
if (!b)
Toast.makeText(context, "Please turn on your Wifi or Mobile data .", Toast.LENGTH_LONG).show();
return b;
}
///Checking permission
public boolean checkPermissions(Context context) {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(context, p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions((Activity) context, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100);
return false;
}
return true;
}
}
| 1,776 | 0.67455 | 0.671171 | 50 | 33.52 | 30.389629 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
8a7cec8c5aa9d974d49b502bffcdb9f823b64e5b | 15,204,184,253,891 | 64211865a508215eff65366499c388b9b124aa1e | /src/main/java/com/seregy77/dss/web/controller/TripleDesController.java | 103c0fd982bb2a2afbf0d68b4e650fed95d391ae | []
| no_license | Seregy/dss-encryption | https://github.com/Seregy/dss-encryption | 628e5b36d7d9245bb8fa184e6aa91fbe206897f5 | a3d2bdcad23070498dcd7827097333e0706ba3d3 | refs/heads/master | 2021-07-22T16:24:51.225000 | 2019-06-13T10:48:03 | 2019-06-13T10:48:03 | 187,908,655 | 0 | 0 | null | false | 2020-06-16T00:10:37 | 2019-05-21T20:27:38 | 2019-06-13T10:48:16 | 2020-06-16T00:10:36 | 39 | 0 | 0 | 1 | Java | false | false | package com.seregy77.dss.web.controller;
import com.seregy77.dss.service.converter.HexToBytesConverter;
import com.seregy77.dss.service.converter.Utf8ToBytesConverter;
import com.seregy77.dss.service.encryption.des.triple.HashingTripleDes;
import com.seregy77.dss.service.encryption.des.triple.TripleDes;
import com.seregy77.dss.web.domain.DecryptionRequest;
import com.seregy77.dss.web.domain.DecryptionResponse;
import com.seregy77.dss.web.domain.EncryptionRequest;
import com.seregy77.dss.web.domain.EncryptionResponse;
import lombok.RequiredArgsConstructor;
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.RestController;
@RestController
@RequestMapping("tdes")
@RequiredArgsConstructor
public class TripleDesController {
private final Utf8ToBytesConverter utf8ToBytesConverter;
private final HexToBytesConverter hexToBytesConverter;
private final TripleDes tripleDes;
private final HashingTripleDes hashingTripleDes;
@PostMapping("/encrypt-strict")
public EncryptionResponse encryptWithTripleDes(@RequestBody EncryptionRequest encryptionRequest) {
byte[] messageBytes = utf8ToBytesConverter.toBytes(encryptionRequest.getMessage());
byte[] keyBytes = utf8ToBytesConverter.toBytes(encryptionRequest.getKey());
byte[] encryptedBytes = tripleDes.encrypt(messageBytes, keyBytes);
return new EncryptionResponse(hexToBytesConverter.toHex(encryptedBytes));
}
@PostMapping("/decrypt-strict")
public DecryptionResponse decryptWithTripleDes(@RequestBody DecryptionRequest decryptionRequest) {
byte[] messageBytes = hexToBytesConverter.toBytes(decryptionRequest.getEncryptedMessage());
byte[] keyBytes = utf8ToBytesConverter.toBytes(decryptionRequest.getKey());
byte[] encryptedBytes = tripleDes.decrypt(messageBytes, keyBytes);
return new DecryptionResponse(utf8ToBytesConverter.toUtf8String(encryptedBytes));
}
@PostMapping("/encrypt")
public EncryptionResponse encryptWithHashingTripleDes(@RequestBody EncryptionRequest encryptionRequest) {
byte[] messageBytes = utf8ToBytesConverter.toBytes(encryptionRequest.getMessage());
byte[] keyBytes = utf8ToBytesConverter.toBytes(encryptionRequest.getKey());
byte[] encryptedBytes = hashingTripleDes.encrypt(messageBytes, keyBytes);
return new EncryptionResponse(hexToBytesConverter.toHex(encryptedBytes));
}
@PostMapping("/decrypt")
public DecryptionResponse decryptWithHashingTripleDes(@RequestBody DecryptionRequest decryptionRequest) {
byte[] messageBytes = hexToBytesConverter.toBytes(decryptionRequest.getEncryptedMessage());
byte[] keyBytes = utf8ToBytesConverter.toBytes(decryptionRequest.getKey());
byte[] encryptedBytes = hashingTripleDes.decrypt(messageBytes, keyBytes);
return new DecryptionResponse(utf8ToBytesConverter.toUtf8String(encryptedBytes));
}
}
| UTF-8 | Java | 3,091 | java | TripleDesController.java | Java | []
| null | []
| package com.seregy77.dss.web.controller;
import com.seregy77.dss.service.converter.HexToBytesConverter;
import com.seregy77.dss.service.converter.Utf8ToBytesConverter;
import com.seregy77.dss.service.encryption.des.triple.HashingTripleDes;
import com.seregy77.dss.service.encryption.des.triple.TripleDes;
import com.seregy77.dss.web.domain.DecryptionRequest;
import com.seregy77.dss.web.domain.DecryptionResponse;
import com.seregy77.dss.web.domain.EncryptionRequest;
import com.seregy77.dss.web.domain.EncryptionResponse;
import lombok.RequiredArgsConstructor;
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.RestController;
@RestController
@RequestMapping("tdes")
@RequiredArgsConstructor
public class TripleDesController {
private final Utf8ToBytesConverter utf8ToBytesConverter;
private final HexToBytesConverter hexToBytesConverter;
private final TripleDes tripleDes;
private final HashingTripleDes hashingTripleDes;
@PostMapping("/encrypt-strict")
public EncryptionResponse encryptWithTripleDes(@RequestBody EncryptionRequest encryptionRequest) {
byte[] messageBytes = utf8ToBytesConverter.toBytes(encryptionRequest.getMessage());
byte[] keyBytes = utf8ToBytesConverter.toBytes(encryptionRequest.getKey());
byte[] encryptedBytes = tripleDes.encrypt(messageBytes, keyBytes);
return new EncryptionResponse(hexToBytesConverter.toHex(encryptedBytes));
}
@PostMapping("/decrypt-strict")
public DecryptionResponse decryptWithTripleDes(@RequestBody DecryptionRequest decryptionRequest) {
byte[] messageBytes = hexToBytesConverter.toBytes(decryptionRequest.getEncryptedMessage());
byte[] keyBytes = utf8ToBytesConverter.toBytes(decryptionRequest.getKey());
byte[] encryptedBytes = tripleDes.decrypt(messageBytes, keyBytes);
return new DecryptionResponse(utf8ToBytesConverter.toUtf8String(encryptedBytes));
}
@PostMapping("/encrypt")
public EncryptionResponse encryptWithHashingTripleDes(@RequestBody EncryptionRequest encryptionRequest) {
byte[] messageBytes = utf8ToBytesConverter.toBytes(encryptionRequest.getMessage());
byte[] keyBytes = utf8ToBytesConverter.toBytes(encryptionRequest.getKey());
byte[] encryptedBytes = hashingTripleDes.encrypt(messageBytes, keyBytes);
return new EncryptionResponse(hexToBytesConverter.toHex(encryptedBytes));
}
@PostMapping("/decrypt")
public DecryptionResponse decryptWithHashingTripleDes(@RequestBody DecryptionRequest decryptionRequest) {
byte[] messageBytes = hexToBytesConverter.toBytes(decryptionRequest.getEncryptedMessage());
byte[] keyBytes = utf8ToBytesConverter.toBytes(decryptionRequest.getKey());
byte[] encryptedBytes = hashingTripleDes.decrypt(messageBytes, keyBytes);
return new DecryptionResponse(utf8ToBytesConverter.toUtf8String(encryptedBytes));
}
}
| 3,091 | 0.796506 | 0.786477 | 62 | 48.854839 | 35.277172 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 3 |
055237e5f75c5ea339798ab8b279c8db8748ee48 | 11,115,375,385,634 | 65d06940e77a3cae245c932146628aa90601eb00 | /jvm/src/main/java/com/polo/GcDemo.java | d0bde92f4f172f8df2a258ff76f1f0e05932d5d3 | []
| no_license | 7polo/practise | https://github.com/7polo/practise | bc6be7dcbd2a7b4cd5775d031f996fd80801a96f | b61db45339cf69f44d68ff13025bb66a4d8d68d5 | refs/heads/main | 2023-04-27T03:08:51.523000 | 2021-05-29T00:46:15 | 2021-05-29T00:46:15 | 340,522,126 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.polo;
/**
* @author baoqianyong
* @date 2021/3/26
*/
public class GcDemo {
public static void main(String[] args) {
// 100M
byte [] MAXOBJ = new byte [1024 * 1024 * 100];
// 60M
byte [] MAXOBJ2 = new byte [1024 * 1024 * 66];
MAXOBJ = null;
// 60M
byte [] MAXOBJ3 = new byte [1024 * 1024 * 60];
}
}
| UTF-8 | Java | 381 | java | GcDemo.java | Java | [
{
"context": "package com.polo;\n\n/**\n * @author baoqianyong\n * @date 2021/3/26\n */\npublic class GcDemo {\n\n ",
"end": 45,
"score": 0.7942683100700378,
"start": 34,
"tag": "USERNAME",
"value": "baoqianyong"
}
]
| null | []
| package com.polo;
/**
* @author baoqianyong
* @date 2021/3/26
*/
public class GcDemo {
public static void main(String[] args) {
// 100M
byte [] MAXOBJ = new byte [1024 * 1024 * 100];
// 60M
byte [] MAXOBJ2 = new byte [1024 * 1024 * 66];
MAXOBJ = null;
// 60M
byte [] MAXOBJ3 = new byte [1024 * 1024 * 60];
}
}
| 381 | 0.506562 | 0.383202 | 20 | 18.049999 | 18.508039 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 3 |
12d26a338c88141797ea2796dec1c0c5a47a779b | 18,081,812,340,092 | 9bc2e16bd25461ee4fa641aafb268b5029f9b0e2 | /embedmongo/src/test/java/UserDaoIntegrationTest.java | bdb5c5e50a62fd4e97cca9b494ade1e9263499c8 | []
| no_license | sergueik/selenium_java | https://github.com/sergueik/selenium_java | 775432bb23f418893551d73d82acd210bf07e43c | 18eca29cd2e87b4e0bdf9f450e7608aae97b8e8d | refs/heads/master | 2023-08-31T21:56:41.765000 | 2023-08-28T23:14:28 | 2023-08-28T23:14:28 | 40,056,997 | 25 | 14 | null | false | 2023-02-22T08:44:35 | 2015-08-01T19:00:35 | 2022-11-20T13:45:21 | 2023-02-22T08:44:33 | 60,548 | 21 | 11 | 225 | Java | false | false | import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import de.flapdoodle.embedmongo.MongoDBRuntime;
import de.flapdoodle.embedmongo.config.MongodConfig;
import de.flapdoodle.embedmongo.distribution.Version;
import org.bson.Document;
import org.junit.Test;
public class UserDaoIntegrationTest {
private static final String DB_NAME = "testDB";
private static final String LOCALHOST = "localhost";
private static final String TABLE_NAME = "testTable";
private static final int testPort = 12345;
private MongoClient mongo;
private MongoDatabase db;
private MongoCollection<Document> collection;
private EmbeddedMongoUtilImpl embeddedMongoUtil;
private EmbeddedMongoConfig embeddedMongoConfig;
public void setup() {
MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();
this.embeddedMongoConfig = new EmbeddedMongoConfig();
boolean ipv6 = embeddedMongoConfig.localhostIsIPv6WithOutException();
MongodConfig mongodConfig = new MongodConfig(Version.V2_1_2, 12345, ipv6);
this.embeddedMongoUtil = new EmbeddedMongoUtilImpl(runtime, mongodConfig);
mongo = embeddedMongoConfig.getMongoInstanceWithoutException(LOCALHOST, testPort);
embeddedMongoUtil.start();
db = mongo.getDatabase(DB_NAME);
collection = db.getCollection(TABLE_NAME);
}
public void tearDown() {
embeddedMongoUtil.stop();
}
@Test
public void InsertANameAndEmailIntheDatabase() {
setup();
UserDao userDao = new UserDao(db);
String name = "TestUser";
String email = "TestUser@test.com";
userDao.insertUser(name, email);
tearDown();
}
}
| UTF-8 | Java | 1,758 | java | UserDaoIntegrationTest.java | Java | [
{
"context": "userDao = new UserDao(db);\n String name = \"TestUser\";\n String email = \"TestUser@test.com\";\n ",
"end": 1642,
"score": 0.9993021488189697,
"start": 1634,
"tag": "USERNAME",
"value": "TestUser"
},
{
"context": "String name = \"TestUser\";\n String email = \"TestUser@test.com\";\n userDao.insertUser(name, email);\n ",
"end": 1686,
"score": 0.999923050403595,
"start": 1669,
"tag": "EMAIL",
"value": "TestUser@test.com"
}
]
| null | []
| import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import de.flapdoodle.embedmongo.MongoDBRuntime;
import de.flapdoodle.embedmongo.config.MongodConfig;
import de.flapdoodle.embedmongo.distribution.Version;
import org.bson.Document;
import org.junit.Test;
public class UserDaoIntegrationTest {
private static final String DB_NAME = "testDB";
private static final String LOCALHOST = "localhost";
private static final String TABLE_NAME = "testTable";
private static final int testPort = 12345;
private MongoClient mongo;
private MongoDatabase db;
private MongoCollection<Document> collection;
private EmbeddedMongoUtilImpl embeddedMongoUtil;
private EmbeddedMongoConfig embeddedMongoConfig;
public void setup() {
MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();
this.embeddedMongoConfig = new EmbeddedMongoConfig();
boolean ipv6 = embeddedMongoConfig.localhostIsIPv6WithOutException();
MongodConfig mongodConfig = new MongodConfig(Version.V2_1_2, 12345, ipv6);
this.embeddedMongoUtil = new EmbeddedMongoUtilImpl(runtime, mongodConfig);
mongo = embeddedMongoConfig.getMongoInstanceWithoutException(LOCALHOST, testPort);
embeddedMongoUtil.start();
db = mongo.getDatabase(DB_NAME);
collection = db.getCollection(TABLE_NAME);
}
public void tearDown() {
embeddedMongoUtil.stop();
}
@Test
public void InsertANameAndEmailIntheDatabase() {
setup();
UserDao userDao = new UserDao(db);
String name = "TestUser";
String email = "<EMAIL>";
userDao.insertUser(name, email);
tearDown();
}
}
| 1,748 | 0.727531 | 0.71843 | 46 | 37.217392 | 23.291082 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.826087 | false | false | 3 |
497b661a6164ad69986326747eea1c2da8511b67 | 37,374,805,420,524 | a69a9d18fe64eb86256d9ec47dceb7f5cf2110c9 | /src/main/java/uk/gov/ea/datareturns/domain/jpa/dao/impl/ReturnTypeDaoImpl.java | 0fd8e8d5e7891295c321aea01c8d60d940276881 | [
"LicenseRef-scancode-unknown-license-reference",
"OGL-UK-3.0"
]
| permissive | uk-gov-mirror/defra.data-returns-data-exchange | https://github.com/uk-gov-mirror/defra.data-returns-data-exchange | a6da5528d705d9d57172ab352afd728ce764ee1d | 1feac50a17fbf148368450698b428c9aef32cc98 | refs/heads/master | 2021-09-13T19:37:39.265000 | 2017-07-26T14:29:40 | 2017-07-27T09:06:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.gov.ea.datareturns.domain.jpa.dao.impl;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import uk.gov.ea.datareturns.domain.jpa.dao.ReturnTypeDao;
import uk.gov.ea.datareturns.domain.jpa.entities.ReturnType;
import uk.gov.ea.datareturns.domain.jpa.hierarchy.processors.GroupingEntityCommon;
import javax.inject.Inject;
/**
* DAO for return types.
*
* @author Graham Willis
*/
@Repository
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ReturnTypeDaoImpl extends AbstractEntityDao<ReturnType> implements ReturnTypeDao {
@Inject
public ReturnTypeDaoImpl(GroupingEntityCommon<ReturnType> groupingEntityCommon) {
super(ReturnType.class, groupingEntityCommon);
}
} | UTF-8 | Java | 839 | java | ReturnTypeDaoImpl.java | Java | [
{
"context": "nject;\n\n/**\n * DAO for return types.\n *\n * @author Graham Willis\n */\n@Repository\n@Scope(ConfigurableBeanFactory.SC",
"end": 517,
"score": 0.9998220205307007,
"start": 504,
"tag": "NAME",
"value": "Graham Willis"
}
]
| null | []
| package uk.gov.ea.datareturns.domain.jpa.dao.impl;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import uk.gov.ea.datareturns.domain.jpa.dao.ReturnTypeDao;
import uk.gov.ea.datareturns.domain.jpa.entities.ReturnType;
import uk.gov.ea.datareturns.domain.jpa.hierarchy.processors.GroupingEntityCommon;
import javax.inject.Inject;
/**
* DAO for return types.
*
* @author <NAME>
*/
@Repository
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ReturnTypeDaoImpl extends AbstractEntityDao<ReturnType> implements ReturnTypeDao {
@Inject
public ReturnTypeDaoImpl(GroupingEntityCommon<ReturnType> groupingEntityCommon) {
super(ReturnType.class, groupingEntityCommon);
}
} | 832 | 0.812872 | 0.812872 | 25 | 32.599998 | 30.629398 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 3 |
6104088fd21f76c258cfdecb83baa084c7509908 | 37,735,582,666,095 | 1bddef117119d7bc9733a5ab6bec7461845e302d | /java16/src/상속응용/Truck.java | fc45595cf0a888790f0ca46739c0e85c18a62c47 | []
| no_license | Minbyeong/androidjava | https://github.com/Minbyeong/androidjava | 46d4f866cd3988068a2f98dfc3f560bdc97e7dd6 | af31929e84093d3e82a7f36be34a6c713a46cae8 | refs/heads/master | 2023-01-02T08:18:04.679000 | 2020-10-30T03:19:28 | 2020-10-30T03:19:28 | 288,131,807 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package 상속응용;
public class Truck extends Car{
String size;
public void trade() {
System.out.println("물건을 실어 나르다");
}
@Override
public String toString() {
return "Truck [size=" + size + ", type=" + type + ", company=" + company + "]";
}
}
| UTF-8 | Java | 295 | java | Truck.java | Java | []
| null | []
| package 상속응용;
public class Truck extends Car{
String size;
public void trade() {
System.out.println("물건을 실어 나르다");
}
@Override
public String toString() {
return "Truck [size=" + size + ", type=" + type + ", company=" + company + "]";
}
}
| 295 | 0.571956 | 0.571956 | 16 | 14.9375 | 20.674467 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 3 |
1108047c8f5d8d27ee59d82895f9ac3daf5bee0f | 38,783,554,686,011 | 763025b259a9a2ee21843ca2c4874872934b76c9 | /TeamCode/src/main/java/org/firstinspires/ftc/AvesAblazeHardware.java | a8ef04e5200c33c67b01213bfc3268fc5f8898f3 | [
"BSD-3-Clause"
]
| permissive | THE-COB/SkyStone | https://github.com/THE-COB/SkyStone | bc2a69a8786d16a48118687f9a6b3eb8a5c55478 | 91c66bc250fe33953115bcf48a71d42dc2f70adf | refs/heads/master | 2020-07-10T18:29:41.347000 | 2020-02-09T20:17:20 | 2020-02-09T20:17:20 | 204,336,249 | 0 | 0 | null | true | 2019-09-26T19:55:49 | 2019-08-25T18:49:27 | 2019-09-26T19:43:06 | 2019-09-26T19:55:49 | 143,575 | 0 | 0 | 0 | Java | false | false | package org.firstinspires.ftc;
import com.qualcomm.hardware.bosch.BNO055IMU;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.DistanceSensor;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.Servo;
import java.util.ArrayList;
import java.util.List;
public class AvesAblazeHardware {
public BNO055IMU imu1;
public BNO055IMU imu;
public DcMotor motor0;
public DcMotor motor1;
public DcMotor motor2;
public DcMotor motor3;
public Servo foundation;
public ColorSensor floorColor;
public DistanceSensor floorRange;
public DcMotor leftIntake;
public DcMotor rightIntake;
int startingAngle = 0;
Orientation angles;
/**public static final float mmPerInch = 25.4f;
public static final float mmFTCFieldWidth = (12*6) * mmPerInch; // the width of the FTC field (from the center point to the outer panels)
public static final float mmTargetHeight = (6) * mmPerInch;
double correction;
// the height of the center of the target image above the floor
VuforiaTrackables targetsRoverRuckus;
List<VuforiaTrackable> allTrackables;
VuforiaTrackable currentTrackable;
// Select which camera you want use. The FRONT camera is the one on the same side as the screen.
// Valid choices are: BACK or FRONT
public static final VuforiaLocalizer.CameraDirection CAMERA_CHOICE = BACK;
public OpenGLMatrix lastLocation = null;
public boolean targetVisible = false;
public Orientation rotation;
public VectorF translation;
Orientation angles;
*/
HardwareMap hardwareMap;
public void init(HardwareMap ahwMap){
hardwareMap = ahwMap;
imu1 = hardwareMap.get(BNO055IMU.class, "imu 1");
imu = hardwareMap.get(BNO055IMU.class, "imu");
motor0 = hardwareMap.get(DcMotor.class, "motor0");
motor1 = hardwareMap.get(DcMotor.class, "motor1");
motor2 = hardwareMap.get(DcMotor.class, "motor2");
motor3 = hardwareMap.get(DcMotor.class, "motor3");
motor0.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor1.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor2.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor3.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor0.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor1.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor2.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor3.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor0.setDirection(DcMotor.Direction.FORWARD);
motor2.setDirection(DcMotor.Direction.FORWARD);
motor1.setDirection(DcMotor.Direction.REVERSE);
motor3.setDirection(DcMotor.Direction.REVERSE);
motor0.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motor1.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motor2.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motor3.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
foundation = hardwareMap.get(Servo.class, "foundation");
floorColor = hardwareMap.get(ColorSensor.class, "floorColor");
floorRange = hardwareMap.get(DistanceSensor.class, "floorColor");
leftIntake = hardwareMap.get(DcMotor.class, "leftIntake");
rightIntake = hardwareMap.get(DcMotor.class, "rightIntake");
leftIntake.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
rightIntake.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
rightIntake.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
leftIntake.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
}
} | UTF-8 | Java | 4,396 | java | AvesAblazeHardware.java | Java | []
| null | []
| package org.firstinspires.ftc;
import com.qualcomm.hardware.bosch.BNO055IMU;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.matrices.OpenGLMatrix;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.matrices.VectorF;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.DistanceSensor;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.hardware.Servo;
import java.util.ArrayList;
import java.util.List;
public class AvesAblazeHardware {
public BNO055IMU imu1;
public BNO055IMU imu;
public DcMotor motor0;
public DcMotor motor1;
public DcMotor motor2;
public DcMotor motor3;
public Servo foundation;
public ColorSensor floorColor;
public DistanceSensor floorRange;
public DcMotor leftIntake;
public DcMotor rightIntake;
int startingAngle = 0;
Orientation angles;
/**public static final float mmPerInch = 25.4f;
public static final float mmFTCFieldWidth = (12*6) * mmPerInch; // the width of the FTC field (from the center point to the outer panels)
public static final float mmTargetHeight = (6) * mmPerInch;
double correction;
// the height of the center of the target image above the floor
VuforiaTrackables targetsRoverRuckus;
List<VuforiaTrackable> allTrackables;
VuforiaTrackable currentTrackable;
// Select which camera you want use. The FRONT camera is the one on the same side as the screen.
// Valid choices are: BACK or FRONT
public static final VuforiaLocalizer.CameraDirection CAMERA_CHOICE = BACK;
public OpenGLMatrix lastLocation = null;
public boolean targetVisible = false;
public Orientation rotation;
public VectorF translation;
Orientation angles;
*/
HardwareMap hardwareMap;
public void init(HardwareMap ahwMap){
hardwareMap = ahwMap;
imu1 = hardwareMap.get(BNO055IMU.class, "imu 1");
imu = hardwareMap.get(BNO055IMU.class, "imu");
motor0 = hardwareMap.get(DcMotor.class, "motor0");
motor1 = hardwareMap.get(DcMotor.class, "motor1");
motor2 = hardwareMap.get(DcMotor.class, "motor2");
motor3 = hardwareMap.get(DcMotor.class, "motor3");
motor0.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor1.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor2.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor3.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
motor0.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor1.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor2.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor3.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
motor0.setDirection(DcMotor.Direction.FORWARD);
motor2.setDirection(DcMotor.Direction.FORWARD);
motor1.setDirection(DcMotor.Direction.REVERSE);
motor3.setDirection(DcMotor.Direction.REVERSE);
motor0.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motor1.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motor2.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
motor3.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
foundation = hardwareMap.get(Servo.class, "foundation");
floorColor = hardwareMap.get(ColorSensor.class, "floorColor");
floorRange = hardwareMap.get(DistanceSensor.class, "floorColor");
leftIntake = hardwareMap.get(DcMotor.class, "leftIntake");
rightIntake = hardwareMap.get(DcMotor.class, "rightIntake");
leftIntake.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
rightIntake.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
rightIntake.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
leftIntake.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
}
} | 4,396 | 0.734531 | 0.722247 | 111 | 38.612614 | 27.759642 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.783784 | false | false | 3 |
3f165ef880916ff079b3b2068222fc99e5e0c7ca | 30,090,540,945,824 | 88f5bdf57b73827727bfaa8ee64dc890c877c5af | /src/main/java/com/snapgroup/Activities/RestorePasswordActivty.java | fb86e4cb56300661e4c37edbdb5b69b22ad765a6 | []
| no_license | mohamadir/TestBranchSg | https://github.com/mohamadir/TestBranchSg | b814453f0230f3ee5a768b38d8e45d84b1928674 | 9f6b1f76ebdf0bdc7d4dfb529dc4a6e1848868dd | refs/heads/master | 2021-07-03T22:26:17.410000 | 2017-09-24T14:07:28 | 2017-09-24T14:07:28 | 104,648,650 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.snapgroup.Activities;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.snapgroup.Classes.MySingleton;
import com.snapgroup.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class RestorePasswordActivty extends AppCompatActivity {
Button sumbitBt ;
public String randomCode;
EditText emailRest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restore_password);
emailRest = (EditText)findViewById(R.id.phoneNUmbers);
sumbitBt = (Button)findViewById(R.id.submit);
sumbitBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ResetPassword(emailRest.getText().toString());
}
});
}
private void validateCode(String s) {
View phoneNumberView= LayoutInflater.from(RestorePasswordActivty.this).inflate(R.layout.enter_code_number_dialog,null);
final EditText validateCodeEt = (EditText) phoneNumberView.findViewById(R.id.validateCodeEt);
AlertDialog.Builder builder = new AlertDialog.Builder(RestorePasswordActivty.this);
builder.setMessage("Validation");
builder.setView(phoneNumberView);
builder.setPositiveButton("אישור", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String validateCodeString =validateCodeEt.getText().toString();
if(!validateCodeString.equals("")&&validateCodeString.equals(randomCode)){
Intent i = new Intent(RestorePasswordActivty.this,NewPasswordActivity.class);
Log.i("asdasdasdasd",randomCode);
i.putExtra("code" , randomCode);
i.putExtra("email" ,emailRest.getText().toString() );
startActivity(i);
}
else
Toast.makeText(RestorePasswordActivty.this, "Not Ok", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("בטל", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, "PIN code: "+message, sentPI, deliveredPI);
}
public void ResetPassword(final String email){
Log.i("responseee" ,"im in ResetPassword");
Log.i("responeseee" , "http://172.104.150.56/api/password/getresetcode");
JsonObjectRequest sr = new JsonObjectRequest(Request.Method.POST, "http://172.104.150.56/api/password/getresetcode", null , new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("responseee" , response.toString());
try {
randomCode = response.getString("code").toString();
sendSMS("0525662875", randomCode);
validateCode(randomCode);
Log.i("responesecode" , randomCode);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("responseee" , "Im in error "+error.networkResponse.statusCode);
}
}) {
@Override
public byte[] getBody() {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("email", email);
return new JSONObject(params2).toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}
/* @Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("email", email);
return new JSONObject(params2).toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}*/
};
MySingleton.getInstance(RestorePasswordActivty.this).addToRequestQueue(sr);
}
}
| UTF-8 | Java | 7,843 | java | RestorePasswordActivty.java | Java | [
{
"context": "assword\");\n\n Log.i(\"responeseee\" , \"http://172.104.150.56/api/password/getresetcode\");\n JsonObjectRe",
"end": 5954,
"score": 0.9007688760757446,
"start": 5940,
"tag": "IP_ADDRESS",
"value": "172.104.150.56"
}
]
| null | []
| package com.snapgroup.Activities;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.snapgroup.Classes.MySingleton;
import com.snapgroup.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class RestorePasswordActivty extends AppCompatActivity {
Button sumbitBt ;
public String randomCode;
EditText emailRest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restore_password);
emailRest = (EditText)findViewById(R.id.phoneNUmbers);
sumbitBt = (Button)findViewById(R.id.submit);
sumbitBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ResetPassword(emailRest.getText().toString());
}
});
}
private void validateCode(String s) {
View phoneNumberView= LayoutInflater.from(RestorePasswordActivty.this).inflate(R.layout.enter_code_number_dialog,null);
final EditText validateCodeEt = (EditText) phoneNumberView.findViewById(R.id.validateCodeEt);
AlertDialog.Builder builder = new AlertDialog.Builder(RestorePasswordActivty.this);
builder.setMessage("Validation");
builder.setView(phoneNumberView);
builder.setPositiveButton("אישור", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String validateCodeString =validateCodeEt.getText().toString();
if(!validateCodeString.equals("")&&validateCodeString.equals(randomCode)){
Intent i = new Intent(RestorePasswordActivty.this,NewPasswordActivity.class);
Log.i("asdasdasdasd",randomCode);
i.putExtra("code" , randomCode);
i.putExtra("email" ,emailRest.getText().toString() );
startActivity(i);
}
else
Toast.makeText(RestorePasswordActivty.this, "Not Ok", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("בטל", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, "PIN code: "+message, sentPI, deliveredPI);
}
public void ResetPassword(final String email){
Log.i("responseee" ,"im in ResetPassword");
Log.i("responeseee" , "http://172.16.31.10/api/password/getresetcode");
JsonObjectRequest sr = new JsonObjectRequest(Request.Method.POST, "http://172.104.150.56/api/password/getresetcode", null , new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("responseee" , response.toString());
try {
randomCode = response.getString("code").toString();
sendSMS("0525662875", randomCode);
validateCode(randomCode);
Log.i("responesecode" , randomCode);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("responseee" , "Im in error "+error.networkResponse.statusCode);
}
}) {
@Override
public byte[] getBody() {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("email", email);
return new JSONObject(params2).toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}
/* @Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("email", email);
return new JSONObject(params2).toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}*/
};
MySingleton.getInstance(RestorePasswordActivty.this).addToRequestQueue(sr);
}
}
| 7,841 | 0.57358 | 0.567454 | 213 | 35.784039 | 28.349932 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.699531 | false | false | 3 |
1ea9dba84d0d7ab3c8c216b4268d5c8a1409a7d9 | 37,443,524,894,065 | 6504352f86c2e4f7ef16cea3f5b7cc00bba96a33 | /WmesWeb/src/com/fsll/app/member/ws/AppMemberSSORest.java | 6b911fdbf1492641a5742871d544711c465f718a | []
| no_license | jedyang/XFAWealth | https://github.com/jedyang/XFAWealth | 1a20c7b4d16c72883b27c4d8aa72d67df4291b9a | 029d45620b3375a86fec8bb1161492325f9f2c6c | refs/heads/master | 2021-05-07T04:53:24.628000 | 2017-08-03T15:25:59 | 2017-08-03T15:25:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fsll.app.member.ws;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fsll.app.member.service.AppMemberBaseService;
import com.fsll.app.member.vo.AppMemberSsoVO;
import com.fsll.common.CommonConstants;
import com.fsll.core.ResultWS;
import com.fsll.core.WSConstants;
import com.fsll.wmes.base.WmesBaseRest;
import com.fsll.wmes.entity.MemberBase;
import com.fsll.wmes.entity.MemberCompany;
/***
* sso认证接口
* @author mjhuang
* @date 2016-6-20
*/
@RestController
@RequestMapping("/service/sso")
public class AppMemberSSORest extends WmesBaseRest{
@Autowired
private AppMemberBaseService memberBaseService;
/**
* 登录认证接口
* 地址:service/sso/loginAuth.r
* {"loginCode":"tst001","loginPwd":"123456","fromType":"android"}
*/
@RequestMapping(value = "/loginAuth")
@ResponseBody
public ResultWS loginAuth(HttpServletRequest request,@RequestBody String body){
JSONObject jsonObject = JSONObject.fromObject(body);
ResultWS result = new ResultWS();
result.setData(null);
if(body == null || "".equals(body) || "{}".equals(body)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg(WSConstants.MSG1002);
return result;
}
String loginCode = jsonObject.optString("loginCode","");
String loginPwd = jsonObject.optString("loginPwd","");
String loginType = jsonObject.optString("loginType", "");//1 investor ,2 ifa
//来源web,ios,android
String fromType = jsonObject.optString("fromType","");
String companyCode = jsonObject.optString("companyCode","");
//String fromIp = this.getRemoteHost(request);
if("".equals(loginCode)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“loginCode”"+WSConstants.MSG1002);
return result;
}
if("".equals(loginPwd)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“loginPwd”"+WSConstants.MSG1002);
return result;
}
if("".equals(loginType)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“loginType”"+WSConstants.MSG1002);
return result;
}
if("".equals(fromType)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“fromType”"+WSConstants.MSG1002);
return result;
}
if("".equals(companyCode)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“companyCode”"+WSConstants.MSG1002);
return result;
}
MemberBase memberBase = memberBaseService.checkIfExistsUserByLoginCode(loginCode);
if (memberBase == null){
// result = new ResultWS();
result.setRet(WSConstants.FAIL);
// result.setData(null);
result.setErrorCode(WSConstants.CODE1008);
result.setErrorMsg("“loginCode”"+WSConstants.MSG1008);
return result;
}else{
Integer memberType = memberBase.getMemberType();
if(!loginType.equals(memberType.toString())){
// result = new ResultWS();
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1016);
result.setErrorMsg("“loginType”"+WSConstants.MSG1016);
return result;
}
}
MemberCompany memberCompany = memberBaseService.checkIfValidUserByLoginCode(loginCode);
if (memberCompany == null || (memberCompany != null && !companyCode.equals(memberCompany.getCompany().getCode()))){
// result = new ResultWS();
result.setRet(WSConstants.FAIL);
// result.setData(null);
result.setErrorCode(WSConstants.CODE1015);
result.setErrorMsg("“loginCode”"+WSConstants.MSG1015);
return result;
}
// if(WSConstants.FAIL.equals(result.getRet())){
// return result;
// }
if("ios".equals(fromType) || "android".equals(fromType)){//来源于手机端
String md5password = this.pwdEncoder.encodePassword(loginPwd);
AppMemberSsoVO ssoVO = memberBaseService.saveLoginAuth(request,loginCode,md5password,fromType);
result.setRet(ssoVO.getRet());
result.setErrorCode(ssoVO.getErrorCode());
result.setErrorMsg(ssoVO.getErrorMsg());
result.setData(ssoVO);
return result;
}else{
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“fromType”"+WSConstants.MSG1002);
}
return result;
}
/**
* 设备注册,保存设备的Token
* 调用示例:[地址]/service/sso/setDeviceToken.r
* {"token":"1679091C5A880FAF6FB5E6087EB1B2DC","deviceId":"JPUwJgGqbZRsQD4qw5xyJKnqwpIOKRh","appType":"1"}
*/
@RequestMapping(value = "/setDeviceToken")
@ResponseBody
public ResultWS setDeviceToken(HttpServletRequest request,@RequestBody String body){
JSONObject jsonObject = JSONObject.fromObject(body);
ResultWS result = new ResultWS();
// result.setData(null);
// String checkPowerResult = checkPower(jsonObject);
// if(!checkPowerResult.equals(WSConstants.SUCCESS)){
// result.setRet(WSConstants.FAIL);
// result.setErrorCode(checkPowerResult);
// return result;
// }
String appType = jsonObject.optString("appType","");
String deviceId = jsonObject.optString("deviceId","");
String token = jsonObject.optString("token","");
if("".equals(token) || "".equals(appType) ){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg(WSConstants.MSG1002);
return result;
}
memberBaseService.saveDeviceToken(appType, deviceId, token);
result.setRet(WSConstants.SUCCESS);
result.setErrorCode("");
result.setErrorMsg("");
return result;
}
/**
* 保存设备的Token与帐号的关联
* 调用示例:[地址]/service/sso/setTokenAccount.r
* {"token":"1679091C5A880FAF6FB5E6087EB1B2DC","memberId":"40280ad65601004c0156010188390012","type":"0","appType":"2"}
*/
@RequestMapping(value = "/setTokenAccount")
@ResponseBody
public ResultWS setTokenAccount(HttpServletRequest request,@RequestBody String body){
JSONObject jsonObject = JSONObject.fromObject(body);
ResultWS result = new ResultWS();
// result.setData(null);
// String checkPowerResult = checkPower(jsonObject);
// if(!checkPowerResult.equals(WSConstants.SUCCESS)){
// result.setRet(WSConstants.FAIL);
// result.setErrorCode(checkPowerResult);
// return result;
// }
String memberId = jsonObject.optString("memberId","");
String type = jsonObject.optString("type","");//操作类型 0:保存帐号关联,1:去掉帐号关联
String appType = jsonObject.optString("appType", "");
String deviceId = jsonObject.optString("deviceId", "");
String token = jsonObject.optString("token","");
String aliasType = jsonObject.optString("aliasType","");
String alias = jsonObject.optString("alias","");
if("".equals(token) || "".equals(type) || "".equals(appType) || ("0".equals(type) && "".equals(memberId))){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg(WSConstants.MSG1002);
return result;
}
memberBaseService.saveTokenAccount(memberId, type, appType, deviceId, token, aliasType, alias);
result.setRet(WSConstants.SUCCESS);
result.setErrorCode("");
result.setErrorMsg("");
return result;
}
}
| UTF-8 | Java | 7,557 | java | AppMemberSSORest.java | Java | [
{
"context": ".entity.MemberCompany;\n\n/***\n * sso认证接口\n * @author mjhuang\n * @date 2016-6-20\n */\n@RestController\n@RequestMa",
"end": 789,
"score": 0.9996792674064636,
"start": 782,
"tag": "USERNAME",
"value": "mjhuang"
},
{
"context": "loginAuth.r\n\t * {\"loginCode\":\"tst001\",\"loginPwd\":\"123456\",\"fromType\":\"android\"}\n\t */\n\t@RequestMapping(valu",
"end": 1069,
"score": 0.9992267489433289,
"start": 1063,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "例:[地址]/service/sso/setDeviceToken.r\n\t * {\"token\":\"1679091C5A880FAF6FB5E6087EB1B2DC\",\"deviceId\":\"JPUwJgGqbZRsQD4qw5xyJKnqwpIOKRh\",\"ap",
"end": 4740,
"score": 0.7690474390983582,
"start": 4708,
"tag": "KEY",
"value": "1679091C5A880FAF6FB5E6087EB1B2DC"
},
{
"context": "n\":\"1679091C5A880FAF6FB5E6087EB1B2DC\",\"deviceId\":\"JPUwJgGqbZRsQD4qw5xyJKnqwpIOKRh\",\"appType\":\"1\"}\n\t */\n\t@RequestMapping(value = \"/s",
"end": 4785,
"score": 0.8155221343040466,
"start": 4754,
"tag": "KEY",
"value": "JPUwJgGqbZRsQD4qw5xyJKnqwpIOKRh"
},
{
"context": ":[地址]/service/sso/setTokenAccount.r\n\t * {\"token\":\"1679091C5A880FAF6FB5E6087EB1B2DC\",\"memberId\":\"40280ad65601004c0156010188390012\",\"t",
"end": 5937,
"score": 0.9941886067390442,
"start": 5905,
"tag": "KEY",
"value": "1679091C5A880FAF6FB5E6087EB1B2DC"
},
{
"context": "n\":\"1679091C5A880FAF6FB5E6087EB1B2DC\",\"memberId\":\"40280ad65601004c0156010188390012\",\"type\":\"0\",\"appType\":\"2\"}\n\t */\n\t@Request",
"end": 5975,
"score": 0.6420432925224304,
"start": 5951,
"tag": "KEY",
"value": "40280ad65601004c01560101"
},
{
"context": "87EB1B2DC\",\"memberId\":\"40280ad65601004c0156010188390012\",\"type\":\"0\",\"appType\":\"2\"}\n\t */\n\t@RequestMapping(",
"end": 5983,
"score": 0.5948120951652527,
"start": 5978,
"tag": "KEY",
"value": "90012"
}
]
| null | []
| package com.fsll.app.member.ws;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fsll.app.member.service.AppMemberBaseService;
import com.fsll.app.member.vo.AppMemberSsoVO;
import com.fsll.common.CommonConstants;
import com.fsll.core.ResultWS;
import com.fsll.core.WSConstants;
import com.fsll.wmes.base.WmesBaseRest;
import com.fsll.wmes.entity.MemberBase;
import com.fsll.wmes.entity.MemberCompany;
/***
* sso认证接口
* @author mjhuang
* @date 2016-6-20
*/
@RestController
@RequestMapping("/service/sso")
public class AppMemberSSORest extends WmesBaseRest{
@Autowired
private AppMemberBaseService memberBaseService;
/**
* 登录认证接口
* 地址:service/sso/loginAuth.r
* {"loginCode":"tst001","loginPwd":"<PASSWORD>","fromType":"android"}
*/
@RequestMapping(value = "/loginAuth")
@ResponseBody
public ResultWS loginAuth(HttpServletRequest request,@RequestBody String body){
JSONObject jsonObject = JSONObject.fromObject(body);
ResultWS result = new ResultWS();
result.setData(null);
if(body == null || "".equals(body) || "{}".equals(body)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg(WSConstants.MSG1002);
return result;
}
String loginCode = jsonObject.optString("loginCode","");
String loginPwd = jsonObject.optString("loginPwd","");
String loginType = jsonObject.optString("loginType", "");//1 investor ,2 ifa
//来源web,ios,android
String fromType = jsonObject.optString("fromType","");
String companyCode = jsonObject.optString("companyCode","");
//String fromIp = this.getRemoteHost(request);
if("".equals(loginCode)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“loginCode”"+WSConstants.MSG1002);
return result;
}
if("".equals(loginPwd)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“loginPwd”"+WSConstants.MSG1002);
return result;
}
if("".equals(loginType)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“loginType”"+WSConstants.MSG1002);
return result;
}
if("".equals(fromType)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“fromType”"+WSConstants.MSG1002);
return result;
}
if("".equals(companyCode)){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“companyCode”"+WSConstants.MSG1002);
return result;
}
MemberBase memberBase = memberBaseService.checkIfExistsUserByLoginCode(loginCode);
if (memberBase == null){
// result = new ResultWS();
result.setRet(WSConstants.FAIL);
// result.setData(null);
result.setErrorCode(WSConstants.CODE1008);
result.setErrorMsg("“loginCode”"+WSConstants.MSG1008);
return result;
}else{
Integer memberType = memberBase.getMemberType();
if(!loginType.equals(memberType.toString())){
// result = new ResultWS();
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1016);
result.setErrorMsg("“loginType”"+WSConstants.MSG1016);
return result;
}
}
MemberCompany memberCompany = memberBaseService.checkIfValidUserByLoginCode(loginCode);
if (memberCompany == null || (memberCompany != null && !companyCode.equals(memberCompany.getCompany().getCode()))){
// result = new ResultWS();
result.setRet(WSConstants.FAIL);
// result.setData(null);
result.setErrorCode(WSConstants.CODE1015);
result.setErrorMsg("“loginCode”"+WSConstants.MSG1015);
return result;
}
// if(WSConstants.FAIL.equals(result.getRet())){
// return result;
// }
if("ios".equals(fromType) || "android".equals(fromType)){//来源于手机端
String md5password = this.pwdEncoder.encodePassword(loginPwd);
AppMemberSsoVO ssoVO = memberBaseService.saveLoginAuth(request,loginCode,md5password,fromType);
result.setRet(ssoVO.getRet());
result.setErrorCode(ssoVO.getErrorCode());
result.setErrorMsg(ssoVO.getErrorMsg());
result.setData(ssoVO);
return result;
}else{
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg("“fromType”"+WSConstants.MSG1002);
}
return result;
}
/**
* 设备注册,保存设备的Token
* 调用示例:[地址]/service/sso/setDeviceToken.r
* {"token":"1679091C5A880FAF6FB5E6087EB1B2DC","deviceId":"<KEY>","appType":"1"}
*/
@RequestMapping(value = "/setDeviceToken")
@ResponseBody
public ResultWS setDeviceToken(HttpServletRequest request,@RequestBody String body){
JSONObject jsonObject = JSONObject.fromObject(body);
ResultWS result = new ResultWS();
// result.setData(null);
// String checkPowerResult = checkPower(jsonObject);
// if(!checkPowerResult.equals(WSConstants.SUCCESS)){
// result.setRet(WSConstants.FAIL);
// result.setErrorCode(checkPowerResult);
// return result;
// }
String appType = jsonObject.optString("appType","");
String deviceId = jsonObject.optString("deviceId","");
String token = jsonObject.optString("token","");
if("".equals(token) || "".equals(appType) ){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg(WSConstants.MSG1002);
return result;
}
memberBaseService.saveDeviceToken(appType, deviceId, token);
result.setRet(WSConstants.SUCCESS);
result.setErrorCode("");
result.setErrorMsg("");
return result;
}
/**
* 保存设备的Token与帐号的关联
* 调用示例:[地址]/service/sso/setTokenAccount.r
* {"token":"1679091C5A880FAF6FB5E6087EB1B2DC","memberId":"40280ad65601004c0156010188390012","type":"0","appType":"2"}
*/
@RequestMapping(value = "/setTokenAccount")
@ResponseBody
public ResultWS setTokenAccount(HttpServletRequest request,@RequestBody String body){
JSONObject jsonObject = JSONObject.fromObject(body);
ResultWS result = new ResultWS();
// result.setData(null);
// String checkPowerResult = checkPower(jsonObject);
// if(!checkPowerResult.equals(WSConstants.SUCCESS)){
// result.setRet(WSConstants.FAIL);
// result.setErrorCode(checkPowerResult);
// return result;
// }
String memberId = jsonObject.optString("memberId","");
String type = jsonObject.optString("type","");//操作类型 0:保存帐号关联,1:去掉帐号关联
String appType = jsonObject.optString("appType", "");
String deviceId = jsonObject.optString("deviceId", "");
String token = jsonObject.optString("token","");
String aliasType = jsonObject.optString("aliasType","");
String alias = jsonObject.optString("alias","");
if("".equals(token) || "".equals(type) || "".equals(appType) || ("0".equals(type) && "".equals(memberId))){
result.setRet(WSConstants.FAIL);
result.setErrorCode(WSConstants.CODE1002);
result.setErrorMsg(WSConstants.MSG1002);
return result;
}
memberBaseService.saveTokenAccount(memberId, type, appType, deviceId, token, aliasType, alias);
result.setRet(WSConstants.SUCCESS);
result.setErrorCode("");
result.setErrorMsg("");
return result;
}
}
| 7,535 | 0.733767 | 0.707876 | 210 | 34.128571 | 24.978041 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.761905 | false | false | 3 |
a11926d5f42fcd987c88e8819547aff07e955fe7 | 4,604,204,990,126 | 6ea5d310885165e1d301fee91e7114499f24fad2 | /client/src/com/mercuryirc/client/ui/ApplicationPane.java | c6f950a8afc69e2903aebbdfb9484b5231fc0a8a | []
| no_license | AnnoLuigi/Eridium | https://github.com/AnnoLuigi/Eridium | 04fd5b260c983aa97588eb7cbb91714e3314fb84 | e8a89e5cc9779062ad2cba69b2475341db15be67 | refs/heads/master | 2021-01-22T16:18:15.663000 | 2015-05-23T10:55:57 | 2015-05-23T10:55:57 | 36,118,950 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mercuryirc.client.ui;
import com.mercuryirc.client.Mercury;
import javafx.event.EventHandler;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
public class ApplicationPane extends HBox {
private final TabPane tabPane;
private final VBox contentPaneContainer;
private ContentPane contentPane;
public ApplicationPane() {
getStylesheets().add(Mercury.class.getResource("/res/css/ApplicationPane.css").toExternalForm());
VBox.setVgrow(this, Priority.ALWAYS);
HBox.setHgrow(this, Priority.ALWAYS);
contentPaneContainer = new VBox();
VBox.setVgrow(contentPaneContainer, Priority.ALWAYS);
HBox.setHgrow(contentPaneContainer, Priority.ALWAYS);
VBox vbox = new VBox();
VBox.setVgrow(vbox, Priority.ALWAYS);
HBox.setHgrow(vbox, Priority.ALWAYS);
vbox.getStyleClass().add("dark-pane");
contentPaneContainer.getChildren().setAll(vbox);
getChildren().addAll(tabPane = new TabPane(this), contentPaneContainer);
setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
if (keyEvent.isControlDown()) {
switch (keyEvent.getCode()) {
case W:
tabPane.close(tabPane.getSelected());
break;
case TAB:
if (keyEvent.isShiftDown()) {
tabPane.selectPrevious();
} else {
tabPane.selectNext();
}
break;
}
}
}
});
}
public TabPane getTabPane() {
return tabPane;
}
public ContentPane getContentPane() {
return contentPane;
}
public void setContentPane(ContentPane contentPane) {
this.contentPane = contentPane;
if (contentPane == null) {
contentPaneContainer.getChildren().clear();
} else {
contentPaneContainer.getChildren().setAll(contentPane);
}
}
} | UTF-8 | Java | 1,826 | java | ApplicationPane.java | Java | []
| null | []
| package com.mercuryirc.client.ui;
import com.mercuryirc.client.Mercury;
import javafx.event.EventHandler;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
public class ApplicationPane extends HBox {
private final TabPane tabPane;
private final VBox contentPaneContainer;
private ContentPane contentPane;
public ApplicationPane() {
getStylesheets().add(Mercury.class.getResource("/res/css/ApplicationPane.css").toExternalForm());
VBox.setVgrow(this, Priority.ALWAYS);
HBox.setHgrow(this, Priority.ALWAYS);
contentPaneContainer = new VBox();
VBox.setVgrow(contentPaneContainer, Priority.ALWAYS);
HBox.setHgrow(contentPaneContainer, Priority.ALWAYS);
VBox vbox = new VBox();
VBox.setVgrow(vbox, Priority.ALWAYS);
HBox.setHgrow(vbox, Priority.ALWAYS);
vbox.getStyleClass().add("dark-pane");
contentPaneContainer.getChildren().setAll(vbox);
getChildren().addAll(tabPane = new TabPane(this), contentPaneContainer);
setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
if (keyEvent.isControlDown()) {
switch (keyEvent.getCode()) {
case W:
tabPane.close(tabPane.getSelected());
break;
case TAB:
if (keyEvent.isShiftDown()) {
tabPane.selectPrevious();
} else {
tabPane.selectNext();
}
break;
}
}
}
});
}
public TabPane getTabPane() {
return tabPane;
}
public ContentPane getContentPane() {
return contentPane;
}
public void setContentPane(ContentPane contentPane) {
this.contentPane = contentPane;
if (contentPane == null) {
contentPaneContainer.getChildren().clear();
} else {
contentPaneContainer.getChildren().setAll(contentPane);
}
}
} | 1,826 | 0.717415 | 0.717415 | 67 | 26.268656 | 20.432329 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.895522 | false | false | 3 |
224e04bd609b30055763fda3075bb12601413246 | 35,820,027,266,454 | 5d086f856103b45e7f42b97b2a24d790d87c215d | /src/main/java/com/joaopedro/ecommerce/checkout/resource/checkout/CheckoutResource.java | 8811d82212b81641ae9449320b615bdecaa6f49f | []
| no_license | JoaoPedroXD/ecommerce_checkout | https://github.com/JoaoPedroXD/ecommerce_checkout | e74ee81511bb2c5e0e79c0f7fc87f1db5c7a4f9b | e3e431bcb1a858723191cdfb5b534665c39f11cf | refs/heads/master | 2023-03-07T11:53:42.995000 | 2021-02-17T01:40:33 | 2021-02-17T01:40:33 | 339,580,841 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.joaopedro.ecommerce.checkout.resource.checkout;
import com.joaopedro.ecommerce.checkout.entity.CheckoutEntity;
import com.joaopedro.ecommerce.checkout.service.CheckoutService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/v1/checkout")
@RequiredArgsConstructor
public class CheckoutResource {
private final CheckoutService checkoutService;
@PostMapping("/")
//Inicia o Checkout
public ResponseEntity<CheckoutResponse> create(CheckoutRequest checkoutRequest) {
//Define e recupera uma Entidade de Checkout, caso o contrário, dispara uma exceção
final CheckoutEntity checkoutEntity = checkoutService.create(checkoutRequest).orElseThrow();
//Define a resposta do Checkout
final CheckoutResponse checkoutResponse = CheckoutResponse.builder()
.code(checkoutEntity.getCode()) //Informa o código
.build();
//Retorna a situação do Checkout
return ResponseEntity.status(HttpStatus.CREATED).body(checkoutResponse);
}
}
| UTF-8 | Java | 1,335 | java | CheckoutResource.java | Java | []
| null | []
| package com.joaopedro.ecommerce.checkout.resource.checkout;
import com.joaopedro.ecommerce.checkout.entity.CheckoutEntity;
import com.joaopedro.ecommerce.checkout.service.CheckoutService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/v1/checkout")
@RequiredArgsConstructor
public class CheckoutResource {
private final CheckoutService checkoutService;
@PostMapping("/")
//Inicia o Checkout
public ResponseEntity<CheckoutResponse> create(CheckoutRequest checkoutRequest) {
//Define e recupera uma Entidade de Checkout, caso o contrário, dispara uma exceção
final CheckoutEntity checkoutEntity = checkoutService.create(checkoutRequest).orElseThrow();
//Define a resposta do Checkout
final CheckoutResponse checkoutResponse = CheckoutResponse.builder()
.code(checkoutEntity.getCode()) //Informa o código
.build();
//Retorna a situação do Checkout
return ResponseEntity.status(HttpStatus.CREATED).body(checkoutResponse);
}
}
| 1,335 | 0.778029 | 0.777276 | 30 | 43.299999 | 28.19474 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
5d807669dcd4eae65f6330725b7ddc13c63375f1 | 33,852,932,260,626 | 3cfdb3e954f98839215bd335b31bd772d731d550 | /app/src/main/java/dk/dtu/philipsclockradio/StateAlarmSet.java | 273f8431169455cb40f353052a7f6233f59234fe | []
| no_license | david-fager/02369_clockradio | https://github.com/david-fager/02369_clockradio | bd0d8a10eb76d01d2e304ae3061551b3c8424998 | 62b14220924ba5c7072402100d643df1b1440287 | refs/heads/master | 2022-11-04T23:26:06.807000 | 2020-07-07T19:09:03 | 2020-07-07T19:09:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dk.dtu.philipsclockradio;
import java.util.Calendar;
import java.util.Date;
public class StateAlarmSet extends StateAdapter {
private Calendar calendar = Calendar.getInstance();
private Date alarmTime;
private String[] savedStations;
private int alarmType = 0; // 0 is muted, 1 is radio, 2 is buzzer
public StateAlarmSet(String[] savedStations, int alarmType) {
if (savedStations != null) {
this.savedStations = savedStations;
}
this.alarmType = alarmType;
}
@Override
public void onEnterState(ContextClockradio context) {
calendar.setTime(context.getTime());
alarmTime = calendar.getTime();
System.out.println("Alarm time: " + alarmTime);
System.out.println("Actual time: " + context.getTime());
context.ui.turnOnTextBlink();
}
@Override
public void onClick_Hour(ContextClockradio context) {
alarmTime.setTime(alarmTime.getTime() + 3600000);
System.out.println("Alarm time: " + alarmTime);
System.out.println("Actual time: " + context.getTime());
context.ui.setDisplayText(alarmTime.toString().substring(11,16));
}
@Override
public void onClick_Min(ContextClockradio context) {
alarmTime.setTime(alarmTime.getTime() + 60000);
System.out.println("Alarm time: " + alarmTime);
System.out.println("Actual time: " + context.getTime());
context.ui.setDisplayText(alarmTime.toString().substring(11,16));
}
@Override
public void onClick_AL1(ContextClockradio context) {
context.setState(new StateStandby(context.getTime(), alarmTime, savedStations, alarmType));
}
@Override
public void onClick_AL2(ContextClockradio context) {
context.setState(new StateStandby(context.getTime(), alarmTime, savedStations, alarmType));
}
@Override
public void onExitState(ContextClockradio context) {
context.ui.turnOffTextBlink();
}
}
| UTF-8 | Java | 1,992 | java | StateAlarmSet.java | Java | []
| null | []
| package dk.dtu.philipsclockradio;
import java.util.Calendar;
import java.util.Date;
public class StateAlarmSet extends StateAdapter {
private Calendar calendar = Calendar.getInstance();
private Date alarmTime;
private String[] savedStations;
private int alarmType = 0; // 0 is muted, 1 is radio, 2 is buzzer
public StateAlarmSet(String[] savedStations, int alarmType) {
if (savedStations != null) {
this.savedStations = savedStations;
}
this.alarmType = alarmType;
}
@Override
public void onEnterState(ContextClockradio context) {
calendar.setTime(context.getTime());
alarmTime = calendar.getTime();
System.out.println("Alarm time: " + alarmTime);
System.out.println("Actual time: " + context.getTime());
context.ui.turnOnTextBlink();
}
@Override
public void onClick_Hour(ContextClockradio context) {
alarmTime.setTime(alarmTime.getTime() + 3600000);
System.out.println("Alarm time: " + alarmTime);
System.out.println("Actual time: " + context.getTime());
context.ui.setDisplayText(alarmTime.toString().substring(11,16));
}
@Override
public void onClick_Min(ContextClockradio context) {
alarmTime.setTime(alarmTime.getTime() + 60000);
System.out.println("Alarm time: " + alarmTime);
System.out.println("Actual time: " + context.getTime());
context.ui.setDisplayText(alarmTime.toString().substring(11,16));
}
@Override
public void onClick_AL1(ContextClockradio context) {
context.setState(new StateStandby(context.getTime(), alarmTime, savedStations, alarmType));
}
@Override
public void onClick_AL2(ContextClockradio context) {
context.setState(new StateStandby(context.getTime(), alarmTime, savedStations, alarmType));
}
@Override
public void onExitState(ContextClockradio context) {
context.ui.turnOffTextBlink();
}
}
| 1,992 | 0.671687 | 0.658635 | 61 | 31.655737 | 27.668343 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590164 | false | false | 3 |
4f605f5c2cc640edddd2793e94ea4dbe0a230efa | 36,490,042,155,865 | 95d76ddd0830666af060b28bdeacf1d62e6909bd | /Spring_Boot_Bank_Application/src/main/java/com/main/Repository/AccountRepo.java | ff2f6c8151767b6f7198ba8d082b41106baa3247 | []
| no_license | Inbasekar/new | https://github.com/Inbasekar/new | b33bad31ae44d9b2597d4484c0b9e7396422523f | 57fcba723e09348153a7ea46c297bbdae292337e | refs/heads/master | 2020-05-09T04:25:38.715000 | 2019-04-12T10:31:19 | 2019-04-12T10:31:19 | 180,984,678 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.main.Repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.main.model.Account;
public interface AccountRepo extends CrudRepository<Account,Integer>{
@Query(value="select * from account t where uid=?1 and t.actype=?2",nativeQuery=true)
Account findByActype(int id, String string);
}
| UTF-8 | Java | 392 | java | AccountRepo.java | Java | []
| null | []
| package com.main.Repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.main.model.Account;
public interface AccountRepo extends CrudRepository<Account,Integer>{
@Query(value="select * from account t where uid=?1 and t.actype=?2",nativeQuery=true)
Account findByActype(int id, String string);
}
| 392 | 0.783163 | 0.778061 | 11 | 33.636364 | 29.533564 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909091 | false | false | 3 |
9d4f04e34f677792f43ec606cd68cfee8d15c0f0 | 36,490,042,157,322 | d22c7d97f54cf6bd526b063e11c066f7f0ab6105 | /src/com/mumoki/saveapp/Splash.java | c6df9085b29373229bea78bc7c8d8089d5b0d468 | []
| no_license | GeekNchic/Save-App | https://github.com/GeekNchic/Save-App | 7d5bc3d4511b430e18341dd829b528e3a0e2b43d | 83ee64c6a9e0237552344017e4bcd9e50d857f58 | refs/heads/master | 2021-01-18T15:24:34.532000 | 2014-09-16T08:26:52 | 2014-09-16T08:26:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mumoki.saveapp;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
public class Splash extends Activity {
private int displayTime = 4000;
/** Called when the activity is first created. */
/** Native methods, implemented in jni folder */
public static native void createEngine();
public static native void createBufferQueueAudioPlayer();
public static native boolean createAssetAudioPlayer(AssetManager assetManager, String filename);
//true == PLAYING, false == PAUSED
public static native void setPlayingAssetAudioPlayer(boolean isPlaying);
public static native void setPlayingUriAudioPlayer(boolean isPlaying);
public static native void setMuteUriAudioPlayer(boolean mute);
public static native void shutdown();
private boolean isPlayingAsset = false;
private AssetManager assetManager;
/** Load jni .so on initialization */
static {
System.loadLibrary("native-audio-jni");
}
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
assetManager = getAssets();
createEngine();
createBufferQueueAudioPlayer();
boolean created = false;
if (!created) {
created = createAssetAudioPlayer(assetManager, "pacman.mp3");
}
if (created) {
isPlayingAsset = !isPlayingAsset;
setPlayingAssetAudioPlayer(isPlayingAsset);
}
TextView brand = (TextView)findViewById(R.id.tvBrand);
Typeface copper = Typeface.createFromAsset(getAssets(), "fonts/fayet.otf");
brand.setTypeface(copper);
brand.setTextColor(Color.DKGRAY);
Thread splashThread = new Thread(){
int wait = 0;
@Override
public void run(){
try{
super.run();
while(wait<displayTime){
sleep(100);
wait += 100;
}
}catch(Exception e){}
finally{
//Intent intent = new Intent(splashActivity.this,toutMain.class);
Intent intent = new Intent(Splash.this, MainMenu.class);
startActivity(intent);
shutdown();
finish();
}
}
};
splashThread.start();
}
}
| UTF-8 | Java | 2,597 | java | Splash.java | Java | []
| null | []
| package com.mumoki.saveapp;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
public class Splash extends Activity {
private int displayTime = 4000;
/** Called when the activity is first created. */
/** Native methods, implemented in jni folder */
public static native void createEngine();
public static native void createBufferQueueAudioPlayer();
public static native boolean createAssetAudioPlayer(AssetManager assetManager, String filename);
//true == PLAYING, false == PAUSED
public static native void setPlayingAssetAudioPlayer(boolean isPlaying);
public static native void setPlayingUriAudioPlayer(boolean isPlaying);
public static native void setMuteUriAudioPlayer(boolean mute);
public static native void shutdown();
private boolean isPlayingAsset = false;
private AssetManager assetManager;
/** Load jni .so on initialization */
static {
System.loadLibrary("native-audio-jni");
}
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
assetManager = getAssets();
createEngine();
createBufferQueueAudioPlayer();
boolean created = false;
if (!created) {
created = createAssetAudioPlayer(assetManager, "pacman.mp3");
}
if (created) {
isPlayingAsset = !isPlayingAsset;
setPlayingAssetAudioPlayer(isPlayingAsset);
}
TextView brand = (TextView)findViewById(R.id.tvBrand);
Typeface copper = Typeface.createFromAsset(getAssets(), "fonts/fayet.otf");
brand.setTypeface(copper);
brand.setTextColor(Color.DKGRAY);
Thread splashThread = new Thread(){
int wait = 0;
@Override
public void run(){
try{
super.run();
while(wait<displayTime){
sleep(100);
wait += 100;
}
}catch(Exception e){}
finally{
//Intent intent = new Intent(splashActivity.this,toutMain.class);
Intent intent = new Intent(Splash.this, MainMenu.class);
startActivity(intent);
shutdown();
finish();
}
}
};
splashThread.start();
}
}
| 2,597 | 0.658837 | 0.654216 | 89 | 28.179775 | 22.256706 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.044944 | false | false | 3 |
3dd0244070fcf98dafa241783f2ee9d9630016cd | 36,283,883,737,968 | d5b8d4573acfbe7072f53aa01653b25f85428181 | /app/src/main/java/chessbet/adapter/MenuOptionsAdapter.java | c7ecbb6c985d37d55fc7ddbed85f348c270c7568 | []
| no_license | iconic-king/chess-bet | https://github.com/iconic-king/chess-bet | fb4f907dc653ff347af61cf25ab6dfc1faef6e52 | c94268353bf4d1c9da22686d510e9526c9badd54 | refs/heads/master | 2023-01-03T05:37:50.570000 | 2020-09-20T07:29:34 | 2020-09-20T07:29:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chessbet.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import chessbet.app.com.BoardActivity;
import chessbet.app.com.PlayComputerSettingsActivity;
import chessbet.app.com.PresenceActivity;
import chessbet.app.com.R;
import chessbet.app.com.tournament.TournamentActivity;
import chessbet.domain.MatchType;
public class MenuOptionsAdapter extends BaseAdapter {
private List<View.OnClickListener> listeners;
private Context context;
private List<Integer> drawables;
private List<String> strings;
public MenuOptionsAdapter(Context context){
listeners=new ArrayList<>();
drawables=new ArrayList<>();
strings=new ArrayList<>();
this.context = context;
// Two Player
listeners.add(v -> {
Intent intent=new Intent(context, BoardActivity.class);
intent.putExtra("match_type", MatchType.TWO_PLAYER.toString());
context.startActivity(intent);
});
drawables.add(R.drawable.two_player);
strings.add("Two Player");
// Single Player
listeners.add(v -> {
Intent intent=new Intent(context, PlayComputerSettingsActivity.class);
intent.putExtra("match_type", MatchType.TWO_PLAYER.toString());
context.startActivity(intent);
});
drawables.add(R.drawable.desktop);
strings.add("Single Player");
// Watch Game
listeners.add(view -> Toast.makeText(context, context.getResources().getString(R.string.feature_unavailable), Toast.LENGTH_LONG).show());
drawables.add(R.drawable.eye);
strings.add("Watch");
// Online users
listeners.add(view -> {
Intent intent = new Intent(context, PresenceActivity.class);
context.startActivity(intent);
});
drawables.add(R.drawable.wifi_four_bar);
strings.add(context.getResources().getString(R.string.online_users));
// // Tournaments
// listeners.add(view -> {
// Intent intent = new Intent(context, TournamentActivity.class);
// context.startActivity(intent);
// });
// drawables.add(R.drawable.tournaments);
// strings.add(context.getResources().getString(R.string.tournaments));
}
@Override
public int getCount() {
return listeners.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater menuInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridMenu;
if(convertView == null){
gridMenu = menuInflater.inflate(R.layout.menu_view,null);
ImageView imgMenu = gridMenu.findViewById(R.id.imgMenu);
TextView txtMenu = gridMenu.findViewById(R.id.txtMenu);
imgMenu.setImageResource(drawables.get(position));
txtMenu.setText(strings.get(position));
gridMenu.setOnClickListener(listeners.get(position));
}
else {
gridMenu = convertView;
}
return gridMenu;
}
}
| UTF-8 | Java | 3,581 | java | MenuOptionsAdapter.java | Java | []
| null | []
| package chessbet.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import chessbet.app.com.BoardActivity;
import chessbet.app.com.PlayComputerSettingsActivity;
import chessbet.app.com.PresenceActivity;
import chessbet.app.com.R;
import chessbet.app.com.tournament.TournamentActivity;
import chessbet.domain.MatchType;
public class MenuOptionsAdapter extends BaseAdapter {
private List<View.OnClickListener> listeners;
private Context context;
private List<Integer> drawables;
private List<String> strings;
public MenuOptionsAdapter(Context context){
listeners=new ArrayList<>();
drawables=new ArrayList<>();
strings=new ArrayList<>();
this.context = context;
// Two Player
listeners.add(v -> {
Intent intent=new Intent(context, BoardActivity.class);
intent.putExtra("match_type", MatchType.TWO_PLAYER.toString());
context.startActivity(intent);
});
drawables.add(R.drawable.two_player);
strings.add("Two Player");
// Single Player
listeners.add(v -> {
Intent intent=new Intent(context, PlayComputerSettingsActivity.class);
intent.putExtra("match_type", MatchType.TWO_PLAYER.toString());
context.startActivity(intent);
});
drawables.add(R.drawable.desktop);
strings.add("Single Player");
// Watch Game
listeners.add(view -> Toast.makeText(context, context.getResources().getString(R.string.feature_unavailable), Toast.LENGTH_LONG).show());
drawables.add(R.drawable.eye);
strings.add("Watch");
// Online users
listeners.add(view -> {
Intent intent = new Intent(context, PresenceActivity.class);
context.startActivity(intent);
});
drawables.add(R.drawable.wifi_four_bar);
strings.add(context.getResources().getString(R.string.online_users));
// // Tournaments
// listeners.add(view -> {
// Intent intent = new Intent(context, TournamentActivity.class);
// context.startActivity(intent);
// });
// drawables.add(R.drawable.tournaments);
// strings.add(context.getResources().getString(R.string.tournaments));
}
@Override
public int getCount() {
return listeners.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater menuInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridMenu;
if(convertView == null){
gridMenu = menuInflater.inflate(R.layout.menu_view,null);
ImageView imgMenu = gridMenu.findViewById(R.id.imgMenu);
TextView txtMenu = gridMenu.findViewById(R.id.txtMenu);
imgMenu.setImageResource(drawables.get(position));
txtMenu.setText(strings.get(position));
gridMenu.setOnClickListener(listeners.get(position));
}
else {
gridMenu = convertView;
}
return gridMenu;
}
}
| 3,581 | 0.657917 | 0.657638 | 110 | 31.554546 | 26.077711 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681818 | false | false | 3 |
99db03d286cb2b13bf170bc54b0ff86b482bbd3c | 37,933,151,161,204 | a45d077ab84409c7fc80d05ed0f55542d86ca6e6 | /app/src/main/java/com/moran/spiceitapp/ui/myRecipes/EditRecipeFragment.java | 6d35cf13f2f008239e350c9ba331271247f57791 | []
| no_license | barzilaymoran/SpiceItApp | https://github.com/barzilaymoran/SpiceItApp | fc1558c571aac50d6404d3963419f382f5a63ea1 | 036c03032b698db70d1cdbf1e2ac42a8883f1f27 | refs/heads/master | 2022-12-14T03:01:24.940000 | 2020-09-20T19:13:54 | 2020-09-20T19:13:54 | 297,129,891 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.moran.spiceitapp.ui.myRecipes;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.moran.spiceitapp.MyApplication;
import com.moran.spiceitapp.R;
import com.moran.spiceitapp.model.Model;
import com.moran.spiceitapp.model.Recipe;
import com.moran.spiceitapp.model.StorageFirebase;
import com.moran.spiceitapp.model.User;
import com.moran.spiceitapp.ui.home.RecipeDetailsFragmentArgs;
import com.moran.spiceitapp.ui.profile.EditProfileViewModel;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import static android.app.Activity.RESULT_OK;
public class EditRecipeFragment extends Fragment {
private EditRecipeViewModel editRecipeViewModel;
Recipe recipe = new Recipe ();
EditText title_editText, ingredients_editText, instructions_editText;
ImageView photo_imageView;
View saveBtn, uploadPhotoBtn;
Bitmap imageBitmap;
String imageUrl;
ProgressBar progressBar;
Boolean isPhotoUploaded;
public static EditRecipeFragment newInstance() {
return new EditRecipeFragment();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
editRecipeViewModel = ViewModelProviders.of(this).get(EditRecipeViewModel.class);
final View root = inflater.inflate(R.layout.fragment_edit_recipe, container, false);
title_editText = root.findViewById(R.id.editRecipe_title_textInputEditText);
ingredients_editText = root.findViewById(R.id.editRecipe_ingredients_editView);
instructions_editText = root.findViewById(R.id.editRecipe_instructions_editView);
photo_imageView = root.findViewById(R.id.editRecipe_photo_imageView);
saveBtn = root.findViewById(R.id.editRecipe_save_btn);
uploadPhotoBtn = root.findViewById(R.id.editRecipe_photo_btn);
progressBar = root.findViewById(R.id.editRecipe_progressBar);
isPhotoUploaded = false;
assert getArguments() != null;
recipe = RecipeDetailsFragmentArgs.fromBundle(getArguments()).getRecipe();
setRecipeLayout(recipe);
//upload photo
uploadPhotoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadPhoto();
}
});
//save changes
saveBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(final View v) {
saveChanges(v);
}
});
return root;
}
public void setRecipeLayout(Recipe recipe){
title_editText.setText(recipe.getTitle());
ingredients_editText.setText(recipe.getIngredients());
instructions_editText.setText(recipe.getInstructions());
if(recipe.getImageUrl() != null && !(recipe.getImageUrl().equals("")))
Picasso.get().load(recipe.getImageUrl()).placeholder(R.drawable.blank_icon).into(photo_imageView);
else
photo_imageView.setImageResource(R.drawable.ic_menu_camera);
}
@Override
public void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
saveBtn.setEnabled(true);
}
public void saveChanges(final View v){
final String id = recipe.getId();
final String title = title_editText.getText().toString();
final String ingredients = ingredients_editText.getText().toString();
final String instructions = instructions_editText.getText().toString();
final String creatorName = recipe.getCreatorName();
final String creatorEmail = recipe.getCreatorEmail();
if (TextUtils.isEmpty(title)) {
title_editText.setError("Title is Required");
return;
}
if (TextUtils.isEmpty(ingredients)) {
ingredients_editText.setError("Ingredients are Required");
return;
}
if (TextUtils.isEmpty(instructions)) {
instructions_editText.setError("Instructions are Required");
return;
}
progressBar.setVisibility(View.VISIBLE);
saveBtn.setEnabled(false);
if (isPhotoUploaded) {
Date date = new Date();
StorageFirebase.uploadImage(imageBitmap, "photo_" + date.getTime(), new StorageFirebase.Listener() {
@Override
public void onSuccess(String url) {
imageUrl = url;
Recipe updatedRecipe = new Recipe(title, ingredients, instructions, imageUrl, creatorName, creatorEmail);
updatedRecipe.setId(id);
editRecipeViewModel.updateData(updatedRecipe).observe(getViewLifecycleOwner(), new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean)
Navigation.findNavController(v).popBackStack(R.id.nav_myRecipes, false); //back to details
else
Toast.makeText(getActivity(), "Could not update recipe.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onFail() {
}
});
}
else {
imageUrl = recipe.getImageUrl();
Recipe updatedRecipe = new Recipe(title, ingredients, instructions, imageUrl, creatorName, creatorEmail);
updatedRecipe.setId(id);
editRecipeViewModel.updateData(updatedRecipe).observe(getViewLifecycleOwner(), new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean)
Navigation.findNavController(v).popBackStack(R.id.nav_myRecipes, false); //back to details
else
Toast.makeText(getActivity(), "Could not update recipe.", Toast.LENGTH_SHORT).show();
}
});
}
}
/*********** PHOTO ***********/
static final int REQUEST_PICK_IMAGE = 1;
void uploadPhoto(){
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (pickPhoto.resolveActivity(requireActivity().getPackageManager()) != null) {
startActivityForResult(pickPhoto, REQUEST_PICK_IMAGE);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { //on return from gallery
if (requestCode == REQUEST_PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null) {
isPhotoUploaded =true;
try {
imageBitmap = MediaStore.Images.Media.getBitmap(MyApplication.context.getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
photo_imageView.setImageBitmap(imageBitmap);
}
}
} | UTF-8 | Java | 7,787 | java | EditRecipeFragment.java | Java | []
| null | []
| package com.moran.spiceitapp.ui.myRecipes;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.moran.spiceitapp.MyApplication;
import com.moran.spiceitapp.R;
import com.moran.spiceitapp.model.Model;
import com.moran.spiceitapp.model.Recipe;
import com.moran.spiceitapp.model.StorageFirebase;
import com.moran.spiceitapp.model.User;
import com.moran.spiceitapp.ui.home.RecipeDetailsFragmentArgs;
import com.moran.spiceitapp.ui.profile.EditProfileViewModel;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import static android.app.Activity.RESULT_OK;
public class EditRecipeFragment extends Fragment {
private EditRecipeViewModel editRecipeViewModel;
Recipe recipe = new Recipe ();
EditText title_editText, ingredients_editText, instructions_editText;
ImageView photo_imageView;
View saveBtn, uploadPhotoBtn;
Bitmap imageBitmap;
String imageUrl;
ProgressBar progressBar;
Boolean isPhotoUploaded;
public static EditRecipeFragment newInstance() {
return new EditRecipeFragment();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
editRecipeViewModel = ViewModelProviders.of(this).get(EditRecipeViewModel.class);
final View root = inflater.inflate(R.layout.fragment_edit_recipe, container, false);
title_editText = root.findViewById(R.id.editRecipe_title_textInputEditText);
ingredients_editText = root.findViewById(R.id.editRecipe_ingredients_editView);
instructions_editText = root.findViewById(R.id.editRecipe_instructions_editView);
photo_imageView = root.findViewById(R.id.editRecipe_photo_imageView);
saveBtn = root.findViewById(R.id.editRecipe_save_btn);
uploadPhotoBtn = root.findViewById(R.id.editRecipe_photo_btn);
progressBar = root.findViewById(R.id.editRecipe_progressBar);
isPhotoUploaded = false;
assert getArguments() != null;
recipe = RecipeDetailsFragmentArgs.fromBundle(getArguments()).getRecipe();
setRecipeLayout(recipe);
//upload photo
uploadPhotoBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadPhoto();
}
});
//save changes
saveBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(final View v) {
saveChanges(v);
}
});
return root;
}
public void setRecipeLayout(Recipe recipe){
title_editText.setText(recipe.getTitle());
ingredients_editText.setText(recipe.getIngredients());
instructions_editText.setText(recipe.getInstructions());
if(recipe.getImageUrl() != null && !(recipe.getImageUrl().equals("")))
Picasso.get().load(recipe.getImageUrl()).placeholder(R.drawable.blank_icon).into(photo_imageView);
else
photo_imageView.setImageResource(R.drawable.ic_menu_camera);
}
@Override
public void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
saveBtn.setEnabled(true);
}
public void saveChanges(final View v){
final String id = recipe.getId();
final String title = title_editText.getText().toString();
final String ingredients = ingredients_editText.getText().toString();
final String instructions = instructions_editText.getText().toString();
final String creatorName = recipe.getCreatorName();
final String creatorEmail = recipe.getCreatorEmail();
if (TextUtils.isEmpty(title)) {
title_editText.setError("Title is Required");
return;
}
if (TextUtils.isEmpty(ingredients)) {
ingredients_editText.setError("Ingredients are Required");
return;
}
if (TextUtils.isEmpty(instructions)) {
instructions_editText.setError("Instructions are Required");
return;
}
progressBar.setVisibility(View.VISIBLE);
saveBtn.setEnabled(false);
if (isPhotoUploaded) {
Date date = new Date();
StorageFirebase.uploadImage(imageBitmap, "photo_" + date.getTime(), new StorageFirebase.Listener() {
@Override
public void onSuccess(String url) {
imageUrl = url;
Recipe updatedRecipe = new Recipe(title, ingredients, instructions, imageUrl, creatorName, creatorEmail);
updatedRecipe.setId(id);
editRecipeViewModel.updateData(updatedRecipe).observe(getViewLifecycleOwner(), new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean)
Navigation.findNavController(v).popBackStack(R.id.nav_myRecipes, false); //back to details
else
Toast.makeText(getActivity(), "Could not update recipe.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onFail() {
}
});
}
else {
imageUrl = recipe.getImageUrl();
Recipe updatedRecipe = new Recipe(title, ingredients, instructions, imageUrl, creatorName, creatorEmail);
updatedRecipe.setId(id);
editRecipeViewModel.updateData(updatedRecipe).observe(getViewLifecycleOwner(), new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean)
Navigation.findNavController(v).popBackStack(R.id.nav_myRecipes, false); //back to details
else
Toast.makeText(getActivity(), "Could not update recipe.", Toast.LENGTH_SHORT).show();
}
});
}
}
/*********** PHOTO ***********/
static final int REQUEST_PICK_IMAGE = 1;
void uploadPhoto(){
Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (pickPhoto.resolveActivity(requireActivity().getPackageManager()) != null) {
startActivityForResult(pickPhoto, REQUEST_PICK_IMAGE);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { //on return from gallery
if (requestCode == REQUEST_PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null) {
isPhotoUploaded =true;
try {
imageBitmap = MediaStore.Images.Media.getBitmap(MyApplication.context.getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
photo_imageView.setImageBitmap(imageBitmap);
}
}
} | 7,787 | 0.642481 | 0.642353 | 207 | 36.623188 | 31.468458 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.661836 | false | false | 3 |
8233b4c4106dde0c5e987bb7766164a6987d95e1 | 36,687,610,655,249 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/28/28_f0e3340ae4c9e37f4c0111064deca894994dcc67/TMXReader/28_f0e3340ae4c9e37f4c0111064deca894994dcc67_TMXReader_s.java | 7f3c5f247e5217bf155deac475aa4d0731638579 | []
| no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | /**************************************************************************
OmegaT - Computer Assisted Translation (CAT) tool
with fuzzy matching, translation memory, keyword search,
glossaries, and translation leveraging into updated projects.
Copyright (C) 2000-2006 Keith Godfrey, Maxym Mykhalchuk, and Henry Pijffers
Home page: http://www.omegat.org/omegat/omegat.html
Support center: http://groups.yahoo.com/group/OmegaT/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**************************************************************************/
package org.omegat.util;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.omegat.core.segmentation.Segmenter;
import org.omegat.core.threads.CommandThread;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.omegat.core.threads.CommandThread;
import org.omegat.util.xml.XMLReader;
/**
* Class that loads TMX (Translation Memory Exchange) files (any version, we're cool).
* <p>
* TMX reader loads all TUVs in a TU first, then tries to decide
* what's source and what's target, by first matching against the full
* source/target language string, then against language codes only.
* This improves TMX handling in a number of ways:
* <ol>
* <li>We now support multiple TUVs in a TU, which makes us more TMX compliant.
* <li>If an exact language match cannot be found, the best alternative is
* loaded, if present. This means that if you set the source or target
* language to EN-US, and all you have is EN-GB, EN-GB will be loaded.
* Or if you've set it to EN, and you have both, the first of either will
* be loaded.
* </ol>
*
* @author Keith Godfrey
* @author Henry Pijffers (henry.pijffers@saxnot.com)
* @author Maxym Mykhalchuk
*/
public class TMXReader extends org.xml.sax.helpers.DefaultHandler
{
/**
* Creates a new TMX Reader.
*
* @param encoding -- encoding to allow specification of alternative encodings (i.e. wordfast)
*/
public TMXReader(String encoding,
Language sourceLanguage,
Language targetLanguage)
{
m_encoding = encoding;
m_srcList = new ArrayList();
m_tarList = new ArrayList();
m_properties = new HashMap();
m_variantLanguages = new HashSet();
this.sourceLanguage = sourceLanguage.getLanguage();
this.targetLanguage = targetLanguage.getLanguage();
}
/** Returns the source language */
public String getSourceLanguage()
{
return sourceLanguage;
}
/** Returns the target language */
public String getTargetLanguage()
{
return targetLanguage;
}
/** Returns the number of segments */
public int numSegments()
{
return m_srcList.size();
}
/** Returns an original text of a source segment #n */
public String getSourceSegment(int n)
{
if (n < 0 || n >= numSegments())
return new String();
else
return (String) m_srcList.get(n);
}
/** Returns a translation of a target segment #n */
public String getTargetSegment(int n)
{
if (n < 0 || n >= numSegments())
return new String();
else
return (String) m_tarList.get(n);
}
private String creationtool = null;
/** Creation Tool attribute value of OmegaT TMXs: "OmegaT" */
public static final String CT_OMEGAT = "OmegaT"; // NOI18N
/** Returns Creation Tool attribute of TMX file */
public String getCreationTool()
{
return creationtool;
}
private String creationtoolversion = null;
/** "1" for OmegaT 1.4.5 and earlier (Creation Tool Version attribute). */
public static final String CTV_OMEGAT_1 = "1"; // NOI18N
/** "1.6" for OmegaT 1.6 RC3 to 1.6.0 RC11 (Creation Tool Version attribute). Pretty misleading. */
public static final String CTV_OMEGAT_1_6_RC3_RC11 = "1.6"; // NOI18N
/** "1.6 RC12" for OmegaT 1.6 RC12 and later RCs (Creation Tool Version attribute). */
public static final String CTV_OMEGAT_1_6_RC12 = "1.6 RC12"; // NOI18N
/** "1.6.0 for OmegaT 1.6.0-final */
public static final String CTV_OMEGAT_1_6_0_FINAL = "1.6.0"; // NOI18N
/** Current version */
public static final String CTV_OMEGAT_CURRENT = CTV_OMEGAT_1_6_0_FINAL; // NOI18N
/** Returns Creation Tool attribute of TMX file */
public String getCreationToolVersion()
{
return creationtoolversion;
}
/**
* Retrieves the value for the specified property.
*
* Properties can be specified in the TMX header,
* please refer to the TMX specification for more information.
*
* @param name - The name of the property to retrieve the value for
* @return The value of the specified property, or null if the property is not present
*/
public String getProperty(String name) {
return (String)m_properties.get(name);
}
///////////////////////////////////////////////////////////////////////////
// TMX Upgrades between OmegaT versions
boolean upgradeCheckComplete = false;
boolean upgrade14X = false;
boolean upgradeSentSeg = false;
/**
* Checks whether any compatibility upgrades are necessary for
* OmegaT-generated TMX files.
*/
private void checkForUpgrades()
{
if (!upgradeCheckComplete)
{
if (getCreationTool()==null || getCreationToolVersion()==null)
return; // we can't check
if (CT_OMEGAT.equals(getCreationTool()))
{
upgrade14X = getCreationToolVersion().compareTo(CTV_OMEGAT_1) <= 0;
upgradeSentSeg = SEG_PARAGRAPH.equals(getSegType()) &&
CommandThread.core.getProjectProperties().isSentenceSegmentingEnabled();
}
upgradeCheckComplete = true;
}
}
/**
* Do we need to upgrade old TMX files with paragraph segmentation
* to new sentence segmentation.
* The upgrade simply breaks source and target segments into sentences,
* and if there's the same number of segments in target as in source,
* several segments are added to memory.
*/
private boolean isUpgradeSentSeg()
{
checkForUpgrades();
return upgradeSentSeg;
}
/**
* Do we need to upgrade old TMX files from OmegaT 1.4.x series.
* The upgrade cannot be done absolutely reliably, but there're some
* heuristics there... For example,
* the old form can be "Bold</b1> text here.", and the new form
* should be "<b0>Bold</b0> text here.".
*/
private boolean isUpgrade14X()
{
checkForUpgrades();
return upgrade14X;
}
/**
* Upgrades segment if required.
*/
private String upgradeSegment(String segment)
{
if (isUpgrade14X()) // if that's 1.4.x, doing both upgrades...
segment = upgradeOldTagsNumberingAndPairs(segment);
return segment;
}
/** Internal class for OmegaT tag */
class Tag
{
/** is this an ending tag, e.g. </b4> */
public boolean end;
/** name of the tag, e.g. "b" for </b4> */
public String name;
/** number of the tag, e.g. 4 for </b4> */
public int num;
/** is this a standalone tag, e.g. <br4/> */
public boolean alone;
/** Creates a tag */
public Tag(boolean end, String name, int num, boolean alone)
{
this.end = end;
this.name = name;
this.num = num;
this.alone = alone;
}
/** String form. */
public String toString()
{
return
"<" + // NOI18N
(end ? "/" : "") + // NOI18N
name +
num +
(alone ? "/" : "") + // NOI18N
">"; // NOI18N
}
/**
* String form of a paired tag: if this is a start tag,
* returns corresponding end tag, if this is an end tag,
* returns corresponding start tag, if this is a standalone tag,
* returns the same as {@link #toString()}.
*/
public String toStringPaired()
{
if (alone)
return toString();
else
return
"<" + // NOI18N
(end ? "" : "/") + // NOI18N
name +
num +
">"; // NOI18N
}
}
/**
* Upgrades segments of OmegaT's 1.4.x series to new tag numbering,
* and to new paired tag policy.
*/
private String upgradeOldTagsNumberingAndPairs(String segment)
{
if (!PatternConsts.OMEGAT_TAG.matcher(segment).find())
return segment;
try
{
StringBuffer buf = new StringBuffer(segment);
Matcher matcher = PatternConsts.OMEGAT_TAG_DECOMPILE.matcher(segment);
int tagstart = matcher.start();
int tagend = matcher.end();
boolean end = matcher.group(1).length()>0;
String name = matcher.group(2);
int num = Integer.parseInt(matcher.group(3));
boolean alone = matcher.group(4).length()>0;
if (num==1)
num = 0;
Tag tag = new Tag(end, name, num, alone);
List unclosedTags = new ArrayList();
List unopenedTags = new ArrayList();
Map unclosedTagsNames = new HashMap();
Map unopenedTagsNames = new HashMap();
if (end)
{
unopenedTags.add(tag);
unopenedTagsNames.put(name, tag);
}
else if (!alone)
{
unclosedTags.add(tag);
unclosedTagsNames.put(name, tag);
}
int maxnum = num;
buf.replace(tagstart, tagend, tag.toString());
while (matcher.find())
{
tagstart = matcher.start();
tagend = matcher.end();
end = matcher.group(1).length()>0;
name = matcher.group(2);
alone = matcher.group(4).length()>0;
tag = new Tag(end, name, num, alone);
if (end && unclosedTagsNames.containsKey(name))
{
Tag starttag = (Tag) unclosedTagsNames.get(name);
num = starttag.num;
unclosedTagsNames.remove(name);
unclosedTags.remove(starttag);
}
else
{
num = maxnum + 1;
if (end)
{
unopenedTags.add(tag);
unopenedTagsNames.put(name, tag);
}
else if (!alone)
{
unclosedTags.add(tag);
unclosedTagsNames.put(name, tag);
}
}
if (maxnum < num)
maxnum = num;
buf.replace(tagstart, tagend, tag.toString());
}
StringBuffer res = new StringBuffer();
for (int i = unopenedTags.size()-1; i>0; i--)
{
tag = (Tag) unopenedTags.get(i);
res.append(tag.toStringPaired());
}
res.append(buf);
for (int i = unclosedTags.size()-1; i>0; i--)
{
tag = (Tag) unclosedTags.get(i);
res.append(tag.toStringPaired());
}
return res.toString();
}
catch (Exception e)
{
return segment;
}
}
///////////////////////////////////////////////////////////////////////////
/** Collects a segment from TMX. Performs upgrades of a segment if needed. */
private void storeSegment(String source, String translation)
{
source = upgradeSegment(source);
translation = upgradeSegment(translation);
if (isUpgradeSentSeg())
{
List srcSegments = Segmenter.segment(source, null, null);
List tarSegments = Segmenter.segment(translation, null, null);
int n = srcSegments.size();
if( n==tarSegments.size() )
{
for(int j=0; j<n; j++)
{
String srcseg = (String)srcSegments.get(j);
String tarseg = (String)tarSegments.get(j);
m_srcList.add(srcseg);
m_tarList.add(tarseg);
}
}
else
{
m_srcList.add(source);
m_tarList.add(translation);
}
}
else
{
m_srcList.add(source);
m_tarList.add(translation);
}
}
///////////////////////////////////////////////////////////////////////////
private String segtype;
/** Segment Type attribute value: "paragraph" */
public static final String SEG_PARAGRAPH = "paragraph"; // NOI18N
/** Segment Type attribute value: "sentence" */
public static final String SEG_SENTENCE = "sentence"; // NOI18N
/** Returns Segment Type attribute of TMX file */
public String getSegType()
{
return segtype;
}
/**
* Determins if TMX level 2 codes should be included or skipped.
*/
private void checkLevel2() {
includeLevel2 = creationtool.equals(CT_OMEGAT);
}
/**
* Loads the specified TMX file by using a SAX parser.
*
* The parser makes callbacks to the TMXReader, to the methods
* warning, error, fatalError, startDocument, endDocument,
* startElement, endElement, characters, ignorableWhiteSpace,
* and resolveEntity. Together these methods implement the
* parsing of the TMX file.
*/
public void loadFile(String filename, boolean isProjectTMX)
throws IOException
{
this.isProjectTMX = isProjectTMX;
// parse the TMX file
try
{
// log the parsing attempt
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_READING_FILE"),
new Object[]{filename}));
// create a new SAX parser factory
javax.xml.parsers.SAXParserFactory parserFactory =
javax.xml.parsers.SAXParserFactory.newInstance();
// configure the factory
parserFactory.setValidating(false); // skips TMX validity checking
// create a new SAX parser
javax.xml.parsers.SAXParser parser = parserFactory.newSAXParser();
// make this TMX reader the default entity resolver for the parser,
// so we can handle DTD declarations ourselves
parser.getXMLReader().setEntityResolver(this);
// parse the TM, provide the current TMX reader as notification handler
InputSource is = new InputSource(new XMLReader(filename, m_encoding));
is.setSystemId(""); // NOI18N
parser.parse(is, this);
// if no source could be found for 1 or more TUs, log this fact
if (sourceNotFound)
StaticUtils.log(OStrings.getString("TMXR_WARNING_SOURCE_NOT_FOUND"));
// log the fact that parsing is done
StaticUtils.log(OStrings.getString("TMXR_INFO_READING_COMPLETE"));
StaticUtils.log("");
}
catch (SAXParseException exception) {
// log error
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_FATAL_ERROR_WHILE_PARSING"),
new Object[]{String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}));
exception.printStackTrace(StaticUtils.getLogStream());
// display error
CommandThread.core.displayErrorMessage(MessageFormat.format(
OStrings.getString("TMXR_FATAL_ERROR_WHILE_PARSING__DISPLAY"),
new Object[]{filename,
String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}),
exception);
}
catch (Exception exception)
{
// log exception
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_EXCEPTION_WHILE_PARSING"),
new Object[]{exception.getLocalizedMessage(), StaticUtils.getLogLocation()}));
exception.printStackTrace(StaticUtils.getLogStream());
// display error
CommandThread.core.displayErrorMessage(MessageFormat.format(
OStrings.getString("TMXR_EXCEPTION_WHILE_PARSING__DISPLAY"),
new Object[]{filename, exception.getLocalizedMessage()}),
exception);
}
}
/**
* Receives notification of a parser warning. Called by SAX parser.
*/
public void warning(SAXParseException exception) throws SAXException
{
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_WARNING_WHILE_PARSING"),
new Object[]{String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}));
exception.printStackTrace(StaticUtils.getLogStream());
}
/**
* Receives notification of a recoverable XML parsing error. Called by SAX parser.
*/
public void error(SAXParseException exception) throws SAXException
{
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_RECOVERABLE_ERROR_WHILE_PARSING"),
new Object[]{String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}));
exception.printStackTrace(StaticUtils.getLogStream());
}
/**
* Receives notification of a fatal XML parsing error. Called by SAX parser.
*/
public void fatalError(SAXParseException exception) throws SAXException
{
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_FATAL_ERROR_WHILE_PARSING"),
new Object[]{String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}));
exception.printStackTrace(StaticUtils.getLogStream());
}
/**
* Receives notification of the start of the XML document. Called by SAX parser.
*/
public void startDocument()
{
// initialise variables needed for parsing of the TMX file
headerParsed = false;
inHeader = false;
inTU = false;
inTUV = false;
inSegment = false;
tuvs = new ArrayList();
currentElement = new Stack();
currentSub = new Stack();
currentElement.push(TMX_TAG_NONE);
}
/**
* Receives notification of the end of the XML document. Called by SAX parser.
*/
public void endDocument()
{
// deallocate temp storage
tuvs = null;
currentElement = null;
currentSub = null;
}
/**
* Receives notification of the start of an element. Called by SAX parser.
*/
public void startElement(String uri,
String localName,
String qName,
Attributes attributes) throws SAXException
{
// determine the type of element and handle it, if required
if (qName.equals(TMX_TAG_HEADER))
startElementHeader(attributes);
else if (qName.equals(TMX_TAG_TU))
startElementTU(attributes);
else if (qName.equals(TMX_TAG_TUV))
startElementTUV(attributes);
else if (qName.equals(TMX_TAG_SEG))
startElementSegment(attributes);
else if ( qName.equals(TMX_TAG_BPT)
|| qName.equals(TMX_TAG_EPT)
|| qName.equals(TMX_TAG_HI)
|| qName.equals(TMX_TAG_IT)
|| qName.equals(TMX_TAG_PH)
|| qName.equals(TMX_TAG_UT))
startElementInline(attributes);
else if (qName.equals(TMX_TAG_SUB))
startElementSub(attributes);
else if (qName.equals(TMX_TAG_PROP))
startElementProperty(attributes);
}
/**
* Receives notification of the end of an element. Called by SAX parser.
*/
public void endElement(String uri,
String localName,
String qName) throws SAXException
{
// determine the type of element and handle it, if required
if (qName.equals(TMX_TAG_HEADER))
endElementHeader();
else if (qName.equals(TMX_TAG_TU))
endElementTU();
else if (qName.equals(TMX_TAG_TUV))
endElementTUV();
else if (qName.equals(TMX_TAG_SEG))
endElementSegment();
else if ( qName.equals(TMX_TAG_BPT)
|| qName.equals(TMX_TAG_EPT)
|| qName.equals(TMX_TAG_HI)
|| qName.equals(TMX_TAG_IT)
|| qName.equals(TMX_TAG_PH)
|| qName.equals(TMX_TAG_UT))
endElementInline();
else if (qName.equals(TMX_TAG_SUB))
endElementSub();
else if (qName.equals(TMX_TAG_PROP))
endElementProperty();
}
/**
* Receives character data in element content. Called by the SAX parser.
*/
public void characters(char[] ch,
int start,
int length) throws SAXException
{
// only read (sub)segments, properties, and inline codes (if required)
if ( inSegment
|| inProperty
|| (includeLevel2 && ((String)currentElement.peek()).equals(TMX_TAG_INLINE)))
{
// append the data to the current buffer
((StringBuffer)currentSub.peek()).append(ch, start, length);
}
}
/**
* Receives ignorable whitespace in element content. Called by the SAX parser.
*/
public void ignorableWhitespace(char[] ch,
int start,
int length) throws SAXException
{
// only read (sub)segments, properties, and inline codes (if required)
if ( inSegment
|| inProperty
|| (includeLevel2 && ((String)currentElement.peek()).equals(TMX_TAG_INLINE)))
{
// append the data to the current buffer
((StringBuffer)currentSub.peek()).append(ch, start, length);
}
}
/**
* Handles the start of the header of a TMX file.
*/
private void startElementHeader(Attributes attributes)
{
// mark the current position as in the header
inHeader = true;
// get the header attributes
creationtool = attributes.getValue(TMX_ATTR_CREATIONTOOL);
creationtoolversion = attributes.getValue(TMX_ATTR_CREATIONTOOLVERSION);
segtype = attributes.getValue(TMX_ATTR_SEGTYPE);
tmxSourceLanguage = attributes.getValue(TMX_ATTR_SRCLANG);
// log some details
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_CREATION_TOOL"),
new Object[]{creationtool}));
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_CREATION_TOOL_VERSION"),
new Object[]{creationtoolversion}));
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_SEG_TYPE"),
new Object[]{segtype}));
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_SOURCE_LANG"),
new Object[]{tmxSourceLanguage}));
// give a warning if the TMX source language is
// different from the project source language
if (!tmxSourceLanguage.equalsIgnoreCase(sourceLanguage))
{
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_WARNING_INCORRECT_SOURCE_LANG"),
new Object[]{tmxSourceLanguage, sourceLanguage}));
}
// give a warning that TMX file will be upgraded from 1.4.x
if (isUpgrade14X())
StaticUtils.log(OStrings.getString("TMXR_WARNING_UPGRADE_14X"));
// give a warning that TMX file will be upgraded to sentence segmentation
if (isUpgradeSentSeg())
StaticUtils.log(OStrings.getString("TMXR_WARNING_UPGRADE_SENTSEG"));
// check if level 2 codes should be included (only for OmegaT 1.6 RC13 and higher)
checkLevel2();
}
/**
* Handles the end of the TMX header
*/
private void endElementHeader() {
// mark the header as parsed
headerParsed = true;
// mark the current position as *not* in the header
inHeader = false;
// check for property OmegaT:VariantLanguages (only variants in these languages are read)
// if present, parse the property value, and get each separate language
String propVariantLanguages = getProperty(PROPERTY_VARIANT_LANGUAGES);
if (propVariantLanguages != null) {
int commaPos = 0;
StringBuffer languages = new StringBuffer();
do {
// get the position of the next comma
commaPos = propVariantLanguages.indexOf(',');
// get the next language
String language = commaPos > 0 ? propVariantLanguages.substring(0, commaPos).trim()
: propVariantLanguages.trim();
// add the language to the set, but trim off any region indicators
// for simplicity's sake, and convert it to all uppercase
if (language.length() > 0) {
m_variantLanguages.add(language.substring(0, 2).toUpperCase());
if (languages.length() > 0)
languages.append(", ");
languages.append(language.substring(0, 2).toUpperCase());
}
// trim the list of languages
propVariantLanguages = propVariantLanguages.substring(commaPos + 1);
}
while (commaPos > 0);
// Log presence of preferred variant languages
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_VARIANT_LANGUAGES_DISPLAYED"),
new Object[]{languages.toString()}));
}
}
/**
* Handles the start of a property
*/
private void startElementProperty(Attributes attributes) throws SAXException {
currentElement.push(TMX_TAG_PROP);
// ignore all properties outside the TMX header
if (!inHeader)
return;
// get the property name
currentProperty = attributes.getValue(TMX_ATTR_TYPE);
// put a property value buffer on the subsegment stack
// (ISSUE: field currentSub should be renamed to reflect this more general use)
currentSub.push(new StringBuffer());
// mark the current position as in a property
inProperty = true;
}
/**
* Handles the end of a property
*/
private void endElementProperty() {
currentElement.pop();
// mark the current position as *not* in a property
inProperty = false;
// ignore all properties outside the TMX header
if (!inHeader)
return;
// add the current property to the property map
StringBuffer propertyValue = (StringBuffer)currentSub.pop();
m_properties.put(currentProperty, propertyValue.toString());
currentProperty = null;
}
/**
* Handles the start of a translation unit.
*/
private void startElementTU(Attributes attributes) throws SAXException
{
currentElement.push(TMX_TAG_TU);
// ensure the header has been parsed
// without the header info, we can't determine what's source and what's target
if (!headerParsed)
throw new SAXException(OStrings.getString("TMXR_ERROR_TU_BEFORE_HEADER"));
// mark the current position as in a translation unit
inTU = true;
// clear the TUV list
tuvs.clear();
}
/**
* Handles the end of a translation unit.
*/
private void endElementTU()
{
currentElement.pop();
// mark the current position as *not* in a translation unit
inTU = false;
// determine source and (primary) target tuv
TUV source = null; // source TUV according to source language set by OmT
TUV target = null; // target TUV according to target language set by OmT
TUV sourceC = null; // candidate for source TUV according to source language set by OmT
TUV targetC = null; // candidate for target TUV according to target language set by OmT
TUV sourceT = null; // source TUV according to TMX source language
TUV sourceTC = null; // candidate for source TUV according to TMX source language
for (int i = 0; i < tuvs.size(); i++)
{
// get the next TUV
TUV tuv = (TUV)tuvs.get(i);
// first match TUV language against entire source language (lang code + reg code)
if ((source == null) && tuv.language.equalsIgnoreCase(sourceLanguage))
// the current TUV is the source
source = tuv;
// against entire target language
else if ((target == null) && tuv.language.equalsIgnoreCase(targetLanguage))
// the current TUV is the target
target = tuv;
// against source language code only
else if ((sourceC == null) && tuv.language.regionMatches(true, 0, sourceLanguage, 0, 2))
// the current TUV is a candidate for the source
sourceC = tuv;
// against target language code only
else if ((targetC == null) && tuv.language.regionMatches(true, 0, targetLanguage, 0, 2))
// the current TUV is a candidate for the target
targetC = tuv;
// if nothing matches, then try matching against the TMX source language
else if (isProjectTMX)
{
// match against entire TMX source language
if ( (sourceT == null)
&& ( tuv.language.equalsIgnoreCase(tmxSourceLanguage)
|| tmxSourceLanguage.equalsIgnoreCase("*all*"))) // NOI18N
// the current TUV is the source according to the TMX source language
sourceT = tuv;
// match against TMX source language code only
else if ( (sourceTC == null)
&& tuv.language.regionMatches(true, 0, tmxSourceLanguage, 0, 2))
// the current TUV is a candidate for the source according to the TMX source language
sourceTC = tuv;
}
// stop looking for source and target if both have been located
if ((source != null) && (target != null))
break;
}
// determine which source TUV to use
if (source == null)
source = sourceC; // try source candidate
if (source == null)
source = sourceT; // try source according to TMX
if (source == null)
source = sourceTC; // try source candidate according to TMX
// if no source was found, log a warning
if (source == null)
{
sourceNotFound = true;
return;
}
// determine what target TUV to use
// if none was found, create a temporary, empty one, for ease of coding
if (target == null)
target = targetC;
if (target == null)
target = new TUV();
// store the source & target segment
storeSegment(source.text.toString(), target.text.toString());
// store the source & target sub segments
// create exactly as many target subs as there are source subs
// "pad" with empty strings, or ommit segments if necessary
// NOTE: this is not the most ideal solution, but the best possible
for (int i = 0; i < source.subSegments.size(); i++)
{
String starget = new String();
if (i < target.subSegments.size())
starget = target.subSegments.get(i).toString();
storeSegment(source.subSegments.get(i).toString(), starget);
}
// store alternative translations
if (!isProjectTMX) {
for (int i = 0; i < tuvs.size(); i++) {
// get the next TUV
TUV tuv = (TUV)tuvs.get(i);
// store the TUV as alternative if it's source nor target
// and its language appears in the set of useful variant languages
if ( (tuv != source)
&& (tuv != target)
&& ( m_variantLanguages.isEmpty()
|| m_variantLanguages.contains(tuv.language.substring(0, 2).toUpperCase())))
storeSegment(source.text.toString(), tuv.text.toString());
}
}
}
/**
* Handles the start of a tuv element.
*/
private void startElementTUV(Attributes attributes)
{
currentElement.push(TMX_TAG_TUV);
// ensure we're in a translation unit
if (!inTU)
{
StaticUtils.log(OStrings.getString("TMXR_WARNING_TUV_NOT_IN_TU"));
return;
}
// get the language of the tuv
// try "xml:lang" first, then "lang"
String language = attributes.getValue(TMX_ATTR_LANG_NS);
if (language == null)
language = attributes.getValue(TMX_ATTR_LANG);
// if the language is not specified, skip the tuv
if (language == null)
{
StaticUtils.log(OStrings.getString("TMXR_WARNING_TUV_LANG_NOT_SPECIFIED"));
return;
}
// put a new TUV in the TUV list
TUV tuv = new TUV();
tuv.language = language;
tuvs.add(tuv);
// mark the current position as in a tuv
inTUV = true;
// clear the stack of sub segments
currentSub.clear();
}
/**
* Handles the end of a tuv element.
*/
private void endElementTUV()
{
currentElement.pop();
// mark the current position as *not* in a tuv element
inTUV = false;
}
/**
* Handles the start of a segment.
*/
private void startElementSegment(Attributes attributes)
{
currentElement.push(TMX_TAG_SEG);
// ensure we are currently in a tuv
if (!inTUV)
{
StaticUtils.log(OStrings.getString("TMXR_WARNING_SEG_NOT_IN_TUV"));
return;
}
// put the current TUV's segment buffer on the subsegment stack
// (ISSUE: field currentSub should be renamed to reflect this more general use)
currentSub.push(((TUV)tuvs.get(tuvs.size() - 1)).text);
// mark the current position as in a segment
inSegment = true;
}
/**
* Handles the end of a segment.
*/
private void endElementSegment()
{
currentElement.pop();
// do nothing if not in a TUV
if (!inTUV)
return;
// remove the current TUV's segment buffer from the subsegment stack
currentSub.pop();
// mark the current position as *not* in a segment
inSegment = false;
}
/**
* Handles the start of a TMX inline element (<bpt>, <ept>, <hi>, <it>, <ph>, <ut>).
*/
private void startElementInline(Attributes attributes)
{
currentElement.push(TMX_TAG_INLINE);
}
/**
* Handles the end of a TMX inline element (<bpt>, <ept>, <hi>, <it>, <ph>, <ut>).
*/
private void endElementInline()
{
currentElement.pop();
}
/**
* Handles the start of a SUB inline element.
*/
private void startElementSub(Attributes attributes)
{
currentElement.push(TMX_TAG_SUB);
// create new entries in the current TUV's sub segment list and on the stack
// NOTE: the assumption is made here that sub segments are
// in the same order in both source and target segments
StringBuffer sub = new StringBuffer(); // NOI18N
((TUV)tuvs.get(tuvs.size() - 1)).subSegments.add(sub);
currentSub.push(sub);
}
/**
* Handles the end of a SUB inline element.
*/
private void endElementSub() throws SAXException
{
currentElement.pop();
// remove the current sub from the sub stack
currentSub.pop();
}
/**
* Makes the parser skip DTDs.
*/
public org.xml.sax.InputSource resolveEntity(String publicId,
String systemId)
throws SAXException
{
// simply return an empty dtd
return new org.xml.sax.InputSource(new java.io.StringReader("")); // NOI18N
}
// Constants for certain TMX tag names/attributes
private final static String TMX_TMX_TAG = "tmx"; // NOI18N
private final static String TMX_TAG_HEADER = "header"; // NOI18N
private final static String TMX_TAG_BODY = "body"; // NOI18N
private final static String TMX_TAG_TU = "tu"; // NOI18N
private final static String TMX_TAG_TUV = "tuv"; // NOI18N
private final static String TMX_TAG_SEG = "seg"; // NOI18N
private final static String TMX_TAG_BPT = "bpt"; // NOI18N
private final static String TMX_TAG_EPT = "ept"; // NOI18N
private final static String TMX_TAG_HI = "hi"; // NOI18N
private final static String TMX_TAG_IT = "it"; // NOI18N
private final static String TMX_TAG_PH = "ph"; // NOI18N
private final static String TMX_TAG_UT = "ut"; // NOI18N
private final static String TMX_TAG_SUB = "sub"; // NOI18N
private final static String TMX_TAG_PROP = "prop"; // NOI18N
private final static String TMX_TAG_INLINE = "inline"; // made up for convenience // NOI18N
private final static String TMX_TAG_NONE = "none"; // made up for convenience // NOI18N
private final static String TMX_ATTR_LANG = "lang"; // NOI18N
private final static String TMX_ATTR_LANG_NS = "xml:lang"; // NOI18N
private final static String TMX_ATTR_CREATIONTOOL = "creationtool"; // NOI18N
private final static String TMX_ATTR_CREATIONTOOLVERSION = "creationtoolversion"; // NOI18N
private final static String TMX_ATTR_SEGTYPE = "segtype"; // NOI18N
private final static String TMX_ATTR_SRCLANG = "srclang"; // NOI18N
private final static String TMX_ATTR_TYPE = "type"; // NOI18N
private final static String PROPERTY_VARIANT_LANGUAGES = "OmegaT:VariantLanguages"; // NOI18N
private String m_encoding;
private List m_srcList;
private List m_tarList;
private Map m_properties; // Map<String, String> of TMX properties, specified in the header
private Set m_variantLanguages; // Set of (user) acceptable variant languages
private String sourceLanguage; // Language/country code set by OmT: LL(-CC)
private String targetLanguage; // Language/country code set by OmT: LL(-CC)
private String tmxSourceLanguage; // Language/country code as specified in TMX header: LL(-CC)
private boolean includeLevel2; // True if TMX level 2 markup must be interpreted
private boolean isProjectTMX; // True if the TMX file being loaded is the project TMX
private boolean headerParsed; // True if the TMX header has been parsed correctly
private boolean inHeader; // True if the current parsing point is in the HEADER element
private boolean inProperty; // True if in a PROP element
private boolean inTU; // True if in a TU element
private boolean inTUV; // True if in a TUV element
private boolean inSegment; // True if in a SEG element
private boolean sourceNotFound; // True if no source segment was found for one or more TUs
private List tuvs; // Contains all TUVs of the current TU
private Stack currentElement; // Stack of tag names up to the current parsing point
private Stack currentSub; // Stack of sub segment buffers
private String currentProperty; // Name of the current property being parsed (null if none)
/**
* Internal class to represent translation unit variants
*/
private class TUV
{
/**
* Language and (optional) country code: LL(C-CC)
*/
public String language;
/**
* Segment text
*/
public StringBuffer text;
/**
* Contains StringBuffers for subsegments
*/
public ArrayList subSegments;
/**
* Default constructor
*/
public TUV()
{
super();
text = new StringBuffer();
subSegments = new ArrayList();
}
}
}
| UTF-8 | Java | 45,975 | java | 28_f0e3340ae4c9e37f4c0111064deca894994dcc67_TMXReader_s.java | Java | [
{
"context": "into updated projects.\n \n Copyright (C) 2000-2006 Keith Godfrey, Maxym Mykhalchuk, and Henry Pijffers\n ",
"end": 313,
"score": 0.9998751878738403,
"start": 300,
"tag": "NAME",
"value": "Keith Godfrey"
},
{
"context": "ojects.\n \n Copyright (C) 2000-2006 Keith Godfrey, Maxym Mykhalchuk, and Henry Pijffers\n Home page: h",
"end": 331,
"score": 0.9998737573623657,
"start": 315,
"tag": "NAME",
"value": "Maxym Mykhalchuk"
},
{
"context": "(C) 2000-2006 Keith Godfrey, Maxym Mykhalchuk, and Henry Pijffers\n Home page: http://www.omegat.org",
"end": 351,
"score": 0.9998754262924194,
"start": 337,
"tag": "NAME",
"value": "Henry Pijffers"
},
{
"context": "will \n * be loaded.\n * </ol>\n *\n * @author Keith Godfrey\n * @author Henry Pijffers (henry.pijffers@saxnot",
"end": 2751,
"score": 0.9998865127563477,
"start": 2738,
"tag": "NAME",
"value": "Keith Godfrey"
},
{
"context": " * </ol>\n *\n * @author Keith Godfrey\n * @author Henry Pijffers (henry.pijffers@saxnot.com)\n * @author Maxym Myk",
"end": 2778,
"score": 0.9998833537101746,
"start": 2764,
"tag": "NAME",
"value": "Henry Pijffers"
},
{
"context": "@author Keith Godfrey\n * @author Henry Pijffers (henry.pijffers@saxnot.com)\n * @author Maxym Mykhalchuk\n */\n public class ",
"end": 2805,
"score": 0.9999197125434875,
"start": 2780,
"tag": "EMAIL",
"value": "henry.pijffers@saxnot.com"
},
{
"context": "y Pijffers (henry.pijffers@saxnot.com)\n * @author Maxym Mykhalchuk\n */\n public class TMXReader extends org.xml.sax.",
"end": 2835,
"score": 0.9998863935470581,
"start": 2819,
"tag": "NAME",
"value": "Maxym Mykhalchuk"
}
]
| null | []
| /**************************************************************************
OmegaT - Computer Assisted Translation (CAT) tool
with fuzzy matching, translation memory, keyword search,
glossaries, and translation leveraging into updated projects.
Copyright (C) 2000-2006 <NAME>, <NAME>, and <NAME>
Home page: http://www.omegat.org/omegat/omegat.html
Support center: http://groups.yahoo.com/group/OmegaT/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**************************************************************************/
package org.omegat.util;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.omegat.core.segmentation.Segmenter;
import org.omegat.core.threads.CommandThread;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.omegat.core.threads.CommandThread;
import org.omegat.util.xml.XMLReader;
/**
* Class that loads TMX (Translation Memory Exchange) files (any version, we're cool).
* <p>
* TMX reader loads all TUVs in a TU first, then tries to decide
* what's source and what's target, by first matching against the full
* source/target language string, then against language codes only.
* This improves TMX handling in a number of ways:
* <ol>
* <li>We now support multiple TUVs in a TU, which makes us more TMX compliant.
* <li>If an exact language match cannot be found, the best alternative is
* loaded, if present. This means that if you set the source or target
* language to EN-US, and all you have is EN-GB, EN-GB will be loaded.
* Or if you've set it to EN, and you have both, the first of either will
* be loaded.
* </ol>
*
* @author <NAME>
* @author <NAME> (<EMAIL>)
* @author <NAME>
*/
public class TMXReader extends org.xml.sax.helpers.DefaultHandler
{
/**
* Creates a new TMX Reader.
*
* @param encoding -- encoding to allow specification of alternative encodings (i.e. wordfast)
*/
public TMXReader(String encoding,
Language sourceLanguage,
Language targetLanguage)
{
m_encoding = encoding;
m_srcList = new ArrayList();
m_tarList = new ArrayList();
m_properties = new HashMap();
m_variantLanguages = new HashSet();
this.sourceLanguage = sourceLanguage.getLanguage();
this.targetLanguage = targetLanguage.getLanguage();
}
/** Returns the source language */
public String getSourceLanguage()
{
return sourceLanguage;
}
/** Returns the target language */
public String getTargetLanguage()
{
return targetLanguage;
}
/** Returns the number of segments */
public int numSegments()
{
return m_srcList.size();
}
/** Returns an original text of a source segment #n */
public String getSourceSegment(int n)
{
if (n < 0 || n >= numSegments())
return new String();
else
return (String) m_srcList.get(n);
}
/** Returns a translation of a target segment #n */
public String getTargetSegment(int n)
{
if (n < 0 || n >= numSegments())
return new String();
else
return (String) m_tarList.get(n);
}
private String creationtool = null;
/** Creation Tool attribute value of OmegaT TMXs: "OmegaT" */
public static final String CT_OMEGAT = "OmegaT"; // NOI18N
/** Returns Creation Tool attribute of TMX file */
public String getCreationTool()
{
return creationtool;
}
private String creationtoolversion = null;
/** "1" for OmegaT 1.4.5 and earlier (Creation Tool Version attribute). */
public static final String CTV_OMEGAT_1 = "1"; // NOI18N
/** "1.6" for OmegaT 1.6 RC3 to 1.6.0 RC11 (Creation Tool Version attribute). Pretty misleading. */
public static final String CTV_OMEGAT_1_6_RC3_RC11 = "1.6"; // NOI18N
/** "1.6 RC12" for OmegaT 1.6 RC12 and later RCs (Creation Tool Version attribute). */
public static final String CTV_OMEGAT_1_6_RC12 = "1.6 RC12"; // NOI18N
/** "1.6.0 for OmegaT 1.6.0-final */
public static final String CTV_OMEGAT_1_6_0_FINAL = "1.6.0"; // NOI18N
/** Current version */
public static final String CTV_OMEGAT_CURRENT = CTV_OMEGAT_1_6_0_FINAL; // NOI18N
/** Returns Creation Tool attribute of TMX file */
public String getCreationToolVersion()
{
return creationtoolversion;
}
/**
* Retrieves the value for the specified property.
*
* Properties can be specified in the TMX header,
* please refer to the TMX specification for more information.
*
* @param name - The name of the property to retrieve the value for
* @return The value of the specified property, or null if the property is not present
*/
public String getProperty(String name) {
return (String)m_properties.get(name);
}
///////////////////////////////////////////////////////////////////////////
// TMX Upgrades between OmegaT versions
boolean upgradeCheckComplete = false;
boolean upgrade14X = false;
boolean upgradeSentSeg = false;
/**
* Checks whether any compatibility upgrades are necessary for
* OmegaT-generated TMX files.
*/
private void checkForUpgrades()
{
if (!upgradeCheckComplete)
{
if (getCreationTool()==null || getCreationToolVersion()==null)
return; // we can't check
if (CT_OMEGAT.equals(getCreationTool()))
{
upgrade14X = getCreationToolVersion().compareTo(CTV_OMEGAT_1) <= 0;
upgradeSentSeg = SEG_PARAGRAPH.equals(getSegType()) &&
CommandThread.core.getProjectProperties().isSentenceSegmentingEnabled();
}
upgradeCheckComplete = true;
}
}
/**
* Do we need to upgrade old TMX files with paragraph segmentation
* to new sentence segmentation.
* The upgrade simply breaks source and target segments into sentences,
* and if there's the same number of segments in target as in source,
* several segments are added to memory.
*/
private boolean isUpgradeSentSeg()
{
checkForUpgrades();
return upgradeSentSeg;
}
/**
* Do we need to upgrade old TMX files from OmegaT 1.4.x series.
* The upgrade cannot be done absolutely reliably, but there're some
* heuristics there... For example,
* the old form can be "Bold</b1> text here.", and the new form
* should be "<b0>Bold</b0> text here.".
*/
private boolean isUpgrade14X()
{
checkForUpgrades();
return upgrade14X;
}
/**
* Upgrades segment if required.
*/
private String upgradeSegment(String segment)
{
if (isUpgrade14X()) // if that's 1.4.x, doing both upgrades...
segment = upgradeOldTagsNumberingAndPairs(segment);
return segment;
}
/** Internal class for OmegaT tag */
class Tag
{
/** is this an ending tag, e.g. </b4> */
public boolean end;
/** name of the tag, e.g. "b" for </b4> */
public String name;
/** number of the tag, e.g. 4 for </b4> */
public int num;
/** is this a standalone tag, e.g. <br4/> */
public boolean alone;
/** Creates a tag */
public Tag(boolean end, String name, int num, boolean alone)
{
this.end = end;
this.name = name;
this.num = num;
this.alone = alone;
}
/** String form. */
public String toString()
{
return
"<" + // NOI18N
(end ? "/" : "") + // NOI18N
name +
num +
(alone ? "/" : "") + // NOI18N
">"; // NOI18N
}
/**
* String form of a paired tag: if this is a start tag,
* returns corresponding end tag, if this is an end tag,
* returns corresponding start tag, if this is a standalone tag,
* returns the same as {@link #toString()}.
*/
public String toStringPaired()
{
if (alone)
return toString();
else
return
"<" + // NOI18N
(end ? "" : "/") + // NOI18N
name +
num +
">"; // NOI18N
}
}
/**
* Upgrades segments of OmegaT's 1.4.x series to new tag numbering,
* and to new paired tag policy.
*/
private String upgradeOldTagsNumberingAndPairs(String segment)
{
if (!PatternConsts.OMEGAT_TAG.matcher(segment).find())
return segment;
try
{
StringBuffer buf = new StringBuffer(segment);
Matcher matcher = PatternConsts.OMEGAT_TAG_DECOMPILE.matcher(segment);
int tagstart = matcher.start();
int tagend = matcher.end();
boolean end = matcher.group(1).length()>0;
String name = matcher.group(2);
int num = Integer.parseInt(matcher.group(3));
boolean alone = matcher.group(4).length()>0;
if (num==1)
num = 0;
Tag tag = new Tag(end, name, num, alone);
List unclosedTags = new ArrayList();
List unopenedTags = new ArrayList();
Map unclosedTagsNames = new HashMap();
Map unopenedTagsNames = new HashMap();
if (end)
{
unopenedTags.add(tag);
unopenedTagsNames.put(name, tag);
}
else if (!alone)
{
unclosedTags.add(tag);
unclosedTagsNames.put(name, tag);
}
int maxnum = num;
buf.replace(tagstart, tagend, tag.toString());
while (matcher.find())
{
tagstart = matcher.start();
tagend = matcher.end();
end = matcher.group(1).length()>0;
name = matcher.group(2);
alone = matcher.group(4).length()>0;
tag = new Tag(end, name, num, alone);
if (end && unclosedTagsNames.containsKey(name))
{
Tag starttag = (Tag) unclosedTagsNames.get(name);
num = starttag.num;
unclosedTagsNames.remove(name);
unclosedTags.remove(starttag);
}
else
{
num = maxnum + 1;
if (end)
{
unopenedTags.add(tag);
unopenedTagsNames.put(name, tag);
}
else if (!alone)
{
unclosedTags.add(tag);
unclosedTagsNames.put(name, tag);
}
}
if (maxnum < num)
maxnum = num;
buf.replace(tagstart, tagend, tag.toString());
}
StringBuffer res = new StringBuffer();
for (int i = unopenedTags.size()-1; i>0; i--)
{
tag = (Tag) unopenedTags.get(i);
res.append(tag.toStringPaired());
}
res.append(buf);
for (int i = unclosedTags.size()-1; i>0; i--)
{
tag = (Tag) unclosedTags.get(i);
res.append(tag.toStringPaired());
}
return res.toString();
}
catch (Exception e)
{
return segment;
}
}
///////////////////////////////////////////////////////////////////////////
/** Collects a segment from TMX. Performs upgrades of a segment if needed. */
private void storeSegment(String source, String translation)
{
source = upgradeSegment(source);
translation = upgradeSegment(translation);
if (isUpgradeSentSeg())
{
List srcSegments = Segmenter.segment(source, null, null);
List tarSegments = Segmenter.segment(translation, null, null);
int n = srcSegments.size();
if( n==tarSegments.size() )
{
for(int j=0; j<n; j++)
{
String srcseg = (String)srcSegments.get(j);
String tarseg = (String)tarSegments.get(j);
m_srcList.add(srcseg);
m_tarList.add(tarseg);
}
}
else
{
m_srcList.add(source);
m_tarList.add(translation);
}
}
else
{
m_srcList.add(source);
m_tarList.add(translation);
}
}
///////////////////////////////////////////////////////////////////////////
private String segtype;
/** Segment Type attribute value: "paragraph" */
public static final String SEG_PARAGRAPH = "paragraph"; // NOI18N
/** Segment Type attribute value: "sentence" */
public static final String SEG_SENTENCE = "sentence"; // NOI18N
/** Returns Segment Type attribute of TMX file */
public String getSegType()
{
return segtype;
}
/**
* Determins if TMX level 2 codes should be included or skipped.
*/
private void checkLevel2() {
includeLevel2 = creationtool.equals(CT_OMEGAT);
}
/**
* Loads the specified TMX file by using a SAX parser.
*
* The parser makes callbacks to the TMXReader, to the methods
* warning, error, fatalError, startDocument, endDocument,
* startElement, endElement, characters, ignorableWhiteSpace,
* and resolveEntity. Together these methods implement the
* parsing of the TMX file.
*/
public void loadFile(String filename, boolean isProjectTMX)
throws IOException
{
this.isProjectTMX = isProjectTMX;
// parse the TMX file
try
{
// log the parsing attempt
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_READING_FILE"),
new Object[]{filename}));
// create a new SAX parser factory
javax.xml.parsers.SAXParserFactory parserFactory =
javax.xml.parsers.SAXParserFactory.newInstance();
// configure the factory
parserFactory.setValidating(false); // skips TMX validity checking
// create a new SAX parser
javax.xml.parsers.SAXParser parser = parserFactory.newSAXParser();
// make this TMX reader the default entity resolver for the parser,
// so we can handle DTD declarations ourselves
parser.getXMLReader().setEntityResolver(this);
// parse the TM, provide the current TMX reader as notification handler
InputSource is = new InputSource(new XMLReader(filename, m_encoding));
is.setSystemId(""); // NOI18N
parser.parse(is, this);
// if no source could be found for 1 or more TUs, log this fact
if (sourceNotFound)
StaticUtils.log(OStrings.getString("TMXR_WARNING_SOURCE_NOT_FOUND"));
// log the fact that parsing is done
StaticUtils.log(OStrings.getString("TMXR_INFO_READING_COMPLETE"));
StaticUtils.log("");
}
catch (SAXParseException exception) {
// log error
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_FATAL_ERROR_WHILE_PARSING"),
new Object[]{String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}));
exception.printStackTrace(StaticUtils.getLogStream());
// display error
CommandThread.core.displayErrorMessage(MessageFormat.format(
OStrings.getString("TMXR_FATAL_ERROR_WHILE_PARSING__DISPLAY"),
new Object[]{filename,
String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}),
exception);
}
catch (Exception exception)
{
// log exception
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_EXCEPTION_WHILE_PARSING"),
new Object[]{exception.getLocalizedMessage(), StaticUtils.getLogLocation()}));
exception.printStackTrace(StaticUtils.getLogStream());
// display error
CommandThread.core.displayErrorMessage(MessageFormat.format(
OStrings.getString("TMXR_EXCEPTION_WHILE_PARSING__DISPLAY"),
new Object[]{filename, exception.getLocalizedMessage()}),
exception);
}
}
/**
* Receives notification of a parser warning. Called by SAX parser.
*/
public void warning(SAXParseException exception) throws SAXException
{
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_WARNING_WHILE_PARSING"),
new Object[]{String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}));
exception.printStackTrace(StaticUtils.getLogStream());
}
/**
* Receives notification of a recoverable XML parsing error. Called by SAX parser.
*/
public void error(SAXParseException exception) throws SAXException
{
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_RECOVERABLE_ERROR_WHILE_PARSING"),
new Object[]{String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}));
exception.printStackTrace(StaticUtils.getLogStream());
}
/**
* Receives notification of a fatal XML parsing error. Called by SAX parser.
*/
public void fatalError(SAXParseException exception) throws SAXException
{
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_FATAL_ERROR_WHILE_PARSING"),
new Object[]{String.valueOf(exception.getLineNumber()),
String.valueOf(exception.getColumnNumber()),
exception.getLocalizedMessage()}));
exception.printStackTrace(StaticUtils.getLogStream());
}
/**
* Receives notification of the start of the XML document. Called by SAX parser.
*/
public void startDocument()
{
// initialise variables needed for parsing of the TMX file
headerParsed = false;
inHeader = false;
inTU = false;
inTUV = false;
inSegment = false;
tuvs = new ArrayList();
currentElement = new Stack();
currentSub = new Stack();
currentElement.push(TMX_TAG_NONE);
}
/**
* Receives notification of the end of the XML document. Called by SAX parser.
*/
public void endDocument()
{
// deallocate temp storage
tuvs = null;
currentElement = null;
currentSub = null;
}
/**
* Receives notification of the start of an element. Called by SAX parser.
*/
public void startElement(String uri,
String localName,
String qName,
Attributes attributes) throws SAXException
{
// determine the type of element and handle it, if required
if (qName.equals(TMX_TAG_HEADER))
startElementHeader(attributes);
else if (qName.equals(TMX_TAG_TU))
startElementTU(attributes);
else if (qName.equals(TMX_TAG_TUV))
startElementTUV(attributes);
else if (qName.equals(TMX_TAG_SEG))
startElementSegment(attributes);
else if ( qName.equals(TMX_TAG_BPT)
|| qName.equals(TMX_TAG_EPT)
|| qName.equals(TMX_TAG_HI)
|| qName.equals(TMX_TAG_IT)
|| qName.equals(TMX_TAG_PH)
|| qName.equals(TMX_TAG_UT))
startElementInline(attributes);
else if (qName.equals(TMX_TAG_SUB))
startElementSub(attributes);
else if (qName.equals(TMX_TAG_PROP))
startElementProperty(attributes);
}
/**
* Receives notification of the end of an element. Called by SAX parser.
*/
public void endElement(String uri,
String localName,
String qName) throws SAXException
{
// determine the type of element and handle it, if required
if (qName.equals(TMX_TAG_HEADER))
endElementHeader();
else if (qName.equals(TMX_TAG_TU))
endElementTU();
else if (qName.equals(TMX_TAG_TUV))
endElementTUV();
else if (qName.equals(TMX_TAG_SEG))
endElementSegment();
else if ( qName.equals(TMX_TAG_BPT)
|| qName.equals(TMX_TAG_EPT)
|| qName.equals(TMX_TAG_HI)
|| qName.equals(TMX_TAG_IT)
|| qName.equals(TMX_TAG_PH)
|| qName.equals(TMX_TAG_UT))
endElementInline();
else if (qName.equals(TMX_TAG_SUB))
endElementSub();
else if (qName.equals(TMX_TAG_PROP))
endElementProperty();
}
/**
* Receives character data in element content. Called by the SAX parser.
*/
public void characters(char[] ch,
int start,
int length) throws SAXException
{
// only read (sub)segments, properties, and inline codes (if required)
if ( inSegment
|| inProperty
|| (includeLevel2 && ((String)currentElement.peek()).equals(TMX_TAG_INLINE)))
{
// append the data to the current buffer
((StringBuffer)currentSub.peek()).append(ch, start, length);
}
}
/**
* Receives ignorable whitespace in element content. Called by the SAX parser.
*/
public void ignorableWhitespace(char[] ch,
int start,
int length) throws SAXException
{
// only read (sub)segments, properties, and inline codes (if required)
if ( inSegment
|| inProperty
|| (includeLevel2 && ((String)currentElement.peek()).equals(TMX_TAG_INLINE)))
{
// append the data to the current buffer
((StringBuffer)currentSub.peek()).append(ch, start, length);
}
}
/**
* Handles the start of the header of a TMX file.
*/
private void startElementHeader(Attributes attributes)
{
// mark the current position as in the header
inHeader = true;
// get the header attributes
creationtool = attributes.getValue(TMX_ATTR_CREATIONTOOL);
creationtoolversion = attributes.getValue(TMX_ATTR_CREATIONTOOLVERSION);
segtype = attributes.getValue(TMX_ATTR_SEGTYPE);
tmxSourceLanguage = attributes.getValue(TMX_ATTR_SRCLANG);
// log some details
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_CREATION_TOOL"),
new Object[]{creationtool}));
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_CREATION_TOOL_VERSION"),
new Object[]{creationtoolversion}));
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_SEG_TYPE"),
new Object[]{segtype}));
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_SOURCE_LANG"),
new Object[]{tmxSourceLanguage}));
// give a warning if the TMX source language is
// different from the project source language
if (!tmxSourceLanguage.equalsIgnoreCase(sourceLanguage))
{
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_WARNING_INCORRECT_SOURCE_LANG"),
new Object[]{tmxSourceLanguage, sourceLanguage}));
}
// give a warning that TMX file will be upgraded from 1.4.x
if (isUpgrade14X())
StaticUtils.log(OStrings.getString("TMXR_WARNING_UPGRADE_14X"));
// give a warning that TMX file will be upgraded to sentence segmentation
if (isUpgradeSentSeg())
StaticUtils.log(OStrings.getString("TMXR_WARNING_UPGRADE_SENTSEG"));
// check if level 2 codes should be included (only for OmegaT 1.6 RC13 and higher)
checkLevel2();
}
/**
* Handles the end of the TMX header
*/
private void endElementHeader() {
// mark the header as parsed
headerParsed = true;
// mark the current position as *not* in the header
inHeader = false;
// check for property OmegaT:VariantLanguages (only variants in these languages are read)
// if present, parse the property value, and get each separate language
String propVariantLanguages = getProperty(PROPERTY_VARIANT_LANGUAGES);
if (propVariantLanguages != null) {
int commaPos = 0;
StringBuffer languages = new StringBuffer();
do {
// get the position of the next comma
commaPos = propVariantLanguages.indexOf(',');
// get the next language
String language = commaPos > 0 ? propVariantLanguages.substring(0, commaPos).trim()
: propVariantLanguages.trim();
// add the language to the set, but trim off any region indicators
// for simplicity's sake, and convert it to all uppercase
if (language.length() > 0) {
m_variantLanguages.add(language.substring(0, 2).toUpperCase());
if (languages.length() > 0)
languages.append(", ");
languages.append(language.substring(0, 2).toUpperCase());
}
// trim the list of languages
propVariantLanguages = propVariantLanguages.substring(commaPos + 1);
}
while (commaPos > 0);
// Log presence of preferred variant languages
StaticUtils.log(MessageFormat.format(
OStrings.getString("TMXR_INFO_VARIANT_LANGUAGES_DISPLAYED"),
new Object[]{languages.toString()}));
}
}
/**
* Handles the start of a property
*/
private void startElementProperty(Attributes attributes) throws SAXException {
currentElement.push(TMX_TAG_PROP);
// ignore all properties outside the TMX header
if (!inHeader)
return;
// get the property name
currentProperty = attributes.getValue(TMX_ATTR_TYPE);
// put a property value buffer on the subsegment stack
// (ISSUE: field currentSub should be renamed to reflect this more general use)
currentSub.push(new StringBuffer());
// mark the current position as in a property
inProperty = true;
}
/**
* Handles the end of a property
*/
private void endElementProperty() {
currentElement.pop();
// mark the current position as *not* in a property
inProperty = false;
// ignore all properties outside the TMX header
if (!inHeader)
return;
// add the current property to the property map
StringBuffer propertyValue = (StringBuffer)currentSub.pop();
m_properties.put(currentProperty, propertyValue.toString());
currentProperty = null;
}
/**
* Handles the start of a translation unit.
*/
private void startElementTU(Attributes attributes) throws SAXException
{
currentElement.push(TMX_TAG_TU);
// ensure the header has been parsed
// without the header info, we can't determine what's source and what's target
if (!headerParsed)
throw new SAXException(OStrings.getString("TMXR_ERROR_TU_BEFORE_HEADER"));
// mark the current position as in a translation unit
inTU = true;
// clear the TUV list
tuvs.clear();
}
/**
* Handles the end of a translation unit.
*/
private void endElementTU()
{
currentElement.pop();
// mark the current position as *not* in a translation unit
inTU = false;
// determine source and (primary) target tuv
TUV source = null; // source TUV according to source language set by OmT
TUV target = null; // target TUV according to target language set by OmT
TUV sourceC = null; // candidate for source TUV according to source language set by OmT
TUV targetC = null; // candidate for target TUV according to target language set by OmT
TUV sourceT = null; // source TUV according to TMX source language
TUV sourceTC = null; // candidate for source TUV according to TMX source language
for (int i = 0; i < tuvs.size(); i++)
{
// get the next TUV
TUV tuv = (TUV)tuvs.get(i);
// first match TUV language against entire source language (lang code + reg code)
if ((source == null) && tuv.language.equalsIgnoreCase(sourceLanguage))
// the current TUV is the source
source = tuv;
// against entire target language
else if ((target == null) && tuv.language.equalsIgnoreCase(targetLanguage))
// the current TUV is the target
target = tuv;
// against source language code only
else if ((sourceC == null) && tuv.language.regionMatches(true, 0, sourceLanguage, 0, 2))
// the current TUV is a candidate for the source
sourceC = tuv;
// against target language code only
else if ((targetC == null) && tuv.language.regionMatches(true, 0, targetLanguage, 0, 2))
// the current TUV is a candidate for the target
targetC = tuv;
// if nothing matches, then try matching against the TMX source language
else if (isProjectTMX)
{
// match against entire TMX source language
if ( (sourceT == null)
&& ( tuv.language.equalsIgnoreCase(tmxSourceLanguage)
|| tmxSourceLanguage.equalsIgnoreCase("*all*"))) // NOI18N
// the current TUV is the source according to the TMX source language
sourceT = tuv;
// match against TMX source language code only
else if ( (sourceTC == null)
&& tuv.language.regionMatches(true, 0, tmxSourceLanguage, 0, 2))
// the current TUV is a candidate for the source according to the TMX source language
sourceTC = tuv;
}
// stop looking for source and target if both have been located
if ((source != null) && (target != null))
break;
}
// determine which source TUV to use
if (source == null)
source = sourceC; // try source candidate
if (source == null)
source = sourceT; // try source according to TMX
if (source == null)
source = sourceTC; // try source candidate according to TMX
// if no source was found, log a warning
if (source == null)
{
sourceNotFound = true;
return;
}
// determine what target TUV to use
// if none was found, create a temporary, empty one, for ease of coding
if (target == null)
target = targetC;
if (target == null)
target = new TUV();
// store the source & target segment
storeSegment(source.text.toString(), target.text.toString());
// store the source & target sub segments
// create exactly as many target subs as there are source subs
// "pad" with empty strings, or ommit segments if necessary
// NOTE: this is not the most ideal solution, but the best possible
for (int i = 0; i < source.subSegments.size(); i++)
{
String starget = new String();
if (i < target.subSegments.size())
starget = target.subSegments.get(i).toString();
storeSegment(source.subSegments.get(i).toString(), starget);
}
// store alternative translations
if (!isProjectTMX) {
for (int i = 0; i < tuvs.size(); i++) {
// get the next TUV
TUV tuv = (TUV)tuvs.get(i);
// store the TUV as alternative if it's source nor target
// and its language appears in the set of useful variant languages
if ( (tuv != source)
&& (tuv != target)
&& ( m_variantLanguages.isEmpty()
|| m_variantLanguages.contains(tuv.language.substring(0, 2).toUpperCase())))
storeSegment(source.text.toString(), tuv.text.toString());
}
}
}
/**
* Handles the start of a tuv element.
*/
private void startElementTUV(Attributes attributes)
{
currentElement.push(TMX_TAG_TUV);
// ensure we're in a translation unit
if (!inTU)
{
StaticUtils.log(OStrings.getString("TMXR_WARNING_TUV_NOT_IN_TU"));
return;
}
// get the language of the tuv
// try "xml:lang" first, then "lang"
String language = attributes.getValue(TMX_ATTR_LANG_NS);
if (language == null)
language = attributes.getValue(TMX_ATTR_LANG);
// if the language is not specified, skip the tuv
if (language == null)
{
StaticUtils.log(OStrings.getString("TMXR_WARNING_TUV_LANG_NOT_SPECIFIED"));
return;
}
// put a new TUV in the TUV list
TUV tuv = new TUV();
tuv.language = language;
tuvs.add(tuv);
// mark the current position as in a tuv
inTUV = true;
// clear the stack of sub segments
currentSub.clear();
}
/**
* Handles the end of a tuv element.
*/
private void endElementTUV()
{
currentElement.pop();
// mark the current position as *not* in a tuv element
inTUV = false;
}
/**
* Handles the start of a segment.
*/
private void startElementSegment(Attributes attributes)
{
currentElement.push(TMX_TAG_SEG);
// ensure we are currently in a tuv
if (!inTUV)
{
StaticUtils.log(OStrings.getString("TMXR_WARNING_SEG_NOT_IN_TUV"));
return;
}
// put the current TUV's segment buffer on the subsegment stack
// (ISSUE: field currentSub should be renamed to reflect this more general use)
currentSub.push(((TUV)tuvs.get(tuvs.size() - 1)).text);
// mark the current position as in a segment
inSegment = true;
}
/**
* Handles the end of a segment.
*/
private void endElementSegment()
{
currentElement.pop();
// do nothing if not in a TUV
if (!inTUV)
return;
// remove the current TUV's segment buffer from the subsegment stack
currentSub.pop();
// mark the current position as *not* in a segment
inSegment = false;
}
/**
* Handles the start of a TMX inline element (<bpt>, <ept>, <hi>, <it>, <ph>, <ut>).
*/
private void startElementInline(Attributes attributes)
{
currentElement.push(TMX_TAG_INLINE);
}
/**
* Handles the end of a TMX inline element (<bpt>, <ept>, <hi>, <it>, <ph>, <ut>).
*/
private void endElementInline()
{
currentElement.pop();
}
/**
* Handles the start of a SUB inline element.
*/
private void startElementSub(Attributes attributes)
{
currentElement.push(TMX_TAG_SUB);
// create new entries in the current TUV's sub segment list and on the stack
// NOTE: the assumption is made here that sub segments are
// in the same order in both source and target segments
StringBuffer sub = new StringBuffer(); // NOI18N
((TUV)tuvs.get(tuvs.size() - 1)).subSegments.add(sub);
currentSub.push(sub);
}
/**
* Handles the end of a SUB inline element.
*/
private void endElementSub() throws SAXException
{
currentElement.pop();
// remove the current sub from the sub stack
currentSub.pop();
}
/**
* Makes the parser skip DTDs.
*/
public org.xml.sax.InputSource resolveEntity(String publicId,
String systemId)
throws SAXException
{
// simply return an empty dtd
return new org.xml.sax.InputSource(new java.io.StringReader("")); // NOI18N
}
// Constants for certain TMX tag names/attributes
private final static String TMX_TMX_TAG = "tmx"; // NOI18N
private final static String TMX_TAG_HEADER = "header"; // NOI18N
private final static String TMX_TAG_BODY = "body"; // NOI18N
private final static String TMX_TAG_TU = "tu"; // NOI18N
private final static String TMX_TAG_TUV = "tuv"; // NOI18N
private final static String TMX_TAG_SEG = "seg"; // NOI18N
private final static String TMX_TAG_BPT = "bpt"; // NOI18N
private final static String TMX_TAG_EPT = "ept"; // NOI18N
private final static String TMX_TAG_HI = "hi"; // NOI18N
private final static String TMX_TAG_IT = "it"; // NOI18N
private final static String TMX_TAG_PH = "ph"; // NOI18N
private final static String TMX_TAG_UT = "ut"; // NOI18N
private final static String TMX_TAG_SUB = "sub"; // NOI18N
private final static String TMX_TAG_PROP = "prop"; // NOI18N
private final static String TMX_TAG_INLINE = "inline"; // made up for convenience // NOI18N
private final static String TMX_TAG_NONE = "none"; // made up for convenience // NOI18N
private final static String TMX_ATTR_LANG = "lang"; // NOI18N
private final static String TMX_ATTR_LANG_NS = "xml:lang"; // NOI18N
private final static String TMX_ATTR_CREATIONTOOL = "creationtool"; // NOI18N
private final static String TMX_ATTR_CREATIONTOOLVERSION = "creationtoolversion"; // NOI18N
private final static String TMX_ATTR_SEGTYPE = "segtype"; // NOI18N
private final static String TMX_ATTR_SRCLANG = "srclang"; // NOI18N
private final static String TMX_ATTR_TYPE = "type"; // NOI18N
private final static String PROPERTY_VARIANT_LANGUAGES = "OmegaT:VariantLanguages"; // NOI18N
private String m_encoding;
private List m_srcList;
private List m_tarList;
private Map m_properties; // Map<String, String> of TMX properties, specified in the header
private Set m_variantLanguages; // Set of (user) acceptable variant languages
private String sourceLanguage; // Language/country code set by OmT: LL(-CC)
private String targetLanguage; // Language/country code set by OmT: LL(-CC)
private String tmxSourceLanguage; // Language/country code as specified in TMX header: LL(-CC)
private boolean includeLevel2; // True if TMX level 2 markup must be interpreted
private boolean isProjectTMX; // True if the TMX file being loaded is the project TMX
private boolean headerParsed; // True if the TMX header has been parsed correctly
private boolean inHeader; // True if the current parsing point is in the HEADER element
private boolean inProperty; // True if in a PROP element
private boolean inTU; // True if in a TU element
private boolean inTUV; // True if in a TUV element
private boolean inSegment; // True if in a SEG element
private boolean sourceNotFound; // True if no source segment was found for one or more TUs
private List tuvs; // Contains all TUVs of the current TU
private Stack currentElement; // Stack of tag names up to the current parsing point
private Stack currentSub; // Stack of sub segment buffers
private String currentProperty; // Name of the current property being parsed (null if none)
/**
* Internal class to represent translation unit variants
*/
private class TUV
{
/**
* Language and (optional) country code: LL(C-CC)
*/
public String language;
/**
* Segment text
*/
public StringBuffer text;
/**
* Contains StringBuffers for subsegments
*/
public ArrayList subSegments;
/**
* Default constructor
*/
public TUV()
{
super();
text = new StringBuffer();
subSegments = new ArrayList();
}
}
}
| 45,907 | 0.536487 | 0.530897 | 1,176 | 38.091835 | 28.331644 | 106 | false | false | 0 | 0 | 0 | 0 | 76 | 0.004959 | 0.49915 | false | false | 3 |
927b5c3f53ed899ed2fa8bf7035ce8a6a564074a | 38,860,864,121,704 | 0f83eb7fa4b7b4992df0f6e6dac1cad14c83cd38 | /src/main/java/net/avuna/aoc/util/FrequencyMap.java | b6fc6ea8524bf152b50f1f43ec39c846cb59d88e | []
| no_license | LovinLifee/Advent-Of-Code-2020 | https://github.com/LovinLifee/Advent-Of-Code-2020 | 1ab95016838d565a7f0eaef9d3b6fa1abd20c0f5 | 414789c7559240bf0fc0fba742e2ffab7b509624 | refs/heads/main | 2023-01-28T23:21:56.485000 | 2020-12-14T04:37:48 | 2020-12-14T04:37:48 | 318,023,145 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.avuna.aoc.util;
import lombok.Getter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
/*
Who knew copying and pasting from your previous projects would be useful?
*/
@Getter
public class FrequencyMap<T> {
private final Map<T, AtomicInteger> backingMap = new HashMap<>();
public void clear() {
backingMap.clear();
}
public int increment(T key) {
AtomicInteger count = backingMap.computeIfAbsent(key, k -> new AtomicInteger());
return count.incrementAndGet();
}
public int getCount(T key) {
return backingMap.get(key).get();
}
public int getTotalCount() {
return backingMap.entrySet().stream().mapToInt(e -> e.getValue().get()).sum();
}
public Tuple<T, Integer> getMin() {
Map.Entry<T, AtomicInteger> entry = backingMap.entrySet().stream().min(Comparator.comparingInt(o -> o.getValue().get())).orElseThrow(NoSuchElementException::new);
return Tuple.of(entry.getKey(), entry.getValue().get());
}
public Tuple<T, Integer> getMax() {
Map.Entry<T, AtomicInteger> entry = backingMap.entrySet().stream().max(Comparator.comparingInt(o -> o.getValue().get())).orElseThrow(NoSuchElementException::new);
return Tuple.of(entry.getKey(), entry.getValue().get());
}
public double getAverageCount() {
return backingMap.entrySet().stream().mapToInt(e -> e.getValue().get()).average().orElseThrow(NoSuchElementException::new);
}
public void forEach(BiConsumer<T, Integer> action) {
backingMap.entrySet().iterator().forEachRemaining(e -> action.accept(e.getKey(), e.getValue().get()));
}
} | UTF-8 | Java | 1,821 | java | FrequencyMap.java | Java | []
| null | []
| package net.avuna.aoc.util;
import lombok.Getter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
/*
Who knew copying and pasting from your previous projects would be useful?
*/
@Getter
public class FrequencyMap<T> {
private final Map<T, AtomicInteger> backingMap = new HashMap<>();
public void clear() {
backingMap.clear();
}
public int increment(T key) {
AtomicInteger count = backingMap.computeIfAbsent(key, k -> new AtomicInteger());
return count.incrementAndGet();
}
public int getCount(T key) {
return backingMap.get(key).get();
}
public int getTotalCount() {
return backingMap.entrySet().stream().mapToInt(e -> e.getValue().get()).sum();
}
public Tuple<T, Integer> getMin() {
Map.Entry<T, AtomicInteger> entry = backingMap.entrySet().stream().min(Comparator.comparingInt(o -> o.getValue().get())).orElseThrow(NoSuchElementException::new);
return Tuple.of(entry.getKey(), entry.getValue().get());
}
public Tuple<T, Integer> getMax() {
Map.Entry<T, AtomicInteger> entry = backingMap.entrySet().stream().max(Comparator.comparingInt(o -> o.getValue().get())).orElseThrow(NoSuchElementException::new);
return Tuple.of(entry.getKey(), entry.getValue().get());
}
public double getAverageCount() {
return backingMap.entrySet().stream().mapToInt(e -> e.getValue().get()).average().orElseThrow(NoSuchElementException::new);
}
public void forEach(BiConsumer<T, Integer> action) {
backingMap.entrySet().iterator().forEachRemaining(e -> action.accept(e.getKey(), e.getValue().get()));
}
} | 1,821 | 0.676551 | 0.676551 | 54 | 32.740742 | 40.520313 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 3 |
a8e110373379912c8ac2923cc69a48f3d655a158 | 35,622,458,784,597 | 4552a4f1d62713951e1002561cc440972b973de4 | /RouterDemo/src/main/java/com/sample/routerdemo/business/controller/ThirdActivity.java | 43dbfe3cf516a1174dd26c8398f8db0f4b652827 | []
| no_license | HaoYundong/AndroidSampleTest | https://github.com/HaoYundong/AndroidSampleTest | 49f92d25afcdd73319bd233790db1f924f6a69a6 | 6b07dc366524be0d720923c452e92e6c995117b0 | refs/heads/master | 2021-01-24T17:01:39.136000 | 2019-01-23T08:33:31 | 2019-01-23T08:33:31 | 96,606,302 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sample.routerdemo.business.controller;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sample.routerdemo.R;
import com.sample.routerdemo.business.model.Person;
import com.sample.routerdemo.router.RouterManager;
@Route(path = RouterManager.PAGE_THIRD)
public class ThirdActivity extends AppCompatActivity {
@Autowired
public Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
ARouter.getInstance().inject(this);
}
public void showMsg(View view) {
if (person != null) {
Toast.makeText(this, person.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "信息为空", Toast.LENGTH_SHORT).show();
}
}
}
| UTF-8 | Java | 1,108 | java | ThirdActivity.java | Java | []
| null | []
| package com.sample.routerdemo.business.controller;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sample.routerdemo.R;
import com.sample.routerdemo.business.model.Person;
import com.sample.routerdemo.router.RouterManager;
@Route(path = RouterManager.PAGE_THIRD)
public class ThirdActivity extends AppCompatActivity {
@Autowired
public Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
ARouter.getInstance().inject(this);
}
public void showMsg(View view) {
if (person != null) {
Toast.makeText(this, person.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "信息为空", Toast.LENGTH_SHORT).show();
}
}
}
| 1,108 | 0.729091 | 0.728182 | 35 | 30.428572 | 23.054329 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
c8e25980772a1db8e59608481b13259af2cf052a | 1,082,331,799,084 | 0341fd626c1b81665abd461892dbb339021f97c5 | /Android_Libs/src/main/java/com/overtake/data/OTDataStatus.java | d4277c6d725df74c406fde211490d07d1024833f | []
| no_license | taixiang/Animation | https://github.com/taixiang/Animation | 6cc5aa40c8f94cdea10d26b7578609a90a6bf8d1 | b9bea3025ac94b39e1ff78b5bb2291e3b3b1ed2c | refs/heads/master | 2020-06-13T10:04:02.886000 | 2016-02-03T06:19:35 | 2016-02-03T06:19:35 | 50,978,411 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.overtake.data;
import java.util.Hashtable;
public final class OTDataStatus {
public OTDataOnlineStatus onlineStatus;
public int total;
public boolean hasMore;
public Hashtable<String, Object> userInfo;
public long timestamp;
public OTDataStatus() {
userInfo = new Hashtable<String, Object>();
}
}
| UTF-8 | Java | 325 | java | OTDataStatus.java | Java | []
| null | []
| package com.overtake.data;
import java.util.Hashtable;
public final class OTDataStatus {
public OTDataOnlineStatus onlineStatus;
public int total;
public boolean hasMore;
public Hashtable<String, Object> userInfo;
public long timestamp;
public OTDataStatus() {
userInfo = new Hashtable<String, Object>();
}
}
| 325 | 0.76 | 0.76 | 17 | 18.117647 | 16.087563 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.235294 | false | false | 3 |
b7da2d9dab83469fb160066dde13129e42595f6d | 14,645,838,501,714 | 3250a871949e432656398a831a798dad93645757 | /src/pl/edu/uwm/wmii/magdalenarajewska/laboratorium11/PairUtil.java | 73ec545828a24cded7a5367051ec11d35767b232 | []
| no_license | Maddallena/java | https://github.com/Maddallena/java | be63f9fce0c94aac43f2199cfc8f6a8ccbcb7539 | efa6775c1343b69eec2e3ccf27e13d73aafe5c41 | refs/heads/master | 2023-04-11T22:53:04.458000 | 2020-12-14T11:30:05 | 2020-12-14T11:30:05 | 362,210,407 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.edu.uwm.wmii.magdalenarajewska.laboratorium11;
public class PairUtil {
public static <T> Pair<T> swap(Pair<T> object){
Pair<T> temp = new Pair<>();
temp.setFirst(object.getSecond());
temp.setSecond(object.getFirst());
return temp;
}
}
| UTF-8 | Java | 288 | java | PairUtil.java | Java | []
| null | []
| package pl.edu.uwm.wmii.magdalenarajewska.laboratorium11;
public class PairUtil {
public static <T> Pair<T> swap(Pair<T> object){
Pair<T> temp = new Pair<>();
temp.setFirst(object.getSecond());
temp.setSecond(object.getFirst());
return temp;
}
}
| 288 | 0.631944 | 0.625 | 11 | 25.181818 | 20.568371 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 3 |
237647b50dba7a643fc472918e9e6bf02fefa62a | 16,226,386,485,702 | e060351bf6020e7718db3f89192cdab16655419c | /app/src/main/java/com/example/cheng/myapplication/room/Detail.java | 81fd39e8a6385833541e40347c299a49f4d5d2a9 | []
| no_license | xyz0z0/RoomDemo | https://github.com/xyz0z0/RoomDemo | 8332511954cacf1b1b40aabdccd709733ac52670 | 2e4af3d4335df28be6d7ce098e080baed678f799 | refs/heads/master | 2020-04-15T20:34:47.837000 | 2019-01-16T01:49:56 | 2019-01-16T01:49:56 | 164,999,875 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.cheng.myapplication.room;
import java.util.List;
/**
* Created by chengxg on 2019/1/10
*/
public class Detail {
public String street;
public String state;
public String city;
public List<String> detail;
public Detail(String street, String state, String city, List<String> detail) {
this.street = street;
this.state = state;
this.city = city;
this.detail = detail;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public List<String> getDetail() {
return detail;
}
public void setDetail(List<String> detail) {
this.detail = detail;
}
}
| UTF-8 | Java | 929 | java | Detail.java | Java | [
{
"context": "n.room;\n\nimport java.util.List;\n\n/**\n * Created by chengxg on 2019/1/10\n */\npublic class Detail {\n\n public ",
"end": 96,
"score": 0.9996585845947266,
"start": 89,
"tag": "USERNAME",
"value": "chengxg"
}
]
| null | []
| package com.example.cheng.myapplication.room;
import java.util.List;
/**
* Created by chengxg on 2019/1/10
*/
public class Detail {
public String street;
public String state;
public String city;
public List<String> detail;
public Detail(String street, String state, String city, List<String> detail) {
this.street = street;
this.state = state;
this.city = city;
this.detail = detail;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public List<String> getDetail() {
return detail;
}
public void setDetail(List<String> detail) {
this.detail = detail;
}
}
| 929 | 0.646932 | 0.639397 | 62 | 13.983871 | 16.286242 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.33871 | false | false | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.