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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d79ffea9b74ca93fb360759081ce14ac32eed9ba
| 6,227,702,597,378 |
dc5c0b9a93f65d065c7e93f6a9c749b02d07e15d
|
/app/src/main/java/fretx/version3/CustomGridViewAdapter.java
|
200691a8eaea60fea9869c317d18de57eb0bc4ef
|
[] |
no_license
|
BruceKhin/FRETXv3.0
|
https://github.com/BruceKhin/FRETXv3.0
|
8a04de8e3732d2d159fb9077f9a527072dac73c6
|
10b1e45f1796558057f15320b7230d865505f0a8
|
refs/heads/master
| 2020-04-06T04:06:00.590000 | 2016-12-16T17:36:02 | 2016-12-16T17:36:02 | 83,034,359 | 1 | 0 | null | true | 2017-02-24T11:22:28 | 2017-02-24T11:22:28 | 2017-02-24T11:22:25 | 2016-12-16T09:39:01 | 30,227 | 0 | 0 | 0 | null | null | null |
package fretx.version3;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
*
* @author manish.s
*
*/
public class CustomGridViewAdapter extends ArrayAdapter<SongItem> {
MainActivity context;
int layoutResourceId;
ArrayList<SongItem> data = new ArrayList<SongItem>();
public CustomGridViewAdapter(MainActivity context, int layoutResourceId,
ArrayList<SongItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
final SongItem item = data.get(position);
holder.txtTitle.setText(item.songName);
holder.imageItem.setImageBitmap(item.image);
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PlayFragmentYoutubeFragment fragmentYoutubeFragment = new PlayFragmentYoutubeFragment();
FragmentManager fragmentManager = context.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle args = new Bundle();
args.putString("URL", item.songURl);
args.putInt("RAW", item.songTxt);
fragmentYoutubeFragment.setArguments(args);
fragmentTransaction.replace(R.id.play_container, fragmentYoutubeFragment);
fragmentTransaction.commit();
}
});
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
|
UTF-8
|
Java
| 2,334 |
java
|
CustomGridViewAdapter.java
|
Java
|
[
{
"context": "\n\nimport java.util.ArrayList;\n\n\n/**\n * \n * @author manish.s\n *\n */\npublic class CustomGridViewAdapter exten",
"end": 460,
"score": 0.6806771159172058,
"start": 454,
"tag": "NAME",
"value": "manish"
},
{
"context": "t java.util.ArrayList;\n\n\n/**\n * \n * @author manish.s\n *\n */\npublic class CustomGridViewAdapter extends",
"end": 462,
"score": 0.5687893629074097,
"start": 461,
"tag": "USERNAME",
"value": "s"
}
] | null |
[] |
package fretx.version3;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
*
* @author manish.s
*
*/
public class CustomGridViewAdapter extends ArrayAdapter<SongItem> {
MainActivity context;
int layoutResourceId;
ArrayList<SongItem> data = new ArrayList<SongItem>();
public CustomGridViewAdapter(MainActivity context, int layoutResourceId,
ArrayList<SongItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
final SongItem item = data.get(position);
holder.txtTitle.setText(item.songName);
holder.imageItem.setImageBitmap(item.image);
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PlayFragmentYoutubeFragment fragmentYoutubeFragment = new PlayFragmentYoutubeFragment();
FragmentManager fragmentManager = context.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle args = new Bundle();
args.putString("URL", item.songURl);
args.putInt("RAW", item.songTxt);
fragmentYoutubeFragment.setArguments(args);
fragmentTransaction.replace(R.id.play_container, fragmentYoutubeFragment);
fragmentTransaction.commit();
}
});
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
| 2,334 | 0.752785 | 0.7515 | 84 | 26.797619 | 23.927858 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.119048 | false | false |
10
|
e7898ac92157a0a2d12abde49f1a6de691da8e82
| 30,416,958,408,801 |
1630f33245991a00088f73784ca3446dd41083dc
|
/src/pro2e/userinterface/plots/PlotPanelAmplituden.java
|
127b50ca704abd0d3ca09536fa2e7f0fac1f8efd
|
[
"MIT"
] |
permissive
|
818ajian/Donut
|
https://github.com/818ajian/Donut
|
23cab5d895f68ec1db2fa93006b5f7f7ba4e99c8
|
0ef29780f306c308d7573d12e01718b4fb56895d
|
refs/heads/master
| 2020-04-24T23:39:29.825000 | 2018-06-10T16:45:40 | 2018-06-10T16:45:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pro2e.userinterface.plots;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Observable;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import pro2e.DPIFixV3;
import pro2e.DonutFramework;
import pro2e.TraceV1;
import pro2e.matlabfunctions.Fensterfunktionen;
import pro2e.matlabfunctions.MiniMatlab;
import pro2e.model.Model;
import pro2e.userinterface.MyBorderFactory;
public class PlotPanelAmplituden extends JPanel {
private static final long serialVersionUID = -4522467773085225830L;
private JFreeChart chart = ChartFactory.createXYLineChart("", "Antennen", "Amplitude", null,
PlotOrientation.VERTICAL, false, false, false);
private TraceV1 trace = new TraceV1(this);
public PlotPanelAmplituden() {
super(new BorderLayout());
trace.constructorCall();
setPreferredSize(new Dimension(DPIFixV3.screen.width / 5, DPIFixV3.screen.height / 3));
setBorder(MyBorderFactory.createMyBorder(" Fensterfunktion "));
// Farben und Settings
chart.setBackgroundPaint(getBackground());
XYPlot xyplot = chart.getXYPlot();
ValueAxis xAxis = xyplot.getDomainAxis(0);
xAxis.setRange(0.0, 1.0);
xAxis.setAutoRange(false);
xAxis.setTickLabelsVisible(false);
ValueAxis yAxis = xyplot.getRangeAxis(0);
yAxis.setRange(0.0, 1.1);
yAxis.setAutoRange(false);
yAxis.setTickLabelsVisible(false);
yAxis.setTickLabelsVisible(true);
// MUSS VOR setRenderer AUFGERUFEN WERDEN
JFreeChartDPIFix.applyChartTheme(chart);
xyplot.setBackgroundPaint(Color.WHITE);
xyplot.setDomainGridlinePaint(Color.GRAY);
xyplot.setRangeGridlinePaint(Color.GRAY);
chart.setBackgroundPaint(this.getBackground());
XYItemRenderer renderer = new StandardXYItemRenderer();
renderer.setSeriesStroke(0, new BasicStroke(3f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
renderer.setSeriesPaint(0, DonutFramework.Colors.Pink);
xyplot.setRenderer(0, renderer);
renderer = new StandardXYItemRenderer();
renderer.setSeriesStroke(0, new BasicStroke(3f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
renderer.setSeriesPaint(0, Color.BLACK);
xyplot.setRenderer(1, renderer);
renderer = new StandardXYItemRenderer();
renderer.setSeriesStroke(0, new BasicStroke(3f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
renderer.setSeriesPaint(0, Color.GRAY);
xyplot.setRenderer(2, renderer);
add(new ChartPanel(chart));
}
/**
* <pre>
* setzt die Darstellung (zoom) auf den Ursprungszustand zurück
* </pre>
*/
public void resetAxis() {
trace.methodeCall();
XYPlot xyplot = chart.getXYPlot();
ValueAxis xAxis = xyplot.getDomainAxis(0);
xAxis.setRange(0.0, 1.0);
xAxis.setAutoRange(false);
ValueAxis yAxis = xyplot.getRangeAxis(0);
yAxis.setRange(0.0, 1.1);
yAxis.setAutoRange(false);
}
/**
* <pre>
* setzt die Daten für 3 Plots y = f(x)
* </pre>
* @param x
* @param y1
* @param y2
* @param y3
*/
public void setData(double[] x, double[] y1, double[] y2, double[] y3) {
trace.methodeCall();
XYSeries series = new XYSeries("Plot1");
for (int i = 0; i < x.length; i++) {
series.add(x[i], y1[i]);
}
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series);
chart.getXYPlot().setDataset(2, dataset);
series = new XYSeries("Plot2");
for (int i = 0; i < x.length; i++) {
series.add(x[i], y2[i]);
}
dataset = new XYSeriesCollection();
dataset.addSeries(series);
chart.getXYPlot().setDataset(1, dataset);
series = new XYSeries("Plot3");
for (int i = 0; i < x.length; i++) {
series.add(x[i], y3[i]);
}
dataset = new XYSeriesCollection();
dataset.addSeries(series);
chart.getXYPlot().setDataset(0, dataset);
repaint();
resetAxis(); // muss hier aufgerufen werden
}
/**
* <pre>
* holt die Daten aus dem Model und generiert 3 verschiedene Kurven
* (Funktion, Funkion mit n-Antennen, Diskretisierte Funktion mit n-Antennen)
* </pre>
* @param obs
* @param obj
*/
public void update(Observable obs, Object obj) {
trace.methodeCall();
Model model = (Model) obs;
int nAnt = model.getNAnt();
int nw = 301; // gewuenschte Anzahl Punkte
int d = nw / nAnt; // Breite (in Punkten) zwischen den Antennen
int N = d * nAnt; // tatsaechliche Anzahl Punkte
double[] xx = MiniMatlab.linspace(0, 1, N);
double[] y1 = new double[N];
double[] y3 = new double[N];
int type = model.getWindow();
double[] y4small = new double[nAnt];
switch (type) {
case Fensterfunktionen.BINOMIAL:
// y1 = Fensterfunktionen.Binominal(N);
y4small = Fensterfunktionen.Binominal(nAnt);
break;
case Fensterfunktionen.CHEBYSHEV:
// y1 = Fensterfunktionen.Chebwin(N, model.getWindowParam());
y4small = Fensterfunktionen.Chebwin(nAnt, model.getWindowParam());
break;
case Fensterfunktionen.COSINE:
y1 = Fensterfunktionen.Cosin(N, model.getWindowParam());
y4small = Fensterfunktionen.Cosin(nAnt, model.getWindowParam());
break;
case Fensterfunktionen.COSINESQUARE:
y1 = Fensterfunktionen.CosinSquare(N, model.getWindowParam());
y4small = Fensterfunktionen.CosinSquare(nAnt, model.getWindowParam());
break;
case Fensterfunktionen.EXPONENTIAL:
y1 = Fensterfunktionen.Exponential(N, model.getWindowParam());
y4small = Fensterfunktionen.Exponential(nAnt, model.getWindowParam());
break;
case Fensterfunktionen.TRIANGULAR:
y1 = Fensterfunktionen.Triangular(N);
y4small = Fensterfunktionen.Triangular(nAnt);
break;
default:
y1 = Fensterfunktionen.Rectangular(N);
y4small = Fensterfunktionen.Rectangular(nAnt);
}
double[] y4 = new double[N];
for (int i = 0; i < y4small.length; i++) {
for (int j = 0; j < d; j++) {
y4[i * d + j] = y4small[i];
}
}
if (model.isDiskretisierung()) {
y3 = Fensterfunktionen.Quantize(y4, model.getnBits());
} else {
y3 = y4;
}
if (type == Fensterfunktionen.CHEBYSHEV || type == Fensterfunktionen.BINOMIAL) {
y1 = y4;
}
setData(xx, y1, y4, y3);
}
}
|
UTF-8
|
Java
| 6,617 |
java
|
PlotPanelAmplituden.java
|
Java
|
[] | null |
[] |
package pro2e.userinterface.plots;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Observable;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import pro2e.DPIFixV3;
import pro2e.DonutFramework;
import pro2e.TraceV1;
import pro2e.matlabfunctions.Fensterfunktionen;
import pro2e.matlabfunctions.MiniMatlab;
import pro2e.model.Model;
import pro2e.userinterface.MyBorderFactory;
public class PlotPanelAmplituden extends JPanel {
private static final long serialVersionUID = -4522467773085225830L;
private JFreeChart chart = ChartFactory.createXYLineChart("", "Antennen", "Amplitude", null,
PlotOrientation.VERTICAL, false, false, false);
private TraceV1 trace = new TraceV1(this);
public PlotPanelAmplituden() {
super(new BorderLayout());
trace.constructorCall();
setPreferredSize(new Dimension(DPIFixV3.screen.width / 5, DPIFixV3.screen.height / 3));
setBorder(MyBorderFactory.createMyBorder(" Fensterfunktion "));
// Farben und Settings
chart.setBackgroundPaint(getBackground());
XYPlot xyplot = chart.getXYPlot();
ValueAxis xAxis = xyplot.getDomainAxis(0);
xAxis.setRange(0.0, 1.0);
xAxis.setAutoRange(false);
xAxis.setTickLabelsVisible(false);
ValueAxis yAxis = xyplot.getRangeAxis(0);
yAxis.setRange(0.0, 1.1);
yAxis.setAutoRange(false);
yAxis.setTickLabelsVisible(false);
yAxis.setTickLabelsVisible(true);
// MUSS VOR setRenderer AUFGERUFEN WERDEN
JFreeChartDPIFix.applyChartTheme(chart);
xyplot.setBackgroundPaint(Color.WHITE);
xyplot.setDomainGridlinePaint(Color.GRAY);
xyplot.setRangeGridlinePaint(Color.GRAY);
chart.setBackgroundPaint(this.getBackground());
XYItemRenderer renderer = new StandardXYItemRenderer();
renderer.setSeriesStroke(0, new BasicStroke(3f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
renderer.setSeriesPaint(0, DonutFramework.Colors.Pink);
xyplot.setRenderer(0, renderer);
renderer = new StandardXYItemRenderer();
renderer.setSeriesStroke(0, new BasicStroke(3f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
renderer.setSeriesPaint(0, Color.BLACK);
xyplot.setRenderer(1, renderer);
renderer = new StandardXYItemRenderer();
renderer.setSeriesStroke(0, new BasicStroke(3f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
renderer.setSeriesPaint(0, Color.GRAY);
xyplot.setRenderer(2, renderer);
add(new ChartPanel(chart));
}
/**
* <pre>
* setzt die Darstellung (zoom) auf den Ursprungszustand zurück
* </pre>
*/
public void resetAxis() {
trace.methodeCall();
XYPlot xyplot = chart.getXYPlot();
ValueAxis xAxis = xyplot.getDomainAxis(0);
xAxis.setRange(0.0, 1.0);
xAxis.setAutoRange(false);
ValueAxis yAxis = xyplot.getRangeAxis(0);
yAxis.setRange(0.0, 1.1);
yAxis.setAutoRange(false);
}
/**
* <pre>
* setzt die Daten für 3 Plots y = f(x)
* </pre>
* @param x
* @param y1
* @param y2
* @param y3
*/
public void setData(double[] x, double[] y1, double[] y2, double[] y3) {
trace.methodeCall();
XYSeries series = new XYSeries("Plot1");
for (int i = 0; i < x.length; i++) {
series.add(x[i], y1[i]);
}
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series);
chart.getXYPlot().setDataset(2, dataset);
series = new XYSeries("Plot2");
for (int i = 0; i < x.length; i++) {
series.add(x[i], y2[i]);
}
dataset = new XYSeriesCollection();
dataset.addSeries(series);
chart.getXYPlot().setDataset(1, dataset);
series = new XYSeries("Plot3");
for (int i = 0; i < x.length; i++) {
series.add(x[i], y3[i]);
}
dataset = new XYSeriesCollection();
dataset.addSeries(series);
chart.getXYPlot().setDataset(0, dataset);
repaint();
resetAxis(); // muss hier aufgerufen werden
}
/**
* <pre>
* holt die Daten aus dem Model und generiert 3 verschiedene Kurven
* (Funktion, Funkion mit n-Antennen, Diskretisierte Funktion mit n-Antennen)
* </pre>
* @param obs
* @param obj
*/
public void update(Observable obs, Object obj) {
trace.methodeCall();
Model model = (Model) obs;
int nAnt = model.getNAnt();
int nw = 301; // gewuenschte Anzahl Punkte
int d = nw / nAnt; // Breite (in Punkten) zwischen den Antennen
int N = d * nAnt; // tatsaechliche Anzahl Punkte
double[] xx = MiniMatlab.linspace(0, 1, N);
double[] y1 = new double[N];
double[] y3 = new double[N];
int type = model.getWindow();
double[] y4small = new double[nAnt];
switch (type) {
case Fensterfunktionen.BINOMIAL:
// y1 = Fensterfunktionen.Binominal(N);
y4small = Fensterfunktionen.Binominal(nAnt);
break;
case Fensterfunktionen.CHEBYSHEV:
// y1 = Fensterfunktionen.Chebwin(N, model.getWindowParam());
y4small = Fensterfunktionen.Chebwin(nAnt, model.getWindowParam());
break;
case Fensterfunktionen.COSINE:
y1 = Fensterfunktionen.Cosin(N, model.getWindowParam());
y4small = Fensterfunktionen.Cosin(nAnt, model.getWindowParam());
break;
case Fensterfunktionen.COSINESQUARE:
y1 = Fensterfunktionen.CosinSquare(N, model.getWindowParam());
y4small = Fensterfunktionen.CosinSquare(nAnt, model.getWindowParam());
break;
case Fensterfunktionen.EXPONENTIAL:
y1 = Fensterfunktionen.Exponential(N, model.getWindowParam());
y4small = Fensterfunktionen.Exponential(nAnt, model.getWindowParam());
break;
case Fensterfunktionen.TRIANGULAR:
y1 = Fensterfunktionen.Triangular(N);
y4small = Fensterfunktionen.Triangular(nAnt);
break;
default:
y1 = Fensterfunktionen.Rectangular(N);
y4small = Fensterfunktionen.Rectangular(nAnt);
}
double[] y4 = new double[N];
for (int i = 0; i < y4small.length; i++) {
for (int j = 0; j < d; j++) {
y4[i * d + j] = y4small[i];
}
}
if (model.isDiskretisierung()) {
y3 = Fensterfunktionen.Quantize(y4, model.getnBits());
} else {
y3 = y4;
}
if (type == Fensterfunktionen.CHEBYSHEV || type == Fensterfunktionen.BINOMIAL) {
y1 = y4;
}
setData(xx, y1, y4, y3);
}
}
| 6,617 | 0.695692 | 0.676946 | 212 | 29.202829 | 22.639534 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.349057 | false | false |
10
|
2e1f7a20987cdc3639d570bf3c8cb133709e2c67
| 30,124,900,629,171 |
a9d53ad7cb2234432fe68b5141ca21e13707ecba
|
/src/com/practice/linkedlist/PartitionLinkedList.java
|
72ac79d4de6ebb185f9626e8eb099f197d2691dc
|
[] |
no_license
|
LearnAndShare/interview
|
https://github.com/LearnAndShare/interview
|
f605ad1dcba0b5d99764e25813357e6afe5bfb05
|
9341bca9daff34ae44cd4563e07e30a949d82251
|
refs/heads/master
| 2021-07-08T12:51:16.515000 | 2020-09-13T00:19:00 | 2020-09-13T00:19:00 | 189,089,156 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.practice.linkedlist;
import com.practice.linkedlist.ListNode;
/*
https://leetcode.com/problems/partition-list/
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->3->4->5
*/
public class PartitionLinkedList {
public ListNode partition(ListNode head, int x) {
ListNode p = head;
ListNode fakeHead = new ListNode(0);
ListNode fakeHead2 = new ListNode(0);
fakeHead.next = head;
ListNode prev = fakeHead;
ListNode p2 = fakeHead2;
while(p != null){
if(p.val < x){
p = p.next;
prev = prev.next;
} else {
p2.next = p;
prev.next = p.next;
p=p.next;
p2=p2.next;
}
}
p2.next = null;
prev.next = fakeHead2.next;
return fakeHead.next;
}
}
|
UTF-8
|
Java
| 1,106 |
java
|
PartitionLinkedList.java
|
Java
|
[] | null |
[] |
package com.practice.linkedlist;
import com.practice.linkedlist.ListNode;
/*
https://leetcode.com/problems/partition-list/
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->3->4->5
*/
public class PartitionLinkedList {
public ListNode partition(ListNode head, int x) {
ListNode p = head;
ListNode fakeHead = new ListNode(0);
ListNode fakeHead2 = new ListNode(0);
fakeHead.next = head;
ListNode prev = fakeHead;
ListNode p2 = fakeHead2;
while(p != null){
if(p.val < x){
p = p.next;
prev = prev.next;
} else {
p2.next = p;
prev.next = p.next;
p=p.next;
p2=p2.next;
}
}
p2.next = null;
prev.next = fakeHead2.next;
return fakeHead.next;
}
}
| 1,106 | 0.565099 | 0.544304 | 42 | 25.333334 | 24.363974 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false |
10
|
6a19ed569c8011d61ae41860f68ca800ba856d76
| 27,350,351,752,254 |
48b8ab6fb873a990a15979bd424bc65c70e54b3e
|
/src/main/java/com/mx/demo/controller/TestController.java
|
4ddf777201a7212a270cd44b753787224a48283a
|
[] |
no_license
|
maxu78/Demo
|
https://github.com/maxu78/Demo
|
7597ff7e34c5765a0a1b67ecf2fcc2144a2cb845
|
09a3cc8d2d1aa4c7537389da26577becfbc873c6
|
refs/heads/master
| 2021-05-07T14:20:20.638000 | 2017-11-17T02:15:57 | 2017-11-17T02:15:57 | 109,807,172 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mx.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/index")
public String index(){
System.out.println("index");
return "test";
}
@RequestMapping("/home1")
public String getHome(){
return "home";
}
@RequestMapping("/indexHtml")
public String getIndex(){
//return "redirect:/index.html";
return "forward:/index.html";
}
@RequestMapping("/indexJsp")
public String getJspIndex(){
//return "redirect:/index.html";
return "index";
}
@RequestMapping("/{para}")
@ResponseBody
public String test(@PathVariable(name = "para") String para){
System.out.println(para);
return para;
}
}
|
UTF-8
|
Java
| 1,019 |
java
|
TestController.java
|
Java
|
[] | null |
[] |
package com.mx.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/index")
public String index(){
System.out.println("index");
return "test";
}
@RequestMapping("/home1")
public String getHome(){
return "home";
}
@RequestMapping("/indexHtml")
public String getIndex(){
//return "redirect:/index.html";
return "forward:/index.html";
}
@RequestMapping("/indexJsp")
public String getJspIndex(){
//return "redirect:/index.html";
return "index";
}
@RequestMapping("/{para}")
@ResponseBody
public String test(@PathVariable(name = "para") String para){
System.out.println(para);
return para;
}
}
| 1,019 | 0.65947 | 0.658489 | 44 | 22.15909 | 18.979586 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false |
10
|
ff2e878f88c540ae01e2313ed3929149752b44f1
| 15,710,990,373,544 |
65ca7b5a1ba85da22a09808fa934f205fa389c83
|
/src/main/java/com/intuit/cg/blackjack/deck/BlackjackCardshoe.java
|
077af6b01f1d37abf4d0fa3efa1c2cf8afb97b31
|
[] |
no_license
|
AKAProfessor/card_games
|
https://github.com/AKAProfessor/card_games
|
067c767190852d93afbbadf5a9442fa9e4f2170b
|
eab72c5613dfa0c35a19b55494953f66c5e148fc
|
refs/heads/master
| 2020-05-04T21:17:57.935000 | 2019-03-29T17:54:21 | 2019-04-10T19:42:43 | 179,471,310 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.intuit.cg.blackjack.deck;
import com.intuit.cg.deck.DefaultCardShoe;
/**
*
* @author sakhim
*/
public class BlackjackCardshoe extends DefaultCardShoe {
public BlackjackCardshoe(int numberOfDecks) {
super(numberOfDecks);
}
@Override
public int draw() {
int cardRank = super.draw();
// Face cards J (11), Q (12) and K (13) are worth 10 in Blackjack
return cardRank > 10 ? 10 : cardRank;
}
}
|
UTF-8
|
Java
| 461 |
java
|
BlackjackCardshoe.java
|
Java
|
[
{
"context": "intuit.cg.deck.DefaultCardShoe;\n\n/**\n *\n * @author sakhim\n */\npublic class BlackjackCardshoe extends Defaul",
"end": 107,
"score": 0.9943258762359619,
"start": 101,
"tag": "USERNAME",
"value": "sakhim"
}
] | null |
[] |
package com.intuit.cg.blackjack.deck;
import com.intuit.cg.deck.DefaultCardShoe;
/**
*
* @author sakhim
*/
public class BlackjackCardshoe extends DefaultCardShoe {
public BlackjackCardshoe(int numberOfDecks) {
super(numberOfDecks);
}
@Override
public int draw() {
int cardRank = super.draw();
// Face cards J (11), Q (12) and K (13) are worth 10 in Blackjack
return cardRank > 10 ? 10 : cardRank;
}
}
| 461 | 0.639913 | 0.613883 | 22 | 19.954546 | 21.805916 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false |
10
|
68f50fbfdad371e42fabbc9b03bfbeb0c331cf09
| 22,230,750,744,914 |
8fd40abf2ba6c63c90a8dbd3e9aeee84675aa959
|
/src/main/java/com/bunchiestudios/robotcode/MyRobot.java
|
80941aef805ac22d4c5801e9f22a27209696d8fd
|
[] |
no_license
|
bunchiestudios/FRsim
|
https://github.com/bunchiestudios/FRsim
|
4cacf51d856d0059667881284b853afb460ab14c
|
dc3a0bd592b074c2d355228aa79188258bb6bdd0
|
refs/heads/master
| 2022-08-18T15:18:47.867000 | 2020-10-20T10:48:50 | 2020-10-20T10:48:50 | 73,127,131 | 0 | 0 | null | false | 2022-07-01T22:17:44 | 2016-11-07T22:34:41 | 2020-10-20T10:48:54 | 2022-07-01T22:17:44 | 49 | 0 | 0 | 1 |
Java
| false | false |
package com.bunchiestudios.robotcode;
import com.bunchiestudios.wpi.IterativeRobot;
/**
* Created by franspaco on 13/11/16.
*/
public class MyRobot extends IterativeRobot {
public void robotInit() {
}
public void autonomousInit() {
}
public void autonomousPeriodic() {
}
public void teleopInit() {
}
public void teleopPeriodic() {
}
}
|
UTF-8
|
Java
| 389 |
java
|
MyRobot.java
|
Java
|
[
{
"context": "chiestudios.wpi.IterativeRobot;\n\n/**\n * Created by franspaco on 13/11/16.\n */\npublic class MyRobot extends Ite",
"end": 113,
"score": 0.9995430111885071,
"start": 104,
"tag": "USERNAME",
"value": "franspaco"
}
] | null |
[] |
package com.bunchiestudios.robotcode;
import com.bunchiestudios.wpi.IterativeRobot;
/**
* Created by franspaco on 13/11/16.
*/
public class MyRobot extends IterativeRobot {
public void robotInit() {
}
public void autonomousInit() {
}
public void autonomousPeriodic() {
}
public void teleopInit() {
}
public void teleopPeriodic() {
}
}
| 389 | 0.650386 | 0.634961 | 29 | 12.413794 | 16.491413 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.068966 | false | false |
10
|
996522d712825fb6456fef43241166feb18b2091
| 5,299,989,669,731 |
80620c94736c30cd8b1d3a15cb5b5d3ae75f59b6
|
/src/com/baobab/m/dao/PaymentMapper.java
|
339ef8346754f1a884512c926360e058e8d7896c
|
[] |
no_license
|
cwy0105/baobab858
|
https://github.com/cwy0105/baobab858
|
71378ba4d2eb8e645884ef15fb8079f45998ca51
|
cde2c53df57de3c8076edf14b5d0059d26e9e6de
|
refs/heads/master
| 2022-12-21T20:34:17.282000 | 2019-08-27T08:35:22 | 2019-08-27T08:35:22 | 204,643,538 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.baobab.m.dao;
import java.util.List;
import com.baobab.m.vo.PaymentVO;
import com.baobab.m.vo.UserLocationVO;
public interface PaymentMapper {
void payInfoInsert(PaymentVO vo);
void statusChange(PaymentVO vo);
List<PaymentVO> payAllSelect(PaymentVO vo);
PaymentVO payOneSelect(PaymentVO vo);
void delPayInfo(PaymentVO vo);
void usedUpdate(PaymentVO vo);
List<PaymentVO> cpAllSelect(PaymentVO vo);
PaymentVO payDetail(PaymentVO vo);
void receiptChange(PaymentVO vo);
String useCheck(String orderNum);
void tidUpdate(PaymentVO vo);
void payCancel(PaymentVO vo);
List<PaymentVO> payCurDate(String email);
List<PaymentVO> cancelCurDate(String email);
UserLocationVO customerPush(String user);
UserLocationVO cpUserPush(int seq);
}
|
UTF-8
|
Java
| 760 |
java
|
PaymentMapper.java
|
Java
|
[] | null |
[] |
package com.baobab.m.dao;
import java.util.List;
import com.baobab.m.vo.PaymentVO;
import com.baobab.m.vo.UserLocationVO;
public interface PaymentMapper {
void payInfoInsert(PaymentVO vo);
void statusChange(PaymentVO vo);
List<PaymentVO> payAllSelect(PaymentVO vo);
PaymentVO payOneSelect(PaymentVO vo);
void delPayInfo(PaymentVO vo);
void usedUpdate(PaymentVO vo);
List<PaymentVO> cpAllSelect(PaymentVO vo);
PaymentVO payDetail(PaymentVO vo);
void receiptChange(PaymentVO vo);
String useCheck(String orderNum);
void tidUpdate(PaymentVO vo);
void payCancel(PaymentVO vo);
List<PaymentVO> payCurDate(String email);
List<PaymentVO> cancelCurDate(String email);
UserLocationVO customerPush(String user);
UserLocationVO cpUserPush(int seq);
}
| 760 | 0.793421 | 0.793421 | 26 | 28.23077 | 14.582149 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.423077 | false | false |
10
|
e029b287e2fe64afeec3152e4cf9c5880126de6e
| 33,466,385,189,971 |
89db485953ac60aea061c90984ac98a90971e818
|
/spring/src/com/cn/test/test06.java
|
781ac7048d663777510f6603dde7a4e2a9479984
|
[] |
no_license
|
duguboxia/spring_low
|
https://github.com/duguboxia/spring_low
|
41540c742c7fb12cf3fbdfe3ea65f09f5e93f4f5
|
f546129122fe10b175d8a5cce3a75217712d68b2
|
refs/heads/master
| 2020-08-31T02:55:42.623000 | 2019-10-30T15:59:22 | 2019-10-30T15:59:22 | 218,565,527 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cn.test;
import com.cn.dao.Animal;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test06 {
public static void main(String[] args) {
ApplicationContext applicationContext=new
ClassPathXmlApplicationContext("beans06.xml");
Animal animal=(Animal)applicationContext.getBean("animal");
System.out.println(animal.getType());
System.out.println(animal.getColor());
System.out.println(animal.getInfos());
System.out.println(animal.getMysqlInfos());
System.out.println(animal.getMembers());//数组打印的是地址
for (String s:animal.getMembers()
) {
System.out.println(s);
}
}
}
|
UTF-8
|
Java
| 806 |
java
|
test06.java
|
Java
|
[] | null |
[] |
package com.cn.test;
import com.cn.dao.Animal;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test06 {
public static void main(String[] args) {
ApplicationContext applicationContext=new
ClassPathXmlApplicationContext("beans06.xml");
Animal animal=(Animal)applicationContext.getBean("animal");
System.out.println(animal.getType());
System.out.println(animal.getColor());
System.out.println(animal.getInfos());
System.out.println(animal.getMysqlInfos());
System.out.println(animal.getMembers());//数组打印的是地址
for (String s:animal.getMembers()
) {
System.out.println(s);
}
}
}
| 806 | 0.677215 | 0.672152 | 22 | 34.909092 | 22.502342 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
10
|
736bd828e3cdf989f1e345735e1218e5dfa2d352
| 26,792,006,002,102 |
e7ca6161e813584c2b5bef43094f4be49013d1de
|
/mongodao-core/src/main/java/com/github/aidensuen/mongo/mapping/ExampleStr.java
|
590c76cb6b03f31da13cf43b170f88b1fbb8a93d
|
[] |
no_license
|
aidensuen/Mongodao
|
https://github.com/aidensuen/Mongodao
|
05d8a559bf988def32a7fb39684a8e3a42a99372
|
639edfc4a6dbe8833df88deb40c51f6ecf5bf276
|
refs/heads/master
| 2020-04-18T18:10:32.782000 | 2019-07-10T04:15:09 | 2019-07-10T04:15:09 | 167,676,267 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.aidensuen.mongo.mapping;
import java.util.HashMap;
public class ExampleStr extends HashMap {
}
|
UTF-8
|
Java
| 116 |
java
|
ExampleStr.java
|
Java
|
[
{
"context": "package com.github.aidensuen.mongo.mapping;\n\nimport java.util.HashMap;\n\npublic",
"end": 28,
"score": 0.9497458338737488,
"start": 19,
"tag": "USERNAME",
"value": "aidensuen"
}
] | null |
[] |
package com.github.aidensuen.mongo.mapping;
import java.util.HashMap;
public class ExampleStr extends HashMap {
}
| 116 | 0.801724 | 0.801724 | 6 | 18.333334 | 18.882679 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
10
|
b3606b3bbd0f34285ed83a5ab05eb2b04ff578a2
| 6,682,969,124,584 |
ef6cece75371f1694e7a1d74c10568cc828b91a9
|
/java/Components/Strata.Foundation.Core/src/strata/foundation/core/value/PhoneNumber.java
|
069d5871ed81c70e3831ae1a0ba842ba1801adb1
|
[] |
no_license
|
StrataFrameworkSet/Strata
|
https://github.com/StrataFrameworkSet/Strata
|
e9a30594cbba0d0d205704e1503cd5aa8e862ebe
|
348c9c68c1fea1377dad9f08014dda6d131e83e6
|
refs/heads/development
| 2021-06-19T07:11:02.304000 | 2021-03-24T00:10:53 | 2021-03-24T00:10:53 | 30,888,199 | 0 | 0 | null | false | 2019-07-31T05:59:07 | 2015-02-16T21:02:51 | 2019-07-31T05:57:14 | 2019-07-31T05:59:06 | 75,107 | 0 | 0 | 0 |
Java
| false | false |
//////////////////////////////////////////////////////////////////////////////
// PhoneNumber.java
//////////////////////////////////////////////////////////////////////////////
package strata.foundation.core.value;
import java.io.Serializable;
public
class PhoneNumber
implements Serializable
{
private String itsPhone;
private static final String NANP_PATTERN =
"^([1][-.\\s]?)?\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$";
private static final String ITU_T_PATTERN =
"^\\+(?:[0-9] ?){6,14}[0-9]$";
private static final String EPP_PATTERN =
"^\\+[0-9]{1,3}\\.[0-9]{4,14}(?:x.+)?$";
public
PhoneNumber(String phoneNumber)
{
validatePhoneNumber(phoneNumber);
itsPhone = phoneNumber;
}
public boolean
equals(PhoneNumber other)
{
return itsPhone.equals(other.itsPhone);
}
@Override
public boolean
equals(Object other)
{
return
other instanceof PhoneNumber && equals((PhoneNumber)other);
}
@Override
public int
hashCode()
{
return 51 * itsPhone.hashCode();
}
@Override
public String
toString()
{
return itsPhone;
}
public String
getDigitsOnly()
{
return
itsPhone
.chars()
.mapToObj(c -> (char)c)
.filter(Character::isDigit)
.collect(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append)
.toString();
}
private static void
validatePhoneNumber(String input)
{
if (!checkPhoneNumber(input))
throw
new IllegalArgumentException(
"Unrecognized phone format: " + input);
}
private static boolean
checkPhoneNumber(String input)
{
if (input.matches(NANP_PATTERN))
return true;
if (input.matches(ITU_T_PATTERN))
return true;
if (input.matches(EPP_PATTERN))
return true;
return false;
}
}
//////////////////////////////////////////////////////////////////////////////
|
UTF-8
|
Java
| 2,230 |
java
|
PhoneNumber.java
|
Java
|
[] | null |
[] |
//////////////////////////////////////////////////////////////////////////////
// PhoneNumber.java
//////////////////////////////////////////////////////////////////////////////
package strata.foundation.core.value;
import java.io.Serializable;
public
class PhoneNumber
implements Serializable
{
private String itsPhone;
private static final String NANP_PATTERN =
"^([1][-.\\s]?)?\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$";
private static final String ITU_T_PATTERN =
"^\\+(?:[0-9] ?){6,14}[0-9]$";
private static final String EPP_PATTERN =
"^\\+[0-9]{1,3}\\.[0-9]{4,14}(?:x.+)?$";
public
PhoneNumber(String phoneNumber)
{
validatePhoneNumber(phoneNumber);
itsPhone = phoneNumber;
}
public boolean
equals(PhoneNumber other)
{
return itsPhone.equals(other.itsPhone);
}
@Override
public boolean
equals(Object other)
{
return
other instanceof PhoneNumber && equals((PhoneNumber)other);
}
@Override
public int
hashCode()
{
return 51 * itsPhone.hashCode();
}
@Override
public String
toString()
{
return itsPhone;
}
public String
getDigitsOnly()
{
return
itsPhone
.chars()
.mapToObj(c -> (char)c)
.filter(Character::isDigit)
.collect(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append)
.toString();
}
private static void
validatePhoneNumber(String input)
{
if (!checkPhoneNumber(input))
throw
new IllegalArgumentException(
"Unrecognized phone format: " + input);
}
private static boolean
checkPhoneNumber(String input)
{
if (input.matches(NANP_PATTERN))
return true;
if (input.matches(ITU_T_PATTERN))
return true;
if (input.matches(EPP_PATTERN))
return true;
return false;
}
}
//////////////////////////////////////////////////////////////////////////////
| 2,230 | 0.46861 | 0.456054 | 100 | 21.299999 | 20.215094 | 81 | false | false | 0 | 0 | 0 | 0 | 92 | 0.113901 | 0.23 | false | false |
10
|
b78e2d181b7fb6dd83520190ce2877d29e2335c2
| 8,521,215,132,761 |
f738046a4d619847135343694be18e0cd7784c0d
|
/RemedialOpdracht2/src/ModelDrinken/SoftDrink.java
|
2fc33664df981aaadfd2ca76df2ac3450f3154b8
|
[] |
no_license
|
ghatasj001/PO2DataStruct
|
https://github.com/ghatasj001/PO2DataStruct
|
5b2f7e5898d04a2e4fd742cec40e7fef8b9c25da
|
449cf204b52d65b5c2b851c7c99c4b72f91f00f9
|
refs/heads/master
| 2017-12-30T01:30:12.345000 | 2016-11-06T21:34:32 | 2016-11-06T21:34:32 | 70,158,062 | 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 ModelDrinken;
/**
*
* @author J
*/
public class SoftDrink extends Drinken{
private boolean heeftPrik;
public SoftDrink(boolean heeftPrik, String naam, String beschrijving, double prijs, int calorien, double cl) {
super(naam, beschrijving, prijs, calorien, cl);
this.heeftPrik = heeftPrik;
}
public boolean isHeeftPrik() {
return heeftPrik;
}
public void setHeeftPrik(boolean heeftPrik) {
this.heeftPrik = heeftPrik;
}
@Override
public String toString() {
return String.format("%-15s", this.getNaam()) + String.format("%-15b", this.heeftPrik) + String.format("%.2f cl", this.getCl()) + String.format("%12.2f", this.getPrijs());
}
}
|
UTF-8
|
Java
| 915 |
java
|
SoftDrink.java
|
Java
|
[
{
"context": "itor.\n */\npackage ModelDrinken;\n\n/**\n *\n * @author J\n */\npublic class SoftDrink extends Drinken{\n p",
"end": 227,
"score": 0.7045650482177734,
"start": 226,
"tag": "NAME",
"value": "J"
}
] | 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 ModelDrinken;
/**
*
* @author J
*/
public class SoftDrink extends Drinken{
private boolean heeftPrik;
public SoftDrink(boolean heeftPrik, String naam, String beschrijving, double prijs, int calorien, double cl) {
super(naam, beschrijving, prijs, calorien, cl);
this.heeftPrik = heeftPrik;
}
public boolean isHeeftPrik() {
return heeftPrik;
}
public void setHeeftPrik(boolean heeftPrik) {
this.heeftPrik = heeftPrik;
}
@Override
public String toString() {
return String.format("%-15s", this.getNaam()) + String.format("%-15b", this.heeftPrik) + String.format("%.2f cl", this.getCl()) + String.format("%12.2f", this.getPrijs());
}
}
| 915 | 0.663388 | 0.654645 | 32 | 27.5625 | 38.048439 | 181 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.71875 | false | false |
10
|
81dde13f88d3d5cb2a481c53d1b061326ef0a29f
| 7,876,970,068,861 |
6ec6ac472e77c874b3b64f3d0a1b1a35c5a7ff34
|
/POO/src/Nivel2/Operaciones4.java
|
fd5fa8fa2cfe08c4089fc7fc0f08b24535d07eff
|
[] |
no_license
|
ItsLuized/Java-Learning
|
https://github.com/ItsLuized/Java-Learning
|
d7bd0af4b204f97423edf39ed6cd47c7a84dfaf4
|
230e8d0f2bec394392591ced2f5e0ef81db0bf50
|
refs/heads/master
| 2021-05-16T00:48:17.525000 | 2020-03-16T22:38:30 | 2020-03-16T22:38:30 | 107,079,649 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Nivel2;
import javax.swing.JOptionPane;
/**
*
* @author Luized
*/
public class Operaciones4
{
//1. Atributos o variables de clases
private float[] datos;
private float[] ordenados;
private float prom;
//2. Métodos:
//Obligatorios:
public static void main(String[] args)
{
new Operaciones4();
}
public Operaciones4()
{
this.datos = null;
this.ordenados = null;
this.prom = 0;
this.menu();
}
// De servivio:
private void menu()
{
char opcion;
boolean yaCapturo = false;
do{
opcion=JOptionPane.showInputDialog("======OPCIONES======\n"
+"1. Captura de datos \n"
+ "2. Mostrar originales\n"
+ "3. Mostrar ordenados\n"
+ "4. Promedio\n"
+ "5. Desviacion\n"
+ "6. Mejor dato\n"
+ "7. Peor dato\n"
+ "8. X mejores\n"
+ "9. X peores\n"
+ "0. Salir.").charAt(0);
switch (opcion) {
case '1':
this.configuracion();
this.capturaDatos();
this.ordenados= this.datos.clone();
this.ordenarDatos();
yaCapturo = true;
break;
case '2':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.mostrarOriginales();
break;
case '3':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.mostrarOrdenados();
break;
case '4':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.promedio();
break;
case '5':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.desviacion();
break;
case '6':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.mejorDato();
break;
case '7':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.peorDato();
break;
case '8':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.xMejores();
break;
case '9':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.xPeores();
break;
case '0':
JOptionPane.showMessageDialog(null, "Chao.");
break;
default:
JOptionPane.showMessageDialog(null, "Ese caso no existe.", "Aviso", 2);
break;
}
}
while(opcion != '0');
}
private void configuracion()
{
//1. Configuracion
int n;
n = Integer.parseInt(JOptionPane.showInputDialog("Cuantos datos son :"));
this.datos = new float [n];
}
private void capturaDatos()
{
//2. Captura de this.datos
float dato;
for (int i = 0; i < this.datos.length; i++)
{
do
{
dato=Float.parseFloat(JOptionPane.showInputDialog("Digite nota del estudiante "+ (i+1)));
if (dato < 0 || dato > 5)
{
JOptionPane.showMessageDialog(null,"Nota no valida. Digitela de nuevo...!", "Error", 0);
}
}
while (dato < 0 || dato > 5);
this.datos[i] = dato;
}
}
private void mostrarOriginales()
{
//3. Mostrar this.this.datos originales
for (int i = 0; i < this.datos.length; i++)
{
System.out.print(this.datos[i] + " ");
}
System.out.println();
}
private void ordenarDatos()
{
//4. Ordenar this.this.datos
float auxiliar;
for (int i = 0; i < this.ordenados.length; i++)
{
for (int j = i+1; j < this.ordenados.length; j++)
{
if (this.ordenados[j] > this.ordenados [i])
{
auxiliar = this.ordenados [i];
this.ordenados[i] = this.ordenados [j];
this.ordenados[j] = auxiliar;
}
}
}
}
private void mostrarOrdenados()
{
//5. Mostrar this.this.datos ordenados
for (int i = 0; i < this.ordenados.length; i++)
{
System.out.print(this.ordenados[i] + " ");
}
System.out.println();
}
private void promedio()
{
//6.Promedio
float acum = 0;
for (int i = 0; i < this.datos.length; i++)
{
acum += this.datos[i];
}
this.prom = acum / this.datos.length;
JOptionPane.showMessageDialog(null, "El promedio es: "+prom, "Resultado", 1);
}
private void desviacion()
{
//7. Desviacion
float acum = 0, desvi = 0;
for (int i = 0; i < this.datos.length; i++)
{
acum = acum + (float)Math.pow(this.datos[i] - prom, 2);
}
acum = acum / (this.datos.length-1);
desvi = (float)Math.sqrt(acum);
JOptionPane.showMessageDialog(null, "La desviacion estandar es: "+desvi, "Resultado", 1);
}
private void mejorDato()
{
//8. Mejor dato
JOptionPane.showMessageDialog(null, "La mejor nota es: "+this.ordenados[0],"Resultado", 1);
}
private void peorDato()
{
//9. Peor dato
JOptionPane.showMessageDialog(null, "La peor nota es: "+this.ordenados[this.datos.length-1],"Resultado", 1);
}
private void xMejores()
{
//10. x Mejores
int x;
x = Integer.parseInt(JOptionPane.showInputDialog("Cuantos mejores quiere?"));
if (x > 0 && x <= this.ordenados.length)
{
for (int i = 0; i < x; i++)
System.out.print(this.ordenados[i]+ " ");
}
else
JOptionPane.showMessageDialog(null, "No hay ese numero de datos...!!!", "Error", 0);
System.out.println();
}
private void xPeores()
{
//11. x Peores
int x;
x = Integer.parseInt(JOptionPane.showInputDialog("Cuantos peores quiere?"));
if (x > 0 && x <= this.ordenados.length)
{
for (int i = this.ordenados.length - x; i < this.ordenados.length; i++)
{
System.out.print(this.ordenados[i] + " ");
}
}
else
JOptionPane.showMessageDialog(null, "No hay ese numero de datos...!!!", "Error", 0);
System.out.println();
}
}
|
UTF-8
|
Java
| 8,621 |
java
|
Operaciones4.java
|
Java
|
[
{
"context": "\nimport javax.swing.JOptionPane;\n/**\n *\n * @author Luized\n */\npublic class Operaciones4 \n{ \n //1. A",
"end": 69,
"score": 0.882928729057312,
"start": 67,
"tag": "NAME",
"value": "Lu"
},
{
"context": "port javax.swing.JOptionPane;\n/**\n *\n * @author Luized\n */\npublic class Operaciones4 \n{ \n //1. Atrib",
"end": 73,
"score": 0.6638213396072388,
"start": 69,
"tag": "USERNAME",
"value": "ized"
}
] | null |
[] |
package Nivel2;
import javax.swing.JOptionPane;
/**
*
* @author Luized
*/
public class Operaciones4
{
//1. Atributos o variables de clases
private float[] datos;
private float[] ordenados;
private float prom;
//2. Métodos:
//Obligatorios:
public static void main(String[] args)
{
new Operaciones4();
}
public Operaciones4()
{
this.datos = null;
this.ordenados = null;
this.prom = 0;
this.menu();
}
// De servivio:
private void menu()
{
char opcion;
boolean yaCapturo = false;
do{
opcion=JOptionPane.showInputDialog("======OPCIONES======\n"
+"1. Captura de datos \n"
+ "2. Mostrar originales\n"
+ "3. Mostrar ordenados\n"
+ "4. Promedio\n"
+ "5. Desviacion\n"
+ "6. Mejor dato\n"
+ "7. Peor dato\n"
+ "8. X mejores\n"
+ "9. X peores\n"
+ "0. Salir.").charAt(0);
switch (opcion) {
case '1':
this.configuracion();
this.capturaDatos();
this.ordenados= this.datos.clone();
this.ordenarDatos();
yaCapturo = true;
break;
case '2':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.mostrarOriginales();
break;
case '3':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.mostrarOrdenados();
break;
case '4':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.promedio();
break;
case '5':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.desviacion();
break;
case '6':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.mejorDato();
break;
case '7':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.peorDato();
break;
case '8':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.xMejores();
break;
case '9':
if (!yaCapturo) {
JOptionPane.showMessageDialog(null,"Lo siento, debe primero capturar datos!");
}
else
this.xPeores();
break;
case '0':
JOptionPane.showMessageDialog(null, "Chao.");
break;
default:
JOptionPane.showMessageDialog(null, "Ese caso no existe.", "Aviso", 2);
break;
}
}
while(opcion != '0');
}
private void configuracion()
{
//1. Configuracion
int n;
n = Integer.parseInt(JOptionPane.showInputDialog("Cuantos datos son :"));
this.datos = new float [n];
}
private void capturaDatos()
{
//2. Captura de this.datos
float dato;
for (int i = 0; i < this.datos.length; i++)
{
do
{
dato=Float.parseFloat(JOptionPane.showInputDialog("Digite nota del estudiante "+ (i+1)));
if (dato < 0 || dato > 5)
{
JOptionPane.showMessageDialog(null,"Nota no valida. Digitela de nuevo...!", "Error", 0);
}
}
while (dato < 0 || dato > 5);
this.datos[i] = dato;
}
}
private void mostrarOriginales()
{
//3. Mostrar this.this.datos originales
for (int i = 0; i < this.datos.length; i++)
{
System.out.print(this.datos[i] + " ");
}
System.out.println();
}
private void ordenarDatos()
{
//4. Ordenar this.this.datos
float auxiliar;
for (int i = 0; i < this.ordenados.length; i++)
{
for (int j = i+1; j < this.ordenados.length; j++)
{
if (this.ordenados[j] > this.ordenados [i])
{
auxiliar = this.ordenados [i];
this.ordenados[i] = this.ordenados [j];
this.ordenados[j] = auxiliar;
}
}
}
}
private void mostrarOrdenados()
{
//5. Mostrar this.this.datos ordenados
for (int i = 0; i < this.ordenados.length; i++)
{
System.out.print(this.ordenados[i] + " ");
}
System.out.println();
}
private void promedio()
{
//6.Promedio
float acum = 0;
for (int i = 0; i < this.datos.length; i++)
{
acum += this.datos[i];
}
this.prom = acum / this.datos.length;
JOptionPane.showMessageDialog(null, "El promedio es: "+prom, "Resultado", 1);
}
private void desviacion()
{
//7. Desviacion
float acum = 0, desvi = 0;
for (int i = 0; i < this.datos.length; i++)
{
acum = acum + (float)Math.pow(this.datos[i] - prom, 2);
}
acum = acum / (this.datos.length-1);
desvi = (float)Math.sqrt(acum);
JOptionPane.showMessageDialog(null, "La desviacion estandar es: "+desvi, "Resultado", 1);
}
private void mejorDato()
{
//8. Mejor dato
JOptionPane.showMessageDialog(null, "La mejor nota es: "+this.ordenados[0],"Resultado", 1);
}
private void peorDato()
{
//9. Peor dato
JOptionPane.showMessageDialog(null, "La peor nota es: "+this.ordenados[this.datos.length-1],"Resultado", 1);
}
private void xMejores()
{
//10. x Mejores
int x;
x = Integer.parseInt(JOptionPane.showInputDialog("Cuantos mejores quiere?"));
if (x > 0 && x <= this.ordenados.length)
{
for (int i = 0; i < x; i++)
System.out.print(this.ordenados[i]+ " ");
}
else
JOptionPane.showMessageDialog(null, "No hay ese numero de datos...!!!", "Error", 0);
System.out.println();
}
private void xPeores()
{
//11. x Peores
int x;
x = Integer.parseInt(JOptionPane.showInputDialog("Cuantos peores quiere?"));
if (x > 0 && x <= this.ordenados.length)
{
for (int i = this.ordenados.length - x; i < this.ordenados.length; i++)
{
System.out.print(this.ordenados[i] + " ");
}
}
else
JOptionPane.showMessageDialog(null, "No hay ese numero de datos...!!!", "Error", 0);
System.out.println();
}
}
| 8,621 | 0.408469 | 0.400116 | 275 | 30.349091 | 25.706064 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false |
10
|
d1f69c580751cf6f934b260dbacece7b918f2f55
| 7,980,049,258,701 |
ee7be4b859427124c2b8671ebcdef916a65234fe
|
/src/main/java/com/bkc/service/IUserService.java
|
f37d78394c1ec59a9811498db0dd4b715023a343
|
[] |
no_license
|
kenie123/dynamicDatasourceDemo
|
https://github.com/kenie123/dynamicDatasourceDemo
|
b80d32d9c606f7ac1209cfc4d3cc2623c8e98d80
|
dd2dfaeb8167c88055c12af5f6feaafe0a21a5ed
|
refs/heads/master
| 2021-01-12T11:54:42.500000 | 2016-09-27T03:45:08 | 2016-09-27T03:45:08 | 69,311,911 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bkc.service;
import java.util.List;
import com.bkc.pojo.po.User;
public interface IUserService {
List<User> findAll();
int add(User user);
void update(User user);
}
|
UTF-8
|
Java
| 186 |
java
|
IUserService.java
|
Java
|
[] | null |
[] |
package com.bkc.service;
import java.util.List;
import com.bkc.pojo.po.User;
public interface IUserService {
List<User> findAll();
int add(User user);
void update(User user);
}
| 186 | 0.72043 | 0.72043 | 14 | 12.285714 | 12.400625 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false |
10
|
4be6f616177603f8f1fae651d161a9e51328c07b
| 27,857,157,887,752 |
53510c908ee82bfae8a960aaada4c4916a3406a7
|
/asp/runtime/RuntimeListValue.java
|
858c5ef2cf9b280fbe03eaace86cef0994b8120d
|
[] |
no_license
|
Enxhis/ASP-Interpreter
|
https://github.com/Enxhis/ASP-Interpreter
|
15f58dbb31053d9ae1a5a5baaf82453e25d5369c
|
a93a1ad71e46016bd59abbf7147034545b958f33
|
refs/heads/main
| 2023-02-04T00:46:25.586000 | 2020-12-23T17:58:51 | 2020-12-23T17:58:51 | 323,953,232 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package no.uio.ifi.asp.runtime;
import java.util.ArrayList;
import no.uio.ifi.asp.main.*;
import no.uio.ifi.asp.parser.AspSyntax;
public class RuntimeListValue extends RuntimeValue {
public ArrayList<RuntimeValue> list = new ArrayList<>();
public RuntimeListValue(ArrayList<RuntimeValue> list) {
this.list = list;
}
@Override
protected String typeName() {
return "list";
}
@Override
public String toString() {
return list.toString();
}
@Override
public String showInfo() {
String retStr = "[";
Boolean b = false;
for (RuntimeValue v : list) {
if (b) retStr = retStr + ", ";
retStr = retStr + v.showInfo();
b = true;
}
retStr = retStr + "]";
return retStr;
}
@Override
public RuntimeValue evalLen(AspSyntax where) {
RuntimeValue v = new RuntimeIntValue(list.size());
return v;
}
@Override
public RuntimeValue evalSubscription(RuntimeValue v, AspSyntax where) {
if (v instanceof RuntimeIntValue) {
RuntimeValue ret = list.get((int)v.getIntValue("[...] operand", where));
return ret;
} else {
runtimeError("A list index must be an integer!", where);
}
return null; // Required by the compiler!
}
@Override
public RuntimeValue evalMultiply(RuntimeValue v, AspSyntax where) {
if (v instanceof RuntimeIntValue) {
ArrayList<RuntimeValue> retList = new ArrayList<>();
long v2 = v.getIntValue(" operand", where);
for (int i = 0; i < v2; i++) {
retList.addAll(list);
}
return new RuntimeListValue(retList);
}
runtimeError("Type error for *.", where);
return null; // Required by the compiler.
}
@Override
public RuntimeValue evalEqual(RuntimeValue v, AspSyntax where) {
if (v instanceof RuntimeNoneValue) {
return new RuntimeBoolValue(false);
}
runtimeError("Type error for ==.", where);
return null; // Required by the compiler!
}
@Override
public RuntimeValue evalNotEqual(RuntimeValue v, AspSyntax where) {
if (v instanceof RuntimeNoneValue) {
return new RuntimeBoolValue(true);
}
runtimeError("Type error for !=.", where);
return null; // Required by the compiler!
}
@Override
public void evalAssignElem(RuntimeValue inx, RuntimeValue value, AspSyntax where) {
if (!(inx instanceof RuntimeIntValue)) runtimeError("Index is not an integer!", where);
int index = (int) inx.getIntValue("integer", where);
if (index < list.size()) {
list.set(index, value);
} else {
runtimeError("Index out of bounds.", where);
}
}
}
|
UTF-8
|
Java
| 2,896 |
java
|
RuntimeListValue.java
|
Java
|
[] | null |
[] |
package no.uio.ifi.asp.runtime;
import java.util.ArrayList;
import no.uio.ifi.asp.main.*;
import no.uio.ifi.asp.parser.AspSyntax;
public class RuntimeListValue extends RuntimeValue {
public ArrayList<RuntimeValue> list = new ArrayList<>();
public RuntimeListValue(ArrayList<RuntimeValue> list) {
this.list = list;
}
@Override
protected String typeName() {
return "list";
}
@Override
public String toString() {
return list.toString();
}
@Override
public String showInfo() {
String retStr = "[";
Boolean b = false;
for (RuntimeValue v : list) {
if (b) retStr = retStr + ", ";
retStr = retStr + v.showInfo();
b = true;
}
retStr = retStr + "]";
return retStr;
}
@Override
public RuntimeValue evalLen(AspSyntax where) {
RuntimeValue v = new RuntimeIntValue(list.size());
return v;
}
@Override
public RuntimeValue evalSubscription(RuntimeValue v, AspSyntax where) {
if (v instanceof RuntimeIntValue) {
RuntimeValue ret = list.get((int)v.getIntValue("[...] operand", where));
return ret;
} else {
runtimeError("A list index must be an integer!", where);
}
return null; // Required by the compiler!
}
@Override
public RuntimeValue evalMultiply(RuntimeValue v, AspSyntax where) {
if (v instanceof RuntimeIntValue) {
ArrayList<RuntimeValue> retList = new ArrayList<>();
long v2 = v.getIntValue(" operand", where);
for (int i = 0; i < v2; i++) {
retList.addAll(list);
}
return new RuntimeListValue(retList);
}
runtimeError("Type error for *.", where);
return null; // Required by the compiler.
}
@Override
public RuntimeValue evalEqual(RuntimeValue v, AspSyntax where) {
if (v instanceof RuntimeNoneValue) {
return new RuntimeBoolValue(false);
}
runtimeError("Type error for ==.", where);
return null; // Required by the compiler!
}
@Override
public RuntimeValue evalNotEqual(RuntimeValue v, AspSyntax where) {
if (v instanceof RuntimeNoneValue) {
return new RuntimeBoolValue(true);
}
runtimeError("Type error for !=.", where);
return null; // Required by the compiler!
}
@Override
public void evalAssignElem(RuntimeValue inx, RuntimeValue value, AspSyntax where) {
if (!(inx instanceof RuntimeIntValue)) runtimeError("Index is not an integer!", where);
int index = (int) inx.getIntValue("integer", where);
if (index < list.size()) {
list.set(index, value);
} else {
runtimeError("Index out of bounds.", where);
}
}
}
| 2,896 | 0.585981 | 0.584945 | 97 | 28.855671 | 23.939352 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57732 | false | false |
10
|
c8392476fd86d8ec045883b5b88e36a974948f33
| 32,762,010,541,162 |
960441ed42df066389b3f79e3f33965e16b0a075
|
/src/com/kdg/angrytanks/Model/Tank.java
|
bccdc7c4e3d32b999f0488173f2632ca9211f0b0
|
[] |
no_license
|
XavierGeerinck/AngryTanks
|
https://github.com/XavierGeerinck/AngryTanks
|
971eecc86b06872dd053f92bb64875ab798f8db1
|
47456378ffca554785b5fcd248f040734e14d102
|
refs/heads/master
| 2021-05-27T06:27:09.407000 | 2013-04-13T14:28:20 | 2013-04-13T14:28:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kdg.angrytanks.Model;
import java.util.Random;
public class Tank {
private final int x_position;
private final int y_position;
private final static double GRAVITATIECONSTANTE = 9.81;
private boolean mode;
private double speed;
private double angle;
private int wind;
private final String symbol;
private String name;
private int score;
public Tank(int x, int y, String symbol) {
x_position = x;
y_position = y;
this.symbol = symbol;
name = symbol;
score = 0;
}
public int getXPosition() {
return x_position;
}
public int getYPosition() {
return y_position;
}
public String getSymbol() {
return symbol;
}
public int getScore() {
return score;
}
public String getName() {
return name;
}
public double getSpeed() {
return speed;
}
public double getAngle() {
return angle;
}
public int getWind() {
return wind;
}
public void setName(String name) {
this.name = name;
}
public void setScore(int score) {
this.score = score;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public void setAngle(double angle) {
this.angle = angle;
}
public void setMode(boolean mode){
this.mode = mode;
}
public int calculateFormula(int x) {
double angle = this.angle * Math.PI / 180;
double temp1 = -GRAVITATIECONSTANTE / 2 / Math.pow(speed * Math.cos(angle) - wind, 2) * Math.pow(x - x_position, 2);
double temp2 = (x - x_position) * Math.sin(angle) / (Math.cos(angle) - wind / speed) + y_position;
double total = temp1 + temp2;
// return 0 if we got negative
if (total > 1 ) {
return (int) total;
} else {
return 1;
}
}
public void createWind() {
if (mode){
wind = 0;
}
else{
Random random = new Random();
wind = random.nextInt(20) - 10;
}
}
}
|
UTF-8
|
Java
| 2,144 |
java
|
Tank.java
|
Java
|
[] | null |
[] |
package com.kdg.angrytanks.Model;
import java.util.Random;
public class Tank {
private final int x_position;
private final int y_position;
private final static double GRAVITATIECONSTANTE = 9.81;
private boolean mode;
private double speed;
private double angle;
private int wind;
private final String symbol;
private String name;
private int score;
public Tank(int x, int y, String symbol) {
x_position = x;
y_position = y;
this.symbol = symbol;
name = symbol;
score = 0;
}
public int getXPosition() {
return x_position;
}
public int getYPosition() {
return y_position;
}
public String getSymbol() {
return symbol;
}
public int getScore() {
return score;
}
public String getName() {
return name;
}
public double getSpeed() {
return speed;
}
public double getAngle() {
return angle;
}
public int getWind() {
return wind;
}
public void setName(String name) {
this.name = name;
}
public void setScore(int score) {
this.score = score;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public void setAngle(double angle) {
this.angle = angle;
}
public void setMode(boolean mode){
this.mode = mode;
}
public int calculateFormula(int x) {
double angle = this.angle * Math.PI / 180;
double temp1 = -GRAVITATIECONSTANTE / 2 / Math.pow(speed * Math.cos(angle) - wind, 2) * Math.pow(x - x_position, 2);
double temp2 = (x - x_position) * Math.sin(angle) / (Math.cos(angle) - wind / speed) + y_position;
double total = temp1 + temp2;
// return 0 if we got negative
if (total > 1 ) {
return (int) total;
} else {
return 1;
}
}
public void createWind() {
if (mode){
wind = 0;
}
else{
Random random = new Random();
wind = random.nextInt(20) - 10;
}
}
}
| 2,144 | 0.545709 | 0.535448 | 110 | 18.49091 | 19.747379 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.390909 | false | false |
10
|
a2d160af1c299360a146baea495580b4bf8198f0
| 31,327,491,520,374 |
0f2a359507c597e78665ca49b2e698e96e48fc13
|
/src/qShop/Checkout.java
|
29bca6e4e534c8fc934f146ea9cdc10f2d5244ff
|
[] |
no_license
|
melaniemkwon/ECommerce-App
|
https://github.com/melaniemkwon/ECommerce-App
|
cb12b6b6e6ebd56dc1205f0816860905a16efbbb
|
a0b78fc863c849713397cb6c7ac3be88e1c9ea75
|
refs/heads/master
| 2020-07-01T20:48:52.001000 | 2016-11-28T22:06:59 | 2016-11-28T22:06:59 | 74,257,439 | 0 | 0 | null | false | 2016-11-28T22:06:59 | 2016-11-20T06:39:16 | 2016-11-23T03:57:54 | 2016-11-28T22:06:59 | 27 | 0 | 0 | 0 |
Java
| null | null |
package qShop.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Checkout
*/
@WebServlet("/Checkout")
public class Checkout extends HttpServlet {
private static final long serialVersionUID = 1L;
public Checkout() {
super();
}
public void init( ServletConfig config ) throws ServletException
{
super.init( config );
try
{
Class.forName( "com.mysql.jdbc.Driver" );
}
catch( ClassNotFoundException e )
{
throw new ServletException( e );
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<cartInventory> cartInventory = new ArrayList<cartInventory>();
Connection c = null;
try
{
String url = "jdbc:mysql://cs3.calstatela.edu/cs3220stu28";
String username = "cs3220stu28";
String password = " ";
c = DriverManager.getConnection( url, username, password );
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "select * from cart" );
while(rs.next()){
cartInventory items = new cartInventory(rs.getInt("id"), rs.getString("itemName"), rs.getString("itemImage"), rs.getInt("itemQuantity"),rs.getDouble("itemPrice"));
cartInventory.add(items);
}
Statement stmt1 = c.createStatement();
ResultSet rs1 = stmt1.executeQuery( "select sum(itemPrice) from cart" );
while(rs1.next()){
String totalPrice = rs1.getString("sum(itemPrice)");
request.setAttribute("totalPrice", totalPrice);
}
}
catch( SQLException e )
{
throw new ServletException( e );
}
finally
{
try
{
if( c != null ) c.close();
}
catch( SQLException e )
{
throw new ServletException( e );
}
}
request.setAttribute("cartInventory", cartInventory);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/store/checkout.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
boolean isError = false;
if (firstName == null || firstName.trim().length() == 0) {
request.setAttribute("error_firstName", "Missing first name.");
isError = true;
}
if (lastName == null || lastName.trim().length() == 0) {
request.setAttribute("error_lastName", "Missing last name.");
isError = true;
}
if (email == null || email.trim().length() == 0) {
request.setAttribute("error_email", "Missing email.");
isError = true;
}
// If there's a user input error, redisplay the form
if (isError) {
System.out.println("Error on order form submission.");
doGet(request, response);
return;
}
// Else successfully submit the order
else {
Connection c = null;
try
{
String url = "jdbc:mysql://cs3.calstatela.edu/cs3220stu28";
String username = "cs3220stu28";
String password = " ";
c = DriverManager.getConnection( url, username, password );
String sql = "truncate cart";
PreparedStatement pstmt = c.prepareStatement( sql );
pstmt.executeUpdate();
}
catch( SQLException e )
{
throw new ServletException( e );
}
finally
{
try
{
if( c != null ) c.close();
}
catch( SQLException e )
{
throw new ServletException( e );
}
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/store/thankyou.jsp");
dispatcher.forward(request, response);
}// end of else part
//doGet(request, response);
}
}
|
UTF-8
|
Java
| 5,088 |
java
|
Checkout.java
|
Java
|
[
{
"context": ".edu/cs3220stu28\";\n String username = \"cs3220stu28\";\n String password = \" \";\n ",
"end": 1456,
"score": 0.99690842628479,
"start": 1445,
"tag": "USERNAME",
"value": "cs3220stu28"
},
{
"context": "/cs3220stu28\";\n String username = \"cs3220stu28\";\n String password = \" \";\n ",
"end": 4146,
"score": 0.9988851547241211,
"start": 4135,
"tag": "USERNAME",
"value": "cs3220stu28"
}
] | null |
[] |
package qShop.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Checkout
*/
@WebServlet("/Checkout")
public class Checkout extends HttpServlet {
private static final long serialVersionUID = 1L;
public Checkout() {
super();
}
public void init( ServletConfig config ) throws ServletException
{
super.init( config );
try
{
Class.forName( "com.mysql.jdbc.Driver" );
}
catch( ClassNotFoundException e )
{
throw new ServletException( e );
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<cartInventory> cartInventory = new ArrayList<cartInventory>();
Connection c = null;
try
{
String url = "jdbc:mysql://cs3.calstatela.edu/cs3220stu28";
String username = "cs3220stu28";
String password = " ";
c = DriverManager.getConnection( url, username, password );
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "select * from cart" );
while(rs.next()){
cartInventory items = new cartInventory(rs.getInt("id"), rs.getString("itemName"), rs.getString("itemImage"), rs.getInt("itemQuantity"),rs.getDouble("itemPrice"));
cartInventory.add(items);
}
Statement stmt1 = c.createStatement();
ResultSet rs1 = stmt1.executeQuery( "select sum(itemPrice) from cart" );
while(rs1.next()){
String totalPrice = rs1.getString("sum(itemPrice)");
request.setAttribute("totalPrice", totalPrice);
}
}
catch( SQLException e )
{
throw new ServletException( e );
}
finally
{
try
{
if( c != null ) c.close();
}
catch( SQLException e )
{
throw new ServletException( e );
}
}
request.setAttribute("cartInventory", cartInventory);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/store/checkout.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
boolean isError = false;
if (firstName == null || firstName.trim().length() == 0) {
request.setAttribute("error_firstName", "Missing first name.");
isError = true;
}
if (lastName == null || lastName.trim().length() == 0) {
request.setAttribute("error_lastName", "Missing last name.");
isError = true;
}
if (email == null || email.trim().length() == 0) {
request.setAttribute("error_email", "Missing email.");
isError = true;
}
// If there's a user input error, redisplay the form
if (isError) {
System.out.println("Error on order form submission.");
doGet(request, response);
return;
}
// Else successfully submit the order
else {
Connection c = null;
try
{
String url = "jdbc:mysql://cs3.calstatela.edu/cs3220stu28";
String username = "cs3220stu28";
String password = " ";
c = DriverManager.getConnection( url, username, password );
String sql = "truncate cart";
PreparedStatement pstmt = c.prepareStatement( sql );
pstmt.executeUpdate();
}
catch( SQLException e )
{
throw new ServletException( e );
}
finally
{
try
{
if( c != null ) c.close();
}
catch( SQLException e )
{
throw new ServletException( e );
}
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/store/thankyou.jsp");
dispatcher.forward(request, response);
}// end of else part
//doGet(request, response);
}
}
| 5,088 | 0.568396 | 0.561517 | 156 | 31.608974 | 27.310083 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.782051 | false | false |
10
|
7326c087f3747efbd908144e9e2a6c194a9bb00a
| 1,073,741,881,460 |
c1746e3eacd55e179f0c756efd1904cf426977c7
|
/src/main/java/com/rods/magicreator/controller/CharactersController.java
|
2e32bf7425d94637a8713f9318ba23e749715fde
|
[] |
no_license
|
rodrigo-om/magicreator
|
https://github.com/rodrigo-om/magicreator
|
e8cca13acaebaf211cf923f4e0da5b9621fd5b86
|
ca6c4246cf3859ce59328ea85cd54eb0b4f84169
|
refs/heads/main
| 2023-05-18T21:56:42.754000 | 2021-06-07T23:20:31 | 2021-06-07T23:20:31 | 373,328,118 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.rods.magicreator.controller;
import com.rods.magicreator.domain.models.Character;
import com.rods.magicreator.domain.ports.in.IManageCharacters;
import com.rods.magicreator.domain.ports.in.IManageCharacters.CouldNotCreateCharacterException;
import com.rods.magicreator.domain.ports.in.IManageCharacters.CouldNotDeleteCharacterException;
import com.rods.magicreator.domain.ports.in.IManageCharacters.CouldNotSearchCharactersException;
import com.rods.magicreator.domain.ports.in.IManageCharacters.CouldNotUpdateCharacterException;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Optional;
@RestController
public class CharactersController {
private final IManageCharacters charactersManager;
public CharactersController(IManageCharacters charactersManager) {
this.charactersManager = charactersManager;
}
@PostMapping("/character")
public ResponseEntity<Character> create(@RequestBody CreateCharacterRequest request) {
try {
return new ResponseEntity<Character>(charactersManager.create(toCharacter(request)), HttpStatus.CREATED);
} catch (CouldNotCreateCharacterException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@PutMapping("/character")
public Character update(@RequestBody Character request) {
try {
return charactersManager.update(request);
} catch (CouldNotUpdateCharacterException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@DeleteMapping("/character/{id}")
public void delete(@PathVariable String id) {
try {
charactersManager.delete(id);
} catch (CouldNotDeleteCharacterException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@GetMapping("/character/{id}")
public ResponseEntity<Object> findById(@PathVariable String id) throws CouldNotSearchCharactersException {
try {
return charactersManager.findBy(id)
.map(x -> new ResponseEntity<Object>(x, HttpStatus.OK))
.orElse(new ResponseEntity<Object>("{ \"message\":\"Id not corresponding to any Character\" }", HttpStatus.OK));
} catch (CouldNotSearchCharactersException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@GetMapping("/characters")
public Page<Character> findAll(@RequestParam int page) {
try {
return charactersManager.findAll(page);
} catch (CouldNotSearchCharactersException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@GetMapping("/character")
public List<Character> findBy(
@RequestParam(required = false) String name,
@RequestParam(required = false) String role,
@RequestParam(required = false) String school,
@RequestParam(required = false) String house,
@RequestParam(required = false) String patronus) {
try {
return charactersManager.findBy(name, role, school, house, patronus);
} catch (CouldNotSearchCharactersException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
private Character toCharacter(CreateCharacterRequest request) {
return Character.builder()
.name(request.getName())
.role(request.getRole())
.school(request.getSchool())
.house(request.getHouse())
.patronus(request.getPatronus())
.build();
}
}
|
UTF-8
|
Java
| 5,271 |
java
|
CharactersController.java
|
Java
|
[] | null |
[] |
package com.rods.magicreator.controller;
import com.rods.magicreator.domain.models.Character;
import com.rods.magicreator.domain.ports.in.IManageCharacters;
import com.rods.magicreator.domain.ports.in.IManageCharacters.CouldNotCreateCharacterException;
import com.rods.magicreator.domain.ports.in.IManageCharacters.CouldNotDeleteCharacterException;
import com.rods.magicreator.domain.ports.in.IManageCharacters.CouldNotSearchCharactersException;
import com.rods.magicreator.domain.ports.in.IManageCharacters.CouldNotUpdateCharacterException;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Optional;
@RestController
public class CharactersController {
private final IManageCharacters charactersManager;
public CharactersController(IManageCharacters charactersManager) {
this.charactersManager = charactersManager;
}
@PostMapping("/character")
public ResponseEntity<Character> create(@RequestBody CreateCharacterRequest request) {
try {
return new ResponseEntity<Character>(charactersManager.create(toCharacter(request)), HttpStatus.CREATED);
} catch (CouldNotCreateCharacterException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@PutMapping("/character")
public Character update(@RequestBody Character request) {
try {
return charactersManager.update(request);
} catch (CouldNotUpdateCharacterException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@DeleteMapping("/character/{id}")
public void delete(@PathVariable String id) {
try {
charactersManager.delete(id);
} catch (CouldNotDeleteCharacterException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@GetMapping("/character/{id}")
public ResponseEntity<Object> findById(@PathVariable String id) throws CouldNotSearchCharactersException {
try {
return charactersManager.findBy(id)
.map(x -> new ResponseEntity<Object>(x, HttpStatus.OK))
.orElse(new ResponseEntity<Object>("{ \"message\":\"Id not corresponding to any Character\" }", HttpStatus.OK));
} catch (CouldNotSearchCharactersException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@GetMapping("/characters")
public Page<Character> findAll(@RequestParam int page) {
try {
return charactersManager.findAll(page);
} catch (CouldNotSearchCharactersException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
@GetMapping("/character")
public List<Character> findBy(
@RequestParam(required = false) String name,
@RequestParam(required = false) String role,
@RequestParam(required = false) String school,
@RequestParam(required = false) String house,
@RequestParam(required = false) String patronus) {
try {
return charactersManager.findBy(name, role, school, house, patronus);
} catch (CouldNotSearchCharactersException e) {
if (e.contains(IllegalArgumentException.class))
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMostSpecificCause().getMessage(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMostSpecificCause().getMessage(), e);
}
}
private Character toCharacter(CreateCharacterRequest request) {
return Character.builder()
.name(request.getName())
.role(request.getRole())
.school(request.getSchool())
.house(request.getHouse())
.patronus(request.getPatronus())
.build();
}
}
| 5,271 | 0.695883 | 0.695883 | 115 | 44.81739 | 38.56707 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.608696 | false | false |
10
|
2addc419deb96f9389e7f430376403be4a8d2bda
| 6,700,149,005,804 |
0fbd4f490ca1ae70ec1841b42c3ef02f6cd8c8d5
|
/hb-bass-role-adaptation/src/main/java/com/asiainfo/hb/bass/role/adaptation/controller/ReportOnOffLineController.java
|
f4e47d7983466a54b2818197f837b11f52b072a3
|
[] |
no_license
|
shanghaif/bass
|
https://github.com/shanghaif/bass
|
9931673260abf141f957fd74af712e587c650f2c
|
681b89cafe33535ee984232f2ad2737233513c8f
|
refs/heads/master
| 2023-07-08T20:36:15.834000 | 2017-10-18T03:34:17 | 2017-10-18T03:34:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.asiainfo.hb.bass.role.adaptation.controller;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.asiainfo.hb.bass.role.adaptation.service.ReportOnOffLineService;
/**
* 报表上下线
* @author xiaoh
*
*/
@Controller
@RequestMapping("/report/onoffline")
public class ReportOnOffLineController {
@Autowired
private ReportOnOffLineService mReportService;
@RequestMapping("/index")
public String index(){
return "ftl/reportOnOffLine/index";
}
@RequestMapping("/online")
public String online(Model model){
model.addAttribute("menuList", mReportService.getMenuList());
return "ftl/reportOnOffLine/online";
}
@RequestMapping("/offline")
public String offline(Model model){
model.addAttribute("menuList", mReportService.getMenuList());
return "ftl/reportOnOffLine/offline";
}
@RequestMapping("/changeSort")
@ResponseBody
public void changeSort(HttpServletRequest req){
String menuId = req.getParameter("menuId");
String sortId = req.getParameter("sortId");
String rid = req.getParameter("rid");
mReportService.changeSort(rid, menuId, sortId);
}
/**
* 查询已上线报表
* @param req
* @return
*/
@RequestMapping("/getHasOnlineReport")
@ResponseBody
public Object getHasOnlineReport(HttpServletRequest req){
String page = req.getParameter("page");
String rows = req.getParameter("rows");
int perPage = 10;
int currentPage = 1;
if(!StringUtils.isEmpty(page)){
currentPage = Integer.valueOf(page);
}
if(!StringUtils.isEmpty(rows)){
perPage = Integer.valueOf(rows);
}
String menuId = req.getParameter("menuId");
String reportName = req.getParameter("reportName");
String reportId = req.getParameter("reportId");
return mReportService.getHasOnlineReport(menuId, reportName,reportId, perPage, currentPage);
}
@RequestMapping(value="/offlineRpt")
@ResponseBody
public void offlineRpt(HttpServletRequest req){
String reportId = req.getParameter("reportId");
String url = req.getParameter("resourceUri");
mReportService.offLineRpt(reportId, url);
}
@RequestMapping("/getWaitOnLineReport")
@ResponseBody
public Object getWaitOnLineReport(HttpServletRequest req){
String page = req.getParameter("page");
String rows = req.getParameter("rows");
int perPage = 10;
int currentPage = 1;
if(!StringUtils.isEmpty(page)){
currentPage = Integer.valueOf(page);
}
if(!StringUtils.isEmpty(rows)){
perPage = Integer.valueOf(rows);
}
String rid = req.getParameter("rid");
String name = req.getParameter("name");
return mReportService.getWaitOnLineReport(name, rid, perPage, currentPage);
}
@RequestMapping("/getSortList")
@ResponseBody
public List<Map<String, Object>> getSortList(HttpServletRequest req){
String menuId = req.getParameter("menuId");
String name = req.getParameter("sortName");
List<Map<String, Object>> list = mReportService.getSortList(menuId, name);
list.get(0).put("selected", true);
return list;
}
@RequestMapping("/onLineRpt")
@ResponseBody
public void onLineRpt(HttpServletRequest req){
String rid = req.getParameter("rid");
String menuId = req.getParameter("menuId");
String sortId = req.getParameter("sortId");
String sortNum = req.getParameter("sortNum");
String keyWord = req.getParameter("keyWord");
String rptCycle = req.getParameter("rptCycle");
mReportService.onLineRpt(menuId, sortId, rid, sortNum, keyWord, rptCycle);
}
@RequestMapping("/addRptSort")
@ResponseBody
public void addRptSort(HttpServletRequest req){
String menuId = req.getParameter("menuId");
String name = req.getParameter("name");
String sortNum = req.getParameter("sortNum");
String sortId = req.getParameter("sortId");
if(StringUtils.isEmpty(sortId)){
mReportService.addRptSort(menuId, name, sortNum);
}else{
mReportService.updateRptSort(sortId, menuId, name, sortNum);
}
}
@RequestMapping("/delRptSort")
@ResponseBody
public void delRptSort(HttpServletRequest req){
String sortIds = req.getParameter("ids");
mReportService.deleteRptSort(sortIds);
}
}
|
UTF-8
|
Java
| 4,586 |
java
|
ReportOnOffLineController.java
|
Java
|
[
{
"context": "portOnOffLineService;\r\n\r\n/**\r\n * 报表上下线\r\n * @author xiaoh\r\n *\r\n */\r\n@Controller\r\n@RequestMapping(\"/report/o",
"end": 595,
"score": 0.9995665550231934,
"start": 590,
"tag": "USERNAME",
"value": "xiaoh"
}
] | null |
[] |
package com.asiainfo.hb.bass.role.adaptation.controller;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.asiainfo.hb.bass.role.adaptation.service.ReportOnOffLineService;
/**
* 报表上下线
* @author xiaoh
*
*/
@Controller
@RequestMapping("/report/onoffline")
public class ReportOnOffLineController {
@Autowired
private ReportOnOffLineService mReportService;
@RequestMapping("/index")
public String index(){
return "ftl/reportOnOffLine/index";
}
@RequestMapping("/online")
public String online(Model model){
model.addAttribute("menuList", mReportService.getMenuList());
return "ftl/reportOnOffLine/online";
}
@RequestMapping("/offline")
public String offline(Model model){
model.addAttribute("menuList", mReportService.getMenuList());
return "ftl/reportOnOffLine/offline";
}
@RequestMapping("/changeSort")
@ResponseBody
public void changeSort(HttpServletRequest req){
String menuId = req.getParameter("menuId");
String sortId = req.getParameter("sortId");
String rid = req.getParameter("rid");
mReportService.changeSort(rid, menuId, sortId);
}
/**
* 查询已上线报表
* @param req
* @return
*/
@RequestMapping("/getHasOnlineReport")
@ResponseBody
public Object getHasOnlineReport(HttpServletRequest req){
String page = req.getParameter("page");
String rows = req.getParameter("rows");
int perPage = 10;
int currentPage = 1;
if(!StringUtils.isEmpty(page)){
currentPage = Integer.valueOf(page);
}
if(!StringUtils.isEmpty(rows)){
perPage = Integer.valueOf(rows);
}
String menuId = req.getParameter("menuId");
String reportName = req.getParameter("reportName");
String reportId = req.getParameter("reportId");
return mReportService.getHasOnlineReport(menuId, reportName,reportId, perPage, currentPage);
}
@RequestMapping(value="/offlineRpt")
@ResponseBody
public void offlineRpt(HttpServletRequest req){
String reportId = req.getParameter("reportId");
String url = req.getParameter("resourceUri");
mReportService.offLineRpt(reportId, url);
}
@RequestMapping("/getWaitOnLineReport")
@ResponseBody
public Object getWaitOnLineReport(HttpServletRequest req){
String page = req.getParameter("page");
String rows = req.getParameter("rows");
int perPage = 10;
int currentPage = 1;
if(!StringUtils.isEmpty(page)){
currentPage = Integer.valueOf(page);
}
if(!StringUtils.isEmpty(rows)){
perPage = Integer.valueOf(rows);
}
String rid = req.getParameter("rid");
String name = req.getParameter("name");
return mReportService.getWaitOnLineReport(name, rid, perPage, currentPage);
}
@RequestMapping("/getSortList")
@ResponseBody
public List<Map<String, Object>> getSortList(HttpServletRequest req){
String menuId = req.getParameter("menuId");
String name = req.getParameter("sortName");
List<Map<String, Object>> list = mReportService.getSortList(menuId, name);
list.get(0).put("selected", true);
return list;
}
@RequestMapping("/onLineRpt")
@ResponseBody
public void onLineRpt(HttpServletRequest req){
String rid = req.getParameter("rid");
String menuId = req.getParameter("menuId");
String sortId = req.getParameter("sortId");
String sortNum = req.getParameter("sortNum");
String keyWord = req.getParameter("keyWord");
String rptCycle = req.getParameter("rptCycle");
mReportService.onLineRpt(menuId, sortId, rid, sortNum, keyWord, rptCycle);
}
@RequestMapping("/addRptSort")
@ResponseBody
public void addRptSort(HttpServletRequest req){
String menuId = req.getParameter("menuId");
String name = req.getParameter("name");
String sortNum = req.getParameter("sortNum");
String sortId = req.getParameter("sortId");
if(StringUtils.isEmpty(sortId)){
mReportService.addRptSort(menuId, name, sortNum);
}else{
mReportService.updateRptSort(sortId, menuId, name, sortNum);
}
}
@RequestMapping("/delRptSort")
@ResponseBody
public void delRptSort(HttpServletRequest req){
String sortIds = req.getParameter("ids");
mReportService.deleteRptSort(sortIds);
}
}
| 4,586 | 0.720079 | 0.718544 | 152 | 28.013159 | 22.040031 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.888158 | false | false |
10
|
d62403c134bacd5eaa0bf141ea43266e0b70013c
| 32,117,765,493,843 |
3190c5b2b14f156d501694443be3fe3878a9869a
|
/pppp/sim/ShuffleTest.java
|
84e6d5df6802e6f2dc8901f61c3939090184c942
|
[] |
no_license
|
tingtingtwice/PiedPiper-Group-4
|
https://github.com/tingtingtwice/PiedPiper-Group-4
|
49cb83f23f2b3dd9071485e6f7fe5ea7fcf4a84c
|
e936bd2dbd2e965c96fbdf2a9e9112f8d41e4ef8
|
refs/heads/master
| 2020-05-13T23:31:36.078000 | 2015-10-05T00:23:05 | 2015-10-05T00:23:05 | 42,819,092 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pppp.sim;
import java.util.Random;
import pppp.g4.Utils;
class ShuffleTest
{
public static void main(String args[])
{
int[] solutionArray = { 1, 2, 3, 5, 6, 7, 8, 9, 1};
Utils.shuffleArray(solutionArray);
for (int i = 0; i < solutionArray.length; i++)
{
System.out.print(solutionArray[i] + " ");
}
System.out.println();
}
}
|
UTF-8
|
Java
| 413 |
java
|
ShuffleTest.java
|
Java
|
[] | null |
[] |
package pppp.sim;
import java.util.Random;
import pppp.g4.Utils;
class ShuffleTest
{
public static void main(String args[])
{
int[] solutionArray = { 1, 2, 3, 5, 6, 7, 8, 9, 1};
Utils.shuffleArray(solutionArray);
for (int i = 0; i < solutionArray.length; i++)
{
System.out.print(solutionArray[i] + " ");
}
System.out.println();
}
}
| 413 | 0.544794 | 0.51816 | 22 | 16.727272 | 18.611292 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.363636 | false | false |
10
|
4f7ec4a945d3bd47cb44398d548cadf2698dd5df
| 9,981,504,038,961 |
23cfcdb05de0fec8fe92870a7df6950aea1267cf
|
/taotao_manager_web/src/main/java/com/taotao/manager/controller/TestController.java
|
3e572e0522f7bbe474f2fc9000545776a2e6df88
|
[] |
no_license
|
HelloWorld4U/taotao
|
https://github.com/HelloWorld4U/taotao
|
953bd9402bed6f432279233139a8c17010ca29b7
|
cd57049615d8a4036f5c5d8c8dd9512f1e446e94
|
refs/heads/master
| 2021-09-09T01:00:13.205000 | 2018-03-13T03:26:29 | 2018-03-13T03:26:47 | 124,995,103 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.taotao.manager.controller;
import com.taotao.test.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/test")
public class TestController {
@Autowired
private TestService testServiceImpl;
@ResponseBody
@RequestMapping(value = "querydate")
public String test(){
return testServiceImpl.queryDate();
}
}
|
UTF-8
|
Java
| 585 |
java
|
TestController.java
|
Java
|
[] | null |
[] |
package com.taotao.manager.controller;
import com.taotao.test.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/test")
public class TestController {
@Autowired
private TestService testServiceImpl;
@ResponseBody
@RequestMapping(value = "querydate")
public String test(){
return testServiceImpl.queryDate();
}
}
| 585 | 0.779487 | 0.779487 | 22 | 25.59091 | 21.449007 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false |
10
|
79bfd46538183294241d1bb685a7bdde162ec30d
| 15,590,731,336,279 |
775ed9054f196aa860224c0a5f906ae11d48939d
|
/emulator-tapi-2.1/tapi2.1-javaServer/src/gen/java/io/swagger/model/TapiNotificationTcaInfo.java
|
a014dfa92a17c752a937fca9cd4951cb7a584b87
|
[
"Apache-2.0"
] |
permissive
|
iicc1/ODTN-emulator
|
https://github.com/iicc1/ODTN-emulator
|
6254e726ef318b58ac452b13e2a023c1aea8c8ee
|
f1e904823758fe15f4060c00119987df31d4c769
|
refs/heads/master
| 2020-11-26T02:34:04.842000 | 2020-09-22T18:24:12 | 2020-09-22T18:24:12 | 228,939,192 | 0 | 0 |
Apache-2.0
| true | 2019-12-18T23:37:43 | 2019-12-18T23:37:42 | 2019-12-18T14:50:35 | 2019-08-02T14:52:17 | 4,973 | 0 | 0 | 0 | null | false | false |
/*
* tapi-common,tapi-dsr,tapi-path-computation,tapi-eth,tapi-virtual-network,tapi-topology,tapi-notification,tapi-oam,tapi-photonic-media,tapi-connectivity API
* tapi-common,tapi-dsr,tapi-path-computation,tapi-eth,tapi-virtual-network,tapi-topology,tapi-notification,tapi-oam,tapi-photonic-media,tapi-connectivity API generated from yang definitions
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.model.TapiNotificationPerceivedTcaSeverity;
import io.swagger.model.TapiNotificationThresholdCrossingType;
import javax.validation.constraints.*;
/**
* TapiNotificationTcaInfo
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2018-11-14T14:58:12.974+01:00")
public class TapiNotificationTcaInfo {
@JsonProperty("threshold-crossing")
private TapiNotificationThresholdCrossingType thresholdCrossing = null;
@JsonProperty("threshold-parameter")
private String thresholdParameter = null;
@JsonProperty("is-transient")
private Boolean isTransient = false;
@JsonProperty("threshold-value")
private Integer thresholdValue = null;
@JsonProperty("perceived-severity")
private TapiNotificationPerceivedTcaSeverity perceivedSeverity = null;
@JsonProperty("suspect-interval-flag")
private Boolean suspectIntervalFlag = false;
@JsonProperty("measurement-interval")
private String measurementInterval = null;
public TapiNotificationTcaInfo thresholdCrossing(TapiNotificationThresholdCrossingType thresholdCrossing) {
this.thresholdCrossing = thresholdCrossing;
return this;
}
/**
* none
* @return thresholdCrossing
**/
@JsonProperty("threshold-crossing")
@ApiModelProperty(value = "none")
public TapiNotificationThresholdCrossingType getThresholdCrossing() {
return thresholdCrossing;
}
public void setThresholdCrossing(TapiNotificationThresholdCrossingType thresholdCrossing) {
this.thresholdCrossing = thresholdCrossing;
}
public TapiNotificationTcaInfo thresholdParameter(String thresholdParameter) {
this.thresholdParameter = thresholdParameter;
return this;
}
/**
* none
* @return thresholdParameter
**/
@JsonProperty("threshold-parameter")
@ApiModelProperty(value = "none")
public String getThresholdParameter() {
return thresholdParameter;
}
public void setThresholdParameter(String thresholdParameter) {
this.thresholdParameter = thresholdParameter;
}
public TapiNotificationTcaInfo isTransient(Boolean isTransient) {
this.isTransient = isTransient;
return this;
}
/**
* none
* @return isTransient
**/
@JsonProperty("is-transient")
@ApiModelProperty(value = "none")
public Boolean isIsTransient() {
return isTransient;
}
public void setIsTransient(Boolean isTransient) {
this.isTransient = isTransient;
}
public TapiNotificationTcaInfo thresholdValue(Integer thresholdValue) {
this.thresholdValue = thresholdValue;
return this;
}
/**
* none
* @return thresholdValue
**/
@JsonProperty("threshold-value")
@ApiModelProperty(value = "none")
public Integer getThresholdValue() {
return thresholdValue;
}
public void setThresholdValue(Integer thresholdValue) {
this.thresholdValue = thresholdValue;
}
public TapiNotificationTcaInfo perceivedSeverity(TapiNotificationPerceivedTcaSeverity perceivedSeverity) {
this.perceivedSeverity = perceivedSeverity;
return this;
}
/**
* none
* @return perceivedSeverity
**/
@JsonProperty("perceived-severity")
@ApiModelProperty(value = "none")
public TapiNotificationPerceivedTcaSeverity getPerceivedSeverity() {
return perceivedSeverity;
}
public void setPerceivedSeverity(TapiNotificationPerceivedTcaSeverity perceivedSeverity) {
this.perceivedSeverity = perceivedSeverity;
}
public TapiNotificationTcaInfo suspectIntervalFlag(Boolean suspectIntervalFlag) {
this.suspectIntervalFlag = suspectIntervalFlag;
return this;
}
/**
* none
* @return suspectIntervalFlag
**/
@JsonProperty("suspect-interval-flag")
@ApiModelProperty(value = "none")
public Boolean isSuspectIntervalFlag() {
return suspectIntervalFlag;
}
public void setSuspectIntervalFlag(Boolean suspectIntervalFlag) {
this.suspectIntervalFlag = suspectIntervalFlag;
}
public TapiNotificationTcaInfo measurementInterval(String measurementInterval) {
this.measurementInterval = measurementInterval;
return this;
}
/**
* none
* @return measurementInterval
**/
@JsonProperty("measurement-interval")
@ApiModelProperty(value = "none")
public String getMeasurementInterval() {
return measurementInterval;
}
public void setMeasurementInterval(String measurementInterval) {
this.measurementInterval = measurementInterval;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TapiNotificationTcaInfo tapiNotificationTcaInfo = (TapiNotificationTcaInfo) o;
return Objects.equals(this.thresholdCrossing, tapiNotificationTcaInfo.thresholdCrossing) &&
Objects.equals(this.thresholdParameter, tapiNotificationTcaInfo.thresholdParameter) &&
Objects.equals(this.isTransient, tapiNotificationTcaInfo.isTransient) &&
Objects.equals(this.thresholdValue, tapiNotificationTcaInfo.thresholdValue) &&
Objects.equals(this.perceivedSeverity, tapiNotificationTcaInfo.perceivedSeverity) &&
Objects.equals(this.suspectIntervalFlag, tapiNotificationTcaInfo.suspectIntervalFlag) &&
Objects.equals(this.measurementInterval, tapiNotificationTcaInfo.measurementInterval);
}
@Override
public int hashCode() {
return Objects.hash(thresholdCrossing, thresholdParameter, isTransient, thresholdValue, perceivedSeverity, suspectIntervalFlag, measurementInterval);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TapiNotificationTcaInfo {\n");
sb.append(" thresholdCrossing: ").append(toIndentedString(thresholdCrossing)).append("\n");
sb.append(" thresholdParameter: ").append(toIndentedString(thresholdParameter)).append("\n");
sb.append(" isTransient: ").append(toIndentedString(isTransient)).append("\n");
sb.append(" thresholdValue: ").append(toIndentedString(thresholdValue)).append("\n");
sb.append(" perceivedSeverity: ").append(toIndentedString(perceivedSeverity)).append("\n");
sb.append(" suspectIntervalFlag: ").append(toIndentedString(suspectIntervalFlag)).append("\n");
sb.append(" measurementInterval: ").append(toIndentedString(measurementInterval)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
UTF-8
|
Java
| 7,512 |
java
|
TapiNotificationTcaInfo.java
|
Java
|
[
{
"context": "ger code generator program.\n * https://github.com/swagger-api/swagger-codegen.git\n * Do not edit the class manu",
"end": 502,
"score": 0.999545156955719,
"start": 491,
"tag": "USERNAME",
"value": "swagger-api"
}
] | null |
[] |
/*
* tapi-common,tapi-dsr,tapi-path-computation,tapi-eth,tapi-virtual-network,tapi-topology,tapi-notification,tapi-oam,tapi-photonic-media,tapi-connectivity API
* tapi-common,tapi-dsr,tapi-path-computation,tapi-eth,tapi-virtual-network,tapi-topology,tapi-notification,tapi-oam,tapi-photonic-media,tapi-connectivity API generated from yang definitions
*
* OpenAPI spec version: 1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.model.TapiNotificationPerceivedTcaSeverity;
import io.swagger.model.TapiNotificationThresholdCrossingType;
import javax.validation.constraints.*;
/**
* TapiNotificationTcaInfo
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2018-11-14T14:58:12.974+01:00")
public class TapiNotificationTcaInfo {
@JsonProperty("threshold-crossing")
private TapiNotificationThresholdCrossingType thresholdCrossing = null;
@JsonProperty("threshold-parameter")
private String thresholdParameter = null;
@JsonProperty("is-transient")
private Boolean isTransient = false;
@JsonProperty("threshold-value")
private Integer thresholdValue = null;
@JsonProperty("perceived-severity")
private TapiNotificationPerceivedTcaSeverity perceivedSeverity = null;
@JsonProperty("suspect-interval-flag")
private Boolean suspectIntervalFlag = false;
@JsonProperty("measurement-interval")
private String measurementInterval = null;
public TapiNotificationTcaInfo thresholdCrossing(TapiNotificationThresholdCrossingType thresholdCrossing) {
this.thresholdCrossing = thresholdCrossing;
return this;
}
/**
* none
* @return thresholdCrossing
**/
@JsonProperty("threshold-crossing")
@ApiModelProperty(value = "none")
public TapiNotificationThresholdCrossingType getThresholdCrossing() {
return thresholdCrossing;
}
public void setThresholdCrossing(TapiNotificationThresholdCrossingType thresholdCrossing) {
this.thresholdCrossing = thresholdCrossing;
}
public TapiNotificationTcaInfo thresholdParameter(String thresholdParameter) {
this.thresholdParameter = thresholdParameter;
return this;
}
/**
* none
* @return thresholdParameter
**/
@JsonProperty("threshold-parameter")
@ApiModelProperty(value = "none")
public String getThresholdParameter() {
return thresholdParameter;
}
public void setThresholdParameter(String thresholdParameter) {
this.thresholdParameter = thresholdParameter;
}
public TapiNotificationTcaInfo isTransient(Boolean isTransient) {
this.isTransient = isTransient;
return this;
}
/**
* none
* @return isTransient
**/
@JsonProperty("is-transient")
@ApiModelProperty(value = "none")
public Boolean isIsTransient() {
return isTransient;
}
public void setIsTransient(Boolean isTransient) {
this.isTransient = isTransient;
}
public TapiNotificationTcaInfo thresholdValue(Integer thresholdValue) {
this.thresholdValue = thresholdValue;
return this;
}
/**
* none
* @return thresholdValue
**/
@JsonProperty("threshold-value")
@ApiModelProperty(value = "none")
public Integer getThresholdValue() {
return thresholdValue;
}
public void setThresholdValue(Integer thresholdValue) {
this.thresholdValue = thresholdValue;
}
public TapiNotificationTcaInfo perceivedSeverity(TapiNotificationPerceivedTcaSeverity perceivedSeverity) {
this.perceivedSeverity = perceivedSeverity;
return this;
}
/**
* none
* @return perceivedSeverity
**/
@JsonProperty("perceived-severity")
@ApiModelProperty(value = "none")
public TapiNotificationPerceivedTcaSeverity getPerceivedSeverity() {
return perceivedSeverity;
}
public void setPerceivedSeverity(TapiNotificationPerceivedTcaSeverity perceivedSeverity) {
this.perceivedSeverity = perceivedSeverity;
}
public TapiNotificationTcaInfo suspectIntervalFlag(Boolean suspectIntervalFlag) {
this.suspectIntervalFlag = suspectIntervalFlag;
return this;
}
/**
* none
* @return suspectIntervalFlag
**/
@JsonProperty("suspect-interval-flag")
@ApiModelProperty(value = "none")
public Boolean isSuspectIntervalFlag() {
return suspectIntervalFlag;
}
public void setSuspectIntervalFlag(Boolean suspectIntervalFlag) {
this.suspectIntervalFlag = suspectIntervalFlag;
}
public TapiNotificationTcaInfo measurementInterval(String measurementInterval) {
this.measurementInterval = measurementInterval;
return this;
}
/**
* none
* @return measurementInterval
**/
@JsonProperty("measurement-interval")
@ApiModelProperty(value = "none")
public String getMeasurementInterval() {
return measurementInterval;
}
public void setMeasurementInterval(String measurementInterval) {
this.measurementInterval = measurementInterval;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TapiNotificationTcaInfo tapiNotificationTcaInfo = (TapiNotificationTcaInfo) o;
return Objects.equals(this.thresholdCrossing, tapiNotificationTcaInfo.thresholdCrossing) &&
Objects.equals(this.thresholdParameter, tapiNotificationTcaInfo.thresholdParameter) &&
Objects.equals(this.isTransient, tapiNotificationTcaInfo.isTransient) &&
Objects.equals(this.thresholdValue, tapiNotificationTcaInfo.thresholdValue) &&
Objects.equals(this.perceivedSeverity, tapiNotificationTcaInfo.perceivedSeverity) &&
Objects.equals(this.suspectIntervalFlag, tapiNotificationTcaInfo.suspectIntervalFlag) &&
Objects.equals(this.measurementInterval, tapiNotificationTcaInfo.measurementInterval);
}
@Override
public int hashCode() {
return Objects.hash(thresholdCrossing, thresholdParameter, isTransient, thresholdValue, perceivedSeverity, suspectIntervalFlag, measurementInterval);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class TapiNotificationTcaInfo {\n");
sb.append(" thresholdCrossing: ").append(toIndentedString(thresholdCrossing)).append("\n");
sb.append(" thresholdParameter: ").append(toIndentedString(thresholdParameter)).append("\n");
sb.append(" isTransient: ").append(toIndentedString(isTransient)).append("\n");
sb.append(" thresholdValue: ").append(toIndentedString(thresholdValue)).append("\n");
sb.append(" perceivedSeverity: ").append(toIndentedString(perceivedSeverity)).append("\n");
sb.append(" suspectIntervalFlag: ").append(toIndentedString(suspectIntervalFlag)).append("\n");
sb.append(" measurementInterval: ").append(toIndentedString(measurementInterval)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 7,512 | 0.746805 | 0.74361 | 235 | 30.961702 | 33.493515 | 190 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.412766 | false | false |
10
|
4a7cd69d7a01303ff4523d20b5b9d78fceaf635c
| 2,070,174,291,339 |
5649995d64e448b028abfd53d9e57aaa22a346cc
|
/EcoCicle/app/src/main/java/com/e2g/ecocicle/Model/Pontodetroca.java
|
c40b9f9f6e61dad3689cc3ba2b8223012856574f
|
[] |
no_license
|
global-urban-datafest/Eco2Cycle
|
https://github.com/global-urban-datafest/Eco2Cycle
|
bb7d559a784eee50788c79ad330a1c86496c8bd6
|
ad07fee0dd034aebe1ee90896600b555b3d7e77c
|
refs/heads/master
| 2021-01-23T12:18:04.969000 | 2015-03-23T00:28:40 | 2015-03-23T00:28:40 | 31,785,272 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.e2g.ecocicle.Model;
/**
* Created by tigrao on 06/03/15.
*/
public class Pontodetroca {
private String idPontoColeta;
private String descricao;
private String responsavel;
private String endereco;
private Double latitude;
private Double longitude;
private String tipo;
public Pontodetroca() {
}
public String getIdPontoColeta() {
return idPontoColeta;
}
public void setIdPontoColeta(String idPontoColeta) {
this.idPontoColeta = idPontoColeta;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getResponsavel() {
return responsavel;
}
public void setResponsavel(String responsavel) {
this.responsavel = responsavel;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
}
|
UTF-8
|
Java
| 1,464 |
java
|
Pontodetroca.java
|
Java
|
[
{
"context": "package com.e2g.ecocicle.Model;\n\n/**\n * Created by tigrao on 06/03/15.\n */\npublic class Pontodetroca {\n ",
"end": 57,
"score": 0.9994797110557556,
"start": 51,
"tag": "USERNAME",
"value": "tigrao"
}
] | null |
[] |
package com.e2g.ecocicle.Model;
/**
* Created by tigrao on 06/03/15.
*/
public class Pontodetroca {
private String idPontoColeta;
private String descricao;
private String responsavel;
private String endereco;
private Double latitude;
private Double longitude;
private String tipo;
public Pontodetroca() {
}
public String getIdPontoColeta() {
return idPontoColeta;
}
public void setIdPontoColeta(String idPontoColeta) {
this.idPontoColeta = idPontoColeta;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getResponsavel() {
return responsavel;
}
public void setResponsavel(String responsavel) {
this.responsavel = responsavel;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
}
| 1,464 | 0.630464 | 0.625683 | 74 | 18.783783 | 16.789049 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.297297 | false | false |
10
|
a0d4e018bb482b64b6c6bd093c17bafc842aef08
| 31,628,139,208,537 |
66003d9f86a68f9a8b15ff4d69fd473c6df38436
|
/src/databank/Transformation.java
|
150fdefa8a926a559cd63e0e32081d76b5b68508
|
[] |
no_license
|
sergiojr/Knowledge_App
|
https://github.com/sergiojr/Knowledge_App
|
f729345a70ffb222181ac81af9840990944b5929
|
498f5549467552fb0a67e8d29ee80322561e7359
|
refs/heads/master
| 2021-01-01T20:17:58.551000 | 2015-10-11T12:00:31 | 2015-10-11T12:00:31 | 3,007,342 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package databank;
public class Transformation {
public Transformation(DataBank databank, int id, int line, String sourcePrefix,
String sourceSuffix, int sourceType, String targetPrefix, String targetSuffix,
int targetType, boolean keepRule, int sourceRule, int targetRule, int type) {
this.databank = databank;
this.id = id;
this.line = line;
this.sourcePrefix = sourcePrefix;
this.sourceSuffix = sourceSuffix;
this.sourceType = sourceType;
this.targetPrefix = targetPrefix;
this.targetSuffix = targetSuffix;
this.targetType = targetType;
this.keepRule = keepRule;
this.sourceRule = sourceRule;
this.targetRule = targetRule;
this.type = type;
}
public int getId() {
return id;
}
public int getLine() {
return line;
}
int id;
int line;
private String sourcePrefix;
String sourceSuffix;
int sourceType;
private String targetPrefix;
String targetSuffix;
int targetType;
boolean keepRule;
int sourceRule;
int targetRule;
int type;
DataBank databank;
public Word forwardTransformation(Word word) {
String oldWord = word.word.intern();
String newWord = oldWord;
int newType = 0;
int newRule = targetRule;
int newRuleVariance = 0;
if (sourceType != 0)
if (word.type != sourceType)
return null;
if (targetType != 0)
newType = targetType;
else
newType = word.type;
if (sourceRule != 0)
if (word.rule_no != sourceRule)
return null;
if (keepRule) {
newRule = word.rule_no;
newRuleVariance = word.rule_variance;
}
Prefix sourcePrefix = databank.getPrefix(this.sourcePrefix);
if (!this.sourcePrefix.isEmpty() && sourcePrefix == null)
return null;
if (sourcePrefix != null) {
newWord = sourcePrefix.dropPrefix(newWord);
if (newWord == null)
return null;
}
Prefix targetPrefix = databank.getPrefix(this.targetPrefix);
if (!this.targetPrefix.isEmpty() && targetPrefix == null)
return null;
if (targetPrefix != null) {
newWord = targetPrefix.addPrefix(newWord);
if (newWord == null)
return null;
}
newWord = dropSuffix(newWord, sourceSuffix);
newWord = addSuffix(newWord, targetSuffix);
if (newWord != oldWord)
return new Word(null, 0, newWord, newType, newRule, newRuleVariance, false, 0, 0, 0);
return null;
}
public Word backwardTransformation(Word word) {
String oldWord = word.word.intern();
String newWord = oldWord;
int newType = 0;
int newRule = sourceRule;
int newRuleVariance = 0;
if (targetType != 0)
if (word.type != targetType)
return null;
if (sourceType != 0)
newType = sourceType;
else
newType = word.type;
if (targetRule != 0)
if (word.rule_no != targetRule)
return null;
if (keepRule) {
newRule = word.rule_no;
newRuleVariance = word.rule_variance;
}
Prefix targetPrefix = databank.getPrefix(this.targetPrefix);
if (!this.targetPrefix.isEmpty() && targetPrefix == null)
return null;
if (targetPrefix != null) {
newWord = targetPrefix.dropPrefix(newWord);
if (newWord == null)
return null;
}
Prefix sourcePrefix = databank.getPrefix(this.sourcePrefix);
if (!this.sourcePrefix.isEmpty() && sourcePrefix == null)
return null;
if (sourcePrefix != null) {
newWord = sourcePrefix.addPrefix(newWord);
if (newWord == null)
return null;
}
newWord = dropSuffix(newWord, targetSuffix);
if (newWord == null)
return null;
newWord = addSuffix(newWord, sourceSuffix);
if (newWord != oldWord)
return new Word(null, 0, newWord, newType, newRule, newRuleVariance, false, 0, 0, 0);
return null;
}
private String addSuffix(String oldWord, String suffix) {
if (suffix.isEmpty())
return oldWord;
return oldWord + suffix;
}
private String dropSuffix(String oldWord, String suffix) {
if (suffix.isEmpty())
return oldWord;
if (oldWord.endsWith(suffix))
return oldWord.substring(0, oldWord.length() - suffix.length());
else
return null;
}
}
|
UTF-8
|
Java
| 4,110 |
java
|
Transformation.java
|
Java
|
[] | null |
[] |
package databank;
public class Transformation {
public Transformation(DataBank databank, int id, int line, String sourcePrefix,
String sourceSuffix, int sourceType, String targetPrefix, String targetSuffix,
int targetType, boolean keepRule, int sourceRule, int targetRule, int type) {
this.databank = databank;
this.id = id;
this.line = line;
this.sourcePrefix = sourcePrefix;
this.sourceSuffix = sourceSuffix;
this.sourceType = sourceType;
this.targetPrefix = targetPrefix;
this.targetSuffix = targetSuffix;
this.targetType = targetType;
this.keepRule = keepRule;
this.sourceRule = sourceRule;
this.targetRule = targetRule;
this.type = type;
}
public int getId() {
return id;
}
public int getLine() {
return line;
}
int id;
int line;
private String sourcePrefix;
String sourceSuffix;
int sourceType;
private String targetPrefix;
String targetSuffix;
int targetType;
boolean keepRule;
int sourceRule;
int targetRule;
int type;
DataBank databank;
public Word forwardTransformation(Word word) {
String oldWord = word.word.intern();
String newWord = oldWord;
int newType = 0;
int newRule = targetRule;
int newRuleVariance = 0;
if (sourceType != 0)
if (word.type != sourceType)
return null;
if (targetType != 0)
newType = targetType;
else
newType = word.type;
if (sourceRule != 0)
if (word.rule_no != sourceRule)
return null;
if (keepRule) {
newRule = word.rule_no;
newRuleVariance = word.rule_variance;
}
Prefix sourcePrefix = databank.getPrefix(this.sourcePrefix);
if (!this.sourcePrefix.isEmpty() && sourcePrefix == null)
return null;
if (sourcePrefix != null) {
newWord = sourcePrefix.dropPrefix(newWord);
if (newWord == null)
return null;
}
Prefix targetPrefix = databank.getPrefix(this.targetPrefix);
if (!this.targetPrefix.isEmpty() && targetPrefix == null)
return null;
if (targetPrefix != null) {
newWord = targetPrefix.addPrefix(newWord);
if (newWord == null)
return null;
}
newWord = dropSuffix(newWord, sourceSuffix);
newWord = addSuffix(newWord, targetSuffix);
if (newWord != oldWord)
return new Word(null, 0, newWord, newType, newRule, newRuleVariance, false, 0, 0, 0);
return null;
}
public Word backwardTransformation(Word word) {
String oldWord = word.word.intern();
String newWord = oldWord;
int newType = 0;
int newRule = sourceRule;
int newRuleVariance = 0;
if (targetType != 0)
if (word.type != targetType)
return null;
if (sourceType != 0)
newType = sourceType;
else
newType = word.type;
if (targetRule != 0)
if (word.rule_no != targetRule)
return null;
if (keepRule) {
newRule = word.rule_no;
newRuleVariance = word.rule_variance;
}
Prefix targetPrefix = databank.getPrefix(this.targetPrefix);
if (!this.targetPrefix.isEmpty() && targetPrefix == null)
return null;
if (targetPrefix != null) {
newWord = targetPrefix.dropPrefix(newWord);
if (newWord == null)
return null;
}
Prefix sourcePrefix = databank.getPrefix(this.sourcePrefix);
if (!this.sourcePrefix.isEmpty() && sourcePrefix == null)
return null;
if (sourcePrefix != null) {
newWord = sourcePrefix.addPrefix(newWord);
if (newWord == null)
return null;
}
newWord = dropSuffix(newWord, targetSuffix);
if (newWord == null)
return null;
newWord = addSuffix(newWord, sourceSuffix);
if (newWord != oldWord)
return new Word(null, 0, newWord, newType, newRule, newRuleVariance, false, 0, 0, 0);
return null;
}
private String addSuffix(String oldWord, String suffix) {
if (suffix.isEmpty())
return oldWord;
return oldWord + suffix;
}
private String dropSuffix(String oldWord, String suffix) {
if (suffix.isEmpty())
return oldWord;
if (oldWord.endsWith(suffix))
return oldWord.substring(0, oldWord.length() - suffix.length());
else
return null;
}
}
| 4,110 | 0.66253 | 0.657908 | 170 | 22.17647 | 19.985394 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.411765 | false | false |
3
|
3287415eb31cea3e8c6f595ced8107e490765c53
| 31,559,419,699,962 |
922a7850c99629f9ef1b8258bcf2da281ea5a56e
|
/vcr4j-sharktopoda/src/main/java/org/mbari/vcr4j/sharktopoda/Constants.java
|
d67b76927fc0716a0c5f763bf095adff4fa493a7
|
[
"Apache-2.0"
] |
permissive
|
mbari-org/vcr4j
|
https://github.com/mbari-org/vcr4j
|
a484f9b907a27659ad87046520123fa28b002a2f
|
51a54beb69d63600329003b54c8fddca5d3e7fa4
|
refs/heads/master
| 2023-04-09T10:20:00.377000 | 2023-01-25T00:13:42 | 2023-01-25T00:13:42 | 90,187,644 | 0 | 0 |
Apache-2.0
| false | 2022-06-12T21:42:35 | 2017-05-03T19:51:48 | 2022-06-03T19:36:29 | 2022-06-12T21:42:35 | 1,153 | 4 | 3 | 4 |
Java
| false | false |
package org.mbari.vcr4j.sharktopoda;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* @author Brian Schlining
* @since 2016-08-26T11:13:00
*/
public class Constants {
public static final Gson GSON = new GsonBuilder().setPrettyPrinting()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
.create();
}
|
UTF-8
|
Java
| 472 |
java
|
Constants.java
|
Java
|
[
{
"context": "mport com.google.gson.GsonBuilder;\n\n/**\n * @author Brian Schlining\n * @since 2016-08-26T11:13:00\n */\npublic class Co",
"end": 176,
"score": 0.9996140003204346,
"start": 161,
"tag": "NAME",
"value": "Brian Schlining"
}
] | null |
[] |
package org.mbari.vcr4j.sharktopoda;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* @author <NAME>
* @since 2016-08-26T11:13:00
*/
public class Constants {
public static final Gson GSON = new GsonBuilder().setPrettyPrinting()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
.create();
}
| 463 | 0.70339 | 0.67161 | 17 | 26.764706 | 24.312983 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false |
3
|
11d0272bd13b61d56b12bb01794edb8cdd3beb79
| 7,705,171,397,387 |
f9f222191774551fede818cf7af14f3f7f13820f
|
/resume-online-frontend/resume-online-jfx-core/src/main/java/resumeonline/jfx/core/ui/component/ImageViewConfigurator.java
|
1174041434f9fb58abaed5505519862958d59130
|
[
"Apache-2.0"
] |
permissive
|
jbrasileiro/resume-online
|
https://github.com/jbrasileiro/resume-online
|
c8c63dad2914bcba39296b762949cb1ff81a711c
|
4cdd3a2d27182d7dd6fa1263ddb3dafffc00afba
|
refs/heads/master
| 2022-12-23T17:41:58.601000 | 2021-04-26T17:18:53 | 2021-04-26T17:18:53 | 76,023,274 | 0 | 0 |
Apache-2.0
| false | 2022-12-16T11:45:02 | 2016-12-09T09:53:37 | 2021-04-26T17:18:55 | 2022-12-16T11:44:59 | 1,442 | 0 | 0 | 5 |
Java
| false | false |
package resumeonline.jfx.core.ui.component;
import java.net.URL;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import resumeonline.jfx.core.ImageResourceLoader;
public final class ImageViewConfigurator {
private final ImageView field;
public ImageViewConfigurator(
final ImageView field) {
this.field = field;
}
public ImageViewConfigurator image(
final String name) {
field.setImage(ImageResourceLoader.load(name));
return this;
}
public ImageViewConfigurator image(
final URL url) {
field.setImage(new Image(url.toExternalForm()));
return this;
}
public ImageViewConfigurator image(
final Image image) {
field.setImage(image);
return this;
}
public ImageViewConfigurator fitWidth(
final double value) {
field.setFitWidth(value);
return this;
}
public ImageViewConfigurator fitHeight(
final double value) {
field.setFitHeight(15);
return this;
}
}
|
UTF-8
|
Java
| 1,071 |
java
|
ImageViewConfigurator.java
|
Java
|
[] | null |
[] |
package resumeonline.jfx.core.ui.component;
import java.net.URL;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import resumeonline.jfx.core.ImageResourceLoader;
public final class ImageViewConfigurator {
private final ImageView field;
public ImageViewConfigurator(
final ImageView field) {
this.field = field;
}
public ImageViewConfigurator image(
final String name) {
field.setImage(ImageResourceLoader.load(name));
return this;
}
public ImageViewConfigurator image(
final URL url) {
field.setImage(new Image(url.toExternalForm()));
return this;
}
public ImageViewConfigurator image(
final Image image) {
field.setImage(image);
return this;
}
public ImageViewConfigurator fitWidth(
final double value) {
field.setFitWidth(value);
return this;
}
public ImageViewConfigurator fitHeight(
final double value) {
field.setFitHeight(15);
return this;
}
}
| 1,071 | 0.65733 | 0.655462 | 47 | 21.787233 | 17.064255 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361702 | false | false |
3
|
7b15a26442e86ec9c4f23cedab1ced5058706d6d
| 28,810,640,652,292 |
d0b0db24670c6a963bc47c47707f405fb3c6f6ad
|
/citi/src/com/web/partner/badbill/action/SettAccountAction.java
|
99f06de4b17ffe91e24b45722a85c3fa53663e55
|
[] |
no_license
|
Lynwood01/asiainfoCode
|
https://github.com/Lynwood01/asiainfoCode
|
3daebf58873dd6a9fd9b29d44bb1899fd7885132
|
93c319428afaf837a96ac79b267118dd9d757eec
|
refs/heads/master
| 2019-03-20T22:38:46.902000 | 2018-09-02T08:09:44 | 2018-09-02T08:09:44 | 124,053,464 | 0 | 10 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.web.partner.badbill.action;
/**
* 错单维护
* 结算账目维护
*/
import com.ailk.common.simple.SimpleAction;
import com.web.partner.badbill.service.SettAccountService;
public class SettAccountAction extends SimpleAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private SettAccountService settAccountService;
public String execute(){
if("getProducts".equals(action)){
search.put("total", settAccountService.getTotal(search));
search.put("products",settAccountService.getProducts(search,start,limit));
}
if("productCombo".equals(action)){
search.put("productCombo", settAccountService.productCombobox());
}
if("getInfo".equals(action)){
search.put("info", settAccountService.getInfo(search));
}
if("insertTemp".equals(action)){
settAccountService.insertTemp(search);
}
if("deleteTemp".equals(action)){
settAccountService.deleteTemp(search);
}
if("moveNode".equals(action)){
settAccountService.moveNode(search);
}
if("check".equals(action)){
search.put("check", settAccountService.check(search));
}
if("stat".equals(action)){
settAccountService.stat(search);
}
return JSON_RESULT;
}
public SettAccountService getSettAccountService() {
return settAccountService;
}
public void setSettAccountService(SettAccountService settAccountService) {
this.settAccountService = settAccountService;
}
}
|
UTF-8
|
Java
| 1,420 |
java
|
SettAccountAction.java
|
Java
|
[] | null |
[] |
package com.web.partner.badbill.action;
/**
* 错单维护
* 结算账目维护
*/
import com.ailk.common.simple.SimpleAction;
import com.web.partner.badbill.service.SettAccountService;
public class SettAccountAction extends SimpleAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private SettAccountService settAccountService;
public String execute(){
if("getProducts".equals(action)){
search.put("total", settAccountService.getTotal(search));
search.put("products",settAccountService.getProducts(search,start,limit));
}
if("productCombo".equals(action)){
search.put("productCombo", settAccountService.productCombobox());
}
if("getInfo".equals(action)){
search.put("info", settAccountService.getInfo(search));
}
if("insertTemp".equals(action)){
settAccountService.insertTemp(search);
}
if("deleteTemp".equals(action)){
settAccountService.deleteTemp(search);
}
if("moveNode".equals(action)){
settAccountService.moveNode(search);
}
if("check".equals(action)){
search.put("check", settAccountService.check(search));
}
if("stat".equals(action)){
settAccountService.stat(search);
}
return JSON_RESULT;
}
public SettAccountService getSettAccountService() {
return settAccountService;
}
public void setSettAccountService(SettAccountService settAccountService) {
this.settAccountService = settAccountService;
}
}
| 1,420 | 0.734286 | 0.733571 | 57 | 23.543859 | 23.150211 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.859649 | false | false |
3
|
3d94020dbae30f2ff4fb3bdaebc8dad844de9f76
| 22,986,664,983,694 |
a79dbc366e245b429c975c635cf5161ea265f660
|
/de.fu_berlin.imp.apiua.groundedtheory/src/de/fu_berlin/imp/apiua/groundedtheory/storage/exceptions/RelationInstanceDoesNotExistException.java
|
d920bae22137f3e0f1f3afd719d7c515f216b075
|
[
"MIT"
] |
permissive
|
bkahlert/api-usability-analyzer
|
https://github.com/bkahlert/api-usability-analyzer
|
b227865d4d5302fc25a1e2453b4ec4029196c80d
|
d3f08af3289879284826b7f1f018e7d6f8862b0e
|
refs/heads/master
| 2023-07-07T09:55:24.168000 | 2016-01-13T13:34:41 | 2016-01-13T13:34:41 | 2,704,610 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.fu_berlin.imp.apiua.groundedtheory.storage.exceptions;
public class RelationInstanceDoesNotExistException extends Exception {
/**
*
*/
private static final long serialVersionUID = -181903820451866588L;
}
|
UTF-8
|
Java
| 224 |
java
|
RelationInstanceDoesNotExistException.java
|
Java
|
[] | null |
[] |
package de.fu_berlin.imp.apiua.groundedtheory.storage.exceptions;
public class RelationInstanceDoesNotExistException extends Exception {
/**
*
*/
private static final long serialVersionUID = -181903820451866588L;
}
| 224 | 0.790179 | 0.709821 | 10 | 21.4 | 30.127064 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false |
3
|
20df3db4c4134cd61fb9d28e629f1e82ed47d06c
| 33,328,946,284,366 |
f6a2d06623c8972478b2a74f2aaae7db22214d69
|
/src/test/java/CSC/CodeForces_input_test/Codeforce/Contest_3/TestTreap.java
|
4dc933c1a106a90b83260eb38befd6253fc23056
|
[] |
no_license
|
ElenaDolgova/Algorithms
|
https://github.com/ElenaDolgova/Algorithms
|
d77ffb5a0113f818c7569c4763324209f0b2527b
|
3063e6fef2567126bc30d43afff402e96e531925
|
refs/heads/master
| 2021-07-10T11:42:15.804000 | 2018-12-16T13:10:47 | 2018-12-16T13:10:47 | 104,872,765 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package CSC.CodeForces_input_test.Codeforce.Contest_3;
public class TestTreap {
}
|
UTF-8
|
Java
| 83 |
java
|
TestTreap.java
|
Java
|
[] | null |
[] |
package CSC.CodeForces_input_test.Codeforce.Contest_3;
public class TestTreap {
}
| 83 | 0.795181 | 0.783133 | 4 | 19.75 | 21.981525 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
3
|
d1ebcede0dd63454c8114b2f03e9e93be0b2acd9
| 2,860,448,220,338 |
fe6e25dfeb29103f0da42cf0d997ae059fad563d
|
/src/main/java/ru/nyrk/gisgmp/database/service/TicketServiceImpl.java
|
7f42c48ff5a7292380c0068d3948f3ec7aa98052
|
[
"Apache-2.0"
] |
permissive
|
OlegNyr/GisGMP
|
https://github.com/OlegNyr/GisGMP
|
089576717837dc8c0d6e9aec8b18fd7c8ef12019
|
35bf3683476e75f6b8afa7aabc1b40d958f4276f
|
refs/heads/master
| 2021-01-19T14:56:33.874000 | 2018-10-17T07:22:09 | 2018-10-17T07:22:09 | 16,102,898 | 3 | 3 | null | false | 2016-03-09T20:18:24 | 2014-01-21T13:14:20 | 2014-01-21T14:54:10 | 2016-03-09T20:18:24 | 9,788 | 0 | 3 | 1 |
Java
| null | null |
package ru.nyrk.gisgmp.database.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.nyrk.gisgmp.database.entity.TicketEntity;
import ru.nyrk.gisgmp.database.reposit.TicketRepository;
import java.util.List;
@Service("ticketService")
@Repository
@Transactional
public class TicketServiceImpl implements TicketService {
@Qualifier("ticketRepository")
@Autowired
private TicketRepository ticketRepository;
@Override
public TicketEntity save(TicketEntity ticketEntity) {
return ticketRepository.save(ticketEntity);
}
@Override
public List<TicketEntity> findByMesIdOrderByTicketDtAsc(Long messId) {
return null;
// return ticketRepository.findByMesIdOrderByTicketDtAsc(messId);
}
}
|
UTF-8
|
Java
| 993 |
java
|
TicketServiceImpl.java
|
Java
|
[] | null |
[] |
package ru.nyrk.gisgmp.database.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.nyrk.gisgmp.database.entity.TicketEntity;
import ru.nyrk.gisgmp.database.reposit.TicketRepository;
import java.util.List;
@Service("ticketService")
@Repository
@Transactional
public class TicketServiceImpl implements TicketService {
@Qualifier("ticketRepository")
@Autowired
private TicketRepository ticketRepository;
@Override
public TicketEntity save(TicketEntity ticketEntity) {
return ticketRepository.save(ticketEntity);
}
@Override
public List<TicketEntity> findByMesIdOrderByTicketDtAsc(Long messId) {
return null;
// return ticketRepository.findByMesIdOrderByTicketDtAsc(messId);
}
}
| 993 | 0.79859 | 0.79859 | 33 | 29.09091 | 25.231491 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.393939 | false | false |
3
|
28aa43e67579f9d1c5c404068081a1024340654f
| 20,143,396,647,332 |
3b65561c4113544cd0b410cc44cc96d3531023f6
|
/taier-datasource/taier-datasource-plugin/taier-datasource-plugin-redis/src/main/java/com/dtstack/taier/datasource/plugin/redis/RedisUtils.java
|
49044153e475b423c842981b203a919e92b62d8a
|
[
"Apache-2.0"
] |
permissive
|
DTStack/Taier
|
https://github.com/DTStack/Taier
|
2bc168d802b028f669131017c996d61286d4f2db
|
5116f9ee195ee0c53b75ddf9724b0dedc62e6b4c
|
refs/heads/master
| 2023-09-04T02:42:02.266000 | 2023-08-10T05:51:36 | 2023-08-10T05:51:36 | 343,649,088 | 1,195 | 308 |
Apache-2.0
| false | 2023-09-10T11:35:57 | 2021-03-02T04:49:33 | 2023-09-09T08:20:07 | 2023-09-10T11:35:52 | 153,991 | 1,187 | 288 | 57 |
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 com.dtstack.taier.datasource.plugin.redis;
import com.dtstack.taier.datasource.api.enums.RedisMode;
import com.dtstack.taier.datasource.plugin.common.exception.IErrorPattern;
import com.dtstack.taier.datasource.plugin.common.service.ErrorAdapterImpl;
import com.dtstack.taier.datasource.plugin.common.service.IErrorAdapter;
import com.dtstack.taier.datasource.plugin.common.utils.AddressUtil;
import com.dtstack.taier.datasource.api.dto.SqlQueryDTO;
import com.dtstack.taier.datasource.api.dto.source.ISourceDTO;
import com.dtstack.taier.datasource.api.dto.source.RedisSourceDTO;
import com.dtstack.taier.datasource.api.exception.SourceException;
import com.dtstack.taier.datasource.api.utils.AssertUtils;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.util.Pool;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* @company: www.dtstack.com
* @Author :Nanqi
* @Date :Created in 16:38 2020/2/4
* @Description:Redis 工具类
*/
@Slf4j
public class RedisUtils {
private static Pattern HOST_PORT_PATTERN = Pattern.compile("(?<host>(.*)):((?<port>\\d+))*");
private static final int DEFAULT_PORT = 6379;
private static final int TIME_OUT = 5 * 1000;
private static final int LIMIT_MAX_KEY = 1000;
private static final IErrorPattern ERROR_PATTERN = new RedisErrorPattern();
// 异常适配器
private static final IErrorAdapter ERROR_ADAPTER = new ErrorAdapterImpl();
public static boolean checkConnection(ISourceDTO iSource) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) iSource;
log.info("get Redis connected, host : {}, port : {}", redisSourceDTO.getMaster(), redisSourceDTO.getHostPort());
RedisMode redisMode = redisSourceDTO.getRedisMode() != null ? redisSourceDTO.getRedisMode() : RedisMode.Standalone;
try {
switch (redisMode) {
case Standalone:
return checkConnectionStandalone(redisSourceDTO);
case Sentinel:
return checkRedisConnectionSentinel(redisSourceDTO);
case Cluster:
return checkRedisConnectionCluster(redisSourceDTO);
default:
throw new SourceException("Unsupported mode");
}
} catch (Exception e) {
String errorMsg = e.getMessage();
if (e instanceof JedisConnectionException && e.getCause() != null) {
errorMsg = e.getCause().getMessage();
}
throw new SourceException(ERROR_ADAPTER.connAdapter(errorMsg, ERROR_PATTERN), e);
}
}
public static List<List<Object>> getPreview(ISourceDTO source, SqlQueryDTO queryDTO) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
String tableName = queryDTO.getTableName();
if (StringUtils.isBlank(tableName)) {
throw new SourceException("preview table name not empty");
}
log.info("get Redis connected, host : {}, port : {}", redisSourceDTO.getMaster(), redisSourceDTO.getHostPort());
RedisMode redisMode = redisSourceDTO.getRedisMode() != null ? redisSourceDTO.getRedisMode() : RedisMode.Standalone;
List<List<Object>> result = Lists.newArrayList();
List<Object> redisResult = Lists.newArrayList();
Map<String, Object> resultMap = Maps.newHashMap();
List<String> fieldKey;
List<String> values ;
if (RedisMode.Standalone.equals(redisMode) || RedisMode.Sentinel.equals(redisMode)) {
Pool<Jedis> redisPool = null;
Jedis jedis = null;
try {
if (RedisMode.Standalone.equals(redisMode)) {
redisPool = getRedisPool(source);
} else {
redisPool = getSentinelPool(source);
}
jedis = redisPool.getResource();
int db = StringUtils.isEmpty(redisSourceDTO.getSchema()) ? 0 : Integer.parseInt(redisSourceDTO.getSchema());
jedis.select(db);
Set<String> keys = jedis.hkeys(tableName);
if (CollectionUtils.isEmpty(keys)) {
return result;
}
fieldKey = keys.stream().limit(queryDTO.getPreviewNum()).collect(Collectors.toList());
values = jedis.hmget(tableName, fieldKey.toArray(new String[]{}));
} finally {
// 关闭资源
close(jedis, redisPool);
}
} else {
JedisCluster redisCluster = null;
try {
redisCluster = getRedisCluster(source);
Set<String> keys = redisCluster.hkeys(tableName);
if (CollectionUtils.isEmpty(keys)) {
return result;
}
fieldKey = keys.stream().limit(queryDTO.getPreviewNum()).collect(Collectors.toList());
values = redisCluster.hmget(tableName, fieldKey.toArray(new String[]{}));
} finally {
// 关闭资源
close(redisCluster);
}
}
if (fieldKey.size() != values.size()) {
throw new SourceException("get redis hash data exception");
}
for (int index = 0; index < values.size(); index++) {
resultMap.put(fieldKey.get(index), values.get(index));
}
redisResult.add(resultMap);
result.add(redisResult);
return result;
}
/**
* 查询 string 类型
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getStringRedisValue(JedisCommands jedis, List<String> keys) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
for (String key : keys) {
String result = jedis.get(key);
resultMap.put(key, result);
}
return resultMap;
}
/**
* 查询list类型
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getListRedisValue(JedisCommands jedis, List<String> keys, Integer limit) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
for (String key : keys) {
List<String> result = jedis.lrange(key, 0, limit);
result = CollectionUtils.isEmpty(result) ? new ArrayList<>() : result;
resultMap.put(key, result);
}
return resultMap;
}
/**
* 查询set 类型, smembers
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getSetRedisValue(JedisCommands jedis, List<String> keys) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
ScanParams scanParams = new ScanParams();
for (String key : keys) {
String cursor = ScanParams.SCAN_POINTER_START;
List<String> list = new ArrayList<>();
do {
ScanResult<String> scanResult = jedis.sscan(key, cursor, scanParams);
List<String> result = scanResult.getResult();
list.addAll(result);
cursor = scanResult.getStringCursor();
} while (!ScanParams.SCAN_POINTER_START.equals(cursor));
resultMap.put(key, list);
}
return resultMap;
}
/**
* 查询zset 类型,zrange
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getSortSetRedisValue(JedisCommands jedis, List<String> keys, Integer limit) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
for (String key : keys) {
Set<String> result = jedis.zrange(key, 0, limit);
result = CollectionUtils.isEmpty(result) ? new HashSet<>() : result;
resultMap.put(key, result);
}
return resultMap;
}
/**
* 查询hash 类型的表
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getHashRedisValue(JedisCommands jedis, List<String> keys) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
ScanParams scanParams = new ScanParams();
for (String key : keys) {
String cursor = ScanParams.SCAN_POINTER_START;
List<Map.Entry<String, String>> list = new ArrayList<>();
do {
ScanResult<Map.Entry<String, String>> scanResult = jedis.hscan(key, cursor, scanParams);
List<Map.Entry<String, String>> tuples = scanResult.getResult();
if (CollectionUtils.isNotEmpty(tuples)) {
list.addAll(tuples);
}
resultMap.put(key, list);
cursor = scanResult.getStringCursor();
} while (!ScanParams.SCAN_POINTER_START.equals(cursor));
}
return resultMap;
}
private static boolean checkConnectionStandalone(ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
JedisPool redisPool = null;
Jedis jedis = null;
int db = StringUtils.isNotEmpty(redisSourceDTO.getSchema()) ? Integer.parseInt(redisSourceDTO.getSchema()) : 0;
try {
redisPool = getRedisPool(source);
jedis = redisPool.getResource();
jedis.select(db);
return true;
} finally {
// 关闭资源
close(jedis, redisPool);
}
}
public static boolean checkRedisConnectionCluster(ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
JedisCluster redisCluster = null;
try {
redisCluster = getRedisCluster(source);
Set<HostAndPort> nodes = getHostAndPorts(redisSourceDTO.getHostPort());
// redis集群模式不带密码,创建客户端不会主动去连接集群,所以需要用telnet检测
for (HostAndPort node : nodes) {
if (!AddressUtil.telnet(node.getHost(), node.getPort())) {
return false;
}
}
return true;
} finally {
close(redisCluster);
}
}
public static boolean checkRedisConnectionSentinel(ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
int db = StringUtils.isEmpty(redisSourceDTO.getSchema()) ? 0 : Integer.parseInt(redisSourceDTO.getSchema());
JedisSentinelPool sentinelPool = null;
Jedis jedis = null;
try {
sentinelPool = getSentinelPool(source);
jedis = sentinelPool.getResource();
jedis.select(db);
return true;
} finally {
// 关闭资源
close(jedis, sentinelPool);
}
}
/**
* 获取redis 哨兵模式连接池
* @param source 数据源信息
* @return redis 连接池
*/
private static JedisSentinelPool getSentinelPool (ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
String masterName = redisSourceDTO.getMaster();
String hostPorts = redisSourceDTO.getHostPort();
String password = redisSourceDTO.getPassword();
Preconditions.checkArgument(StringUtils.isNotBlank(hostPorts), "hostPort not empty");
Set<HostAndPort> nodes = getHostAndPorts(hostPorts);
Preconditions.checkArgument(CollectionUtils.isNotEmpty(nodes), "invalid ip and port");
Set<String> sentinels = nodes.stream().map(hostAndPort -> hostAndPort.getHost() + ":" + hostAndPort.getPort())
.collect(Collectors.toSet());
JedisSentinelPool sentinelPool;
if (StringUtils.isNotBlank(password)) {
sentinelPool = new JedisSentinelPool(masterName, sentinels, password);
} else {
sentinelPool = new JedisSentinelPool(masterName, sentinels);
}
return sentinelPool;
}
/**
* 获取redis 单机模式连接池
* @param source 数据源信息
* @return redis 连接池
*/
private static JedisPool getRedisPool (ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
String password = redisSourceDTO.getPassword();
String hostPort = redisSourceDTO.getHostPort();
int db = StringUtils.isNotEmpty(redisSourceDTO.getSchema()) ? Integer.parseInt(redisSourceDTO.getSchema()) : 0;
Matcher matcher = HOST_PORT_PATTERN.matcher(hostPort);
Preconditions.checkArgument(matcher.find(), "hostPort Format exception");
String host = matcher.group("host");
String portStr = matcher.group("port");
int port = portStr == null ? DEFAULT_PORT : Integer.parseInt(portStr);
JedisPool pool;
if (StringUtils.isEmpty(password)) {
pool = new JedisPool(new GenericObjectPoolConfig(), host, port, TIME_OUT);
} else {
pool = new JedisPool(new GenericObjectPoolConfig(), host, port, TIME_OUT, password, db);
}
return pool;
}
/**
* 获取redis 集群模式 客户端
* @param source 数据源信息
* @return redis客户端
*/
private static JedisCluster getRedisCluster (ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
String hostPorts = redisSourceDTO.getHostPort();
String password = redisSourceDTO.getPassword();
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(2);
poolConfig.setMaxIdle(2);
poolConfig.setMaxWaitMillis(1000);
JedisCluster cluster;
Preconditions.checkArgument(StringUtils.isNotBlank(hostPorts), "hostPort not empty");
Set<HostAndPort> nodes = getHostAndPorts(hostPorts);
Preconditions.checkArgument(CollectionUtils.isNotEmpty(nodes), "invalid ip and port");
if (StringUtils.isNotBlank(password)) {
cluster = new JedisCluster(nodes, 1000, 1000, 100, password, poolConfig);
} else {
cluster = new JedisCluster(nodes, poolConfig);
}
return cluster;
}
private static Set<HostAndPort> getHostAndPorts(String hostPorts) {
Set<HostAndPort> nodes = new LinkedHashSet<>();
String[] split = hostPorts.split(",");
for (String node : split) {
Matcher matcher = HOST_PORT_PATTERN.matcher(node);
if (matcher.find()) {
String host = matcher.group("host");
String portStr = matcher.group("port");
if (StringUtils.isNotBlank(host) && StringUtils.isNotBlank(portStr)) {
// 转化为int格式的端口
int port = Integer.parseInt(portStr);
nodes.add(new HostAndPort(host, port));
}
}
}
return nodes;
}
private static void close(Closeable... closeables) {
try {
if (Objects.nonNull(closeables)) {
for (Closeable closeable : closeables) {
if (Objects.nonNull(closeable)) {
closeable.close();
}
}
}
} catch (Exception e) {
throw new SourceException(String.format("redis close resource error,%s", e.getMessage()), e);
}
}
}
|
UTF-8
|
Java
| 17,622 |
java
|
RedisUtils.java
|
Java
|
[
{
"context": "rs;\n\n/**\n * @company: www.dtstack.com\n * @Author :Nanqi\n * @Date :Created in 16:38 2020/2/4\n * @Descripti",
"end": 2747,
"score": 0.9965550899505615,
"start": 2742,
"tag": "NAME",
"value": "Nanqi"
},
{
"context": "SourceDTO.getHostPort();\n String password = redisSourceDTO.getPassword();\n Preconditions.che",
"end": 13253,
"score": 0.8749780058860779,
"start": 13248,
"tag": "PASSWORD",
"value": "redis"
},
{
"context": "(RedisSourceDTO) source;\n String password = redisSourceDTO.getPassword();\n String hostPort = redisSourceDTO.getHo",
"end": 14274,
"score": 0.9951640963554382,
"start": 14248,
"tag": "PASSWORD",
"value": "redisSourceDTO.getPassword"
}
] | 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 com.dtstack.taier.datasource.plugin.redis;
import com.dtstack.taier.datasource.api.enums.RedisMode;
import com.dtstack.taier.datasource.plugin.common.exception.IErrorPattern;
import com.dtstack.taier.datasource.plugin.common.service.ErrorAdapterImpl;
import com.dtstack.taier.datasource.plugin.common.service.IErrorAdapter;
import com.dtstack.taier.datasource.plugin.common.utils.AddressUtil;
import com.dtstack.taier.datasource.api.dto.SqlQueryDTO;
import com.dtstack.taier.datasource.api.dto.source.ISourceDTO;
import com.dtstack.taier.datasource.api.dto.source.RedisSourceDTO;
import com.dtstack.taier.datasource.api.exception.SourceException;
import com.dtstack.taier.datasource.api.utils.AssertUtils;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.util.Pool;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* @company: www.dtstack.com
* @Author :Nanqi
* @Date :Created in 16:38 2020/2/4
* @Description:Redis 工具类
*/
@Slf4j
public class RedisUtils {
private static Pattern HOST_PORT_PATTERN = Pattern.compile("(?<host>(.*)):((?<port>\\d+))*");
private static final int DEFAULT_PORT = 6379;
private static final int TIME_OUT = 5 * 1000;
private static final int LIMIT_MAX_KEY = 1000;
private static final IErrorPattern ERROR_PATTERN = new RedisErrorPattern();
// 异常适配器
private static final IErrorAdapter ERROR_ADAPTER = new ErrorAdapterImpl();
public static boolean checkConnection(ISourceDTO iSource) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) iSource;
log.info("get Redis connected, host : {}, port : {}", redisSourceDTO.getMaster(), redisSourceDTO.getHostPort());
RedisMode redisMode = redisSourceDTO.getRedisMode() != null ? redisSourceDTO.getRedisMode() : RedisMode.Standalone;
try {
switch (redisMode) {
case Standalone:
return checkConnectionStandalone(redisSourceDTO);
case Sentinel:
return checkRedisConnectionSentinel(redisSourceDTO);
case Cluster:
return checkRedisConnectionCluster(redisSourceDTO);
default:
throw new SourceException("Unsupported mode");
}
} catch (Exception e) {
String errorMsg = e.getMessage();
if (e instanceof JedisConnectionException && e.getCause() != null) {
errorMsg = e.getCause().getMessage();
}
throw new SourceException(ERROR_ADAPTER.connAdapter(errorMsg, ERROR_PATTERN), e);
}
}
public static List<List<Object>> getPreview(ISourceDTO source, SqlQueryDTO queryDTO) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
String tableName = queryDTO.getTableName();
if (StringUtils.isBlank(tableName)) {
throw new SourceException("preview table name not empty");
}
log.info("get Redis connected, host : {}, port : {}", redisSourceDTO.getMaster(), redisSourceDTO.getHostPort());
RedisMode redisMode = redisSourceDTO.getRedisMode() != null ? redisSourceDTO.getRedisMode() : RedisMode.Standalone;
List<List<Object>> result = Lists.newArrayList();
List<Object> redisResult = Lists.newArrayList();
Map<String, Object> resultMap = Maps.newHashMap();
List<String> fieldKey;
List<String> values ;
if (RedisMode.Standalone.equals(redisMode) || RedisMode.Sentinel.equals(redisMode)) {
Pool<Jedis> redisPool = null;
Jedis jedis = null;
try {
if (RedisMode.Standalone.equals(redisMode)) {
redisPool = getRedisPool(source);
} else {
redisPool = getSentinelPool(source);
}
jedis = redisPool.getResource();
int db = StringUtils.isEmpty(redisSourceDTO.getSchema()) ? 0 : Integer.parseInt(redisSourceDTO.getSchema());
jedis.select(db);
Set<String> keys = jedis.hkeys(tableName);
if (CollectionUtils.isEmpty(keys)) {
return result;
}
fieldKey = keys.stream().limit(queryDTO.getPreviewNum()).collect(Collectors.toList());
values = jedis.hmget(tableName, fieldKey.toArray(new String[]{}));
} finally {
// 关闭资源
close(jedis, redisPool);
}
} else {
JedisCluster redisCluster = null;
try {
redisCluster = getRedisCluster(source);
Set<String> keys = redisCluster.hkeys(tableName);
if (CollectionUtils.isEmpty(keys)) {
return result;
}
fieldKey = keys.stream().limit(queryDTO.getPreviewNum()).collect(Collectors.toList());
values = redisCluster.hmget(tableName, fieldKey.toArray(new String[]{}));
} finally {
// 关闭资源
close(redisCluster);
}
}
if (fieldKey.size() != values.size()) {
throw new SourceException("get redis hash data exception");
}
for (int index = 0; index < values.size(); index++) {
resultMap.put(fieldKey.get(index), values.get(index));
}
redisResult.add(resultMap);
result.add(redisResult);
return result;
}
/**
* 查询 string 类型
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getStringRedisValue(JedisCommands jedis, List<String> keys) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
for (String key : keys) {
String result = jedis.get(key);
resultMap.put(key, result);
}
return resultMap;
}
/**
* 查询list类型
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getListRedisValue(JedisCommands jedis, List<String> keys, Integer limit) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
for (String key : keys) {
List<String> result = jedis.lrange(key, 0, limit);
result = CollectionUtils.isEmpty(result) ? new ArrayList<>() : result;
resultMap.put(key, result);
}
return resultMap;
}
/**
* 查询set 类型, smembers
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getSetRedisValue(JedisCommands jedis, List<String> keys) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
ScanParams scanParams = new ScanParams();
for (String key : keys) {
String cursor = ScanParams.SCAN_POINTER_START;
List<String> list = new ArrayList<>();
do {
ScanResult<String> scanResult = jedis.sscan(key, cursor, scanParams);
List<String> result = scanResult.getResult();
list.addAll(result);
cursor = scanResult.getStringCursor();
} while (!ScanParams.SCAN_POINTER_START.equals(cursor));
resultMap.put(key, list);
}
return resultMap;
}
/**
* 查询zset 类型,zrange
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getSortSetRedisValue(JedisCommands jedis, List<String> keys, Integer limit) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
for (String key : keys) {
Set<String> result = jedis.zrange(key, 0, limit);
result = CollectionUtils.isEmpty(result) ? new HashSet<>() : result;
resultMap.put(key, result);
}
return resultMap;
}
/**
* 查询hash 类型的表
* @param jedis
* @param keys
* @return
*/
private static Map<String, Object> getHashRedisValue(JedisCommands jedis, List<String> keys) {
Map<String, Object> resultMap = new HashMap<>();
if (CollectionUtils.isEmpty(keys)) {
return resultMap;
}
ScanParams scanParams = new ScanParams();
for (String key : keys) {
String cursor = ScanParams.SCAN_POINTER_START;
List<Map.Entry<String, String>> list = new ArrayList<>();
do {
ScanResult<Map.Entry<String, String>> scanResult = jedis.hscan(key, cursor, scanParams);
List<Map.Entry<String, String>> tuples = scanResult.getResult();
if (CollectionUtils.isNotEmpty(tuples)) {
list.addAll(tuples);
}
resultMap.put(key, list);
cursor = scanResult.getStringCursor();
} while (!ScanParams.SCAN_POINTER_START.equals(cursor));
}
return resultMap;
}
private static boolean checkConnectionStandalone(ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
JedisPool redisPool = null;
Jedis jedis = null;
int db = StringUtils.isNotEmpty(redisSourceDTO.getSchema()) ? Integer.parseInt(redisSourceDTO.getSchema()) : 0;
try {
redisPool = getRedisPool(source);
jedis = redisPool.getResource();
jedis.select(db);
return true;
} finally {
// 关闭资源
close(jedis, redisPool);
}
}
public static boolean checkRedisConnectionCluster(ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
JedisCluster redisCluster = null;
try {
redisCluster = getRedisCluster(source);
Set<HostAndPort> nodes = getHostAndPorts(redisSourceDTO.getHostPort());
// redis集群模式不带密码,创建客户端不会主动去连接集群,所以需要用telnet检测
for (HostAndPort node : nodes) {
if (!AddressUtil.telnet(node.getHost(), node.getPort())) {
return false;
}
}
return true;
} finally {
close(redisCluster);
}
}
public static boolean checkRedisConnectionSentinel(ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
int db = StringUtils.isEmpty(redisSourceDTO.getSchema()) ? 0 : Integer.parseInt(redisSourceDTO.getSchema());
JedisSentinelPool sentinelPool = null;
Jedis jedis = null;
try {
sentinelPool = getSentinelPool(source);
jedis = sentinelPool.getResource();
jedis.select(db);
return true;
} finally {
// 关闭资源
close(jedis, sentinelPool);
}
}
/**
* 获取redis 哨兵模式连接池
* @param source 数据源信息
* @return redis 连接池
*/
private static JedisSentinelPool getSentinelPool (ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
String masterName = redisSourceDTO.getMaster();
String hostPorts = redisSourceDTO.getHostPort();
String password = <PASSWORD>SourceDTO.getPassword();
Preconditions.checkArgument(StringUtils.isNotBlank(hostPorts), "hostPort not empty");
Set<HostAndPort> nodes = getHostAndPorts(hostPorts);
Preconditions.checkArgument(CollectionUtils.isNotEmpty(nodes), "invalid ip and port");
Set<String> sentinels = nodes.stream().map(hostAndPort -> hostAndPort.getHost() + ":" + hostAndPort.getPort())
.collect(Collectors.toSet());
JedisSentinelPool sentinelPool;
if (StringUtils.isNotBlank(password)) {
sentinelPool = new JedisSentinelPool(masterName, sentinels, password);
} else {
sentinelPool = new JedisSentinelPool(masterName, sentinels);
}
return sentinelPool;
}
/**
* 获取redis 单机模式连接池
* @param source 数据源信息
* @return redis 连接池
*/
private static JedisPool getRedisPool (ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
String password = <PASSWORD>();
String hostPort = redisSourceDTO.getHostPort();
int db = StringUtils.isNotEmpty(redisSourceDTO.getSchema()) ? Integer.parseInt(redisSourceDTO.getSchema()) : 0;
Matcher matcher = HOST_PORT_PATTERN.matcher(hostPort);
Preconditions.checkArgument(matcher.find(), "hostPort Format exception");
String host = matcher.group("host");
String portStr = matcher.group("port");
int port = portStr == null ? DEFAULT_PORT : Integer.parseInt(portStr);
JedisPool pool;
if (StringUtils.isEmpty(password)) {
pool = new JedisPool(new GenericObjectPoolConfig(), host, port, TIME_OUT);
} else {
pool = new JedisPool(new GenericObjectPoolConfig(), host, port, TIME_OUT, password, db);
}
return pool;
}
/**
* 获取redis 集群模式 客户端
* @param source 数据源信息
* @return redis客户端
*/
private static JedisCluster getRedisCluster (ISourceDTO source) {
RedisSourceDTO redisSourceDTO = (RedisSourceDTO) source;
String hostPorts = redisSourceDTO.getHostPort();
String password = redisSourceDTO.getPassword();
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(2);
poolConfig.setMaxIdle(2);
poolConfig.setMaxWaitMillis(1000);
JedisCluster cluster;
Preconditions.checkArgument(StringUtils.isNotBlank(hostPorts), "hostPort not empty");
Set<HostAndPort> nodes = getHostAndPorts(hostPorts);
Preconditions.checkArgument(CollectionUtils.isNotEmpty(nodes), "invalid ip and port");
if (StringUtils.isNotBlank(password)) {
cluster = new JedisCluster(nodes, 1000, 1000, 100, password, poolConfig);
} else {
cluster = new JedisCluster(nodes, poolConfig);
}
return cluster;
}
private static Set<HostAndPort> getHostAndPorts(String hostPorts) {
Set<HostAndPort> nodes = new LinkedHashSet<>();
String[] split = hostPorts.split(",");
for (String node : split) {
Matcher matcher = HOST_PORT_PATTERN.matcher(node);
if (matcher.find()) {
String host = matcher.group("host");
String portStr = matcher.group("port");
if (StringUtils.isNotBlank(host) && StringUtils.isNotBlank(portStr)) {
// 转化为int格式的端口
int port = Integer.parseInt(portStr);
nodes.add(new HostAndPort(host, port));
}
}
}
return nodes;
}
private static void close(Closeable... closeables) {
try {
if (Objects.nonNull(closeables)) {
for (Closeable closeable : closeables) {
if (Objects.nonNull(closeable)) {
closeable.close();
}
}
}
} catch (Exception e) {
throw new SourceException(String.format("redis close resource error,%s", e.getMessage()), e);
}
}
}
| 17,611 | 0.621742 | 0.618512 | 444 | 38.054054 | 28.815845 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
3
|
aa77b6587ad4580b4eb0523dde36c9bb80bc1075
| 33,406,255,659,598 |
11d3a82fe5241978eddd7cd745d9821f92712778
|
/MinPathSum/Solution.java
|
76e9ef15ffeb7219831487d1f94a3bfa8129be6c
|
[] |
no_license
|
zhongyn/coding-man
|
https://github.com/zhongyn/coding-man
|
8477fafa5893d41a1206ed6659314d4fd887f2b9
|
7a9c8f7f64e6b0e5051b0c3e8638d3cba88b432e
|
refs/heads/master
| 2021-04-09T16:48:28.069000 | 2017-10-29T17:55:14 | 2017-10-29T17:55:14 | 28,938,456 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Solution {
public int minPathSum(int[][] grid) {
int row = grid.length;
if (row == 0) {
return 0;
}
int col = grid[0].length;
for (int i = 1; i < col; i++) {
grid[0][i] += grid[0][i -1];
}
for (int i = 1; i < row; i++) {
grid[i][0] += grid[i - 1][0];
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
grid[i][j] += grid[i - 1][j] < grid[i][j - 1]? grid[i - 1][j] : grid[i][j - 1];
}
}
return grid[row - 1][col - 1];
}
public int uniquePaths(int m, int n) {
int[][] grid = new int[m][n];
for (int i = 0; i < n; i++) {
grid[0][i] = 1;
}
for (int i = 1; i < m; i++) {
grid[i][0] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
grid[i][j] = grid[i - 1][j] + grid[i][j - 1];
}
}
return grid[m - 1][n - 1];
}
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
obstacleGrid[0][0] = obstacleGrid[0][0] == 1? 0 : 1;
for (int i = 1; i < n; i++) {
obstacleGrid[0][i] = obstacleGrid[0][i] == 1? 0 : obstacleGrid[0][i - 1];
}
for (int i = 1; i < m; i++) {
obstacleGrid[i][0] = obstacleGrid[i][0] == 1? 0 : obstacleGrid[i - 1][0];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
obstacleGrid[i][j] = obstacleGrid[i][j] == 1? 0 : obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
}
}
return obstacleGrid[m - 1][n - 1];
}
public static void main(String[] args) {
int[][] g = {{1,0}};
Solution s = new Solution();
System.out.println(s.uniquePathsWithObstacles(g));
}
}
class Solution {
public:
int uniquePaths(int m, int n) {
int table[m + 1][n + 1] = {0};
table[0][1] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j < n; j++) {
table[i][j] = table[i - 1][j] + table[i][j - 1];
}
}
return table[m][n];
}
int uniquePaths(int m, int n) {
int table[n + 1] = {0};
table[1] = 1;
for (int i = 0; i < m; i++) {
for (int j = 1; j <= n; j++) {
table[j] = table[j] + table[j - 1];
}
}
return table[n];
}
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> t(m + 1, vector<int>(n + 1, 0));
t[0][1] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (!obstacleGrid[i - 1][j - 1]) {
t[i][j] = t[i - 1][j] + t[i][j - 1];
}
}
}
return t[m][n];
}
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
int t[n + 1] = {0};
t[1] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
t[j] = obstacleGrid[i - 1][j - 1] == 0 ? t[j] + t[j - 1] : 0;
}
}
return t[n];
}
};
|
UTF-8
|
Java
| 3,558 |
java
|
Solution.java
|
Java
|
[] | null |
[] |
public class Solution {
public int minPathSum(int[][] grid) {
int row = grid.length;
if (row == 0) {
return 0;
}
int col = grid[0].length;
for (int i = 1; i < col; i++) {
grid[0][i] += grid[0][i -1];
}
for (int i = 1; i < row; i++) {
grid[i][0] += grid[i - 1][0];
}
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
grid[i][j] += grid[i - 1][j] < grid[i][j - 1]? grid[i - 1][j] : grid[i][j - 1];
}
}
return grid[row - 1][col - 1];
}
public int uniquePaths(int m, int n) {
int[][] grid = new int[m][n];
for (int i = 0; i < n; i++) {
grid[0][i] = 1;
}
for (int i = 1; i < m; i++) {
grid[i][0] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
grid[i][j] = grid[i - 1][j] + grid[i][j - 1];
}
}
return grid[m - 1][n - 1];
}
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
obstacleGrid[0][0] = obstacleGrid[0][0] == 1? 0 : 1;
for (int i = 1; i < n; i++) {
obstacleGrid[0][i] = obstacleGrid[0][i] == 1? 0 : obstacleGrid[0][i - 1];
}
for (int i = 1; i < m; i++) {
obstacleGrid[i][0] = obstacleGrid[i][0] == 1? 0 : obstacleGrid[i - 1][0];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
obstacleGrid[i][j] = obstacleGrid[i][j] == 1? 0 : obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
}
}
return obstacleGrid[m - 1][n - 1];
}
public static void main(String[] args) {
int[][] g = {{1,0}};
Solution s = new Solution();
System.out.println(s.uniquePathsWithObstacles(g));
}
}
class Solution {
public:
int uniquePaths(int m, int n) {
int table[m + 1][n + 1] = {0};
table[0][1] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j < n; j++) {
table[i][j] = table[i - 1][j] + table[i][j - 1];
}
}
return table[m][n];
}
int uniquePaths(int m, int n) {
int table[n + 1] = {0};
table[1] = 1;
for (int i = 0; i < m; i++) {
for (int j = 1; j <= n; j++) {
table[j] = table[j] + table[j - 1];
}
}
return table[n];
}
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> t(m + 1, vector<int>(n + 1, 0));
t[0][1] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (!obstacleGrid[i - 1][j - 1]) {
t[i][j] = t[i - 1][j] + t[i][j - 1];
}
}
}
return t[m][n];
}
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
int t[n + 1] = {0};
t[1] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
t[j] = obstacleGrid[i - 1][j - 1] == 0 ? t[j] + t[j - 1] : 0;
}
}
return t[n];
}
};
| 3,558 | 0.381113 | 0.351602 | 133 | 25.759399 | 22.583563 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.669173 | false | false |
3
|
d7b61dd25dac92d922cf084082f01bb89214cc92
| 4,690,104,304,221 |
a38594d82826583275d20449f7abf686bfb72019
|
/saf-db/saf-db-druid/src/main/java/com/future/saf/db/druid/core/DBDruidBeanPostProcessor.java
|
f6894536d1a69ad674c2656bf67eae656cb6f37a
|
[
"Apache-2.0"
] |
permissive
|
qq529234787/saf
|
https://github.com/qq529234787/saf
|
19e6b8da367ded7f6faa9305530e8ce79e340c20
|
053f4e93f4e6aa08abaf5110e682f6e849cd9d06
|
refs/heads/master
| 2022-11-13T03:02:40.382000 | 2020-02-24T08:04:53 | 2020-02-24T08:04:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.future.saf.db.druid.core;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.util.Assert;
import com.alibaba.druid.pool.DruidDataSource;
import com.future.saf.core.CustomizedConfigurationPropertiesBinder;
public class DBDruidBeanPostProcessor implements BeanPostProcessor, Ordered, EnvironmentAware, BeanFactoryAware {
private static String MYBATIS_CONFIG = "mybatis-config.xml";
private static final Logger logger = LoggerFactory.getLogger(DBDruidBeanPostProcessor.class);
public static final String PREFIX_APP_DATASOURCE = "db";
@Autowired
private CustomizedConfigurationPropertiesBinder binder;
private Environment environment;
private BeanFactory beanFactory;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
String instance = DBDruidRegistrar.instanceMap.get(beanName);
if (bean instanceof DruidDataSource) {
DruidDataSource druidDataSource = (DruidDataSource) bean;
initDataSource(druidDataSource);
if (environment.containsProperty(PREFIX_APP_DATASOURCE + "." + instance + ".data-source" + ".filters")) {
druidDataSource.clearFilters();
}
Bindable<?> target = Bindable.of(DruidDataSource.class).withExistingValue(druidDataSource);
binder.bind(PREFIX_APP_DATASOURCE + "." + instance + ".data-source", target);
} else if (bean instanceof SqlSessionFactoryBean) {
SqlSessionFactoryBean sqlSessionFactoryBean = (SqlSessionFactoryBean) bean;
DataSource dataSource = beanFactory.getBean(instance + DataSource.class.getSimpleName(), DataSource.class);
String typeAliasesPackageKey = PREFIX_APP_DATASOURCE + "." + instance + ".type-aliases-package";
String typeAliasesPackage = environment.getProperty(typeAliasesPackageKey);
Assert.isTrue(StringUtils.isNotEmpty(typeAliasesPackage),
String.format("%s=%s must be not null! ", typeAliasesPackageKey, typeAliasesPackage));
initSqlSessionFactoryBean(dataSource, typeAliasesPackage, sqlSessionFactoryBean);
} else if (bean instanceof DataSourceTransactionManager) {
DataSourceTransactionManager dataSourceTransactionManager = (DataSourceTransactionManager) bean;
DataSource dataSource = beanFactory.getBean(instance + DataSource.class.getSimpleName(), DataSource.class);
dataSourceTransactionManager.setDataSource(dataSource);
dataSourceTransactionManager.afterPropertiesSet();
}
return bean;
}
@Override
public int getOrder() {
return 0;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
private void initSqlSessionFactoryBean(DataSource dataSource, String typeAliasesPackage,
SqlSessionFactoryBean sqlSessionFactoryBean) {
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
if (StringUtils.isNotEmpty(typeAliasesPackage)) {
sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
}
}
private void initDataSource(DruidDataSource datasource) {
/**
* https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8
*/
datasource.setDriverClassName("com.mysql.jdbc.Driver");
datasource.setInitialSize(1);
datasource.setMinIdle(1);
datasource.setMaxActive(5);
datasource.setMaxWait(60000);
datasource.setTimeBetweenEvictionRunsMillis(60000);
datasource.setMinEvictableIdleTimeMillis(300000);
datasource.setTimeBetweenLogStatsMillis(30000);
datasource.setValidationQuery("SELECT 'x'");
datasource.setTestWhileIdle(true);
datasource.setTestOnBorrow(false);
datasource.setTestOnReturn(false);
try {
datasource.setFilters("config,wall");
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
}
}
|
UTF-8
|
Java
| 4,741 |
java
|
DBDruidBeanPostProcessor.java
|
Java
|
[
{
"context": "ource datasource) {\n\t\t/**\n\t\t * https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B",
"end": 4006,
"score": 0.8916240334510803,
"start": 3999,
"tag": "USERNAME",
"value": "alibaba"
}
] | null |
[] |
package com.future.saf.db.druid.core;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.util.Assert;
import com.alibaba.druid.pool.DruidDataSource;
import com.future.saf.core.CustomizedConfigurationPropertiesBinder;
public class DBDruidBeanPostProcessor implements BeanPostProcessor, Ordered, EnvironmentAware, BeanFactoryAware {
private static String MYBATIS_CONFIG = "mybatis-config.xml";
private static final Logger logger = LoggerFactory.getLogger(DBDruidBeanPostProcessor.class);
public static final String PREFIX_APP_DATASOURCE = "db";
@Autowired
private CustomizedConfigurationPropertiesBinder binder;
private Environment environment;
private BeanFactory beanFactory;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
String instance = DBDruidRegistrar.instanceMap.get(beanName);
if (bean instanceof DruidDataSource) {
DruidDataSource druidDataSource = (DruidDataSource) bean;
initDataSource(druidDataSource);
if (environment.containsProperty(PREFIX_APP_DATASOURCE + "." + instance + ".data-source" + ".filters")) {
druidDataSource.clearFilters();
}
Bindable<?> target = Bindable.of(DruidDataSource.class).withExistingValue(druidDataSource);
binder.bind(PREFIX_APP_DATASOURCE + "." + instance + ".data-source", target);
} else if (bean instanceof SqlSessionFactoryBean) {
SqlSessionFactoryBean sqlSessionFactoryBean = (SqlSessionFactoryBean) bean;
DataSource dataSource = beanFactory.getBean(instance + DataSource.class.getSimpleName(), DataSource.class);
String typeAliasesPackageKey = PREFIX_APP_DATASOURCE + "." + instance + ".type-aliases-package";
String typeAliasesPackage = environment.getProperty(typeAliasesPackageKey);
Assert.isTrue(StringUtils.isNotEmpty(typeAliasesPackage),
String.format("%s=%s must be not null! ", typeAliasesPackageKey, typeAliasesPackage));
initSqlSessionFactoryBean(dataSource, typeAliasesPackage, sqlSessionFactoryBean);
} else if (bean instanceof DataSourceTransactionManager) {
DataSourceTransactionManager dataSourceTransactionManager = (DataSourceTransactionManager) bean;
DataSource dataSource = beanFactory.getBean(instance + DataSource.class.getSimpleName(), DataSource.class);
dataSourceTransactionManager.setDataSource(dataSource);
dataSourceTransactionManager.afterPropertiesSet();
}
return bean;
}
@Override
public int getOrder() {
return 0;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
private void initSqlSessionFactoryBean(DataSource dataSource, String typeAliasesPackage,
SqlSessionFactoryBean sqlSessionFactoryBean) {
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
if (StringUtils.isNotEmpty(typeAliasesPackage)) {
sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
}
}
private void initDataSource(DruidDataSource datasource) {
/**
* https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8
*/
datasource.setDriverClassName("com.mysql.jdbc.Driver");
datasource.setInitialSize(1);
datasource.setMinIdle(1);
datasource.setMaxActive(5);
datasource.setMaxWait(60000);
datasource.setTimeBetweenEvictionRunsMillis(60000);
datasource.setMinEvictableIdleTimeMillis(300000);
datasource.setTimeBetweenLogStatsMillis(30000);
datasource.setValidationQuery("SELECT 'x'");
datasource.setTestWhileIdle(true);
datasource.setTestOnBorrow(false);
datasource.setTestOnReturn(false);
try {
datasource.setFilters("config,wall");
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
}
}
| 4,741 | 0.803839 | 0.793714 | 126 | 36.626984 | 32.748619 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.857143 | false | false |
3
|
d9d509ce2e79ef35e2cae70545ba4a68b7026668
| 8,074,538,542,734 |
6a48e8244484977a9d8ac77d3e498ad985445be0
|
/src/com/talkative/Parser.java
|
ce57506091f3310c8cc80e00a44bbfd286ffdb40
|
[] |
no_license
|
jleblanc64/talkative
|
https://github.com/jleblanc64/talkative
|
45264fc1c4619e457baab56c2f295eb52e813c5c
|
51a9ec19ce1ff80671b058ce482f60f98154f93f
|
refs/heads/master
| 2016-09-11T15:16:10.694000 | 2016-08-12T11:01:22 | 2016-08-12T11:01:22 | 64,543,007 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.talkative;
import com.talkative.Talkee.Type;
import com.talkative.penn.PennTree;
import com.talkative.penn.PennUtils;
public class Parser {
public static Talkee parse(String sentence) throws ActionObjectException,
ConditionException {
Talkee talkee = new Talkee();
// 1) trim sentence
sentence = sentence.trim();
// 2) find type
if (sentence.contains("?")) {
talkee.setType(Type.question);
}
PennTree pennTree = PennUtils.toPennTree(sentence);
if (ActionObject.has(pennTree, "JJR")) {
talkee.setType(Type.comp);
}
if (talkee.getType() == null) {
talkee.setType(Type.order);
}
// 3) build corresponding structure
if (talkee.getType() == Type.order) {
ActionObject actionObject = new ActionObject(sentence);
Condition condition = new Condition(actionObject.getForward());
Couple couple = new Couple();
couple.part1 = actionObject;
couple.part2 = condition;
talkee.setOrigStructure(couple);
} else if (talkee.getType() == Type.question) {
ActionObjectQuestion aoq = new ActionObjectQuestion(sentence);
talkee.setOrigStructure(aoq);
} else if (talkee.getType() == Type.comp) {
ActionObject actionObject = new ActionObject(sentence);
ConditionComp cc = new ConditionComp(actionObject.getForward());
Couple couple = new Couple();
couple.part1 = actionObject;
couple.part2 = cc;
talkee.setOrigStructure(couple);
}
return talkee;
}
}
|
UTF-8
|
Java
| 1,507 |
java
|
Parser.java
|
Java
|
[] | null |
[] |
package com.talkative;
import com.talkative.Talkee.Type;
import com.talkative.penn.PennTree;
import com.talkative.penn.PennUtils;
public class Parser {
public static Talkee parse(String sentence) throws ActionObjectException,
ConditionException {
Talkee talkee = new Talkee();
// 1) trim sentence
sentence = sentence.trim();
// 2) find type
if (sentence.contains("?")) {
talkee.setType(Type.question);
}
PennTree pennTree = PennUtils.toPennTree(sentence);
if (ActionObject.has(pennTree, "JJR")) {
talkee.setType(Type.comp);
}
if (talkee.getType() == null) {
talkee.setType(Type.order);
}
// 3) build corresponding structure
if (talkee.getType() == Type.order) {
ActionObject actionObject = new ActionObject(sentence);
Condition condition = new Condition(actionObject.getForward());
Couple couple = new Couple();
couple.part1 = actionObject;
couple.part2 = condition;
talkee.setOrigStructure(couple);
} else if (talkee.getType() == Type.question) {
ActionObjectQuestion aoq = new ActionObjectQuestion(sentence);
talkee.setOrigStructure(aoq);
} else if (talkee.getType() == Type.comp) {
ActionObject actionObject = new ActionObject(sentence);
ConditionComp cc = new ConditionComp(actionObject.getForward());
Couple couple = new Couple();
couple.part1 = actionObject;
couple.part2 = cc;
talkee.setOrigStructure(couple);
}
return talkee;
}
}
| 1,507 | 0.678832 | 0.674187 | 61 | 22.704918 | 21.100342 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.918033 | false | false |
3
|
379d6a91384a1ddda3e8602a986bd4a10e6d7534
| 18,253,611,059,529 |
bfb129b6c6fcb854dfb3f1867d8dc1aa03469c72
|
/Java Exam Problems/CognateWords/CognateWords.java
|
e5212a53cf6ffcf14e984ddf6d9a920c619e664e
|
[] |
no_license
|
gharizanov92/Java
|
https://github.com/gharizanov92/Java
|
f81bc3b33740cd4e57eee926f3ed38d3c966d74a
|
f3b785120db27eff8617604b30c63e7915ce9a8f
|
refs/heads/master
| 2021-01-19T00:21:42.982000 | 2015-11-17T18:27:27 | 2015-11-17T18:27:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import javafx.util.Pair;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by user on 10/17/2015.
*/
public class CognateWords {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
Pattern pattern = Pattern.compile("[a-zA-Z]+");
Matcher matcher = pattern.matcher(input);
ArrayList<String> allWords = new ArrayList<String>();
while (matcher.find()){
String word = matcher.group();
allWords.add(word);
}
HashSet<String> set = new HashSet<>();
int size = allWords.size();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
if (i != j && ((allWords.get(i) + allWords.get(j)).equals(allWords.get(k)))){
if (!set.contains(allWords.get(k))){
System.out.printf("%s|%s=%s\n", allWords.get(i), allWords.get(j), allWords.get(k));
set.add(allWords.get(k));
}
}
}
}
}
if (set.isEmpty()){
System.out.println("No");
}
}
}
|
UTF-8
|
Java
| 1,326 |
java
|
CognateWords.java
|
Java
|
[
{
"context": "import java.util.regex.Pattern;\n\n/**\n * Created by user on 10/17/2015.\n */\npublic class CognateWords {\n ",
"end": 133,
"score": 0.870853841304779,
"start": 129,
"tag": "USERNAME",
"value": "user"
}
] | null |
[] |
import javafx.util.Pair;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by user on 10/17/2015.
*/
public class CognateWords {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
Pattern pattern = Pattern.compile("[a-zA-Z]+");
Matcher matcher = pattern.matcher(input);
ArrayList<String> allWords = new ArrayList<String>();
while (matcher.find()){
String word = matcher.group();
allWords.add(word);
}
HashSet<String> set = new HashSet<>();
int size = allWords.size();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
if (i != j && ((allWords.get(i) + allWords.get(j)).equals(allWords.get(k)))){
if (!set.contains(allWords.get(k))){
System.out.printf("%s|%s=%s\n", allWords.get(i), allWords.get(j), allWords.get(k));
set.add(allWords.get(k));
}
}
}
}
}
if (set.isEmpty()){
System.out.println("No");
}
}
}
| 1,326 | 0.482655 | 0.474359 | 44 | 29.136364 | 24.994173 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590909 | false | false |
3
|
91d86ff521aff38ca97f78db333cd631c03daae6
| 19,533,511,306,999 |
688474b7d0d423cc636c7cc71f8196ab327306be
|
/src/main/java/taskqueue/json/JsonReplyList.java
|
57ec7de52a6115df0c9bc73414f7fbc7eecca57c
|
[] |
no_license
|
kassiny/QueueJava2
|
https://github.com/kassiny/QueueJava2
|
78b0569c576f67a91b419fa1825ac1b2be1e57df
|
a42b731261726e0b4f20ff1ff14389a0ec5235d3
|
refs/heads/master
| 2022-07-25T09:29:43.287000 | 2020-03-25T15:28:49 | 2020-03-25T15:28:49 | 250,008,835 | 0 | 0 | null | false | 2022-07-07T22:13:00 | 2020-03-25T14:58:06 | 2020-03-25T15:29:59 | 2022-07-07T22:12:57 | 2,190 | 0 | 0 | 2 |
Java
| false | false |
package taskqueue.json;
import java.util.ArrayList;
public class JsonReplyList<V> extends ArrayList<V> implements JsonReply {
/**
*
*/
private static final long serialVersionUID = 6954566321352503369L;
public boolean add(V v) {
if(v instanceof String) {
return super.add((V)new JsonReplyString(v.toString()));
}
if(v instanceof Boolean) {
return super.add((V)new JsonReplyBool((Boolean) v));
}
return super.add(v);
}
}
|
UTF-8
|
Java
| 457 |
java
|
JsonReplyList.java
|
Java
|
[] | null |
[] |
package taskqueue.json;
import java.util.ArrayList;
public class JsonReplyList<V> extends ArrayList<V> implements JsonReply {
/**
*
*/
private static final long serialVersionUID = 6954566321352503369L;
public boolean add(V v) {
if(v instanceof String) {
return super.add((V)new JsonReplyString(v.toString()));
}
if(v instanceof Boolean) {
return super.add((V)new JsonReplyBool((Boolean) v));
}
return super.add(v);
}
}
| 457 | 0.689278 | 0.647702 | 24 | 18.041666 | 22.747673 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.416667 | false | false |
3
|
fbe99d30311f8ed590a3a3865bcb53e631d639f4
| 14,113,262,562,198 |
e3f93901d621a790871587c0a9f089d496af5662
|
/V10-PRIMEFACES-GRAFICOS-MYSQL/PrimeFaces-Graficos-Mysql/src/java/dao/ProductoDAO.java
|
dded2ac6c44cf9987810ee40bc38149bfeceb954
|
[] |
no_license
|
github6742/0206-mitocode-primefaces
|
https://github.com/github6742/0206-mitocode-primefaces
|
8134644608cde059a6859195b346e34b861339b3
|
a61db66b3ef701ba995912b197a1308fbbb34af0
|
refs/heads/master
| 2023-05-12T18:20:26.824000 | 2021-05-26T04:39:07 | 2021-05-26T04:39:07 | 371,055,308 | 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 dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.Producto;
public class ProductoDAO {
public List<Producto> listar() throws SQLException {
List<Producto> lista = null;
ResultSet rs;
Connection cn = null;
System.out.println("00-ProductoDAO-listar()");
try {
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mitocode?user=root&password=admin");
PreparedStatement st = cn.prepareStatement("SELECT codigo, nombre, precio FROM Producto");
rs = st.executeQuery();
lista = new ArrayList();
while(rs.next()){
Producto prod = new Producto();
prod.setCodigo(rs.getInt("codigo"));
prod.setNombre(rs.getString("nombre"));
prod.setPrecio(rs.getDouble("precio"));
System.out.println("03-ProductoDAO-listar()");
lista.add(prod);
System.out.println("04-ProductoDAO-listar()");
}
} catch (Exception e) {
System.out.println("05-ProductoDAO-listar()");
// throw e;
} finally {
if (cn != null){
cn.close();
}
}
return lista;
}
}
|
UTF-8
|
Java
| 1,696 |
java
|
ProductoDAO.java
|
Java
|
[
{
"context": "ysql://localhost:3306/mitocode?user=root&password=admin\");\n \n PreparedStatement ",
"end": 835,
"score": 0.9987126588821411,
"start": 830,
"tag": "PASSWORD",
"value": "admin"
}
] | 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 dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.Producto;
public class ProductoDAO {
public List<Producto> listar() throws SQLException {
List<Producto> lista = null;
ResultSet rs;
Connection cn = null;
System.out.println("00-ProductoDAO-listar()");
try {
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mitocode?user=root&password=<PASSWORD>");
PreparedStatement st = cn.prepareStatement("SELECT codigo, nombre, precio FROM Producto");
rs = st.executeQuery();
lista = new ArrayList();
while(rs.next()){
Producto prod = new Producto();
prod.setCodigo(rs.getInt("codigo"));
prod.setNombre(rs.getString("nombre"));
prod.setPrecio(rs.getDouble("precio"));
System.out.println("03-ProductoDAO-listar()");
lista.add(prod);
System.out.println("04-ProductoDAO-listar()");
}
} catch (Exception e) {
System.out.println("05-ProductoDAO-listar()");
// throw e;
} finally {
if (cn != null){
cn.close();
}
}
return lista;
}
}
| 1,701 | 0.583726 | 0.576651 | 54 | 30.425926 | 24.66036 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62963 | false | false |
3
|
cdd71a05529c96fa2034197d59776a81b56843c9
| 26,328,149,557,083 |
815cca661d657bae18be0d2cf353ab6aff59a11a
|
/src/test/java/org/springframework/boot/rhino/web/HamlTemplateStandaloneTests.java
|
a934cb8b761236205216f8344f6609678d1cc17e
|
[] |
no_license
|
scratches/spring-boot-rhino
|
https://github.com/scratches/spring-boot-rhino
|
0063eeeea696e078e2c5de60b69248a6ff977e65
|
117f52210bb576fcc202f241008b4c65d30d35f7
|
refs/heads/main
| 2021-05-21T11:55:49.033000 | 2014-05-09T22:29:26 | 2014-05-09T22:29:26 | 19,590,355 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.springframework.boot.rhino.web;
import static org.junit.Assert.assertTrue;
import java.util.Collections;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.rhino.HamlCompiler;
import org.springframework.boot.rhino.web.HamlTemplateStandaloneTests.Application;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@IntegrationTest({ "spring.main.web_environment=false", "env.foo=Heaven",
"foo=World" })
public class HamlTemplateStandaloneTests {
@Autowired
private HamlCompiler compiler;
@Value("classpath:/templates/foo.html.haml")
private Resource simple;
public String getWorld() {
return "World";
}
@Test
public void directCompilation() throws Exception {
String result = compiler.compile(simple).execute(
Collections.singletonMap("world", "World"));
assertTrue("Wrong content", result.contains("Hello World"));
}
@EnableAutoConfiguration
@Configuration
protected static class Application {
}
}
|
UTF-8
|
Java
| 1,524 |
java
|
HamlTemplateStandaloneTests.java
|
Java
|
[] | null |
[] |
package org.springframework.boot.rhino.web;
import static org.junit.Assert.assertTrue;
import java.util.Collections;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.rhino.HamlCompiler;
import org.springframework.boot.rhino.web.HamlTemplateStandaloneTests.Application;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@IntegrationTest({ "spring.main.web_environment=false", "env.foo=Heaven",
"foo=World" })
public class HamlTemplateStandaloneTests {
@Autowired
private HamlCompiler compiler;
@Value("classpath:/templates/foo.html.haml")
private Resource simple;
public String getWorld() {
return "World";
}
@Test
public void directCompilation() throws Exception {
String result = compiler.compile(simple).execute(
Collections.singletonMap("world", "World"));
assertTrue("Wrong content", result.contains("Hello World"));
}
@EnableAutoConfiguration
@Configuration
protected static class Application {
}
}
| 1,524 | 0.814304 | 0.812336 | 49 | 30.102041 | 25.492092 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
3
|
9c00bc16ffb6c2c8258968f8bbe7a487eb6d3df7
| 6,657,199,359,621 |
63353403f0e67323631b186bf47d2f128485a9dc
|
/springMVC_hibernate_oneToMany_crud/src/main/java/com/app/controller/EmployeeController.java
|
5191df79513d73da65c9ac8df3d38f6f2ac1978c
|
[] |
no_license
|
RutujaDighewar/spring_MVC_oneToMany_crud
|
https://github.com/RutujaDighewar/spring_MVC_oneToMany_crud
|
610462ea8a01783e25014e7fed81c4b8fc44b7cd
|
83ac9a61f15e8bd7968fb54b78c26e5de9bfcd1f
|
refs/heads/master
| 2023-03-15T09:34:45.232000 | 2021-03-18T08:15:37 | 2021-03-18T08:15:37 | 348,992,092 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.app.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.app.dto.AddressDto;
import com.app.dto.EmployeeDto;
import com.app.entity.Address;
import com.app.entity.Employee;
import com.app.repo.EmployeeRepo;
import com.app.transformer.AddressTransformer;
import com.app.transformer.EmployeeTransformer;
import com.app.validator.EmployeeValidator;
@Controller
public class EmployeeController {
@Autowired
EmployeeRepo employeeRepo;
@GetMapping(value = { "/", "edit" })
public String viewHome(Model model, @RequestParam(value = "id", required = false) Integer id) {
List<AddressDto> addressesDto = new ArrayList<AddressDto>();
EmployeeDto employeeDto=null;
if (id != null) {
Employee employee = employeeRepo.getId(id);
employeeDto = EmployeeTransformer.entityToemployeeBean(employee);
for (Address address : employee.getAddresses()) {
AddressDto addressDto = AddressTransformer.entityToaddressBean(address);
addressesDto.add(addressDto);
}
employeeDto.setAddresses(addressesDto);
} else {
employeeDto = new EmployeeDto();
AddressDto local = new AddressDto();
AddressDto permanent = new AddressDto();
addressesDto.add(local);
addressesDto.add(permanent);
employeeDto.setAddresses(addressesDto);
}
model.addAttribute("employeeForm", employeeDto);
return "welcome";
}
@PostMapping("save")
public String save(Model model, @ModelAttribute("employeeForm") @Validated EmployeeDto employeeDto,
BindingResult bindingResult, RedirectAttributes redirectAttribute) {
if (bindingResult.hasErrors()) {
model.addAttribute("employeeForm", employeeDto);
return "welcome";
} else {
List<Address> addresses = new ArrayList<Address>();
Employee employee = EmployeeTransformer.employeeBeanToEntity(employeeDto);
for (AddressDto addressDto : employeeDto.getAddresses()) {
Address address = AddressTransformer.addressBeanToEntity(addressDto);
address.setEmployee(employee);
addresses.add(address);
}
employee.setAddresses(addresses);
Boolean flag = employeeRepo.saveOrUpdate(employee);
if (flag) {
redirectAttribute.addFlashAttribute("success", "Employee saved successfully");
} else {
redirectAttribute.addFlashAttribute("error", "Employee not saved...Try again");
}
return "redirect:/";
}
}
@InitBinder("employeeForm")
public void formBinding(WebDataBinder webDataBinder) {
webDataBinder.setValidator(new EmployeeValidator());
}
@ModelAttribute("employees")
public List<Employee> listofEmp() {
return employeeRepo.getEmployees();
}
@GetMapping(value = "delete")
public String deleteEmployee(@RequestParam("id") Integer id, RedirectAttributes redirectAttribute) {
Boolean flag = employeeRepo.deleteEmployee(id);
if (flag) {
redirectAttribute.addFlashAttribute("success", "Employee deleted successfully");
} else {
redirectAttribute.addFlashAttribute("error", "Employee not deleted...Try again");
}
return "redirect:/";
}
}
|
UTF-8
|
Java
| 3,761 |
java
|
EmployeeController.java
|
Java
|
[] | null |
[] |
package com.app.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.app.dto.AddressDto;
import com.app.dto.EmployeeDto;
import com.app.entity.Address;
import com.app.entity.Employee;
import com.app.repo.EmployeeRepo;
import com.app.transformer.AddressTransformer;
import com.app.transformer.EmployeeTransformer;
import com.app.validator.EmployeeValidator;
@Controller
public class EmployeeController {
@Autowired
EmployeeRepo employeeRepo;
@GetMapping(value = { "/", "edit" })
public String viewHome(Model model, @RequestParam(value = "id", required = false) Integer id) {
List<AddressDto> addressesDto = new ArrayList<AddressDto>();
EmployeeDto employeeDto=null;
if (id != null) {
Employee employee = employeeRepo.getId(id);
employeeDto = EmployeeTransformer.entityToemployeeBean(employee);
for (Address address : employee.getAddresses()) {
AddressDto addressDto = AddressTransformer.entityToaddressBean(address);
addressesDto.add(addressDto);
}
employeeDto.setAddresses(addressesDto);
} else {
employeeDto = new EmployeeDto();
AddressDto local = new AddressDto();
AddressDto permanent = new AddressDto();
addressesDto.add(local);
addressesDto.add(permanent);
employeeDto.setAddresses(addressesDto);
}
model.addAttribute("employeeForm", employeeDto);
return "welcome";
}
@PostMapping("save")
public String save(Model model, @ModelAttribute("employeeForm") @Validated EmployeeDto employeeDto,
BindingResult bindingResult, RedirectAttributes redirectAttribute) {
if (bindingResult.hasErrors()) {
model.addAttribute("employeeForm", employeeDto);
return "welcome";
} else {
List<Address> addresses = new ArrayList<Address>();
Employee employee = EmployeeTransformer.employeeBeanToEntity(employeeDto);
for (AddressDto addressDto : employeeDto.getAddresses()) {
Address address = AddressTransformer.addressBeanToEntity(addressDto);
address.setEmployee(employee);
addresses.add(address);
}
employee.setAddresses(addresses);
Boolean flag = employeeRepo.saveOrUpdate(employee);
if (flag) {
redirectAttribute.addFlashAttribute("success", "Employee saved successfully");
} else {
redirectAttribute.addFlashAttribute("error", "Employee not saved...Try again");
}
return "redirect:/";
}
}
@InitBinder("employeeForm")
public void formBinding(WebDataBinder webDataBinder) {
webDataBinder.setValidator(new EmployeeValidator());
}
@ModelAttribute("employees")
public List<Employee> listofEmp() {
return employeeRepo.getEmployees();
}
@GetMapping(value = "delete")
public String deleteEmployee(@RequestParam("id") Integer id, RedirectAttributes redirectAttribute) {
Boolean flag = employeeRepo.deleteEmployee(id);
if (flag) {
redirectAttribute.addFlashAttribute("success", "Employee deleted successfully");
} else {
redirectAttribute.addFlashAttribute("error", "Employee not deleted...Try again");
}
return "redirect:/";
}
}
| 3,761 | 0.772135 | 0.772135 | 115 | 31.713043 | 26.947861 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.017391 | false | false |
3
|
c64f1a8b9fc793523db6d2ee32c3f8b42b2aa62b
| 35,665,408,448,408 |
d75ce8bc3ed471f2b82b5df484a3fb40cb22d181
|
/queue-application-palindrome-checker/PlindromeChecker.java
|
99ef1afe908011fba179185cec5f3ccb61e72654
|
[] |
no_license
|
goldenrati0/academic
|
https://github.com/goldenrati0/academic
|
c0ba2fa2d934404672da7defdcfaf9809764aee3
|
fca261723b506f8c45a7ceabcacac934ef030178
|
refs/heads/master
| 2022-04-16T20:52:57.245000 | 2020-03-28T15:45:11 | 2020-03-28T15:45:11 | 54,793,708 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.util.Scanner;
public class PlindromeChecker{
public static void main(String[] args){
Scanner katniss = new Scanner(System.in);
ArrayQueue aq = new ArrayQueue(1000);
ArrayStack as = new ArrayStack(1000);
String x = katniss.nextLine();
char[] xArray = x.toCharArray();
try{
boolean isPalindrome = true;
for(int i=0; i<xArray.length; i++){
if( (x.codePointAt(i) >=65 && x.codePointAt(i) <=90) || (x.codePointAt(i) >=97 && x.codePointAt(i) <=122)){
if( x.codePointAt(i) >=65 && x.codePointAt(i) <=90 ){
int ascii = x.codePointAt(i) + 32;
xArray[i] = (char) ascii;
as.push(xArray[i]);
aq.enqueue(xArray[i]);
}else if( x.codePointAt(i) >=97 && x.codePointAt(i) <=122 ){
as.push(xArray[i]);
aq.enqueue(xArray[i]);
}
}
}
while(!aq.isEmpty()){
char c1 = (char)aq.dequeue();
char c2 = (char)as.pop();
if( c1 != c2){
isPalindrome = false;
break;
}
}
if(isPalindrome){
System.out.println("This is a Palindrome");
}else if(!isPalindrome){
System.out.println("This is NOT a Palindrome");
}
}catch(Exception e){
System.err.println(e);
// e.printStackTrace();
}
}
}
|
UTF-8
|
Java
| 1,526 |
java
|
PlindromeChecker.java
|
Java
|
[] | null |
[] |
import java.util.Scanner;
public class PlindromeChecker{
public static void main(String[] args){
Scanner katniss = new Scanner(System.in);
ArrayQueue aq = new ArrayQueue(1000);
ArrayStack as = new ArrayStack(1000);
String x = katniss.nextLine();
char[] xArray = x.toCharArray();
try{
boolean isPalindrome = true;
for(int i=0; i<xArray.length; i++){
if( (x.codePointAt(i) >=65 && x.codePointAt(i) <=90) || (x.codePointAt(i) >=97 && x.codePointAt(i) <=122)){
if( x.codePointAt(i) >=65 && x.codePointAt(i) <=90 ){
int ascii = x.codePointAt(i) + 32;
xArray[i] = (char) ascii;
as.push(xArray[i]);
aq.enqueue(xArray[i]);
}else if( x.codePointAt(i) >=97 && x.codePointAt(i) <=122 ){
as.push(xArray[i]);
aq.enqueue(xArray[i]);
}
}
}
while(!aq.isEmpty()){
char c1 = (char)aq.dequeue();
char c2 = (char)as.pop();
if( c1 != c2){
isPalindrome = false;
break;
}
}
if(isPalindrome){
System.out.println("This is a Palindrome");
}else if(!isPalindrome){
System.out.println("This is NOT a Palindrome");
}
}catch(Exception e){
System.err.println(e);
// e.printStackTrace();
}
}
}
| 1,526 | 0.46789 | 0.446265 | 62 | 23.629032 | 20.598492 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.403226 | false | false |
3
|
886e88fa613fbf7e1b654f0eb06e98f70477d00b
| 34,488,587,417,914 |
34c17f35f4f16cec8456d68912d3594d7da9ee40
|
/p_banner_viewpager/src/main/java/com/jingcaiwang/transformer/RotateDownPageTransformer.java
|
b6d918111aea183e3ce757ea1f9fdd2580aa4582
|
[] |
no_license
|
jiangzhengyan/Fast_Dev_Demo_jzy
|
https://github.com/jiangzhengyan/Fast_Dev_Demo_jzy
|
7aa0c205e3c9cec6e90e62b0c2723e2c8764aa14
|
ecd735b038093618cebb41b561c2678346081522
|
refs/heads/master
| 2019-08-06T18:42:39.831000 | 2018-03-15T09:58:28 | 2018-03-15T09:58:28 | 68,788,496 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jingcaiwang.transformer;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.View;
/**
* Created by wang on 2016/10/24.
* 角度旋转
*/
public class RotateDownPageTransformer implements ViewPager.PageTransformer {
private static final float ROT_MAX = 20.0f;
private static final int radiusMultiple = 2;
private int radius;
public RotateDownPageTransformer(ViewPager viewPager) {
radius = viewPager.getLayoutParams().height / radiusMultiple;
int margin = (int) (Math.tan(ROT_MAX / 90f) * radius);
viewPager.setPageMargin(margin);
}
@Override
public void transformPage(View page, float position) {
float mRot = ROT_MAX * position;
float translationY = radius * position * (ROT_MAX / 90f);
translationY = Math.abs(translationY);
page.setPivotX(page.getMeasuredWidth() * 0.5f);
page.setPivotY(radius);
page.setRotation(mRot);
page.setTranslationY(translationY);
// if (position < -1) {
// page.setRotation(0);
// } else if (position <= 1) {
// page.setPivotX(page.getMeasuredWidth() * 0.5f);
// page.setPivotY(page.getMeasuredHeight());
// page.setRotation(mRot);
// } else {
// page.setRotation(0);
// }
}
}
|
UTF-8
|
Java
| 1,365 |
java
|
RotateDownPageTransformer.java
|
Java
|
[
{
"context": "ager;\nimport android.view.View;\n\n/**\n * Created by wang on 2016/10/24.\n * 角度旋转\n */\n\npublic class RotateDo",
"end": 161,
"score": 0.9976497888565063,
"start": 157,
"tag": "USERNAME",
"value": "wang"
}
] | null |
[] |
package com.jingcaiwang.transformer;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.View;
/**
* Created by wang on 2016/10/24.
* 角度旋转
*/
public class RotateDownPageTransformer implements ViewPager.PageTransformer {
private static final float ROT_MAX = 20.0f;
private static final int radiusMultiple = 2;
private int radius;
public RotateDownPageTransformer(ViewPager viewPager) {
radius = viewPager.getLayoutParams().height / radiusMultiple;
int margin = (int) (Math.tan(ROT_MAX / 90f) * radius);
viewPager.setPageMargin(margin);
}
@Override
public void transformPage(View page, float position) {
float mRot = ROT_MAX * position;
float translationY = radius * position * (ROT_MAX / 90f);
translationY = Math.abs(translationY);
page.setPivotX(page.getMeasuredWidth() * 0.5f);
page.setPivotY(radius);
page.setRotation(mRot);
page.setTranslationY(translationY);
// if (position < -1) {
// page.setRotation(0);
// } else if (position <= 1) {
// page.setPivotX(page.getMeasuredWidth() * 0.5f);
// page.setPivotY(page.getMeasuredHeight());
// page.setRotation(mRot);
// } else {
// page.setRotation(0);
// }
}
}
| 1,365 | 0.633751 | 0.615328 | 43 | 30.55814 | 22.456472 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534884 | false | false |
3
|
0522f87ca9e34ad98ac83b30d3f93131f55e5fd5
| 38,156,489,463,985 |
6fc9256e3842cd6c3ec1a29c7147432b3876be46
|
/src/main/java/com/linshuo/graduation/entity/Skill.java
|
1abca990b3cd51833aaf709ef554f0d326a8130f
|
[] |
no_license
|
linshuo1998/graduation
|
https://github.com/linshuo1998/graduation
|
db5515436d823f5e8fe54f3c1a779921f3eef007
|
8725eb26a90e0b4b003a7a9cede92a70e328a64f
|
refs/heads/master
| 2023-01-12T06:10:36.616000 | 2020-11-18T09:22:00 | 2020-11-18T09:22:00 | 309,643,303 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.linshuo.graduation.entity;
public class Skill {
private String skillName;
private String getSkillDate;
public String getSkillName() {
return skillName;
}
public void setSkillName(String skillName) {
this.skillName = skillName;
}
public String getGetSkillDate() {
return getSkillDate;
}
public void setGetSkillDate(String getSkillDate) {
this.getSkillDate = getSkillDate;
}
}
|
UTF-8
|
Java
| 466 |
java
|
Skill.java
|
Java
|
[] | null |
[] |
package com.linshuo.graduation.entity;
public class Skill {
private String skillName;
private String getSkillDate;
public String getSkillName() {
return skillName;
}
public void setSkillName(String skillName) {
this.skillName = skillName;
}
public String getGetSkillDate() {
return getSkillDate;
}
public void setGetSkillDate(String getSkillDate) {
this.getSkillDate = getSkillDate;
}
}
| 466 | 0.665236 | 0.665236 | 24 | 18.416666 | 17.946487 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.291667 | false | false |
3
|
e36dbb3d1ee307e5704430d20a50645c86851f1d
| 33,526,514,759,474 |
a19688ce51d22d8c5799ed5155f0ebd1cc710043
|
/Choudhury_p1/src/Choudhury_p1.java
|
2b511e0b4a594037e13f88dfa7f844ba389e8980
|
[] |
no_license
|
Chapanata/COP3330_ProgramAssignment3
|
https://github.com/Chapanata/COP3330_ProgramAssignment3
|
0bcffefa22eae6583ff1d40d8a0a209b06f812e7
|
66d59a2728743f48caffd270b93f05325ba208b2
|
refs/heads/master
| 2020-08-21T04:07:34.647000 | 2019-10-18T19:50:59 | 2019-10-18T19:50:59 | 216,095,861 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.security.SecureRandom; // Needed for random numbers
import java.util.Scanner;
// Part 1 Completed
// Part 2 Completed
// Part 3 Completed
// Part 4 Completed
// Part 5 In Progress
// Rubric Checkpoints
// Use Secure Int 1
// Use display randomly generated questions and asks for answer 1
// Program stores students response in double precision fp variabl
public class Choudhury_p1 {
public static double randomNumberGenerator (int difficultyLevel, int boundLevel, int problemType) {
SecureRandom randomNumbers = new SecureRandom();
double x = 0.0;
double y = 0.0;
switch (difficultyLevel){
case 1:
boundLevel = 10;
break;
case 2:
boundLevel = 90; // 0-89
break;
case 3:
boundLevel = 900; //0-899
break;
case 4:
boundLevel = 9000; //0-8999
break;
default:
System.out.println("Invalid difficulty level.");
askQuestion();
}
if (boundLevel == 10) {
x = randomNumbers.nextInt(boundLevel - 1) + 1; //Generate number from 1-9
y = randomNumbers.nextInt(boundLevel - 1) + 1; // Generate number from 1-9
}
else if (boundLevel == 90) {
x = randomNumbers.nextInt(boundLevel) + 10; //Generate number from 10-99
y = randomNumbers.nextInt(boundLevel) + 10; // Generate number from 10-99
}
else if (boundLevel == 900) {
x = randomNumbers.nextInt(boundLevel) + 100; //Generate number from 100-999
y = randomNumbers.nextInt(boundLevel) + 100; // Generate number from 100-999
}
else if (boundLevel == 9000) {
x = randomNumbers.nextInt(boundLevel) + 1000; //Generate number from 1000-9999
y = randomNumbers.nextInt(boundLevel) + 1000; // Generate number from 1000-9999
}
if (problemType == 1) {
System.out.println("How much is " + x + " plus " + y + "?");
return x + y;
}
else if (problemType == 2) {
System.out.println("How much is " + x + " times " + y + "?");
return x * y;
}
else if (problemType == 3) {
System.out.println("How much is " + x + " minus " + y + "?");
return x - y;
}
else if (problemType == 4) {
System.out.println("How much is " + x + " divided " + y + "?");
return x / y;
}
else if (problemType == 5) {
int randomType;
randomType = randomNumbers.nextInt(4) + 1;
if (randomType == 1) {
System.out.println("How much is " + x + " plus " + y + "?");
return x + y;
}
else if (randomType == 2) {
System.out.println("How much is " + x + " times " + y + "?");
return x * y;
}
else if (randomType == 3) {
System.out.println("How much is " + x + " minus " + y + "?");
return x - y;
}
else if (randomType == 4) {
System.out.println("How much is " + x + " divided " + y + "?");
return x / y;
}
}
return 0;
}
public static int askQuestion() {
Scanner scnr = new Scanner(System.in);
SecureRandom randomNumbers = new SecureRandom(); // Needed for random numbers
// User enters a difficulty number
int difficultyNumber;
char choiceLetter;
System.out.println("Please enter a difficulty level from 1 -4.");
System.out.println("1 for one-digit numbers. 2 for two-digit numbers. 3 for three-digit numbers. 4 for four-digit numbers.");
difficultyNumber = scnr.nextInt();
System.out.println("");
int boundNumber = 0;
// User enters the type of arithmetic problem to do
int problemType;
System.out.println("Please enter the type of arithmetic problems you would like to do.");
System.out.println("1 for Addition Problems. 2 for Multiplication Problems. 3 for Subtraction Problems. 4 for Division Problems. 5 for a random mixture of all these");
problemType = scnr.nextInt();
System.out.println("");
// Initialize i for incrementing, and a counter for correct responses
int i = 0;
int rightCount;
rightCount = 0;
int badCount = 0;
// Ask 10 Questions
while(i < 10) {
System.out.print(i + 1 + ") ");
double z = randomNumberGenerator(difficultyNumber, boundNumber, problemType);
// Calls a separate method to generate
// Random Numbers for Question
int answer = scnr.nextInt(); // Enter answer
// If correct increment correct count
if (answer == z) {
rightCount++;
}
else {
badCount++;
}
System.out.println("");
i++;
}
System.out.println("You got " + rightCount + " correct and " + badCount + " wrong");
int finalGrade = (rightCount * 100) / 10; // Calculate grade
if (finalGrade >= 75) {
System.out.println("Your final score is: " + finalGrade +"%");
System.out.println("Congratulations, you are ready to go to the next level!");
System.out.println("Enter 'y' to reset the program for the next student");
choiceLetter = scnr.next().charAt(0);
if (choiceLetter == 'y') {
System.out.println("");
askQuestion();
}
System.out.println("Ending program....");
return 0;
}
System.out.println("You scored: " + finalGrade +"%");
System.out.println("Please ask your teacher for extra help.");
System.out.println("Enter 'y' to reset the program for the next student. To exit enter anything else.");
choiceLetter = scnr.next().charAt(0);
if (choiceLetter == 'y') {
System.out.println("");
askQuestion();
}
System.out.println("Ending program....");
return 0;
}
public static void main(String[] args) {
askQuestion();
}
}
|
UTF-8
|
Java
| 6,418 |
java
|
Choudhury_p1.java
|
Java
|
[] | null |
[] |
import java.security.SecureRandom; // Needed for random numbers
import java.util.Scanner;
// Part 1 Completed
// Part 2 Completed
// Part 3 Completed
// Part 4 Completed
// Part 5 In Progress
// Rubric Checkpoints
// Use Secure Int 1
// Use display randomly generated questions and asks for answer 1
// Program stores students response in double precision fp variabl
public class Choudhury_p1 {
public static double randomNumberGenerator (int difficultyLevel, int boundLevel, int problemType) {
SecureRandom randomNumbers = new SecureRandom();
double x = 0.0;
double y = 0.0;
switch (difficultyLevel){
case 1:
boundLevel = 10;
break;
case 2:
boundLevel = 90; // 0-89
break;
case 3:
boundLevel = 900; //0-899
break;
case 4:
boundLevel = 9000; //0-8999
break;
default:
System.out.println("Invalid difficulty level.");
askQuestion();
}
if (boundLevel == 10) {
x = randomNumbers.nextInt(boundLevel - 1) + 1; //Generate number from 1-9
y = randomNumbers.nextInt(boundLevel - 1) + 1; // Generate number from 1-9
}
else if (boundLevel == 90) {
x = randomNumbers.nextInt(boundLevel) + 10; //Generate number from 10-99
y = randomNumbers.nextInt(boundLevel) + 10; // Generate number from 10-99
}
else if (boundLevel == 900) {
x = randomNumbers.nextInt(boundLevel) + 100; //Generate number from 100-999
y = randomNumbers.nextInt(boundLevel) + 100; // Generate number from 100-999
}
else if (boundLevel == 9000) {
x = randomNumbers.nextInt(boundLevel) + 1000; //Generate number from 1000-9999
y = randomNumbers.nextInt(boundLevel) + 1000; // Generate number from 1000-9999
}
if (problemType == 1) {
System.out.println("How much is " + x + " plus " + y + "?");
return x + y;
}
else if (problemType == 2) {
System.out.println("How much is " + x + " times " + y + "?");
return x * y;
}
else if (problemType == 3) {
System.out.println("How much is " + x + " minus " + y + "?");
return x - y;
}
else if (problemType == 4) {
System.out.println("How much is " + x + " divided " + y + "?");
return x / y;
}
else if (problemType == 5) {
int randomType;
randomType = randomNumbers.nextInt(4) + 1;
if (randomType == 1) {
System.out.println("How much is " + x + " plus " + y + "?");
return x + y;
}
else if (randomType == 2) {
System.out.println("How much is " + x + " times " + y + "?");
return x * y;
}
else if (randomType == 3) {
System.out.println("How much is " + x + " minus " + y + "?");
return x - y;
}
else if (randomType == 4) {
System.out.println("How much is " + x + " divided " + y + "?");
return x / y;
}
}
return 0;
}
public static int askQuestion() {
Scanner scnr = new Scanner(System.in);
SecureRandom randomNumbers = new SecureRandom(); // Needed for random numbers
// User enters a difficulty number
int difficultyNumber;
char choiceLetter;
System.out.println("Please enter a difficulty level from 1 -4.");
System.out.println("1 for one-digit numbers. 2 for two-digit numbers. 3 for three-digit numbers. 4 for four-digit numbers.");
difficultyNumber = scnr.nextInt();
System.out.println("");
int boundNumber = 0;
// User enters the type of arithmetic problem to do
int problemType;
System.out.println("Please enter the type of arithmetic problems you would like to do.");
System.out.println("1 for Addition Problems. 2 for Multiplication Problems. 3 for Subtraction Problems. 4 for Division Problems. 5 for a random mixture of all these");
problemType = scnr.nextInt();
System.out.println("");
// Initialize i for incrementing, and a counter for correct responses
int i = 0;
int rightCount;
rightCount = 0;
int badCount = 0;
// Ask 10 Questions
while(i < 10) {
System.out.print(i + 1 + ") ");
double z = randomNumberGenerator(difficultyNumber, boundNumber, problemType);
// Calls a separate method to generate
// Random Numbers for Question
int answer = scnr.nextInt(); // Enter answer
// If correct increment correct count
if (answer == z) {
rightCount++;
}
else {
badCount++;
}
System.out.println("");
i++;
}
System.out.println("You got " + rightCount + " correct and " + badCount + " wrong");
int finalGrade = (rightCount * 100) / 10; // Calculate grade
if (finalGrade >= 75) {
System.out.println("Your final score is: " + finalGrade +"%");
System.out.println("Congratulations, you are ready to go to the next level!");
System.out.println("Enter 'y' to reset the program for the next student");
choiceLetter = scnr.next().charAt(0);
if (choiceLetter == 'y') {
System.out.println("");
askQuestion();
}
System.out.println("Ending program....");
return 0;
}
System.out.println("You scored: " + finalGrade +"%");
System.out.println("Please ask your teacher for extra help.");
System.out.println("Enter 'y' to reset the program for the next student. To exit enter anything else.");
choiceLetter = scnr.next().charAt(0);
if (choiceLetter == 'y') {
System.out.println("");
askQuestion();
}
System.out.println("Ending program....");
return 0;
}
public static void main(String[] args) {
askQuestion();
}
}
| 6,418 | 0.529293 | 0.505142 | 186 | 33.505375 | 30.117912 | 175 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.494624 | false | false |
3
|
532734e07d735eb581d78ebcf656ce5106217daf
| 19,000,935,375,459 |
57fb9e1c3e133b396ccfbc0f25870a4ffe138dac
|
/core/src/org/liberty/multi/bulletproof/util/BackgroundColorGenerator.java
|
083faef44b3af510af6d0406832abf85322eada3
|
[] |
no_license
|
helloworld1/BulletProof
|
https://github.com/helloworld1/BulletProof
|
15046f0275cae9fb3d2e754207417daaf7188ebd
|
29f0951be6c4cfc67bc87b51e5f5038cb69db5ae
|
refs/heads/master
| 2021-01-10T10:39:18.500000 | 2016-02-08T05:23:50 | 2016-02-08T05:23:50 | 51,320,062 | 4 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.liberty.multi.bulletproof.util;
import com.badlogic.gdx.Gdx;
public class BackgroundColorGenerator {
public static void setBgColor(int highLevel) {
if (highLevel % 12 < 2) {
Gdx.gl.glClearColor(0, 0, 0.1f + 0.1f * highLevel / 12, 1);
return;
}
if (highLevel % 12 < 4) {
Gdx.gl.glClearColor(0, 0.1f + 0.1f * highLevel / 12, 0, 1);
return;
}
if (highLevel % 12 < 6) {
Gdx.gl.glClearColor(0.1f + 0.1f * highLevel / 12, 0, 0, 1);
return;
}
if (highLevel % 12 < 8) {
Gdx.gl.glClearColor(0.0f, 0.07f + 0.07f * (highLevel % 12), 0.07f + 0.07f * (highLevel % 12), 1);
return;
}
if (highLevel % 12 < 10) {
Gdx.gl.glClearColor(0.07f + 0.07f * (highLevel % 12), 0, 0.07f + 0.07f * (highLevel % 12), 1);
return;
}
if (highLevel % 12 < 12) {
Gdx.gl.glClearColor(0, 0.07f + 0.07f * (highLevel % 12), 0.07f + 0.07f * (highLevel % 12), 1);
return;
}
}
}
|
UTF-8
|
Java
| 1,102 |
java
|
BackgroundColorGenerator.java
|
Java
|
[] | null |
[] |
package org.liberty.multi.bulletproof.util;
import com.badlogic.gdx.Gdx;
public class BackgroundColorGenerator {
public static void setBgColor(int highLevel) {
if (highLevel % 12 < 2) {
Gdx.gl.glClearColor(0, 0, 0.1f + 0.1f * highLevel / 12, 1);
return;
}
if (highLevel % 12 < 4) {
Gdx.gl.glClearColor(0, 0.1f + 0.1f * highLevel / 12, 0, 1);
return;
}
if (highLevel % 12 < 6) {
Gdx.gl.glClearColor(0.1f + 0.1f * highLevel / 12, 0, 0, 1);
return;
}
if (highLevel % 12 < 8) {
Gdx.gl.glClearColor(0.0f, 0.07f + 0.07f * (highLevel % 12), 0.07f + 0.07f * (highLevel % 12), 1);
return;
}
if (highLevel % 12 < 10) {
Gdx.gl.glClearColor(0.07f + 0.07f * (highLevel % 12), 0, 0.07f + 0.07f * (highLevel % 12), 1);
return;
}
if (highLevel % 12 < 12) {
Gdx.gl.glClearColor(0, 0.07f + 0.07f * (highLevel % 12), 0.07f + 0.07f * (highLevel % 12), 1);
return;
}
}
}
| 1,102 | 0.489111 | 0.396552 | 34 | 31.411764 | 30.64418 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.941176 | false | false |
3
|
ce697fa9e51404623cb987c1932bba8ad9ae4590
| 22,711,787,116,923 |
be29e3d42ed952b7d7bcdfdde78477f5b10c19c8
|
/Game.java
|
9890539a391e446af29e80d943179f867ba80cb9
|
[] |
no_license
|
saajidmoyen/Tetris
|
https://github.com/saajidmoyen/Tetris
|
d63e403a40566917481bc7cb90b102694a66a1af
|
0af4ac2bba9268a22a503457b5a4ba2d53bd63a0
|
refs/heads/master
| 2020-12-24T14:01:50.975000 | 2012-11-22T17:45:01 | 2012-11-22T17:45:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tetris;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.*;
public class Game implements Runnable {
// Arrays are used to allow other classes to edit values
// gameStats contains the score, level, and lines
private int[] gameStats = new int[3];
private Tetromino[] nextPiece = new Tetromino[1];
public void run() {
// Top-level frame
final JFrame frame = new JFrame("Tetris");
frame.setLocation(300, 300);
// A list for formatting
JPanel list = new JPanel();
list.setLayout(new BoxLayout(list, BoxLayout.Y_AXIS));
JLabel score = new JLabel();
score.setText("Score: " + Integer.toString(gameStats[0]));
JLabel level = new JLabel();
level.setText("Level: " + Integer.toString(gameStats[1]));
JLabel lines = new JLabel();
lines.setText("Lines: " + Integer.toString(gameStats[2]));
// Main playing area
final TetrisGrid game = new TetrisGrid(gameStats, score, level, lines,
nextPiece);
// Start button
final JButton start = new JButton("Start/Restart");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
game.start();
}
});
// The instructions are drawn from a .txt file in the package
final JButton instructions = new JButton("Instructions");
instructions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFrame help = new JFrame("Instructions");
help.setLocation(700,100);
InputStream in = getClass().getResourceAsStream("instructions.txt");
JTextArea text = new JTextArea();
try {
text.read(new InputStreamReader(in), null);
} catch (IOException ex) {
ex.printStackTrace();
}
help.add(text);
help.pack();
help.setVisible(true);
}
});
// RigidAreas are used to space out the parts of the game
list.add(start);
list.add(Box.createRigidArea(new Dimension(10, 10)));
list.add(instructions);
list.add(Box.createRigidArea(new Dimension(10, 10)));
list.add(score);
list.add(Box.createRigidArea(new Dimension(10, 10)));
list.add(level);
list.add(Box.createRigidArea(new Dimension(10, 10)));
list.add(lines);
frame.add(game, BorderLayout.CENTER);
frame.add(list, BorderLayout.EAST);
// Put the frame on the screen
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
// Starts the game
public static void main(String[] args) {
SwingUtilities.invokeLater(new Game());
}
}
|
UTF-8
|
Java
| 2,633 |
java
|
Game.java
|
Java
|
[] | null |
[] |
package tetris;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.*;
public class Game implements Runnable {
// Arrays are used to allow other classes to edit values
// gameStats contains the score, level, and lines
private int[] gameStats = new int[3];
private Tetromino[] nextPiece = new Tetromino[1];
public void run() {
// Top-level frame
final JFrame frame = new JFrame("Tetris");
frame.setLocation(300, 300);
// A list for formatting
JPanel list = new JPanel();
list.setLayout(new BoxLayout(list, BoxLayout.Y_AXIS));
JLabel score = new JLabel();
score.setText("Score: " + Integer.toString(gameStats[0]));
JLabel level = new JLabel();
level.setText("Level: " + Integer.toString(gameStats[1]));
JLabel lines = new JLabel();
lines.setText("Lines: " + Integer.toString(gameStats[2]));
// Main playing area
final TetrisGrid game = new TetrisGrid(gameStats, score, level, lines,
nextPiece);
// Start button
final JButton start = new JButton("Start/Restart");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
game.start();
}
});
// The instructions are drawn from a .txt file in the package
final JButton instructions = new JButton("Instructions");
instructions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JFrame help = new JFrame("Instructions");
help.setLocation(700,100);
InputStream in = getClass().getResourceAsStream("instructions.txt");
JTextArea text = new JTextArea();
try {
text.read(new InputStreamReader(in), null);
} catch (IOException ex) {
ex.printStackTrace();
}
help.add(text);
help.pack();
help.setVisible(true);
}
});
// RigidAreas are used to space out the parts of the game
list.add(start);
list.add(Box.createRigidArea(new Dimension(10, 10)));
list.add(instructions);
list.add(Box.createRigidArea(new Dimension(10, 10)));
list.add(score);
list.add(Box.createRigidArea(new Dimension(10, 10)));
list.add(level);
list.add(Box.createRigidArea(new Dimension(10, 10)));
list.add(lines);
frame.add(game, BorderLayout.CENTER);
frame.add(list, BorderLayout.EAST);
// Put the frame on the screen
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
// Starts the game
public static void main(String[] args) {
SwingUtilities.invokeLater(new Game());
}
}
| 2,633 | 0.683631 | 0.671098 | 94 | 27.010639 | 21.171284 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.553191 | false | false |
3
|
3f8fbf9836dfc5570358f7ccb2b3577896e467ce
| 30,356,828,896,513 |
09628ca7c25625fb4776e243590298d387f6912f
|
/Project_Messanger_Client/src/kr/or/kosta/chat/addition/ImageButton.java
|
776c39a02793c7c8c84122ed60fa68d301776d56
|
[] |
no_license
|
ssolssolham/ssolssolham
|
https://github.com/ssolssolham/ssolssolham
|
89b23b0c577fcc67cd3d8a3eb6a8f686c0ae818b
|
3d591ca07480ac34fbdd3c1a3d6dec40feef617d
|
refs/heads/master
| 2021-06-12T16:22:32.387000 | 2020-01-14T15:13:52 | 2020-01-14T15:13:52 | 148,002,925 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package kr.or.kosta.chat.addition;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import kr.or.kosta.chat.client.ChatUI;
public class ImageButton extends JButton {
public ImageButton(int width,int height, String imageIcon, Color backgroundColor,ChatUI component){
setIcon(new ImageIcon(imageIcon));
setBackground(backgroundColor);
setBorderPainted(false);
setFocusPainted(false);
setContentAreaFilled(false);
}
}
|
UTF-8
|
Java
| 471 |
java
|
ImageButton.java
|
Java
|
[] | null |
[] |
package kr.or.kosta.chat.addition;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import kr.or.kosta.chat.client.ChatUI;
public class ImageButton extends JButton {
public ImageButton(int width,int height, String imageIcon, Color backgroundColor,ChatUI component){
setIcon(new ImageIcon(imageIcon));
setBackground(backgroundColor);
setBorderPainted(false);
setFocusPainted(false);
setContentAreaFilled(false);
}
}
| 471 | 0.779193 | 0.779193 | 21 | 21.428572 | 23.327015 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.428571 | false | false |
3
|
a7cfd3b4edac6190de059285a7bbbf1fb42150b1
| 5,050,881,594,826 |
1d2fda2245888413e3eef8798a61236822f022db
|
/com/wurmonline/server/items/ItemDbPruner.java
|
4d3e090171000357da50ab27f352a66414dc8179
|
[
"IJG"
] |
permissive
|
SynieztroLedPar/Wu
|
https://github.com/SynieztroLedPar/Wu
|
3b4391e916f6a5605d60663f800702f3e45d5dfc
|
5f7daebc2fb430411ddb76a179005eeecde9802b
|
refs/heads/master
| 2023-04-29T17:27:08.301000 | 2020-10-10T22:28:40 | 2020-10-10T22:28:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wurmonline.server.items;
public final class ItemDbPruner {}
/* Location: C:\Games\SteamLibrary\steamapps\common\Wurm Unlimited Dedicated Server\server.jar!\com\wurmonline\server\items\ItemDbPruner.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
|
UTF-8
|
Java
| 301 |
java
|
ItemDbPruner.java
|
Java
|
[] | null |
[] |
package com.wurmonline.server.items;
public final class ItemDbPruner {}
/* Location: C:\Games\SteamLibrary\steamapps\common\Wurm Unlimited Dedicated Server\server.jar!\com\wurmonline\server\items\ItemDbPruner.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
| 301 | 0.72093 | 0.697674 | 9 | 32.555557 | 46.024418 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.111111 | false | false |
3
|
f0dfc522bb95a68124d7e2334af33a348f54fc88
| 24,086,176,652,713 |
14a5d365e6c2cc3536d57cd86ed80d0f23e16ae1
|
/aula02/temadecasaaula02/src/Guerreiro.java
|
2fbe5f542690d137912aa7f372c386a1e879349e
|
[] |
no_license
|
TheisenLucas/reset-01
|
https://github.com/TheisenLucas/reset-01
|
f6044401ff395147eff23f88601cfda7c8ea29f0
|
802e34866bfa4f1d2da7b30f2d31bd424b1e018f
|
refs/heads/master
| 2021-02-27T20:37:55.439000 | 2020-04-05T17:28:05 | 2020-04-05T17:28:05 | 245,634,373 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Guerreiro extends HomemDeArmas{
public Guerreiro(final String nome, final double vida, final double ataque, final double defesa) {
super(nome, vida, ataque, defesa);
}
}
|
UTF-8
|
Java
| 200 |
java
|
Guerreiro.java
|
Java
|
[] | null |
[] |
public class Guerreiro extends HomemDeArmas{
public Guerreiro(final String nome, final double vida, final double ataque, final double defesa) {
super(nome, vida, ataque, defesa);
}
}
| 200 | 0.715 | 0.715 | 6 | 32.333332 | 36.187782 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false |
3
|
15d7484710f1d8d39949bc842f977b081c07d26a
| 10,591,389,389,924 |
51fd83e68c529b3f9b0582b57c8a5d9420b5e92a
|
/src/test/java/com/wcaaotr/community/CaffeineTests.java
|
1b06a85677c711956c1467ba3aa4d5fb79727ee6
|
[] |
no_license
|
Connor-Wang/communitydemo
|
https://github.com/Connor-Wang/communitydemo
|
6ae87e4d07029f68ac43f941bf29847a4c5496a1
|
4e9c27b7fcb6ad9948a364b8164a43ead4e5ed33
|
refs/heads/master
| 2023-06-29T01:04:38.703000 | 2021-07-31T06:24:08 | 2021-07-31T06:24:08 | 391,264,859 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.wcaaotr.community;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wcaaotr.community.entity.DiscussPost;
import com.wcaaotr.community.service.DiscussPostService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.List;
/**
* @author Connor
* @create 2021-07-14-19:03
*/
@SpringBootTest
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = CommunitydemoApplication.class)
public class CaffeineTests {
@Autowired
private DiscussPostService discussPostService;
@Test
public void initDataForTest() {
for (int i = 0; i < 300000; i++) {
DiscussPost post = new DiscussPost();
post.setUserId(111);
post.setTitle("本地缓存测试数据 -- 标题");
post.setContent("本地缓存测试数据.本地缓存测试数据.本地缓存测试数据.本地缓存测试数据.本地缓存测试数据.");
post.setType(0);
post.setStatus(0);
post.setCreateTime(new Date());
post.setCommentCount(0);
post.setScore(Math.random() * 2000);
discussPostService.addDiscussPost(post);
}
}
@Test
public void testCache() {
PageHelper.startPage(1, 10);
List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(1, 1);
PageInfo<DiscussPost> pageInfo = new PageInfo<DiscussPost>(discussPosts);
PageHelper.startPage(1, 10);
List<DiscussPost> discussPosts2 = discussPostService.findDiscussPosts(1, 1);
PageInfo<DiscussPost> pageInfo2 = new PageInfo<DiscussPost>(discussPosts);
PageHelper.startPage(1, 10);
List<DiscussPost> discussPosts3 = discussPostService.findDiscussPosts(1, 1);
PageInfo<DiscussPost> pageInfo3 = new PageInfo<DiscussPost>(discussPosts);
PageHelper.startPage(1, 10);
List<DiscussPost> discussPosts4 = discussPostService.findDiscussPosts(1, 2);
PageInfo<DiscussPost> pageInfo4 = new PageInfo<DiscussPost>(discussPosts);
}
}
|
UTF-8
|
Java
| 2,354 |
java
|
CaffeineTests.java
|
Java
|
[
{
"context": ".util.Date;\nimport java.util.List;\n\n/**\n * @author Connor\n * @create 2021-07-14-19:03\n */\n@SpringBootTest\n@",
"end": 590,
"score": 0.9768010377883911,
"start": 584,
"tag": "NAME",
"value": "Connor"
}
] | null |
[] |
package com.wcaaotr.community;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wcaaotr.community.entity.DiscussPost;
import com.wcaaotr.community.service.DiscussPostService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.List;
/**
* @author Connor
* @create 2021-07-14-19:03
*/
@SpringBootTest
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = CommunitydemoApplication.class)
public class CaffeineTests {
@Autowired
private DiscussPostService discussPostService;
@Test
public void initDataForTest() {
for (int i = 0; i < 300000; i++) {
DiscussPost post = new DiscussPost();
post.setUserId(111);
post.setTitle("本地缓存测试数据 -- 标题");
post.setContent("本地缓存测试数据.本地缓存测试数据.本地缓存测试数据.本地缓存测试数据.本地缓存测试数据.");
post.setType(0);
post.setStatus(0);
post.setCreateTime(new Date());
post.setCommentCount(0);
post.setScore(Math.random() * 2000);
discussPostService.addDiscussPost(post);
}
}
@Test
public void testCache() {
PageHelper.startPage(1, 10);
List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(1, 1);
PageInfo<DiscussPost> pageInfo = new PageInfo<DiscussPost>(discussPosts);
PageHelper.startPage(1, 10);
List<DiscussPost> discussPosts2 = discussPostService.findDiscussPosts(1, 1);
PageInfo<DiscussPost> pageInfo2 = new PageInfo<DiscussPost>(discussPosts);
PageHelper.startPage(1, 10);
List<DiscussPost> discussPosts3 = discussPostService.findDiscussPosts(1, 1);
PageInfo<DiscussPost> pageInfo3 = new PageInfo<DiscussPost>(discussPosts);
PageHelper.startPage(1, 10);
List<DiscussPost> discussPosts4 = discussPostService.findDiscussPosts(1, 2);
PageInfo<DiscussPost> pageInfo4 = new PageInfo<DiscussPost>(discussPosts);
}
}
| 2,354 | 0.707187 | 0.682343 | 64 | 34.21875 | 26.927258 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.71875 | false | false |
3
|
87c4b1981653b0c6982e5d33bb6fc53c6c2b8b95
| 3,401,614,105,224 |
6296b8500a91598d6308e6b54a8b7d4a642726a3
|
/src/org/apache/hadoop/examples/CreateDir.java
|
7e1509fdf525aafb19df144d2392ec283f58d544
|
[] |
no_license
|
dipwater/HadoopProject
|
https://github.com/dipwater/HadoopProject
|
467ac4a7d984446391f9f90dc51dbbab6ec1564c
|
245fb9516bc44e9d6851133d60078fa772d4555f
|
refs/heads/master
| 2021-01-19T10:57:34.806000 | 2014-07-31T00:59:42 | 2014-07-31T00:59:42 | 19,400,642 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.apache.hadoop.examples;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class CreateDir {
public static void main(String[] args) throws Exception{
Configuration conf = new Configuration();
//conf.set("mapred.job.tracker", "192.168.1.51:9001");
//conf.set("fs.default.name", "hdfs://192.168.1.51:9000");
FileSystem hdfs = FileSystem.get(conf);
Path dfs = new Path("/TestDir");
boolean result = hdfs.mkdirs(dfs);
System.out.println(result);
}
}
|
UTF-8
|
Java
| 563 |
java
|
CreateDir.java
|
Java
|
[
{
"context": "figuration();\n\t\t//conf.set(\"mapred.job.tracker\", \"192.168.1.51:9001\");\n\t //conf.set(\"fs.default.name\", \"hdfs:",
"end": 332,
"score": 0.9996338486671448,
"start": 320,
"tag": "IP_ADDRESS",
"value": "192.168.1.51"
},
{
"context": "001\");\n\t //conf.set(\"fs.default.name\", \"hdfs://192.168.1.51:9000\");\n\t \n\t\tFileSystem hdfs = FileSystem.get(",
"end": 396,
"score": 0.9996163845062256,
"start": 384,
"tag": "IP_ADDRESS",
"value": "192.168.1.51"
}
] | null |
[] |
package org.apache.hadoop.examples;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class CreateDir {
public static void main(String[] args) throws Exception{
Configuration conf = new Configuration();
//conf.set("mapred.job.tracker", "192.168.1.51:9001");
//conf.set("fs.default.name", "hdfs://192.168.1.51:9000");
FileSystem hdfs = FileSystem.get(conf);
Path dfs = new Path("/TestDir");
boolean result = hdfs.mkdirs(dfs);
System.out.println(result);
}
}
| 563 | 0.708703 | 0.662522 | 19 | 28.631578 | 20.497009 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.631579 | false | false |
3
|
de623efea3d72d95a7df2e52889a350b1d41d453
| 292,057,805,192 |
da1d7fa18ab8d1b528b805546df3ab1adbc3e220
|
/src/lab4_richardson_wilfredo/Dragones.java
|
48e8d987fa18bb1ec0fcc30e59e5b7d5598f06d9
|
[] |
no_license
|
RALC365/Lab4_Wilfredo_Richardson
|
https://github.com/RALC365/Lab4_Wilfredo_Richardson
|
af2e97fe965090828faa7b69d46998d822021b80
|
d0cc42590e30d2c05cf0f5df147cf7d8dea206d5
|
refs/heads/master
| 2021-08-06T06:47:18.113000 | 2017-11-03T23:57:15 | 2017-11-03T23:57:15 | 109,403,263 | 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 lab4_richardson_wilfredo;
import java.util.ArrayList;
/**
*
* @author RALC
*/
public class Dragones extends Guerreros{
private String Color;
private String Raza;
public Dragones() {
super();
}
public Dragones(String Color, String Raza) {
super();
this.Color = Color;
this.Raza = Raza;
}
public Dragones(String Color, String Raza, String Nombre, int Edad, String LugarNacimiento, int PoderAtaque, int Salud, int Costo) {
super(Nombre, Edad, LugarNacimiento, PoderAtaque, Salud, Costo);
this.Color = Color;
this.Raza = Raza;
}
public String getColor() {
return Color;
}
public void setColor(String Color) {
this.Color = Color;
}
public String getRaza() {
return Raza;
}
public void setRaza(String Raza) {
this.Raza = Raza;
}
@Override
public String toString() {
return "Dragones{" + "Color=" + Color + ", Raza=" + Raza + '}';
}
@Override
public ArrayList<Jugadores> Atacar(int jud, ArrayList<Jugadores> Jugadores) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
double salud = Jugadores.get(jud).getGuerrero().getSalud();
int ataq2 = Jugadores.get(jud).getGuerrero().getPoderAtaque();
ataq2 = ataq2 - (int)(ataq2 *0.25);
Jugadores.get(jud).getGuerrero().setPoderAtaque(ataq2);
int jud2;
if (jud ==0) {
jud2 = 1;
}else{
jud2 = 0;
}
double ataq1 = Jugadores.get(jud2).getGuerrero().getPoderAtaque();
salud = salud - ataq1;
if (salud <= 0) {
Jugadores.get(jud).getGuerrero().setSalud(0);
System.out.println("\u001b[31m La salud del contrario: "+ 0 +"\u001b[0m" );
}else{
Jugadores.get(jud).getGuerrero().setSalud(((int)salud));
System.out.println("\u001b[31m La salud del contrario: "+ salud +"\u001b[0m" );
}
//Jugadores.get(jud).getGuerrero().setSalud(((int)salud));
//System.out.println("\u001b[31m La salud del contrario: "+ salud +"\u001b[0m" );
System.out.println("\u001b[31m El poder de ataque del contrincante es: "+ ataq2 +"\u001b[0m" );
return Jugadores;
}
}
|
UTF-8
|
Java
| 2,670 |
java
|
Dragones.java
|
Java
|
[
{
"context": "import java.util.ArrayList;\r\n\r\n/**\r\n *\r\n * @author RALC\r\n */\r\npublic class Dragones extends Guerreros{\r\n ",
"end": 282,
"score": 0.9987953305244446,
"start": 278,
"tag": "USERNAME",
"value": "RALC"
}
] | 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 lab4_richardson_wilfredo;
import java.util.ArrayList;
/**
*
* @author RALC
*/
public class Dragones extends Guerreros{
private String Color;
private String Raza;
public Dragones() {
super();
}
public Dragones(String Color, String Raza) {
super();
this.Color = Color;
this.Raza = Raza;
}
public Dragones(String Color, String Raza, String Nombre, int Edad, String LugarNacimiento, int PoderAtaque, int Salud, int Costo) {
super(Nombre, Edad, LugarNacimiento, PoderAtaque, Salud, Costo);
this.Color = Color;
this.Raza = Raza;
}
public String getColor() {
return Color;
}
public void setColor(String Color) {
this.Color = Color;
}
public String getRaza() {
return Raza;
}
public void setRaza(String Raza) {
this.Raza = Raza;
}
@Override
public String toString() {
return "Dragones{" + "Color=" + Color + ", Raza=" + Raza + '}';
}
@Override
public ArrayList<Jugadores> Atacar(int jud, ArrayList<Jugadores> Jugadores) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
double salud = Jugadores.get(jud).getGuerrero().getSalud();
int ataq2 = Jugadores.get(jud).getGuerrero().getPoderAtaque();
ataq2 = ataq2 - (int)(ataq2 *0.25);
Jugadores.get(jud).getGuerrero().setPoderAtaque(ataq2);
int jud2;
if (jud ==0) {
jud2 = 1;
}else{
jud2 = 0;
}
double ataq1 = Jugadores.get(jud2).getGuerrero().getPoderAtaque();
salud = salud - ataq1;
if (salud <= 0) {
Jugadores.get(jud).getGuerrero().setSalud(0);
System.out.println("\u001b[31m La salud del contrario: "+ 0 +"\u001b[0m" );
}else{
Jugadores.get(jud).getGuerrero().setSalud(((int)salud));
System.out.println("\u001b[31m La salud del contrario: "+ salud +"\u001b[0m" );
}
//Jugadores.get(jud).getGuerrero().setSalud(((int)salud));
//System.out.println("\u001b[31m La salud del contrario: "+ salud +"\u001b[0m" );
System.out.println("\u001b[31m El poder de ataque del contrincante es: "+ ataq2 +"\u001b[0m" );
return Jugadores;
}
}
| 2,670 | 0.576405 | 0.554682 | 86 | 29.046511 | 31.239847 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.627907 | false | false |
3
|
417ee5614da6fd0ac7ca2ad139bc68641806d450
| 11,802,570,198,008 |
4ead943bb91dc4c5fda9e41dbac265436659973e
|
/app/src/main/java/org/techtown/testsubway/Like.java
|
c98174ccc14c45d67d3c5f1da64ff7ca91ff240b
|
[] |
no_license
|
choiyeeun1010/subway
|
https://github.com/choiyeeun1010/subway
|
59784e1ee05eefb6e5321310e36da5476209d1a6
|
16b30c0e0c3ae83862461d30b6550dde5442a454
|
refs/heads/main
| 2023-01-21T07:38:10.804000 | 2022-01-27T14:23:33 | 2022-01-27T14:23:33 | 318,272,400 | 0 | 0 | null | false | 2020-12-04T13:47:47 | 2020-12-03T17:38:37 | 2020-12-04T07:32:41 | 2020-12-04T13:47:45 | 1,971 | 0 | 0 | 0 |
Java
| false | false |
package org.techtown.testsubway;
import androidx.appcompat.app.AppCompatActivity;
public class Like extends AppCompatActivity {
}
|
UTF-8
|
Java
| 132 |
java
|
Like.java
|
Java
|
[] | null |
[] |
package org.techtown.testsubway;
import androidx.appcompat.app.AppCompatActivity;
public class Like extends AppCompatActivity {
}
| 132 | 0.833333 | 0.833333 | 6 | 21 | 21.244608 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
3
|
7dd9bda6d40a5f9bd4377a02a53bdde21fe5264d
| 12,481,175,029,594 |
b96b430136fd3cbe90f948a981aea2347984c4d3
|
/src/main/java/mx/gob/renapo/registrocivil/actos/adopcion/bean/AdopcionPrincipalBean.java
|
957c1fcff5027d7ad93682d4eee8913cf55c0dbf
|
[] |
no_license
|
jverde48/RegistroCivil
|
https://github.com/jverde48/RegistroCivil
|
f11afdbbe5670a62bce405236cdbde4aac25a65f
|
7c07fd54f4765704d624091e1f9a15f1966dcc82
|
refs/heads/master
| 2020-05-25T11:24:37.446000 | 2014-05-01T20:19:05 | 2014-05-01T20:19:05 | 19,465,214 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package mx.gob.renapo.registrocivil.actos.adopcion.bean;
import lombok.Data;
import mx.gob.renapo.registrocivil.actos.adopcion.dto.AdopcionDTO;
import mx.gob.renapo.registrocivil.actos.adopcion.service.AdopcionService;
import mx.gob.renapo.registrocivil.catalogos.dto.*;
import mx.gob.renapo.registrocivil.catalogos.service.impl.*;
import mx.gob.renapo.registrocivil.comun.dto.PersonaDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import java.util.List;
@Data
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@ViewScoped
@ManagedBean(name = "adopcionPrincipalBean")
public abstract class AdopcionPrincipalBean implements Serializable {
@Autowired
AdopcionDTO adopcionDTO;
@Autowired
AdopcionDTO adopcionHistoricoDTO;
@Autowired
AdopcionDTO adopcionEspecialDTO;
@Autowired
AdopcionDTO detalleAdopcion;
@Autowired
AdopcionService adopcionService;
//En caso de que se registren los abuelos del adoptado
private Boolean existenciaAbueloUnoProgenitor;
private Boolean existenciaAbueloDosProgenitor;
private Boolean existenciaAbueloUnoAdoptante;
private Boolean existenciaAbueloDosAdoptante;
//Services de catalogos a utilizar
@Autowired
private CatPaisServiceImpl paisService;
@Autowired
private CatEstadoServiceImpl estadoService;
@Autowired
private CatInegiPaisServiceImpl inegiPaisService;
@Autowired
private CatInegiEstadoServiceImpl inegiEstadoService;
@Autowired
private CatInegiMunicipioServiceImpl inegiMunicipioService;
@Autowired
private CatMunicipioServiceImpl municipioService;
@Autowired
private CatEstadoCivilServiceImpl estadoCivilService;
@Autowired
private CatColoniaLocalidadServiceImpl localidadService;
@Autowired
private CatTipoLocalidadServiceImpl tipoLocalidadService;
/**
* Listas para carga de paises de cada una de las personas
* involucradas en el acto de adopcion
*/
private List<PaisDTO> paises;
private List<PaisDTO> paisesInegi;
/**
* Listas para carga de estados de cada persona del acto de nacimiento
*/
private List<EstadoDTO> estadosAdoptado;
private List<EstadoDTO> estadosProgenitor;
private List<EstadoDTO> estadosAdoptante;
private List<EstadoDTO> estadosPadreUnoProgenitor;
private List<EstadoDTO> estadosPadreDosProgenitor;
private List<EstadoDTO> estadosPadreUnoAdoptante;
private List<EstadoDTO> estadosPadreDosAdoptante;
private List<EstadoDTO> estadosTestigoUno;
private List<EstadoDTO> estadosTestigoDos;
private List<EstadoDTO> estadosInegiAdoptado;
private List<EstadoDTO> estadosInegiProgenitor;
private List<EstadoDTO> estadosInegiAdoptante;
private List<EstadoDTO> estadosInegiPadreUnoProgenitor;
private List<EstadoDTO> estadosInegiPadreDosProgenitor;
private List<EstadoDTO> estadosInegiPadreUnoAdoptante;
private List<EstadoDTO> estadosInegiPadreDosAdoptante;
private List<EstadoDTO> estadosInegiTestigoUno;
private List<EstadoDTO> estadosInegiTestigoDos;
/**
* Listas para carga de municipios de cada persona
*/
private List<MunicipioDTO> municipiosAdoptado;
private List<MunicipioDTO> municipiosProgenitor;
private List<MunicipioDTO> municipiosAdoptante;
private List<MunicipioDTO> municipiosPadreUnoProgenitor;
private List<MunicipioDTO> municipiosPadreDosProgenitor;
private List<MunicipioDTO> municipiosPadreUnoAdoptante;
private List<MunicipioDTO> municipiosPadreDosAdoptante;
private List<MunicipioDTO> municipiosTestigoUno;
private List<MunicipioDTO> municipiosTestigoDos;
private List<MunicipioDTO> municipiosInegiAdoptado;
private List<MunicipioDTO> municipiosInegiProgenitor;
private List<MunicipioDTO> municipiosInegiAdoptante;
private List<MunicipioDTO> municipiosInegiPadreUnoProgenitor;
private List<MunicipioDTO> municipiosInegiPadreDosProgenitor;
private List<MunicipioDTO> municipiosInegiPadreUnoAdoptante;
private List<MunicipioDTO> municipiosInegiPadreDosAdoptante;
private List<MunicipioDTO> municipiosInegiTestigoUno;
private List<MunicipioDTO> municipiosInegiTestigoDos;
/**
* Listas para carga de localidades de cada persona
*/
private List<LocalidadDTO> localidadesAdoptado;
private List<LocalidadDTO> localidadesProgenitor;
private List<LocalidadDTO> localidadesAdoptante;
private List<LocalidadDTO> localidadesPadreUnoAdoptante;
private List<LocalidadDTO> localidadesPadreDosAdoptante;
private List<LocalidadDTO> localidadesPadreUnoProgenitor;
private List<LocalidadDTO> localidadesPadreDosProgenitor;
private List<LocalidadDTO> localidadesTestigoUno;
private List<LocalidadDTO> localidadesTestigoDos;
/**
* Lista para tipo de localidad para cada persona
*/
private List<CatTipoLocalidadDTO> tipoLocalidadList;
private List<CatEstadoCivilDTO> estadoCivilList;
/**
* Metodo para recupear los estados por pais de una persona
* @param tipoPersona
*/
public void consultaEstados(Integer tipoPersona, Integer tipoRegistro) {
//Obtenemos la persona de la que se trata
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
//Obtenemos el pais de nacimeiento de esa persona
PaisDTO pais = persona.getPaisNacimiento();
switch(tipoPersona) {
case 2:
setEstadosProgenitor(getEstadoService().recuperarPorPais(pais));
break;
case 3:
setEstadosAdoptante(getEstadoService().recuperarPorPais(pais));
break;
case 4:
setEstadosPadreUnoProgenitor(getEstadoService().recuperarPorPais(pais));
break;
case 5:
setEstadosPadreDosProgenitor(getEstadoService().recuperarPorPais(pais));
break;
case 6:
setEstadosPadreUnoAdoptante(getEstadoService().recuperarPorPais(pais));
break;
case 7:
setEstadosPadreDosAdoptante(getEstadoService().recuperarPorPais(pais));
break;
case 8:
setEstadosTestigoUno(getEstadoService().recuperarPorPais(pais));
break;
case 9:
setEstadosTestigoDos(getEstadoService().recuperarPorPais(pais));
break;
}
}
/**
* Metodo que carga los municipios de un estado seleccionado segun la persona
* @param tipoPersona
*/
public void consultaMuncipios(Integer tipoPersona, Integer tipoRegistro) {
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
EstadoDTO estado = persona.getEntidadNacimiento();
switch(tipoPersona) {
case 1:
setMunicipiosAdoptado(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 2:
setMunicipiosProgenitor(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 3:
setMunicipiosAdoptante(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 4:
setMunicipiosPadreUnoProgenitor(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 5:
setMunicipiosPadreDosProgenitor(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 6:
setMunicipiosPadreUnoAdoptante(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 7:
setMunicipiosPadreDosAdoptante(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 8:
setMunicipiosTestigoUno(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 9:
setMunicipiosTestigoDos(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
}
}
/**
* Metodo para recuperar una persona dependiendo su rol
* @param tipoPersona
* @return PersonaDTO
*/
private PersonaDTO obtienePersona(Integer tipoPersona, Integer tipoRegistro) {
AdopcionDTO adopcion = null;
if(tipoRegistro==1) {
adopcion = getAdopcionDTO();
}else if(tipoRegistro==2){
adopcion = getAdopcionHistoricoDTO();
}else if (tipoRegistro==3){
adopcion = getAdopcionEspecialDTO();
}
PersonaDTO persona = null;
switch (tipoPersona) {
case 1: //En caso de ser el adoptado
persona = adopcion.getPersona();
break;
case 2: //En caso de ser el progenitor
persona = adopcion.getProgenitor();
break;
case 3: //En caso de ser el adoptante
persona = adopcion.getAdoptante();
break;
case 4: //En caso de ser el padre uno del progenitor
persona = adopcion.getPadreUnoProgenitor();
break;
case 5: //En caso de ser el padre dos del progenitor
persona = adopcion.getPadreDosProgenitor();
break;
case 6: //En caso de ser el padre uno del adoptante
persona = adopcion.getPadreUnoAdoptante();
break;
case 7: //En caso de ser el padre dos del adoptante
persona = adopcion.getPadreDosAdoptante();
break;
case 8:
persona = adopcion.getTestigoUno();
break;
case 9:
persona = adopcion.getTestigoDos();
break;
}
return persona;
}
public void consultaLocalidadesInegi(Integer tipoPersona, Integer tipoRegistro) {
//Obtenemos a la persona que se refiere
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
MunicipioDTO municipio = persona.getDomicilio().getMunicipio();
switch(tipoPersona) {
case 1:
setLocalidadesAdoptado(getLocalidadService().findAllByMunicipio(municipio));
break;
case 2:
setLocalidadesProgenitor(getLocalidadService().findAllByMunicipio(municipio));
break;
case 3:
setLocalidadesAdoptante(getLocalidadService().findAllByMunicipio(municipio));
break;
case 4:
setLocalidadesPadreUnoProgenitor(getLocalidadService().findAllByMunicipio(municipio));
break;
case 5:
setLocalidadesPadreDosProgenitor(getLocalidadService().findAllByMunicipio(municipio));
break;
case 6:
setLocalidadesPadreUnoAdoptante(getLocalidadService().findAllByMunicipio(municipio));
break;
case 7:
setLocalidadesPadreDosAdoptante(getLocalidadService().findAllByMunicipio(municipio));
break;
case 8:
setLocalidadesTestigoUno(getLocalidadService().findAllByMunicipio(municipio));
break;
case 9:
setLocalidadesTestigoDos(getLocalidadService().findAllByMunicipio(municipio));
break;
}
}
public void consultaEstadosInegi(Integer tipoPersona, Integer tipoRegistro) {
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
PaisDTO pais = persona.getDomicilio().getPais();
switch(tipoPersona) {
case 1:
setEstadosInegiAdoptado(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 2:
setEstadosInegiProgenitor(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 3:
setEstadosInegiAdoptante(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 4:
setEstadosInegiPadreUnoProgenitor(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 5:
setEstadosInegiPadreDosProgenitor(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 6:
setEstadosInegiPadreUnoAdoptante(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 7:
setEstadosInegiPadreDosAdoptante(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 8:
setEstadosInegiTestigoUno(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 9:
setEstadosInegiTestigoDos(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
}
}
public void consultaMunicipiosInegi(Integer tipoPersona, Integer tipoRegistro) {
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
EstadoDTO estado = persona.getDomicilio().getEstado();
switch(tipoPersona) {
case 1:
setMunicipiosInegiAdoptado(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 2:
setMunicipiosInegiProgenitor(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 3:
setMunicipiosInegiAdoptante(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 4:
setMunicipiosInegiPadreUnoProgenitor(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 5:
setMunicipiosInegiPadreDosProgenitor(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 6:
setMunicipiosInegiPadreUnoAdoptante(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 7:
setMunicipiosInegiPadreDosAdoptante(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 8:
setMunicipiosInegiTestigoUno(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 9:
setMunicipiosInegiTestigoDos(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
}
}
}
|
UTF-8
|
Java
| 15,011 |
java
|
AdopcionPrincipalBean.java
|
Java
|
[] | null |
[] |
package mx.gob.renapo.registrocivil.actos.adopcion.bean;
import lombok.Data;
import mx.gob.renapo.registrocivil.actos.adopcion.dto.AdopcionDTO;
import mx.gob.renapo.registrocivil.actos.adopcion.service.AdopcionService;
import mx.gob.renapo.registrocivil.catalogos.dto.*;
import mx.gob.renapo.registrocivil.catalogos.service.impl.*;
import mx.gob.renapo.registrocivil.comun.dto.PersonaDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import java.util.List;
@Data
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@ViewScoped
@ManagedBean(name = "adopcionPrincipalBean")
public abstract class AdopcionPrincipalBean implements Serializable {
@Autowired
AdopcionDTO adopcionDTO;
@Autowired
AdopcionDTO adopcionHistoricoDTO;
@Autowired
AdopcionDTO adopcionEspecialDTO;
@Autowired
AdopcionDTO detalleAdopcion;
@Autowired
AdopcionService adopcionService;
//En caso de que se registren los abuelos del adoptado
private Boolean existenciaAbueloUnoProgenitor;
private Boolean existenciaAbueloDosProgenitor;
private Boolean existenciaAbueloUnoAdoptante;
private Boolean existenciaAbueloDosAdoptante;
//Services de catalogos a utilizar
@Autowired
private CatPaisServiceImpl paisService;
@Autowired
private CatEstadoServiceImpl estadoService;
@Autowired
private CatInegiPaisServiceImpl inegiPaisService;
@Autowired
private CatInegiEstadoServiceImpl inegiEstadoService;
@Autowired
private CatInegiMunicipioServiceImpl inegiMunicipioService;
@Autowired
private CatMunicipioServiceImpl municipioService;
@Autowired
private CatEstadoCivilServiceImpl estadoCivilService;
@Autowired
private CatColoniaLocalidadServiceImpl localidadService;
@Autowired
private CatTipoLocalidadServiceImpl tipoLocalidadService;
/**
* Listas para carga de paises de cada una de las personas
* involucradas en el acto de adopcion
*/
private List<PaisDTO> paises;
private List<PaisDTO> paisesInegi;
/**
* Listas para carga de estados de cada persona del acto de nacimiento
*/
private List<EstadoDTO> estadosAdoptado;
private List<EstadoDTO> estadosProgenitor;
private List<EstadoDTO> estadosAdoptante;
private List<EstadoDTO> estadosPadreUnoProgenitor;
private List<EstadoDTO> estadosPadreDosProgenitor;
private List<EstadoDTO> estadosPadreUnoAdoptante;
private List<EstadoDTO> estadosPadreDosAdoptante;
private List<EstadoDTO> estadosTestigoUno;
private List<EstadoDTO> estadosTestigoDos;
private List<EstadoDTO> estadosInegiAdoptado;
private List<EstadoDTO> estadosInegiProgenitor;
private List<EstadoDTO> estadosInegiAdoptante;
private List<EstadoDTO> estadosInegiPadreUnoProgenitor;
private List<EstadoDTO> estadosInegiPadreDosProgenitor;
private List<EstadoDTO> estadosInegiPadreUnoAdoptante;
private List<EstadoDTO> estadosInegiPadreDosAdoptante;
private List<EstadoDTO> estadosInegiTestigoUno;
private List<EstadoDTO> estadosInegiTestigoDos;
/**
* Listas para carga de municipios de cada persona
*/
private List<MunicipioDTO> municipiosAdoptado;
private List<MunicipioDTO> municipiosProgenitor;
private List<MunicipioDTO> municipiosAdoptante;
private List<MunicipioDTO> municipiosPadreUnoProgenitor;
private List<MunicipioDTO> municipiosPadreDosProgenitor;
private List<MunicipioDTO> municipiosPadreUnoAdoptante;
private List<MunicipioDTO> municipiosPadreDosAdoptante;
private List<MunicipioDTO> municipiosTestigoUno;
private List<MunicipioDTO> municipiosTestigoDos;
private List<MunicipioDTO> municipiosInegiAdoptado;
private List<MunicipioDTO> municipiosInegiProgenitor;
private List<MunicipioDTO> municipiosInegiAdoptante;
private List<MunicipioDTO> municipiosInegiPadreUnoProgenitor;
private List<MunicipioDTO> municipiosInegiPadreDosProgenitor;
private List<MunicipioDTO> municipiosInegiPadreUnoAdoptante;
private List<MunicipioDTO> municipiosInegiPadreDosAdoptante;
private List<MunicipioDTO> municipiosInegiTestigoUno;
private List<MunicipioDTO> municipiosInegiTestigoDos;
/**
* Listas para carga de localidades de cada persona
*/
private List<LocalidadDTO> localidadesAdoptado;
private List<LocalidadDTO> localidadesProgenitor;
private List<LocalidadDTO> localidadesAdoptante;
private List<LocalidadDTO> localidadesPadreUnoAdoptante;
private List<LocalidadDTO> localidadesPadreDosAdoptante;
private List<LocalidadDTO> localidadesPadreUnoProgenitor;
private List<LocalidadDTO> localidadesPadreDosProgenitor;
private List<LocalidadDTO> localidadesTestigoUno;
private List<LocalidadDTO> localidadesTestigoDos;
/**
* Lista para tipo de localidad para cada persona
*/
private List<CatTipoLocalidadDTO> tipoLocalidadList;
private List<CatEstadoCivilDTO> estadoCivilList;
/**
* Metodo para recupear los estados por pais de una persona
* @param tipoPersona
*/
public void consultaEstados(Integer tipoPersona, Integer tipoRegistro) {
//Obtenemos la persona de la que se trata
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
//Obtenemos el pais de nacimeiento de esa persona
PaisDTO pais = persona.getPaisNacimiento();
switch(tipoPersona) {
case 2:
setEstadosProgenitor(getEstadoService().recuperarPorPais(pais));
break;
case 3:
setEstadosAdoptante(getEstadoService().recuperarPorPais(pais));
break;
case 4:
setEstadosPadreUnoProgenitor(getEstadoService().recuperarPorPais(pais));
break;
case 5:
setEstadosPadreDosProgenitor(getEstadoService().recuperarPorPais(pais));
break;
case 6:
setEstadosPadreUnoAdoptante(getEstadoService().recuperarPorPais(pais));
break;
case 7:
setEstadosPadreDosAdoptante(getEstadoService().recuperarPorPais(pais));
break;
case 8:
setEstadosTestigoUno(getEstadoService().recuperarPorPais(pais));
break;
case 9:
setEstadosTestigoDos(getEstadoService().recuperarPorPais(pais));
break;
}
}
/**
* Metodo que carga los municipios de un estado seleccionado segun la persona
* @param tipoPersona
*/
public void consultaMuncipios(Integer tipoPersona, Integer tipoRegistro) {
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
EstadoDTO estado = persona.getEntidadNacimiento();
switch(tipoPersona) {
case 1:
setMunicipiosAdoptado(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 2:
setMunicipiosProgenitor(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 3:
setMunicipiosAdoptante(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 4:
setMunicipiosPadreUnoProgenitor(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 5:
setMunicipiosPadreDosProgenitor(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 6:
setMunicipiosPadreUnoAdoptante(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 7:
setMunicipiosPadreDosAdoptante(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 8:
setMunicipiosTestigoUno(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
case 9:
setMunicipiosTestigoDos(getMunicipioService().recuperarMunicipiosPorEstado(estado));
break;
}
}
/**
* Metodo para recuperar una persona dependiendo su rol
* @param tipoPersona
* @return PersonaDTO
*/
private PersonaDTO obtienePersona(Integer tipoPersona, Integer tipoRegistro) {
AdopcionDTO adopcion = null;
if(tipoRegistro==1) {
adopcion = getAdopcionDTO();
}else if(tipoRegistro==2){
adopcion = getAdopcionHistoricoDTO();
}else if (tipoRegistro==3){
adopcion = getAdopcionEspecialDTO();
}
PersonaDTO persona = null;
switch (tipoPersona) {
case 1: //En caso de ser el adoptado
persona = adopcion.getPersona();
break;
case 2: //En caso de ser el progenitor
persona = adopcion.getProgenitor();
break;
case 3: //En caso de ser el adoptante
persona = adopcion.getAdoptante();
break;
case 4: //En caso de ser el padre uno del progenitor
persona = adopcion.getPadreUnoProgenitor();
break;
case 5: //En caso de ser el padre dos del progenitor
persona = adopcion.getPadreDosProgenitor();
break;
case 6: //En caso de ser el padre uno del adoptante
persona = adopcion.getPadreUnoAdoptante();
break;
case 7: //En caso de ser el padre dos del adoptante
persona = adopcion.getPadreDosAdoptante();
break;
case 8:
persona = adopcion.getTestigoUno();
break;
case 9:
persona = adopcion.getTestigoDos();
break;
}
return persona;
}
public void consultaLocalidadesInegi(Integer tipoPersona, Integer tipoRegistro) {
//Obtenemos a la persona que se refiere
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
MunicipioDTO municipio = persona.getDomicilio().getMunicipio();
switch(tipoPersona) {
case 1:
setLocalidadesAdoptado(getLocalidadService().findAllByMunicipio(municipio));
break;
case 2:
setLocalidadesProgenitor(getLocalidadService().findAllByMunicipio(municipio));
break;
case 3:
setLocalidadesAdoptante(getLocalidadService().findAllByMunicipio(municipio));
break;
case 4:
setLocalidadesPadreUnoProgenitor(getLocalidadService().findAllByMunicipio(municipio));
break;
case 5:
setLocalidadesPadreDosProgenitor(getLocalidadService().findAllByMunicipio(municipio));
break;
case 6:
setLocalidadesPadreUnoAdoptante(getLocalidadService().findAllByMunicipio(municipio));
break;
case 7:
setLocalidadesPadreDosAdoptante(getLocalidadService().findAllByMunicipio(municipio));
break;
case 8:
setLocalidadesTestigoUno(getLocalidadService().findAllByMunicipio(municipio));
break;
case 9:
setLocalidadesTestigoDos(getLocalidadService().findAllByMunicipio(municipio));
break;
}
}
public void consultaEstadosInegi(Integer tipoPersona, Integer tipoRegistro) {
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
PaisDTO pais = persona.getDomicilio().getPais();
switch(tipoPersona) {
case 1:
setEstadosInegiAdoptado(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 2:
setEstadosInegiProgenitor(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 3:
setEstadosInegiAdoptante(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 4:
setEstadosInegiPadreUnoProgenitor(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 5:
setEstadosInegiPadreDosProgenitor(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 6:
setEstadosInegiPadreUnoAdoptante(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 7:
setEstadosInegiPadreDosAdoptante(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 8:
setEstadosInegiTestigoUno(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
case 9:
setEstadosInegiTestigoDos(getInegiEstadoService().recupearEstadosPorPais(pais));
break;
}
}
public void consultaMunicipiosInegi(Integer tipoPersona, Integer tipoRegistro) {
PersonaDTO persona = obtienePersona(tipoPersona, tipoRegistro);
EstadoDTO estado = persona.getDomicilio().getEstado();
switch(tipoPersona) {
case 1:
setMunicipiosInegiAdoptado(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 2:
setMunicipiosInegiProgenitor(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 3:
setMunicipiosInegiAdoptante(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 4:
setMunicipiosInegiPadreUnoProgenitor(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 5:
setMunicipiosInegiPadreDosProgenitor(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 6:
setMunicipiosInegiPadreUnoAdoptante(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 7:
setMunicipiosInegiPadreDosAdoptante(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 8:
setMunicipiosInegiTestigoUno(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
case 9:
setMunicipiosInegiTestigoDos(getInegiMunicipioService().recuperaMunicipiosPorEstado(estado));
break;
}
}
}
| 15,011 | 0.665712 | 0.661981 | 369 | 39.680218 | 30.26425 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.582656 | false | false |
3
|
65a5dddbf95cf5739f74fa1d56235a8e3afcf9c9
| 7,928,509,655,026 |
4094f183a5e61431db7e6e78a3282aa4cd298464
|
/app/src/main/java/com/example/android/reportcard/SchoolSubjects.java
|
667d9584de01d27cf8ee644a16df12aee371b9d6
|
[] |
no_license
|
lukaszgo3/ReportCard
|
https://github.com/lukaszgo3/ReportCard
|
639972aa3581f6a0980d72097e390a6d284e47a7
|
cdefd2d9445ae63d2d6b9ce1ed3b6fe005feca5f
|
refs/heads/master
| 2021-01-20T08:40:54.990000 | 2017-05-03T17:41:11 | 2017-05-03T17:41:11 | 90,176,514 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.android.reportcard;
public class SchoolSubjects {
//School grade (e.q. 4, 5, 2)
private String SchoolGrade;
//Name of subject (e.q. Math, Biology)
private String SchoolSubject;
//Date of the assessment
private String SchoolDate;
public SchoolSubjects(String mGrade, String mSubject, String mDate) {
SchoolGrade = mGrade;
SchoolSubject = mSubject;
SchoolDate = mDate;
}
/**
* Get the grade
*/
public String getGrade() {
return SchoolGrade;
}
/**
* Get the name of Subject
*/
public String getSubject() {
return SchoolSubject;
}
/**
* Get the date of assessment
*/
public String getDate() {
return SchoolDate;
}
}
|
UTF-8
|
Java
| 787 |
java
|
SchoolSubjects.java
|
Java
|
[] | null |
[] |
package com.example.android.reportcard;
public class SchoolSubjects {
//School grade (e.q. 4, 5, 2)
private String SchoolGrade;
//Name of subject (e.q. Math, Biology)
private String SchoolSubject;
//Date of the assessment
private String SchoolDate;
public SchoolSubjects(String mGrade, String mSubject, String mDate) {
SchoolGrade = mGrade;
SchoolSubject = mSubject;
SchoolDate = mDate;
}
/**
* Get the grade
*/
public String getGrade() {
return SchoolGrade;
}
/**
* Get the name of Subject
*/
public String getSubject() {
return SchoolSubject;
}
/**
* Get the date of assessment
*/
public String getDate() {
return SchoolDate;
}
}
| 787 | 0.594663 | 0.590851 | 42 | 17.761906 | 16.533962 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false |
3
|
d18c8264e5cecec0e6989935145e0a445c9b2269
| 17,025,250,398,615 |
1c73717e2c6dda20e9b9ee2357ca92d653d29ee2
|
/SpringCloud-Consumer/src/main/java/com/xiao/skywalking/consumer/common/CommonConstants.java
|
f66a537a57436f2d47ef37557a161d4662146964
|
[
"MIT"
] |
permissive
|
Xlinlin/SpringCloud-Demo
|
https://github.com/Xlinlin/SpringCloud-Demo
|
80c0de59d60036697aa9a03e2bfa3026412e4ebf
|
5efd083d427f9a14d3b41c2d9dd4df00a7b3d412
|
refs/heads/master
| 2023-06-29T00:23:11.958000 | 2022-10-21T01:11:40 | 2022-10-21T01:11:40 | 129,914,529 | 220 | 126 |
MIT
| false | 2023-06-14T22:29:02 | 2018-04-17T14:09:42 | 2023-05-31T03:02:39 | 2023-06-14T22:29:01 | 122,644 | 208 | 120 | 12 |
Java
| false | false |
package com.xiao.skywalking.consumer.common;
/**
* [简要描述]:
* [详细描述]:
*
* @author llxiao
* @version 1.0, 2019/11/1 11:16
* @since JDK 1.8
*/
public interface CommonConstants
{
/**
* yyyy-MM-dd
*/
String YYYYMMDD_DATE_FORMAT = "yyyy-MM-dd";
/**
* 投放使用
*/
int ACTIVITY_USED = 1;
/**
* 投放使用
*/
int ACTIVITY_UN_USED = 0;
}
|
UTF-8
|
Java
| 413 |
java
|
CommonConstants.java
|
Java
|
[
{
"context": "r.common;\n\n/**\n * [简要描述]:\n * [详细描述]:\n *\n * @author llxiao\n * @version 1.0, 2019/11/1 11:16\n * @since JDK 1.",
"end": 92,
"score": 0.9995276927947998,
"start": 86,
"tag": "USERNAME",
"value": "llxiao"
}
] | null |
[] |
package com.xiao.skywalking.consumer.common;
/**
* [简要描述]:
* [详细描述]:
*
* @author llxiao
* @version 1.0, 2019/11/1 11:16
* @since JDK 1.8
*/
public interface CommonConstants
{
/**
* yyyy-MM-dd
*/
String YYYYMMDD_DATE_FORMAT = "yyyy-MM-dd";
/**
* 投放使用
*/
int ACTIVITY_USED = 1;
/**
* 投放使用
*/
int ACTIVITY_UN_USED = 0;
}
| 413 | 0.524934 | 0.480315 | 26 | 13.653846 | 13.141076 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.192308 | false | false |
3
|
d192643a7d288d1a62e654e43b455b42f55e2519
| 257,698,057,042 |
e4ab9e111b3c4a2b58c9c4a0b5d2dcc249e78ad3
|
/src/main/java/com/inno/companies/groupon/PhoneScreen2.java
|
eda637633455ce76ccb9c4db13fff9298112ae50
|
[] |
no_license
|
Irving09/interview2017
|
https://github.com/Irving09/interview2017
|
c8e101de4098e2f3e6d6ddb4ca7cf5239ec5d0b8
|
c711464e4348e8bd3010d9be0316c1eab6b62447
|
refs/heads/master
| 2018-12-07T09:02:35.324000 | 2018-04-05T07:03:44 | 2018-04-05T07:03:44 | 94,568,083 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* CONFIDENTIAL INFORMATION
*
* All Rights Reserved. Unauthorized reproduction, transmission, or
* distribution of this software is a violation of applicable laws.
*
* Date: Mar 29, 2018
* Copyright 2018 innoirvinge@gmail.com
*/
package com.inno.companies.groupon;
/**
* @author irving09 <innoirvinge@gmail.com>
*/
public class PhoneScreen2 {
public static void main(String[] args) {
String s1, s2;
s1 = "IndiaUSAEngland";
s2 = "USAEnglandIndia";
System.out.println(isRotated(s1, s2));
System.out.println(isRotated(s2, s1));
s1 = "IndiaUSAEngland";
s2 = "IndiaEnglandUSA";
System.out.println(isRotated(s2, s1));
}
public static boolean isRotated(String s1, String s2) {
if (s1.length() != s2.length())
return false;
int n = s1.length();
String missed = "";
for (int i = 0; i < n; i++) { // O(n)
String rotated = s1.substring(i);
int s2Location = s2.indexOf(rotated);
if (s2Location >= 0) {
return missed.equals(s2.substring(s2Location + rotated.length())); // India, IndiaUSAEngland
}
missed = missed + s1.charAt(i);
}
return false;
}
}
|
UTF-8
|
Java
| 1,164 |
java
|
PhoneScreen2.java
|
Java
|
[
{
"context": "e laws.\n *\n * Date: Mar 29, 2018\n * Copyright 2018 innoirvinge@gmail.com\n */\npackage com.inno.companies.groupon;\n\n/**\n * @",
"end": 236,
"score": 0.9999291896820068,
"start": 215,
"tag": "EMAIL",
"value": "innoirvinge@gmail.com"
},
{
"context": "ackage com.inno.companies.groupon;\n\n/**\n * @author irving09 <innoirvinge@gmail.com>\n */\npublic class PhoneScr",
"end": 301,
"score": 0.9995946288108826,
"start": 293,
"tag": "USERNAME",
"value": "irving09"
},
{
"context": "inno.companies.groupon;\n\n/**\n * @author irving09 <innoirvinge@gmail.com>\n */\npublic class PhoneScreen2 {\n public static ",
"end": 324,
"score": 0.9999325275421143,
"start": 303,
"tag": "EMAIL",
"value": "innoirvinge@gmail.com"
}
] | null |
[] |
/**
* CONFIDENTIAL INFORMATION
*
* All Rights Reserved. Unauthorized reproduction, transmission, or
* distribution of this software is a violation of applicable laws.
*
* Date: Mar 29, 2018
* Copyright 2018 <EMAIL>
*/
package com.inno.companies.groupon;
/**
* @author irving09 <<EMAIL>>
*/
public class PhoneScreen2 {
public static void main(String[] args) {
String s1, s2;
s1 = "IndiaUSAEngland";
s2 = "USAEnglandIndia";
System.out.println(isRotated(s1, s2));
System.out.println(isRotated(s2, s1));
s1 = "IndiaUSAEngland";
s2 = "IndiaEnglandUSA";
System.out.println(isRotated(s2, s1));
}
public static boolean isRotated(String s1, String s2) {
if (s1.length() != s2.length())
return false;
int n = s1.length();
String missed = "";
for (int i = 0; i < n; i++) { // O(n)
String rotated = s1.substring(i);
int s2Location = s2.indexOf(rotated);
if (s2Location >= 0) {
return missed.equals(s2.substring(s2Location + rotated.length())); // India, IndiaUSAEngland
}
missed = missed + s1.charAt(i);
}
return false;
}
}
| 1,136 | 0.63488 | 0.601375 | 45 | 24.866667 | 21.932827 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622222 | false | false |
3
|
5bc016a1a8803a1affbf10450dcfac73806064e4
| 26,577,257,682,890 |
b6107a223c757281fb9d95065376cc2a17bfe0a3
|
/src/com/managementsystem/guestroom/domain/hibernate/Emailaddress.java
|
51af6ec652fb4562fde59beb826ccd0f8e4967f4
|
[] |
no_license
|
chenflat/guestroomcs
|
https://github.com/chenflat/guestroomcs
|
550c39ee4f6b64ee5bb5deecf67f0006bfda460d
|
e28bd641f209a6faa73b89697b27b67366ae07c3
|
refs/heads/master
| 2021-01-10T13:39:59.817000 | 2013-08-21T07:19:08 | 2013-08-21T07:19:08 | 55,110,401 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.managementsystem.guestroom.domain.hibernate;
import java.util.Date;
/**
* 用户电子邮件
* */
public class Emailaddress implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String emailAddressId;
private User user;
private Date createdOnDate;
private Date lastModifiedOnDate;
private String address;
private Boolean primary;
private String entryid;
private String comment;
private String keyname;
public Emailaddress() {
}
public Emailaddress(String emailAddressId) {
this.emailAddressId = emailAddressId;
}
public Emailaddress(String emailAddressId, User user, Date createdOnDate,
Date lastModifiedOnDate, String address, Boolean primary,
String entryid) {
this.emailAddressId = emailAddressId;
this.user = user;
this.createdOnDate = createdOnDate;
this.lastModifiedOnDate = lastModifiedOnDate;
this.address = address;
this.primary = primary;
this.entryid = entryid;
}
public String getEmailAddressId() {
return this.emailAddressId;
}
public void setEmailAddressId(String emailAddressId) {
this.emailAddressId = emailAddressId;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public Date getCreatedOnDate() {
return this.createdOnDate;
}
public void setCreatedOnDate(Date createdOnDate) {
this.createdOnDate = createdOnDate;
}
public Date getLastModifiedOnDate() {
return this.lastModifiedOnDate;
}
public void setLastModifiedOnDate(Date lastModifiedOnDate) {
this.lastModifiedOnDate = lastModifiedOnDate;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Boolean getPrimary() {
return this.primary;
}
public void setPrimary(Boolean primary) {
this.primary = primary;
}
public String getEntryid() {
return this.entryid;
}
public void setEntryid(String entryid) {
this.entryid = entryid;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getKeyname() {
return keyname;
}
public void setKeyname(String keyname) {
this.keyname = keyname;
}
/*@Override
public String toString() {
return String
.format("{emailAddressId:%s,createdOnDate:%1$tY-%1$tm-%1$te %1$tH:%1$tM:%1$tS%n,lastModifiedOnDate:%1$tY-%1$tm-%1$te %1$tH:%1$tM:%1$tS%n,address:%s,primary:%s,entryid:%s,comment:%s,keyname:%s}",
emailAddressId, createdOnDate, lastModifiedOnDate,
address, primary, entryid, comment, keyname);
}*/
}
|
UTF-8
|
Java
| 2,729 |
java
|
Emailaddress.java
|
Java
|
[] | null |
[] |
package com.managementsystem.guestroom.domain.hibernate;
import java.util.Date;
/**
* 用户电子邮件
* */
public class Emailaddress implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String emailAddressId;
private User user;
private Date createdOnDate;
private Date lastModifiedOnDate;
private String address;
private Boolean primary;
private String entryid;
private String comment;
private String keyname;
public Emailaddress() {
}
public Emailaddress(String emailAddressId) {
this.emailAddressId = emailAddressId;
}
public Emailaddress(String emailAddressId, User user, Date createdOnDate,
Date lastModifiedOnDate, String address, Boolean primary,
String entryid) {
this.emailAddressId = emailAddressId;
this.user = user;
this.createdOnDate = createdOnDate;
this.lastModifiedOnDate = lastModifiedOnDate;
this.address = address;
this.primary = primary;
this.entryid = entryid;
}
public String getEmailAddressId() {
return this.emailAddressId;
}
public void setEmailAddressId(String emailAddressId) {
this.emailAddressId = emailAddressId;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public Date getCreatedOnDate() {
return this.createdOnDate;
}
public void setCreatedOnDate(Date createdOnDate) {
this.createdOnDate = createdOnDate;
}
public Date getLastModifiedOnDate() {
return this.lastModifiedOnDate;
}
public void setLastModifiedOnDate(Date lastModifiedOnDate) {
this.lastModifiedOnDate = lastModifiedOnDate;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Boolean getPrimary() {
return this.primary;
}
public void setPrimary(Boolean primary) {
this.primary = primary;
}
public String getEntryid() {
return this.entryid;
}
public void setEntryid(String entryid) {
this.entryid = entryid;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getKeyname() {
return keyname;
}
public void setKeyname(String keyname) {
this.keyname = keyname;
}
/*@Override
public String toString() {
return String
.format("{emailAddressId:%s,createdOnDate:%1$tY-%1$tm-%1$te %1$tH:%1$tM:%1$tS%n,lastModifiedOnDate:%1$tY-%1$tm-%1$te %1$tH:%1$tM:%1$tS%n,address:%s,primary:%s,entryid:%s,comment:%s,keyname:%s}",
emailAddressId, createdOnDate, lastModifiedOnDate,
address, primary, entryid, comment, keyname);
}*/
}
| 2,729 | 0.702981 | 0.698197 | 119 | 20.831932 | 24.67514 | 198 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.605042 | false | false |
3
|
afb1dd1525b1fb064f4e1d1d09607048276ec156
| 11,467,562,749,345 |
8dfb2b27dbb6dfd6da8b6449eff919cc36dc2b0c
|
/src/main/gol/controller/GUIController.java
|
75f0c285b370aa9299abbbff27419ffe6e152c7e
|
[] |
no_license
|
frodemathiass1/GameOfLife2017
|
https://github.com/frodemathiass1/GameOfLife2017
|
d2810d0482c9d7007b54d34084c419a562e68131
|
784f4d8cfdfa29b4e4176858253bdc571547c704
|
refs/heads/master
| 2021-03-27T14:13:09.645000 | 2017-05-05T18:24:41 | 2017-05-05T18:24:41 | 80,172,358 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package main.gol.controller;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.media.MediaException;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import main.gol.controller.util.Colors;
import main.gol.controller.util.Dialogs;
import main.gol.controller.util.Draw;
import main.gol.controller.util.Sound;
import main.gol.model.boards.Config;
import main.gol.model.boards.DynamicBoard;
import main.gol.model.Cell;
import main.gol.model.filemanager.*;
import java.io.*;
import java.net.URL;
import java.util.Optional;
import java.util.Random;
import java.util.ResourceBundle;
/**
* The GUIController contains a series of functions that handles the GUI-elements and their
* actionEvents to make the application do what its supposed to do.
*
* @version 1.5
*/
public class GUIController implements Initializable {
@FXML private MenuItem url1, url2, url3, url4, url5, url6, url7, url8, url9, url10;
@FXML private MenuItem file1, file2, file3, file4, file5, file6, file7, file8, file9, file10, fileBlock;
@FXML private MenuItem small, medium, large, largest;
@FXML private ColorPicker cpCell, cpGrid, cpBackground;
@FXML private Slider speedSlider,zoomSlider;
@FXML private ToggleButton play, toggleSound;
@FXML private Label speedIcon, counter, zoomIcon;
@FXML private Button next;
@FXML private Canvas canvas;
@FXML private Menu fileInfo;
//private FixedBoard fb;
private DynamicBoard board;
private GraphicsContext context;
private Timeline timeline;
private Dialogs dialog;
private Sound sound;
private Config config;
private Colors colors;
private Draw draw;
private FileHandler fileHandler;
private URLHandler urlHandler;
private BoardParser boardParser;
/**
* This method is overridden from initializable interface.
* Spits out the the default gameBoard and initialize the observable GUI components,
* and instantiates needed objects for controller handling.
*
* @param location java..net.URL
* @param resources java.util.ResourceBundle
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
try {
// Initialize needed objects
initializeObjects();
// Set default gameBoard and draw it to canvas
board = new DynamicBoard(config.getRows(), config.getColumns());
//board.setCellState(200, 200, true); // Set cellState outside array bounds and fill empty slots
draw.drawBoard(board.getGrid());
// Initialize animation timeline.
timeline = new Timeline();
KeyFrame kf = new KeyFrame(Duration.seconds(0.1), event -> {
timeline.setRate(speedSlider.getValue());
board.nextGeneration();
draw.drawGeneration(board.getGeneration());
int cellsCounter = board.getGeneration().size();
if (cellsCounter >= 0) {
counter.setText("Cells: " + cellsCounter);
}
});
timeline.getKeyFrames().add(kf);
timeline.setCycleCount(Timeline.INDEFINITE);
// Initialize observable gui components & fire off a pattern
initializeObservables();
} catch(Exception e) {
dialog.oops();
quit();
}
}
//================================================================================
// Container functions for initializing objects and observable components
//================================================================================
/**
* Wrapper: This method is a wrapper/container for instantiating needed objects.
*/
private void initializeObjects() {
config = new Config();
colors = new Colors();
draw = new Draw(getContext(), colors);
dialog = new Dialogs();
sound = new Sound();
}
/**
* Wrapper: This method is a wrapper/container method for initializing the observable GUI components.
*/
private void initializeObservables() {
togglePlay(); // Initialize play
handleGridSizeEvents(); // Initialize "Select drawBoard size" menu. Select Size on GUI.
handlePatternSelector(); // Initialize "Select pattern" menu. Select pattern on GUI
handleZoomSlider(); // Initialize Zoom slider. Zoom by changing CellSize
handleToggleSound(); // Initialize soundToggleButton. Toggle Sound on/off by
updateColorPickerValues();
}
//================================================================================
// Functions related to setting up new boards from : Files, URL's , byte[][]
//================================================================================
/**
* This method create new boards by parsed from files, strings, or what3ever.
* Sets up a new board with byte[][] arrays as inputParameter.
*
* @param board byte[][]
*/
private void newBoard(byte[][] board) {
try {
this.board = new DynamicBoard(config.getRows(), config.getColumns());
this.board.setBoard(board);
//this.board.setCellState(6, 8, true); // Expand board
draw.drawBoard(this.board.getGrid());
zoomSlider.setValue(zoomSlider.getMin());
} catch (NullPointerException ne) {
System.err.println("NullPointer Exception!");
} catch (ArrayIndexOutOfBoundsException oob) {
System.err.println("ArrayIndex out of bounds!");
}
}
/**
* This method sets the file info menu option.
*/
private void setFileInfo() {
// Show the file info.
Decoder info = new Decoder();
fileInfo.setDisable(false);
fileInfo.setText("(" + info.getTheName() + ")");
fileInfo.setStyle("-fx-font-weight: bold;");
}
/**
* This method runs the files that are loaded from the File/Patterns menu-selection
*/
private void runFile() {
if (!(fileHandler.getTheFile() == null)) {
try {
fileHandler = new FileHandler();
boardParser = new BoardParser();
largest.fire();
// Get correct file type, and parse to BoardParser.
if (fileHandler.getTheFileType().equals("RLE File")) {
// Instantiate a new temp file, and delete it after use.
File temp = new File("temp.gol");
boardParser.readAndParseFile(temp);
temp.delete();
} else if (fileHandler.getTheFileType().equals("Text File")) {
// Plaintext files is parsed directly.
boardParser.readAndParseFile(fileHandler.getTheFile());
}
// Reset the old board
board.clearBoard();
updateColorPickerValues();
// Draw the new board.
newBoard(boardParser.getTheBoard());
setFileInfo();
zoomSlider.setValue(1);
} catch (Exception e) {
dialog.fileError();
}
}
}
/**
* This method runs the URL's that are loaded from the File/Patterns menu-selection
*
* @param url String
*/
private void runURL(String url) {
try {
urlHandler = new URLHandler();
boardParser = new BoardParser();
urlHandler.selectUrlType(url);
largest.fire();
if (urlHandler.getUrlType().equals("RLE Url")) {
// Instantiate a new temp file, and delete it after use.
File temp = new File("temp.gol");
boardParser.readAndParseFile(temp);
temp.delete();
} else if (urlHandler.getUrlType().equals("Text Url")) {
// Plaintext URLs is parsed directly.
boardParser.readAndParseURL(url);
}
// Reset the old board.
board.clearBoard();
updateColorPickerValues();
// Draw the new board.
newBoard(boardParser.getTheBoard());
setFileInfo();
zoomSlider.setValue(1);
} catch (Exception e) {
dialog.urlError();
System.err.println("Something went wrong reading the URL.");
}
}
/**
* Event Handlers "Patterns" menu-button. Set predefined boards from project resources.
*/
@FXML
private void handlePatternSelector() {
// URL actions PlainText URLs
url1.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/airforce.cells"));
url2.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/b52bomber.cells"));
url3.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/backrake1.cells"));
url4.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/beaconmaker.cells"));
url5.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/bigglider.cells"));
// URL actions RLE URLs
url6.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/3enginecordership.rle"));
url7.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/blinkership1.rle"));
url8.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/brain.rle"));
url9.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/chemist.rle"));
url10.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/jolson.rle"));
// File actions PlainText files
file1.setOnAction(e -> handleFile("resources/patterns/candelabra.cells"));
file2.setOnAction(e -> handleFile("resources/patterns/candlefrobra.cells"));
file3.setOnAction(e -> handleFile("resources/patterns/carnival_shuttle.cells"));
file4.setOnAction(e -> handleFile("resources/patterns/158P3.cells"));
file5.setOnAction(e -> handleFile("resources/patterns/cow.cells"));
fileBlock.setOnAction(e -> {
handleFile("resources/patterns/block.txt");
Decoder.getTheName("A BIG BLOCK!");
Decoder.setOrigin("Tommy Pedersen");
Decoder.setContent("This block was created by one of the coders for this project.");
Decoder.setLink("Not published on internet.");
});
// File actions RLE files
file6.setOnAction(e -> handleFile("resources/patterns/mirage.rle"));
file7.setOnAction(e -> handleFile("resources/patterns/loaflipflop.rle"));
file8.setOnAction(e -> handleFile("resources/patterns/pinwheel.rle"));
file9.setOnAction(e -> handleFile("resources/patterns/ringoffire.rle"));
file10.setOnAction(e -> handleFile("resources/patterns/sailboat.rle"));
}
/**
* This method create boards with a valid URL string as inputParameter.
* Takes url for valid GOL .txt/.cells file patterns.
*
* @param url String
*/
private void handleURL(String url) {
runURL(url);
}
/**
* This method create boards with a valid path string as inputParameter.
* Takes String filepath for valid GOL .txt/.cells file patterns.
*
* @param path String
*/
private void handleFile(String path) {
File file = new File(path);
fileHandler = new FileHandler();
fileHandler.setTheFile(file);
fileHandler.fileSelectType(file);
runFile();
}
/**
* EventHandler "Open File" menu-button.
* Sets a new board by selecting a file, parsing it to the correct decoder and creating a new board.
*/
@FXML
public void loadFileFromDisk() {
fileHandler = new FileHandler();
fileHandler.chooseAndSelectType();
runFile();
}
/**
* EventHandler "Open URL" menu-button.
* Sets a new board by getting the URL you type, parsing it to the correct decoder and creating a new board.
*/
@FXML
public void loadFileFromURL() {
// Opens a new input dialog window for URLs
TextInputDialog inputURL = new TextInputDialog();
inputURL.setTitle("Open URL");
inputURL.setHeaderText("Resources: http://conwaylife.com/wiki/Category:Patterns");
inputURL.setContentText("Enter URL here");
Optional<String> result = inputURL.showAndWait();
if (result.isPresent()) {
// URLs must start with http for this method to work.
if (!(result.get().toLowerCase().startsWith("http"))) {
dialog.httpError();
} else {
runURL(result.get());
}
}
}
//================================================================================
// Functions related to Play, Reset and Bomb Buttons
//================================================================================
/**
* EventHandler: "Next" button. Draw the next generation of cells (no animation).
*/
@FXML
public void nextStep() {
board.nextGeneration();
draw.drawGeneration(board.getGeneration());
sound.play(sound.getFx3());
}
/**
* This method stop timeline animation if its running and changes the buttonText
*/
private void stopAnimationIfRunning() {
if (timeline.getStatus() == Animation.Status.RUNNING) {
timeline.stop();
play.setText("Play");
play.setSelected(false);
}
}
/**
* EventHandler: "Reset" button.
* Stop animation and clear the editor-window of living cells.
* Reset settings to default and play a oneshot fx sound.
*/
@FXML
public void reset() {
stopAnimationIfRunning();
colors.resetAll();
board.clearBoard();
config.setDefault();
board = new DynamicBoard(config.getRows(), config.getColumns());
draw.drawBoard(board.getGrid());
play.setText("Play");
next.setText("Next");
fileInfo.setDisable(true);
fileInfo.setText("");
sound.play(sound.getFx8());
counter.setText("Cells: ");
}
/**
* EventHandler: "Bomb Icon" button.
* Fills the Board with random live cells to simulate a MadManPacMan sorta game."Cell consumer".
*/
@FXML
public void handleTheBomber() {
board.clearBoard();
try {
setRandomColor();
} catch (Exception e) {
e.printStackTrace();
}
updateColorPickerValues();
// This combination of calls enables the MadManPacMan sort of Game simulation.
draw.drawBoard(board.getGrid());
board.randomize();
draw.drawGeneration(board.getGeneration());
}
//================================================================================
// Functions related to Buttons and sliders for speed, sound and size
//================================================================================
/**
* This method resets the board before loading a new one.
*/
public void resetBoard() {
board.clearBoard();
fileInfo.setDisable(true);
fileInfo.setText("");
sound.play(sound.getFx8());
counter.setText("Cells: ");
}
/**
* EventHandler: "Select Grid size" MenuButton
*/
@FXML
private void handleGridSizeEvents() {
stopAnimationIfRunning();
largest.setOnAction(e -> {
resetBoard();
board = new DynamicBoard(104,160);
config.setDefault();
draw.drawBoard(board.getGrid());
});
large.setOnAction(e -> {
resetBoard();
board = new DynamicBoard(35,54);
config.setCellSize(15);
draw.drawBoard(board.getGrid());
});
medium.setOnAction(e -> {
resetBoard();
board = new DynamicBoard(17,27);
config.setCellSize(31);
draw.drawBoard(board.getGrid());
});
small.setOnAction(e -> {
resetBoard();
board = new DynamicBoard(13,20);
config.setCellSize(40);
draw.drawBoard(board.getGrid());
});
}
/**
* EventHandler/Listener: "Zoom slider". Handle the slider listener.
*/
private void handleZoomSlider() {
zoomSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
canvas.setScaleX(newValue.intValue());
canvas.setScaleY(newValue.intValue());
});
}
/**
* EventHandler: "Sound icon". Toggle sound.
*/
private void handleToggleSound() {
toggleSound.setOnAction(e -> {
if (toggleSound.isSelected()) {
sound.play(sound.getPop3());
sound.setVol(0.0);
} else {
sound.setVol(0.2);
sound.play(sound.getPop1());
}
});
}
/**
* EventHandler: "Play/Stop Button".
* Toggle animation, change buttonText and play a one shot sound when triggered.
*/
private void togglePlay() {
play.setOnAction((event -> {
if (timeline.getStatus() == Animation.Status.RUNNING) {
timeline.stop();
play.setText("Play");
sound.play(sound.getPop2());
} else if (timeline.getStatus() == Animation.Status.STOPPED) {
timeline.play();
play.setText("Stop");
sound.play(sound.getPop1());
}
}));
}
/**
* Event Handler "Zoom icon". Flip max/min zoom values.
*/
@FXML
public void flipZoom() {
zoomIcon.setOnMouseClicked(event -> {
if (event.getClickCount() == 1) {
zoomSlider.setValue(3);
} else if (event.getClickCount() == 2) {
zoomSlider.setValue(1);
}
});
}
/**
* Event Handler: "Speed icon". Flip max/min animation rate
*/
@FXML
public void flipSpeed() {
speedIcon.setOnMouseClicked(event -> {
if (event.getClickCount() == 1) {
speedSlider.setValue(speedSlider.getMax());
} else if (event.getClickCount() == 2) {
speedSlider.setValue(speedSlider.getMin());
}
});
}
//================================================================================
// Functions related to Mouse events
//================================================================================
/**
* EventHandler:
* <p>
* This method handle Cell coordinates of canvas by mouseEvents and the Logic of placing cells
* correct on the screen and sceneGraph node canvas.
* <p>
* Draw, erase, and toggle cells in editor by MouseGestures:
* <p>
* Drag: Draw cells.
* LeftClick : Toggle Cell alive / Dead.
* DoubleClick (Hold button and Move support): Erase one or multiple Cells.
*
* @param event MouseEvent
*/
@FXML
public void handleMouseEvent(MouseEvent event) {
try {
double x = event.getX(); // mouse x pos
double y = event.getY(); // mouse y pos
// Find Cell position in board Cell drawBoard array
int cellPosX = (int) Math.floor(x / config.getCellSize());
int cellPosY = (int) Math.floor(y / config.getCellSize());
// Get Cell
Cell cell = board.getCell(cellPosX, cellPosY);
// Toggle alive
boolean toggleState = !cell.getState();
// For smooth drawing
if (toggleState) {
cell.setState(toggleState);
}
// Double click and drag to smooth erase
if (event.getClickCount() > 1) {
toggleState = false;
cell.setState(toggleState);
}
draw.drawCell(cell);
} catch (NullPointerException ne) {
// Do nothing!
}
}
//================================================================================
// Methods related to Graphics and Color settings
//================================================================================
/**
* This method returns the Canvas graphicsContext(Helper method for Draw calls).
*
* @return GraphicContext
*/
private GraphicsContext getContext() {
context = canvas.getGraphicsContext2D();
return context;
}
/**
* EventHandler: "ColorPicker Cell". Set cell-color from ColorPicker.
*/
@FXML
public void setCellColor() {
colors.setCell(cpCell.getValue());
draw.drawBoard(board.getGrid());
updateColorPickerValues();
}
/**
* EventHandler: "ColorPicker Grid". Set grid-color from ColorPicker.
*/
@FXML
public void setGridColor() {
colors.setGridLine(cpGrid.getValue());
draw.drawBoard(board.getGrid());
updateColorPickerValues();
}
/**
* EventHandler: "ColorPicker: Background". Set background-color from ColorPicker.
*/
@FXML
public void setBackgroundColor() {
colors.setBackground(cpBackground.getValue());
draw.drawBoard(board.getGrid());
updateColorPickerValues();
}
/**
* EventHandler: "Random color" menu-button. Set random colors to Cells, GridLine and Background.
*/
@FXML
public void setRandomColor() {
Random rand = new Random();
int b = 255; // int bounder
Color cell = Color.rgb(rand.nextInt(b), rand.nextInt(b), rand.nextInt(b));
Color grid = Color.rgb(rand.nextInt(b), rand.nextInt(b), rand.nextInt(b));
Color background = Color.rgb(rand.nextInt(b), rand.nextInt(b), rand.nextInt(b));
// Set Random colors
colors.setCell(cell);
colors.setGridLine(grid);
colors.setBackground(background);
updateColorPickerValues();
draw.drawBoard(board.getGrid());
sound.play(sound.getFx2());
}
/**
* EventHandler: "Reset color" menu-button. Reset all colors to default settings.
*/
@FXML
public void resetColor() {
colors.resetAll();
updateColorPickerValues();
draw.drawBoard(board.getGrid());
try {
sound.play(sound.getFx8());
} catch (MediaException me) {
dialog.audioError();
}
}
/**
* This method updates the colorPicker widget values.
*/
private void updateColorPickerValues() {
cpCell.setValue(colors.getCell());
cpBackground.setValue(colors.getBackground());
cpGrid.setValue(colors.getGridLine());
}
//================================================================================
// Functions related to the MenuBar-buttons and Information Dialogs
//================================================================================
/**
* EventHandler: "FileInfo". Shows the dialog box with the loaded file information.
*/
@FXML
public void showFileInfo() {
dialog.fileInfo();
}
/**
*
* EventHandler: "Info" menu-button. Show information dialog box when info button is clicked.
*/
@FXML
public void showInfo() {
dialog.showInfo();
}
/**
*
* EventHandler: "About Game Of Life" menu-button. Show information dialog box with Game of Life rules and description.
*/
@FXML
public void aboutGameOfLife() {
dialog.aboutGol();
}
/**
* EventHandler: "How to play" menu-button. Show information dialog box about how to play the game.
*/
@FXML
public void howToPlay() {
dialog.howToPlay();
}
/**
* EventHandler: "Quit" menu-button". Exit the application.
*/
@FXML
public void quit() {
try {
sound.play(sound.getFx3());
} catch (MediaException me) {
dialog.audioError();
}
Platform.exit();
}
}
|
UTF-8
|
Java
| 24,590 |
java
|
GUIController.java
|
Java
|
[
{
"context": "e(\"A BIG BLOCK!\");\n Decoder.setOrigin(\"Tommy Pedersen\");\n Decoder.setContent(\"This block was",
"end": 10651,
"score": 0.9992809295654297,
"start": 10637,
"tag": "NAME",
"value": "Tommy Pedersen"
}
] | null |
[] |
package main.gol.controller;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.media.MediaException;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import main.gol.controller.util.Colors;
import main.gol.controller.util.Dialogs;
import main.gol.controller.util.Draw;
import main.gol.controller.util.Sound;
import main.gol.model.boards.Config;
import main.gol.model.boards.DynamicBoard;
import main.gol.model.Cell;
import main.gol.model.filemanager.*;
import java.io.*;
import java.net.URL;
import java.util.Optional;
import java.util.Random;
import java.util.ResourceBundle;
/**
* The GUIController contains a series of functions that handles the GUI-elements and their
* actionEvents to make the application do what its supposed to do.
*
* @version 1.5
*/
public class GUIController implements Initializable {
@FXML private MenuItem url1, url2, url3, url4, url5, url6, url7, url8, url9, url10;
@FXML private MenuItem file1, file2, file3, file4, file5, file6, file7, file8, file9, file10, fileBlock;
@FXML private MenuItem small, medium, large, largest;
@FXML private ColorPicker cpCell, cpGrid, cpBackground;
@FXML private Slider speedSlider,zoomSlider;
@FXML private ToggleButton play, toggleSound;
@FXML private Label speedIcon, counter, zoomIcon;
@FXML private Button next;
@FXML private Canvas canvas;
@FXML private Menu fileInfo;
//private FixedBoard fb;
private DynamicBoard board;
private GraphicsContext context;
private Timeline timeline;
private Dialogs dialog;
private Sound sound;
private Config config;
private Colors colors;
private Draw draw;
private FileHandler fileHandler;
private URLHandler urlHandler;
private BoardParser boardParser;
/**
* This method is overridden from initializable interface.
* Spits out the the default gameBoard and initialize the observable GUI components,
* and instantiates needed objects for controller handling.
*
* @param location java..net.URL
* @param resources java.util.ResourceBundle
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
try {
// Initialize needed objects
initializeObjects();
// Set default gameBoard and draw it to canvas
board = new DynamicBoard(config.getRows(), config.getColumns());
//board.setCellState(200, 200, true); // Set cellState outside array bounds and fill empty slots
draw.drawBoard(board.getGrid());
// Initialize animation timeline.
timeline = new Timeline();
KeyFrame kf = new KeyFrame(Duration.seconds(0.1), event -> {
timeline.setRate(speedSlider.getValue());
board.nextGeneration();
draw.drawGeneration(board.getGeneration());
int cellsCounter = board.getGeneration().size();
if (cellsCounter >= 0) {
counter.setText("Cells: " + cellsCounter);
}
});
timeline.getKeyFrames().add(kf);
timeline.setCycleCount(Timeline.INDEFINITE);
// Initialize observable gui components & fire off a pattern
initializeObservables();
} catch(Exception e) {
dialog.oops();
quit();
}
}
//================================================================================
// Container functions for initializing objects and observable components
//================================================================================
/**
* Wrapper: This method is a wrapper/container for instantiating needed objects.
*/
private void initializeObjects() {
config = new Config();
colors = new Colors();
draw = new Draw(getContext(), colors);
dialog = new Dialogs();
sound = new Sound();
}
/**
* Wrapper: This method is a wrapper/container method for initializing the observable GUI components.
*/
private void initializeObservables() {
togglePlay(); // Initialize play
handleGridSizeEvents(); // Initialize "Select drawBoard size" menu. Select Size on GUI.
handlePatternSelector(); // Initialize "Select pattern" menu. Select pattern on GUI
handleZoomSlider(); // Initialize Zoom slider. Zoom by changing CellSize
handleToggleSound(); // Initialize soundToggleButton. Toggle Sound on/off by
updateColorPickerValues();
}
//================================================================================
// Functions related to setting up new boards from : Files, URL's , byte[][]
//================================================================================
/**
* This method create new boards by parsed from files, strings, or what3ever.
* Sets up a new board with byte[][] arrays as inputParameter.
*
* @param board byte[][]
*/
private void newBoard(byte[][] board) {
try {
this.board = new DynamicBoard(config.getRows(), config.getColumns());
this.board.setBoard(board);
//this.board.setCellState(6, 8, true); // Expand board
draw.drawBoard(this.board.getGrid());
zoomSlider.setValue(zoomSlider.getMin());
} catch (NullPointerException ne) {
System.err.println("NullPointer Exception!");
} catch (ArrayIndexOutOfBoundsException oob) {
System.err.println("ArrayIndex out of bounds!");
}
}
/**
* This method sets the file info menu option.
*/
private void setFileInfo() {
// Show the file info.
Decoder info = new Decoder();
fileInfo.setDisable(false);
fileInfo.setText("(" + info.getTheName() + ")");
fileInfo.setStyle("-fx-font-weight: bold;");
}
/**
* This method runs the files that are loaded from the File/Patterns menu-selection
*/
private void runFile() {
if (!(fileHandler.getTheFile() == null)) {
try {
fileHandler = new FileHandler();
boardParser = new BoardParser();
largest.fire();
// Get correct file type, and parse to BoardParser.
if (fileHandler.getTheFileType().equals("RLE File")) {
// Instantiate a new temp file, and delete it after use.
File temp = new File("temp.gol");
boardParser.readAndParseFile(temp);
temp.delete();
} else if (fileHandler.getTheFileType().equals("Text File")) {
// Plaintext files is parsed directly.
boardParser.readAndParseFile(fileHandler.getTheFile());
}
// Reset the old board
board.clearBoard();
updateColorPickerValues();
// Draw the new board.
newBoard(boardParser.getTheBoard());
setFileInfo();
zoomSlider.setValue(1);
} catch (Exception e) {
dialog.fileError();
}
}
}
/**
* This method runs the URL's that are loaded from the File/Patterns menu-selection
*
* @param url String
*/
private void runURL(String url) {
try {
urlHandler = new URLHandler();
boardParser = new BoardParser();
urlHandler.selectUrlType(url);
largest.fire();
if (urlHandler.getUrlType().equals("RLE Url")) {
// Instantiate a new temp file, and delete it after use.
File temp = new File("temp.gol");
boardParser.readAndParseFile(temp);
temp.delete();
} else if (urlHandler.getUrlType().equals("Text Url")) {
// Plaintext URLs is parsed directly.
boardParser.readAndParseURL(url);
}
// Reset the old board.
board.clearBoard();
updateColorPickerValues();
// Draw the new board.
newBoard(boardParser.getTheBoard());
setFileInfo();
zoomSlider.setValue(1);
} catch (Exception e) {
dialog.urlError();
System.err.println("Something went wrong reading the URL.");
}
}
/**
* Event Handlers "Patterns" menu-button. Set predefined boards from project resources.
*/
@FXML
private void handlePatternSelector() {
// URL actions PlainText URLs
url1.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/airforce.cells"));
url2.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/b52bomber.cells"));
url3.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/backrake1.cells"));
url4.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/beaconmaker.cells"));
url5.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/bigglider.cells"));
// URL actions RLE URLs
url6.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/3enginecordership.rle"));
url7.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/blinkership1.rle"));
url8.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/brain.rle"));
url9.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/chemist.rle"));
url10.setOnAction(e -> handleURL("http://www.conwaylife.com/patterns/jolson.rle"));
// File actions PlainText files
file1.setOnAction(e -> handleFile("resources/patterns/candelabra.cells"));
file2.setOnAction(e -> handleFile("resources/patterns/candlefrobra.cells"));
file3.setOnAction(e -> handleFile("resources/patterns/carnival_shuttle.cells"));
file4.setOnAction(e -> handleFile("resources/patterns/158P3.cells"));
file5.setOnAction(e -> handleFile("resources/patterns/cow.cells"));
fileBlock.setOnAction(e -> {
handleFile("resources/patterns/block.txt");
Decoder.getTheName("A BIG BLOCK!");
Decoder.setOrigin("<NAME>");
Decoder.setContent("This block was created by one of the coders for this project.");
Decoder.setLink("Not published on internet.");
});
// File actions RLE files
file6.setOnAction(e -> handleFile("resources/patterns/mirage.rle"));
file7.setOnAction(e -> handleFile("resources/patterns/loaflipflop.rle"));
file8.setOnAction(e -> handleFile("resources/patterns/pinwheel.rle"));
file9.setOnAction(e -> handleFile("resources/patterns/ringoffire.rle"));
file10.setOnAction(e -> handleFile("resources/patterns/sailboat.rle"));
}
/**
* This method create boards with a valid URL string as inputParameter.
* Takes url for valid GOL .txt/.cells file patterns.
*
* @param url String
*/
private void handleURL(String url) {
runURL(url);
}
/**
* This method create boards with a valid path string as inputParameter.
* Takes String filepath for valid GOL .txt/.cells file patterns.
*
* @param path String
*/
private void handleFile(String path) {
File file = new File(path);
fileHandler = new FileHandler();
fileHandler.setTheFile(file);
fileHandler.fileSelectType(file);
runFile();
}
/**
* EventHandler "Open File" menu-button.
* Sets a new board by selecting a file, parsing it to the correct decoder and creating a new board.
*/
@FXML
public void loadFileFromDisk() {
fileHandler = new FileHandler();
fileHandler.chooseAndSelectType();
runFile();
}
/**
* EventHandler "Open URL" menu-button.
* Sets a new board by getting the URL you type, parsing it to the correct decoder and creating a new board.
*/
@FXML
public void loadFileFromURL() {
// Opens a new input dialog window for URLs
TextInputDialog inputURL = new TextInputDialog();
inputURL.setTitle("Open URL");
inputURL.setHeaderText("Resources: http://conwaylife.com/wiki/Category:Patterns");
inputURL.setContentText("Enter URL here");
Optional<String> result = inputURL.showAndWait();
if (result.isPresent()) {
// URLs must start with http for this method to work.
if (!(result.get().toLowerCase().startsWith("http"))) {
dialog.httpError();
} else {
runURL(result.get());
}
}
}
//================================================================================
// Functions related to Play, Reset and Bomb Buttons
//================================================================================
/**
* EventHandler: "Next" button. Draw the next generation of cells (no animation).
*/
@FXML
public void nextStep() {
board.nextGeneration();
draw.drawGeneration(board.getGeneration());
sound.play(sound.getFx3());
}
/**
* This method stop timeline animation if its running and changes the buttonText
*/
private void stopAnimationIfRunning() {
if (timeline.getStatus() == Animation.Status.RUNNING) {
timeline.stop();
play.setText("Play");
play.setSelected(false);
}
}
/**
* EventHandler: "Reset" button.
* Stop animation and clear the editor-window of living cells.
* Reset settings to default and play a oneshot fx sound.
*/
@FXML
public void reset() {
stopAnimationIfRunning();
colors.resetAll();
board.clearBoard();
config.setDefault();
board = new DynamicBoard(config.getRows(), config.getColumns());
draw.drawBoard(board.getGrid());
play.setText("Play");
next.setText("Next");
fileInfo.setDisable(true);
fileInfo.setText("");
sound.play(sound.getFx8());
counter.setText("Cells: ");
}
/**
* EventHandler: "Bomb Icon" button.
* Fills the Board with random live cells to simulate a MadManPacMan sorta game."Cell consumer".
*/
@FXML
public void handleTheBomber() {
board.clearBoard();
try {
setRandomColor();
} catch (Exception e) {
e.printStackTrace();
}
updateColorPickerValues();
// This combination of calls enables the MadManPacMan sort of Game simulation.
draw.drawBoard(board.getGrid());
board.randomize();
draw.drawGeneration(board.getGeneration());
}
//================================================================================
// Functions related to Buttons and sliders for speed, sound and size
//================================================================================
/**
* This method resets the board before loading a new one.
*/
public void resetBoard() {
board.clearBoard();
fileInfo.setDisable(true);
fileInfo.setText("");
sound.play(sound.getFx8());
counter.setText("Cells: ");
}
/**
* EventHandler: "Select Grid size" MenuButton
*/
@FXML
private void handleGridSizeEvents() {
stopAnimationIfRunning();
largest.setOnAction(e -> {
resetBoard();
board = new DynamicBoard(104,160);
config.setDefault();
draw.drawBoard(board.getGrid());
});
large.setOnAction(e -> {
resetBoard();
board = new DynamicBoard(35,54);
config.setCellSize(15);
draw.drawBoard(board.getGrid());
});
medium.setOnAction(e -> {
resetBoard();
board = new DynamicBoard(17,27);
config.setCellSize(31);
draw.drawBoard(board.getGrid());
});
small.setOnAction(e -> {
resetBoard();
board = new DynamicBoard(13,20);
config.setCellSize(40);
draw.drawBoard(board.getGrid());
});
}
/**
* EventHandler/Listener: "Zoom slider". Handle the slider listener.
*/
private void handleZoomSlider() {
zoomSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
canvas.setScaleX(newValue.intValue());
canvas.setScaleY(newValue.intValue());
});
}
/**
* EventHandler: "Sound icon". Toggle sound.
*/
private void handleToggleSound() {
toggleSound.setOnAction(e -> {
if (toggleSound.isSelected()) {
sound.play(sound.getPop3());
sound.setVol(0.0);
} else {
sound.setVol(0.2);
sound.play(sound.getPop1());
}
});
}
/**
* EventHandler: "Play/Stop Button".
* Toggle animation, change buttonText and play a one shot sound when triggered.
*/
private void togglePlay() {
play.setOnAction((event -> {
if (timeline.getStatus() == Animation.Status.RUNNING) {
timeline.stop();
play.setText("Play");
sound.play(sound.getPop2());
} else if (timeline.getStatus() == Animation.Status.STOPPED) {
timeline.play();
play.setText("Stop");
sound.play(sound.getPop1());
}
}));
}
/**
* Event Handler "Zoom icon". Flip max/min zoom values.
*/
@FXML
public void flipZoom() {
zoomIcon.setOnMouseClicked(event -> {
if (event.getClickCount() == 1) {
zoomSlider.setValue(3);
} else if (event.getClickCount() == 2) {
zoomSlider.setValue(1);
}
});
}
/**
* Event Handler: "Speed icon". Flip max/min animation rate
*/
@FXML
public void flipSpeed() {
speedIcon.setOnMouseClicked(event -> {
if (event.getClickCount() == 1) {
speedSlider.setValue(speedSlider.getMax());
} else if (event.getClickCount() == 2) {
speedSlider.setValue(speedSlider.getMin());
}
});
}
//================================================================================
// Functions related to Mouse events
//================================================================================
/**
* EventHandler:
* <p>
* This method handle Cell coordinates of canvas by mouseEvents and the Logic of placing cells
* correct on the screen and sceneGraph node canvas.
* <p>
* Draw, erase, and toggle cells in editor by MouseGestures:
* <p>
* Drag: Draw cells.
* LeftClick : Toggle Cell alive / Dead.
* DoubleClick (Hold button and Move support): Erase one or multiple Cells.
*
* @param event MouseEvent
*/
@FXML
public void handleMouseEvent(MouseEvent event) {
try {
double x = event.getX(); // mouse x pos
double y = event.getY(); // mouse y pos
// Find Cell position in board Cell drawBoard array
int cellPosX = (int) Math.floor(x / config.getCellSize());
int cellPosY = (int) Math.floor(y / config.getCellSize());
// Get Cell
Cell cell = board.getCell(cellPosX, cellPosY);
// Toggle alive
boolean toggleState = !cell.getState();
// For smooth drawing
if (toggleState) {
cell.setState(toggleState);
}
// Double click and drag to smooth erase
if (event.getClickCount() > 1) {
toggleState = false;
cell.setState(toggleState);
}
draw.drawCell(cell);
} catch (NullPointerException ne) {
// Do nothing!
}
}
//================================================================================
// Methods related to Graphics and Color settings
//================================================================================
/**
* This method returns the Canvas graphicsContext(Helper method for Draw calls).
*
* @return GraphicContext
*/
private GraphicsContext getContext() {
context = canvas.getGraphicsContext2D();
return context;
}
/**
* EventHandler: "ColorPicker Cell". Set cell-color from ColorPicker.
*/
@FXML
public void setCellColor() {
colors.setCell(cpCell.getValue());
draw.drawBoard(board.getGrid());
updateColorPickerValues();
}
/**
* EventHandler: "ColorPicker Grid". Set grid-color from ColorPicker.
*/
@FXML
public void setGridColor() {
colors.setGridLine(cpGrid.getValue());
draw.drawBoard(board.getGrid());
updateColorPickerValues();
}
/**
* EventHandler: "ColorPicker: Background". Set background-color from ColorPicker.
*/
@FXML
public void setBackgroundColor() {
colors.setBackground(cpBackground.getValue());
draw.drawBoard(board.getGrid());
updateColorPickerValues();
}
/**
* EventHandler: "Random color" menu-button. Set random colors to Cells, GridLine and Background.
*/
@FXML
public void setRandomColor() {
Random rand = new Random();
int b = 255; // int bounder
Color cell = Color.rgb(rand.nextInt(b), rand.nextInt(b), rand.nextInt(b));
Color grid = Color.rgb(rand.nextInt(b), rand.nextInt(b), rand.nextInt(b));
Color background = Color.rgb(rand.nextInt(b), rand.nextInt(b), rand.nextInt(b));
// Set Random colors
colors.setCell(cell);
colors.setGridLine(grid);
colors.setBackground(background);
updateColorPickerValues();
draw.drawBoard(board.getGrid());
sound.play(sound.getFx2());
}
/**
* EventHandler: "Reset color" menu-button. Reset all colors to default settings.
*/
@FXML
public void resetColor() {
colors.resetAll();
updateColorPickerValues();
draw.drawBoard(board.getGrid());
try {
sound.play(sound.getFx8());
} catch (MediaException me) {
dialog.audioError();
}
}
/**
* This method updates the colorPicker widget values.
*/
private void updateColorPickerValues() {
cpCell.setValue(colors.getCell());
cpBackground.setValue(colors.getBackground());
cpGrid.setValue(colors.getGridLine());
}
//================================================================================
// Functions related to the MenuBar-buttons and Information Dialogs
//================================================================================
/**
* EventHandler: "FileInfo". Shows the dialog box with the loaded file information.
*/
@FXML
public void showFileInfo() {
dialog.fileInfo();
}
/**
*
* EventHandler: "Info" menu-button. Show information dialog box when info button is clicked.
*/
@FXML
public void showInfo() {
dialog.showInfo();
}
/**
*
* EventHandler: "About Game Of Life" menu-button. Show information dialog box with Game of Life rules and description.
*/
@FXML
public void aboutGameOfLife() {
dialog.aboutGol();
}
/**
* EventHandler: "How to play" menu-button. Show information dialog box about how to play the game.
*/
@FXML
public void howToPlay() {
dialog.howToPlay();
}
/**
* EventHandler: "Quit" menu-button". Exit the application.
*/
@FXML
public void quit() {
try {
sound.play(sound.getFx3());
} catch (MediaException me) {
dialog.audioError();
}
Platform.exit();
}
}
| 24,582 | 0.56283 | 0.558032 | 744 | 32.051075 | 27.709711 | 123 | false | false | 0 | 0 | 0 | 0 | 84 | 0.04754 | 0.462366 | false | false |
3
|
4e9f918f00ff0a1401293dbfd80fe9e932845b54
| 31,086,973,308,546 |
62d7001e9991e8d8cfa08612a02b5a96cb867248
|
/reveno-core/src/main/java/org/reveno/atp/core/EngineEventsContext.java
|
95dcbc50f55caab6884fcd76af877bdfd7d28e5a
|
[
"Apache-2.0"
] |
permissive
|
ulwfcyvi791837060/reveno
|
https://github.com/ulwfcyvi791837060/reveno
|
b12610fd45e162b0c7fd2d76d6722f23cb72388f
|
ecbf6ebcbf2966e989fe5cd50b76c4efa23758aa
|
refs/heads/master
| 2020-08-28T08:43:55.851000 | 2019-10-27T14:49:51 | 2019-10-27T14:49:51 | 217,652,488 | 0 | 0 |
Apache-2.0
| true | 2019-10-26T03:50:14 | 2019-10-26T03:50:14 | 2019-10-24T02:18:31 | 2019-06-04T06:16:59 | 1,350 | 0 | 0 | 0 | null | false | false |
package org.reveno.atp.core;
import org.reveno.atp.core.api.EventsCommitInfo.Builder;
import org.reveno.atp.core.api.Journaler;
import org.reveno.atp.core.api.serialization.EventsInfoSerializer;
import org.reveno.atp.core.events.EventHandlersManager;
import org.reveno.atp.core.events.EventsContext;
public class EngineEventsContext implements EventsContext {
private Journaler eventsJournaler;
private Builder eventsCommitBuilder;
private EventsInfoSerializer serializer;
private EventHandlersManager manager;
@Override
public Journaler eventsJournaler() {
return eventsJournaler;
}
public EngineEventsContext eventsJournaler(Journaler eventsJournaler) {
this.eventsJournaler = eventsJournaler;
return this;
}
@Override
public Builder eventsCommitBuilder() {
return eventsCommitBuilder;
}
public EngineEventsContext eventsCommitBuilder(Builder eventsCommitBuilder) {
this.eventsCommitBuilder = eventsCommitBuilder;
return this;
}
@Override
public EventsInfoSerializer serializer() {
return serializer;
}
public EngineEventsContext serializer(EventsInfoSerializer serializer) {
this.serializer = serializer;
return this;
}
@Override
public EventHandlersManager manager() {
return manager;
}
public EngineEventsContext manager(EventHandlersManager manager) {
this.manager = manager;
return this;
}
}
|
UTF-8
|
Java
| 1,501 |
java
|
EngineEventsContext.java
|
Java
|
[] | null |
[] |
package org.reveno.atp.core;
import org.reveno.atp.core.api.EventsCommitInfo.Builder;
import org.reveno.atp.core.api.Journaler;
import org.reveno.atp.core.api.serialization.EventsInfoSerializer;
import org.reveno.atp.core.events.EventHandlersManager;
import org.reveno.atp.core.events.EventsContext;
public class EngineEventsContext implements EventsContext {
private Journaler eventsJournaler;
private Builder eventsCommitBuilder;
private EventsInfoSerializer serializer;
private EventHandlersManager manager;
@Override
public Journaler eventsJournaler() {
return eventsJournaler;
}
public EngineEventsContext eventsJournaler(Journaler eventsJournaler) {
this.eventsJournaler = eventsJournaler;
return this;
}
@Override
public Builder eventsCommitBuilder() {
return eventsCommitBuilder;
}
public EngineEventsContext eventsCommitBuilder(Builder eventsCommitBuilder) {
this.eventsCommitBuilder = eventsCommitBuilder;
return this;
}
@Override
public EventsInfoSerializer serializer() {
return serializer;
}
public EngineEventsContext serializer(EventsInfoSerializer serializer) {
this.serializer = serializer;
return this;
}
@Override
public EventHandlersManager manager() {
return manager;
}
public EngineEventsContext manager(EventHandlersManager manager) {
this.manager = manager;
return this;
}
}
| 1,501 | 0.728847 | 0.728847 | 54 | 26.796297 | 23.678698 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false |
3
|
094746aa41e7a6ff1d34471c393f937b941f8a41
| 32,203,664,817,670 |
be3ecbb5f4b545c1d43e31ef48155ba9e08baf88
|
/backend/week1-4/Darleen1/src/com/yl/BookList.java
|
63fe0a9a1b71820e32606e2496e7b900b4495a40
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Darleen1/TechMap-Works
|
https://github.com/Darleen1/TechMap-Works
|
a18135b212fd67017875b8e209be95fac434cc81
|
2c4f37ce38752f5a28a0b88daa4e4cbef79d47dd
|
refs/heads/master
| 2020-05-19T02:28:28.679000 | 2019-05-20T14:35:05 | 2019-05-20T14:35:05 | 184,781,842 | 0 | 0 |
NOASSERTION
| true | 2019-05-21T09:18:14 | 2019-05-03T15:46:44 | 2019-05-20T14:39:14 | 2019-05-20T14:39:12 | 13 | 0 | 0 | 0 |
Java
| false | false |
package com.yl;
import java.util.ArrayList;
public class BookList {
private String id;
private String name;
private String borrow;
public BookList(String id, String name, String borrow) {
super();
this.id = id;
this.name = name;
this.borrow = borrow;
}
public BookList() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getBorrow() {
return borrow;
}
public void setBorrow(String borrow) {
this.borrow = borrow;
}
public void main(String[] args) {
ArrayList bookArray;
bookArray = new ArrayList();
}
}
|
UTF-8
|
Java
| 842 |
java
|
BookList.java
|
Java
|
[] | null |
[] |
package com.yl;
import java.util.ArrayList;
public class BookList {
private String id;
private String name;
private String borrow;
public BookList(String id, String name, String borrow) {
super();
this.id = id;
this.name = name;
this.borrow = borrow;
}
public BookList() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getBorrow() {
return borrow;
}
public void setBorrow(String borrow) {
this.borrow = borrow;
}
public void main(String[] args) {
ArrayList bookArray;
bookArray = new ArrayList();
}
}
| 842 | 0.559382 | 0.559382 | 38 | 20.921053 | 13.189672 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
b9268524cd1d35cea7743c165fd334e03c9837f7
| 3,006,477,159,931 |
b1d2249f58c98730dc588612b0e43844ae6b0ed0
|
/Notepad.java
|
16992b9862588ebdc82f8e3df25fbf0674a3eb66
|
[] |
no_license
|
0909023/project_4_app
|
https://github.com/0909023/project_4_app
|
783c66d6d4130bc4678be6d3b851022c7c8837af
|
650b8d5812c9c0f357d95874050a3ce17e98ded8
|
refs/heads/master
| 2017-12-01T03:06:04.008000 | 2016-07-07T13:38:59 | 2016-07-07T13:38:59 | 61,535,577 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.alexandra.myapplication.Misc;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.alexandra.myapplication.Activities.MenuActivity;
import com.example.alexandra.myapplication.R;
import java.io.File;
public class Notepad extends MenuActivity {
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notepad);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
CheckLocationPermission();
// check if GPS enabled
final GPSTracker gpsTracker = new GPSTracker(this);
gpsTracker.updateGPSCoordinates();
Button mapButton = (Button) findViewById(R.id.button);
mapButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final GPSTracker gpsTracker = new GPSTracker(Notepad.this);
gpsTracker.updateGPSCoordinates();
gpsTracker.getGeocoderAddress(Notepad.this);
Log.d("it works", "fine");
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView) findViewById(R.id.fieldLatitude);
textview.setText("Latitude:" + stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
textview = (TextView) findViewById(R.id.fieldLongitude);
textview.setText("Longitude: "+ stringLongitude);
String country = gpsTracker.getCountryName(Notepad.this);
textview = (TextView)findViewById(R.id.fieldCountry);
textview.setText("Country: "+ country);
// String city = gpsTracker.getLocality(Notepad.this);
// textview = (TextView)findViewById(R.id.fieldCity);
// textview.setText(city);
//
// String postalCode = gpsTracker.getPostalCode(Notepad.this);
// textview = (TextView)findViewById(R.id.fieldPostalCode);
// textview.setText(postalCode);
String addressLine = gpsTracker.getAddressLine(Notepad.this);
textview = (TextView)findViewById(R.id.fieldAddressLine);
textview.setText("Adress line: "+ addressLine);
//gpsTracker.updateGPSCoordinates();
gpsTracker.generateNoteOnSD(Notepad.this, "location.txt", ""+ "Latitude: "+ stringLatitude +"\n" + "Longitude " + stringLongitude + "\n" + "link: http://maps.google.com/maps?q="+ stringLatitude+ ","+stringLongitude + "\n " + addressLine+ "\n" + country);
}
});
Button dButton = (Button) findViewById(R.id.deleteButton);
dButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bikefacts/location.txt");
boolean deleted = root.delete();
Toast.makeText(Notepad.this, "Deleted", Toast.LENGTH_SHORT).show();
}
});
if (gpsTracker.getIsGPSTrackingEnabled())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView) findViewById(R.id.fieldLatitude);
textview.setText("Latitude:" + stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
textview = (TextView) findViewById(R.id.fieldLongitude);
textview.setText("Longitude: "+ stringLongitude);
String country = gpsTracker.getCountryName(Notepad.this);
textview = (TextView)findViewById(R.id.fieldCountry);
textview.setText("Country: "+ country);
// String city = gpsTracker.getLocality(this);
// textview = (TextView)findViewById(R.id.fieldCity);
// textview.setText(city);
//
// String postalCode = gpsTracker.getPostalCode(this);
// textview = (TextView)findViewById(R.id.fieldPostalCode);
// textview.setText(postalCode);
String addressLine = gpsTracker.getAddressLine(Notepad.this);
textview = (TextView)findViewById(R.id.fieldAddressLine);
textview.setText("Adress line: "+ addressLine);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public boolean CheckLocationPermission()
{
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
}
|
UTF-8
|
Java
| 6,151 |
java
|
Notepad.java
|
Java
|
[] | null |
[] |
package com.example.alexandra.myapplication.Misc;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.alexandra.myapplication.Activities.MenuActivity;
import com.example.alexandra.myapplication.R;
import java.io.File;
public class Notepad extends MenuActivity {
TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notepad);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
CheckLocationPermission();
// check if GPS enabled
final GPSTracker gpsTracker = new GPSTracker(this);
gpsTracker.updateGPSCoordinates();
Button mapButton = (Button) findViewById(R.id.button);
mapButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final GPSTracker gpsTracker = new GPSTracker(Notepad.this);
gpsTracker.updateGPSCoordinates();
gpsTracker.getGeocoderAddress(Notepad.this);
Log.d("it works", "fine");
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView) findViewById(R.id.fieldLatitude);
textview.setText("Latitude:" + stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
textview = (TextView) findViewById(R.id.fieldLongitude);
textview.setText("Longitude: "+ stringLongitude);
String country = gpsTracker.getCountryName(Notepad.this);
textview = (TextView)findViewById(R.id.fieldCountry);
textview.setText("Country: "+ country);
// String city = gpsTracker.getLocality(Notepad.this);
// textview = (TextView)findViewById(R.id.fieldCity);
// textview.setText(city);
//
// String postalCode = gpsTracker.getPostalCode(Notepad.this);
// textview = (TextView)findViewById(R.id.fieldPostalCode);
// textview.setText(postalCode);
String addressLine = gpsTracker.getAddressLine(Notepad.this);
textview = (TextView)findViewById(R.id.fieldAddressLine);
textview.setText("Adress line: "+ addressLine);
//gpsTracker.updateGPSCoordinates();
gpsTracker.generateNoteOnSD(Notepad.this, "location.txt", ""+ "Latitude: "+ stringLatitude +"\n" + "Longitude " + stringLongitude + "\n" + "link: http://maps.google.com/maps?q="+ stringLatitude+ ","+stringLongitude + "\n " + addressLine+ "\n" + country);
}
});
Button dButton = (Button) findViewById(R.id.deleteButton);
dButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bikefacts/location.txt");
boolean deleted = root.delete();
Toast.makeText(Notepad.this, "Deleted", Toast.LENGTH_SHORT).show();
}
});
if (gpsTracker.getIsGPSTrackingEnabled())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
textview = (TextView) findViewById(R.id.fieldLatitude);
textview.setText("Latitude:" + stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
textview = (TextView) findViewById(R.id.fieldLongitude);
textview.setText("Longitude: "+ stringLongitude);
String country = gpsTracker.getCountryName(Notepad.this);
textview = (TextView)findViewById(R.id.fieldCountry);
textview.setText("Country: "+ country);
// String city = gpsTracker.getLocality(this);
// textview = (TextView)findViewById(R.id.fieldCity);
// textview.setText(city);
//
// String postalCode = gpsTracker.getPostalCode(this);
// textview = (TextView)findViewById(R.id.fieldPostalCode);
// textview.setText(postalCode);
String addressLine = gpsTracker.getAddressLine(Notepad.this);
textview = (TextView)findViewById(R.id.fieldAddressLine);
textview.setText("Adress line: "+ addressLine);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public boolean CheckLocationPermission()
{
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
}
| 6,151 | 0.608519 | 0.607543 | 164 | 35.506096 | 35.675621 | 270 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548781 | false | false |
3
|
673a266a43b4d38120d3d6eb56a2a225f943f086
| 3,006,477,158,417 |
e4bd1d497ac06af8c2b20c414114bdba3a9cdced
|
/src/test/java/com/example/cryptogramgamewithspring/Controllers/GameplayControllerTests.java
|
f1317f43c7421e4f42dad9a9e84af74b6f1c1ea0
|
[] |
no_license
|
pcich42/CryptogramsSpringBoot
|
https://github.com/pcich42/CryptogramsSpringBoot
|
9124957beed0101e6cdc054681576db118dd1c8f
|
38d2314265f842b93ef124bffb5fe4e0ae01c4e4
|
refs/heads/main
| 2023-05-14T10:59:20.001000 | 2021-06-01T21:34:58 | 2021-06-01T21:34:58 | 366,531,752 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.cryptogramgamewithspring.Controllers;
import com.example.cryptogramgamewithspring.Controllers.Commands.Command;
import com.example.cryptogramgamewithspring.Controllers.Commands.CommandSupplier.CommandSupplier;
import com.example.cryptogramgamewithspring.Controllers.Commands.CommandSupplier.GameContext;
import com.example.cryptogramgamewithspring.Cryptogram.Cryptogram;
import com.example.cryptogramgamewithspring.Player.Player;
import com.example.cryptogramgamewithspring.Presentation.ConsoleView;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.*;
import static uk.org.webcompere.systemstubs.SystemStubs.tapSystemOut;
import static uk.org.webcompere.systemstubs.SystemStubs.withTextFromSystemIn;
@ExtendWith(MockitoExtension.class)
public class GameplayControllerTests {
@Mock
private ConsoleView mockView;
@Mock
private Cryptogram cryptogram;
@Mock
private Player player;
@Mock
private CommandSupplier<GameContext> commandSupplier;
private GameplayController gameplay;
@BeforeEach
void setUp() {
gameplay = new GameplayController(commandSupplier, mockView, cryptogram, player);
}
@Test
void whenUserTypesInExit_GameExits() throws Exception {
String[] inputExit = {"exit"};
willCallRealMethod().given(mockView).displayMessage(anyString());
given(mockView.getInput())
.willReturn(inputExit);
withTextFromSystemIn(inputExit)
.execute(() -> {
String output = tapSystemOut(gameplay::mainLoop);
assertEquals(">>>>> Type help to list all available commands.\n" +
"\n" +
">>>>> Please enter a mapping in format <letter><space><cryptogram value>:\n" +
"\n",
output);
});
}
@Test
void givenMenuIsRunning_WhenUserInputsACommandWithArguments_CommandIsExecuted(@Mock Command command1) throws Exception {
String[] input = {"command", "argument"};
String[] exitInput = {"exit"};
willCallRealMethod().given(mockView).displayMessage(anyString());
given(mockView.getInput())
.willReturn(input)
.willReturn(exitInput);
will((invocationOnMock -> {
Arrays.stream(input).forEach(System.out::println);
return null;
})).given(command1).execute();
given(commandSupplier.fetchCommand(any(), any()))
.willReturn(command1);
withTextFromSystemIn(input[0] + " " + input[1], exitInput[0])
.execute(() -> {
String output = tapSystemOut(gameplay::mainLoop);
assertEquals(
">>>>> Type help to list all available commands.\n" +
"\n" +
">>>>> Please enter a mapping in format <letter><space><cryptogram value>:\n" +
"\n" +
"command\n" +
"argument\n" +
">>>>> Type help to list all available commands.\n" +
"\n" +
">>>>> Please enter a mapping in format <letter><space><cryptogram value>:\n" +
"\n",
output);
});
}
@Test
void WhenUserInputsMultipleCommandsWithArguments_CommandsAreExecuted(@Mock Command command1,
@Mock Command command2,
@Mock Command command3
) throws Exception {
String[] inputOne = {"one", "argument_one"};
String[] inputTwo = {"two", "argument_two"};
String[] inputThree = {"three"};
String[] exitInput = {"exit"};
given(mockView.getInput())
.willReturn(inputOne)
.willReturn(inputTwo)
.willReturn(inputThree)
.willReturn(exitInput);
will((invocationOnMock -> {
System.out.println(inputOne[0] + " " + inputOne[1]);
return null;
})).given(command1).execute();
will((invocationOnMock -> {
System.out.println("command two performed successfully.");
return null;
})).given(command2).execute();
will((invocationOnMock -> {
System.out.println("What? You egg?");
return null;
})).given(command3).execute();
given(commandSupplier.fetchCommand(any(), any()))
.willReturn(command1)
.willReturn(command2)
.willReturn(command3);
willDoNothing().given(mockView).displayMessage(anyString());
withTextFromSystemIn(
String.join(" ", inputOne),
String.join(" ", inputTwo),
inputThree[0],
exitInput[0])
.execute(() -> {
String output = tapSystemOut(gameplay::mainLoop);
assertEquals("one argument_one\n" +
"command two performed successfully.\n" +
"What? You egg?\n",
output);
});
}
}
|
UTF-8
|
Java
| 5,846 |
java
|
GameplayControllerTests.java
|
Java
|
[] | null |
[] |
package com.example.cryptogramgamewithspring.Controllers;
import com.example.cryptogramgamewithspring.Controllers.Commands.Command;
import com.example.cryptogramgamewithspring.Controllers.Commands.CommandSupplier.CommandSupplier;
import com.example.cryptogramgamewithspring.Controllers.Commands.CommandSupplier.GameContext;
import com.example.cryptogramgamewithspring.Cryptogram.Cryptogram;
import com.example.cryptogramgamewithspring.Player.Player;
import com.example.cryptogramgamewithspring.Presentation.ConsoleView;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.*;
import static uk.org.webcompere.systemstubs.SystemStubs.tapSystemOut;
import static uk.org.webcompere.systemstubs.SystemStubs.withTextFromSystemIn;
@ExtendWith(MockitoExtension.class)
public class GameplayControllerTests {
@Mock
private ConsoleView mockView;
@Mock
private Cryptogram cryptogram;
@Mock
private Player player;
@Mock
private CommandSupplier<GameContext> commandSupplier;
private GameplayController gameplay;
@BeforeEach
void setUp() {
gameplay = new GameplayController(commandSupplier, mockView, cryptogram, player);
}
@Test
void whenUserTypesInExit_GameExits() throws Exception {
String[] inputExit = {"exit"};
willCallRealMethod().given(mockView).displayMessage(anyString());
given(mockView.getInput())
.willReturn(inputExit);
withTextFromSystemIn(inputExit)
.execute(() -> {
String output = tapSystemOut(gameplay::mainLoop);
assertEquals(">>>>> Type help to list all available commands.\n" +
"\n" +
">>>>> Please enter a mapping in format <letter><space><cryptogram value>:\n" +
"\n",
output);
});
}
@Test
void givenMenuIsRunning_WhenUserInputsACommandWithArguments_CommandIsExecuted(@Mock Command command1) throws Exception {
String[] input = {"command", "argument"};
String[] exitInput = {"exit"};
willCallRealMethod().given(mockView).displayMessage(anyString());
given(mockView.getInput())
.willReturn(input)
.willReturn(exitInput);
will((invocationOnMock -> {
Arrays.stream(input).forEach(System.out::println);
return null;
})).given(command1).execute();
given(commandSupplier.fetchCommand(any(), any()))
.willReturn(command1);
withTextFromSystemIn(input[0] + " " + input[1], exitInput[0])
.execute(() -> {
String output = tapSystemOut(gameplay::mainLoop);
assertEquals(
">>>>> Type help to list all available commands.\n" +
"\n" +
">>>>> Please enter a mapping in format <letter><space><cryptogram value>:\n" +
"\n" +
"command\n" +
"argument\n" +
">>>>> Type help to list all available commands.\n" +
"\n" +
">>>>> Please enter a mapping in format <letter><space><cryptogram value>:\n" +
"\n",
output);
});
}
@Test
void WhenUserInputsMultipleCommandsWithArguments_CommandsAreExecuted(@Mock Command command1,
@Mock Command command2,
@Mock Command command3
) throws Exception {
String[] inputOne = {"one", "argument_one"};
String[] inputTwo = {"two", "argument_two"};
String[] inputThree = {"three"};
String[] exitInput = {"exit"};
given(mockView.getInput())
.willReturn(inputOne)
.willReturn(inputTwo)
.willReturn(inputThree)
.willReturn(exitInput);
will((invocationOnMock -> {
System.out.println(inputOne[0] + " " + inputOne[1]);
return null;
})).given(command1).execute();
will((invocationOnMock -> {
System.out.println("command two performed successfully.");
return null;
})).given(command2).execute();
will((invocationOnMock -> {
System.out.println("What? You egg?");
return null;
})).given(command3).execute();
given(commandSupplier.fetchCommand(any(), any()))
.willReturn(command1)
.willReturn(command2)
.willReturn(command3);
willDoNothing().given(mockView).displayMessage(anyString());
withTextFromSystemIn(
String.join(" ", inputOne),
String.join(" ", inputTwo),
inputThree[0],
exitInput[0])
.execute(() -> {
String output = tapSystemOut(gameplay::mainLoop);
assertEquals("one argument_one\n" +
"command two performed successfully.\n" +
"What? You egg?\n",
output);
});
}
}
| 5,846 | 0.551659 | 0.548409 | 149 | 38.234898 | 28.65799 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.530201 | false | false |
3
|
193212b5ac9d2abc22aceb75a1ff5e1d3c9bd20a
| 19,808,389,202,671 |
6c9ae8655eb02b748515486579a1f4cd02e69f44
|
/fipzWorklog-core/src/main/java/com/fipz/common/LoggerAdapter.java
|
78285b3f7115f94228d286ded3858c1f7ad8a5bf
|
[] |
no_license
|
ZPF6/worklog
|
https://github.com/ZPF6/worklog
|
9cd35590a44f803f3578d7d0b123818bb49c0dea
|
8875d403dd8fb67d463de3a462be7447f73dea15
|
refs/heads/master
| 2018-01-15T05:11:59.881000 | 2016-10-06T06:49:41 | 2016-10-06T06:49:41 | 70,129,250 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.fipz.common;
/**
* @author 点钢 自引用的日志接口,用来对接其他的日志框架
*/
public interface LoggerAdapter {
public void info(String msg);
public void info(Throwable ex);
public void info(String msg, Throwable ex);
public void debug(String msg, Throwable ex);
public void debug(String msg);
public void debug(Throwable ex);
public void error(String msg, Throwable ex);
public void error(String msg);
public void error(Throwable ex);
public void warn(String msg);
public void warn(Throwable ex);
public void warn(String msg, Throwable ex);
}
|
UTF-8
|
Java
| 603 |
java
|
LoggerAdapter.java
|
Java
|
[
{
"context": "\npackage com.fipz.common;\n\n/**\n * @author 点钢 自引用的日志接口,用来对接其他的日志框架\n */\npublic interface LoggerA",
"end": 44,
"score": 0.7329092025756836,
"start": 42,
"tag": "USERNAME",
"value": "点钢"
}
] | null |
[] |
package com.fipz.common;
/**
* @author 点钢 自引用的日志接口,用来对接其他的日志框架
*/
public interface LoggerAdapter {
public void info(String msg);
public void info(Throwable ex);
public void info(String msg, Throwable ex);
public void debug(String msg, Throwable ex);
public void debug(String msg);
public void debug(Throwable ex);
public void error(String msg, Throwable ex);
public void error(String msg);
public void error(Throwable ex);
public void warn(String msg);
public void warn(Throwable ex);
public void warn(String msg, Throwable ex);
}
| 603 | 0.731664 | 0.731664 | 31 | 17 | 17.6763 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.935484 | false | false |
3
|
07b632339260a9053750e7dd77664aec710b0faf
| 14,053,133,026,878 |
78da53beded61a30e3cbd5761e5b13d9dad44101
|
/app/src/main/java/com/example/substandard/ui/model/SimilarArtistsViewModel.java
|
23cf90cdb2a45fd91ae8e21b40bbed95ae0ef57a
|
[] |
no_license
|
bboggess/substandard
|
https://github.com/bboggess/substandard
|
636a277dcebf22bea4d730d3b89de3b07c5e6934
|
2af1d7ac34060780867bdbb5c4f308677ab95aac
|
refs/heads/master
| 2021-07-04T08:26:44.357000 | 2021-01-15T16:35:02 | 2021-01-15T16:35:02 | 218,411,369 | 1 | 0 | null | false | 2020-01-31T16:36:10 | 2019-10-30T00:42:03 | 2020-01-29T03:22:52 | 2020-01-31T16:36:09 | 298 | 0 | 0 | 0 |
Java
| false | false |
package com.example.substandard.ui.model;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import com.example.substandard.database.SubsonicLibraryRepository;
import com.example.substandard.database.data.Artist;
import java.util.List;
public class SimilarArtistsViewModel extends ViewModel {
private final LiveData<List<Artist>> similarArtists;
private final SubsonicLibraryRepository repository;
SimilarArtistsViewModel(String artistId, SubsonicLibraryRepository repository) {
this.repository = repository;
this.similarArtists = repository.getSimilarArtists(artistId);
}
public LiveData<List<Artist>> getSimilarArtists() { return similarArtists; }
}
|
UTF-8
|
Java
| 716 |
java
|
SimilarArtistsViewModel.java
|
Java
|
[] | null |
[] |
package com.example.substandard.ui.model;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import com.example.substandard.database.SubsonicLibraryRepository;
import com.example.substandard.database.data.Artist;
import java.util.List;
public class SimilarArtistsViewModel extends ViewModel {
private final LiveData<List<Artist>> similarArtists;
private final SubsonicLibraryRepository repository;
SimilarArtistsViewModel(String artistId, SubsonicLibraryRepository repository) {
this.repository = repository;
this.similarArtists = repository.getSimilarArtists(artistId);
}
public LiveData<List<Artist>> getSimilarArtists() { return similarArtists; }
}
| 716 | 0.798883 | 0.798883 | 21 | 33.095238 | 28.994097 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
3
|
b8ba2413857201c9855d62f373f1dc2264d55f40
| 29,755,533,481,240 |
6f99a6b2711196e06fb8361665357bd92cd39e57
|
/app/src/main/java/pozzo/apps/javascriptautomator/model/BaseModel.java
|
9b41e8d155443230a2e012bc7fb126bc2a1d9562
|
[] |
no_license
|
Pozzoooo/JavascriptAutomator
|
https://github.com/Pozzoooo/JavascriptAutomator
|
b7eefe6b8ef0ad39e911d494c39df8d237c9cc99
|
df2b852f291498244edc1233f8722c11ed084983
|
refs/heads/master
| 2021-01-10T16:01:48.338000 | 2016-02-26T11:03:41 | 2016-02-26T11:03:41 | 50,146,261 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pozzo.apps.javascriptautomator.model;
import com.activeandroid.Model;
import com.splunk.mint.Mint;
import java.lang.reflect.Field;
/**
* Our baisc model.
*
* @author Luiz Gustavo Pozzo
* @since 30/01/2016
*/
public class BaseModel extends Model {
/**
* Bypass para setarmos o ID no ActiveAndroid.
*/
public void setId(Long mId) {
try {
Class clas = getClass().getSuperclass().getSuperclass();
while(!clas.getName().equals(Model.class.getName()))
clas = clas.getSuperclass();
Field mIdField = clas.getDeclaredField("mId");
mIdField.setAccessible(true);
mIdField.set(this, mId);
} catch (NoSuchFieldException e) {
//Estas duas excessoes nao devem ocorrer, jamais!
Mint.logException(e);
} catch (IllegalAccessException e) {
Mint.logException(e);
}
}
}
|
UTF-8
|
Java
| 810 |
java
|
BaseModel.java
|
Java
|
[
{
"context": "lect.Field;\n\n/**\n * Our baisc model.\n *\n * @author Luiz Gustavo Pozzo\n * @since 30/01/2016\n */\npublic class BaseModel e",
"end": 198,
"score": 0.9998856782913208,
"start": 180,
"tag": "NAME",
"value": "Luiz Gustavo Pozzo"
}
] | null |
[] |
package pozzo.apps.javascriptautomator.model;
import com.activeandroid.Model;
import com.splunk.mint.Mint;
import java.lang.reflect.Field;
/**
* Our baisc model.
*
* @author <NAME>
* @since 30/01/2016
*/
public class BaseModel extends Model {
/**
* Bypass para setarmos o ID no ActiveAndroid.
*/
public void setId(Long mId) {
try {
Class clas = getClass().getSuperclass().getSuperclass();
while(!clas.getName().equals(Model.class.getName()))
clas = clas.getSuperclass();
Field mIdField = clas.getDeclaredField("mId");
mIdField.setAccessible(true);
mIdField.set(this, mId);
} catch (NoSuchFieldException e) {
//Estas duas excessoes nao devem ocorrer, jamais!
Mint.logException(e);
} catch (IllegalAccessException e) {
Mint.logException(e);
}
}
}
| 798 | 0.698765 | 0.688889 | 35 | 22.142857 | 18.610508 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.542857 | false | false |
3
|
3cd3541abfac89a3765427dc7d85416ae41af6ba
| 15,144,054,724,919 |
d0b29bd26dacb886ab0b16a5463c14ea489a8095
|
/Problems/Convert to byte array/src/Main.java
|
88cbf5a55ebadb866f42623d44ee7020ebd99a32
|
[] |
no_license
|
bodyk59/Digit-Recognition
|
https://github.com/bodyk59/Digit-Recognition
|
bf4e61016dc15220e63343036d1a35a49ebfb5a3
|
1f17e4e4984559b9a76d2bca6eb94718dcd6edec
|
refs/heads/master
| 2021-02-10T12:55:09.664000 | 2020-05-31T18:44:59 | 2020-05-31T18:44:59 | 244,384,103 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
// The method is OK, no need to change it
public void writeWords(String[] words) throws IOException {
LetterPrinter printer = new LetterPrinter();
char[] letters = convert(words);
for (char letter : letters) {
printer.write(letter);
}
}
private char[] convert(String[] words) throws IOException {
String temp = "";
for (String string : words) {
temp += string;
}
return temp.toCharArray();
}
|
UTF-8
|
Java
| 442 |
java
|
Main.java
|
Java
|
[] | null |
[] |
// The method is OK, no need to change it
public void writeWords(String[] words) throws IOException {
LetterPrinter printer = new LetterPrinter();
char[] letters = convert(words);
for (char letter : letters) {
printer.write(letter);
}
}
private char[] convert(String[] words) throws IOException {
String temp = "";
for (String string : words) {
temp += string;
}
return temp.toCharArray();
}
| 442 | 0.635747 | 0.635747 | 19 | 22.31579 | 20.178291 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false |
3
|
1e5e11986c75562e7d5c429944677f3b1b7fef7d
| 21,208,548,569,857 |
936aa88990d1e478491aa66627b0263b5590aaa0
|
/Platform/mo-5-cloud/src/cloud-data/org/mo/cloud/data/statistics/FStatisticsFinancialAmountUnit.java
|
543c202a73d26db748f516ca579edf3d2a1c11e3
|
[] |
no_license
|
favedit/MoCloud3d
|
https://github.com/favedit/MoCloud3d
|
f6d417412c5686a0f043a2cc53cd34214ee35618
|
ef6116df5b66fbc16468bd5e915ba19bb982d867
|
refs/heads/master
| 2021-01-10T12:12:22.837000 | 2016-02-21T09:05:53 | 2016-02-21T09:05:53 | 48,077,310 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.mo.cloud.data.statistics;
import java.util.Map;
import org.mo.com.collections.FRow;
import org.mo.com.io.IDataInput;
import org.mo.com.io.IDataOutput;
import org.mo.com.lang.FFatalError;
import org.mo.com.lang.IStringPair;
import org.mo.com.lang.RBoolean;
import org.mo.com.lang.RDouble;
import org.mo.com.lang.RInteger;
import org.mo.com.lang.RLong;
import org.mo.com.lang.RString;
import org.mo.com.lang.reflect.RClass;
import org.mo.com.lang.type.TDateTime;
import org.mo.core.aop.face.ASourceMachine;
import org.mo.data.logic.FLogicUnit;
//============================================================
// <T>动态数据表逻辑单元。</T>
//============================================================
@ASourceMachine
public class FStatisticsFinancialAmountUnit
extends FLogicUnit
{
// 存储字段对象标识的定义。
private long __ouid;
// 字段对象标识的定义。
protected long _ouid;
// 存储字段有效性的定义。
private boolean __ovld;
// 字段有效性的定义。
protected boolean _ovld;
// 存储字段对象唯一标识的定义。
private String __guid;
// 字段对象唯一标识的定义。
protected String _guid;
// 存储字段关联编号的定义。
private long __linkId;
// 字段关联编号的定义。
protected long _linkId;
// 存储字段记录时间的定义。
private TDateTime __linkDate = new TDateTime();
// 字段记录时间的定义。
protected TDateTime _linkDate = new TDateTime();
// 存储字段部门总数的定义。
private int __departmentTotal;
// 字段部门总数的定义。
protected int _departmentTotal;
// 存储字段理财师总数的定义。
private int __marketerTotal;
// 字段理财师总数的定义。
protected int _marketerTotal;
// 存储字段客户总数的定义。
private int __customerTotal;
// 字段客户总数的定义。
protected int _customerTotal;
// 存储字段投资总金额的定义。
private double __investmentTotal;
// 字段投资总金额的定义。
protected double _investmentTotal;
// 存储字段投资总次数的定义。
private int __investmentNumberTotal;
// 字段投资总次数的定义。
protected int _investmentNumberTotal;
// 存储字段赎回总金额的定义。
private double __redemptionTotal;
// 字段赎回总金额的定义。
protected double _redemptionTotal;
// 存储字段赎回总次数的定义。
private int __redemptionNumberTotal;
// 字段赎回总次数的定义。
protected int _redemptionNumberTotal;
// 存储字段净投总金额的定义。
private double __netinvestmentTotal;
// 字段净投总金额的定义。
protected double _netinvestmentTotal;
// 存储字段利息总金额的定义。
private double __interestTotal;
// 字段利息总金额的定义。
protected double _interestTotal;
// 存储字段业绩总金额的定义。
private double __performanceTotal;
// 字段业绩总金额的定义。
protected double _performanceTotal;
// 存储字段创建用户标识的定义。
private long __createUserId;
// 字段创建用户标识的定义。
protected long _createUserId;
// 存储字段创建日期的定义。
private TDateTime __createDate = new TDateTime();
// 字段创建日期的定义。
protected TDateTime _createDate = new TDateTime();
// 存储字段更新者标识的定义。
private long __updateUserId;
// 字段更新者标识的定义。
protected long _updateUserId;
// 存储字段更新时间的定义。
private TDateTime __updateDate = new TDateTime();
// 字段更新时间的定义。
protected TDateTime _updateDate = new TDateTime();
//============================================================
// <T>构造动态数据表逻辑单元。</T>
//============================================================
public FStatisticsFinancialAmountUnit(){
}
//============================================================
// <T>判断对象标识的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isOuidChanged(){
return __ouid != _ouid;
}
//============================================================
// <T>获得对象标识的数据内容。</T>
//
// @return 数据内容
//============================================================
public long ouid(){
return _ouid;
}
//============================================================
// <T>设置对象标识的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setOuid(long value){
_ouid = value;
}
//============================================================
// <T>判断有效性的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isOvldChanged(){
return __ovld != _ovld;
}
//============================================================
// <T>获得有效性的数据内容。</T>
//
// @return 数据内容
//============================================================
public boolean ovld(){
return _ovld;
}
//============================================================
// <T>设置有效性的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setOvld(boolean value){
_ovld = value;
}
//============================================================
// <T>判断对象唯一标识的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isGuidChanged(){
return !RString.equals(__guid, _guid);
}
//============================================================
// <T>获得对象唯一标识的数据内容。</T>
//
// @return 数据内容
//============================================================
public String guid(){
return _guid;
}
//============================================================
// <T>设置对象唯一标识的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setGuid(String value){
_guid = value;
}
//============================================================
// <T>判断关联编号的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isLinkIdChanged(){
return __linkId != _linkId;
}
//============================================================
// <T>获得关联编号的数据内容。</T>
//
// @return 数据内容
//============================================================
public long linkId(){
return _linkId;
}
//============================================================
// <T>设置关联编号的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setLinkId(long value){
_linkId = value;
}
//============================================================
// <T>判断记录时间的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isLinkDateChanged(){
return !__linkDate.equals(_linkDate);
}
//============================================================
// <T>获得记录时间的数据内容。</T>
//
// @return 数据内容
//============================================================
public TDateTime linkDate(){
return _linkDate;
}
//============================================================
// <T>设置记录时间的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setLinkDate(TDateTime value){
_linkDate = value;
}
//============================================================
// <T>判断部门总数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isDepartmentTotalChanged(){
return __departmentTotal != _departmentTotal;
}
//============================================================
// <T>获得部门总数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int departmentTotal(){
return _departmentTotal;
}
//============================================================
// <T>设置部门总数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setDepartmentTotal(int value){
_departmentTotal = value;
}
//============================================================
// <T>判断理财师总数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isMarketerTotalChanged(){
return __marketerTotal != _marketerTotal;
}
//============================================================
// <T>获得理财师总数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int marketerTotal(){
return _marketerTotal;
}
//============================================================
// <T>设置理财师总数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setMarketerTotal(int value){
_marketerTotal = value;
}
//============================================================
// <T>判断客户总数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isCustomerTotalChanged(){
return __customerTotal != _customerTotal;
}
//============================================================
// <T>获得客户总数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int customerTotal(){
return _customerTotal;
}
//============================================================
// <T>设置客户总数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setCustomerTotal(int value){
_customerTotal = value;
}
//============================================================
// <T>判断投资总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isInvestmentTotalChanged(){
return __investmentTotal != _investmentTotal;
}
//============================================================
// <T>获得投资总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double investmentTotal(){
return _investmentTotal;
}
//============================================================
// <T>设置投资总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setInvestmentTotal(double value){
_investmentTotal = value;
}
//============================================================
// <T>判断投资总次数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isInvestmentNumberTotalChanged(){
return __investmentNumberTotal != _investmentNumberTotal;
}
//============================================================
// <T>获得投资总次数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int investmentNumberTotal(){
return _investmentNumberTotal;
}
//============================================================
// <T>设置投资总次数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setInvestmentNumberTotal(int value){
_investmentNumberTotal = value;
}
//============================================================
// <T>判断赎回总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isRedemptionTotalChanged(){
return __redemptionTotal != _redemptionTotal;
}
//============================================================
// <T>获得赎回总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double redemptionTotal(){
return _redemptionTotal;
}
//============================================================
// <T>设置赎回总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setRedemptionTotal(double value){
_redemptionTotal = value;
}
//============================================================
// <T>判断赎回总次数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isRedemptionNumberTotalChanged(){
return __redemptionNumberTotal != _redemptionNumberTotal;
}
//============================================================
// <T>获得赎回总次数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int redemptionNumberTotal(){
return _redemptionNumberTotal;
}
//============================================================
// <T>设置赎回总次数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setRedemptionNumberTotal(int value){
_redemptionNumberTotal = value;
}
//============================================================
// <T>判断净投总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isNetinvestmentTotalChanged(){
return __netinvestmentTotal != _netinvestmentTotal;
}
//============================================================
// <T>获得净投总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double netinvestmentTotal(){
return _netinvestmentTotal;
}
//============================================================
// <T>设置净投总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setNetinvestmentTotal(double value){
_netinvestmentTotal = value;
}
//============================================================
// <T>判断利息总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isInterestTotalChanged(){
return __interestTotal != _interestTotal;
}
//============================================================
// <T>获得利息总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double interestTotal(){
return _interestTotal;
}
//============================================================
// <T>设置利息总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setInterestTotal(double value){
_interestTotal = value;
}
//============================================================
// <T>判断业绩总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isPerformanceTotalChanged(){
return __performanceTotal != _performanceTotal;
}
//============================================================
// <T>获得业绩总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double performanceTotal(){
return _performanceTotal;
}
//============================================================
// <T>设置业绩总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setPerformanceTotal(double value){
_performanceTotal = value;
}
//============================================================
// <T>判断创建用户标识的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isCreateUserIdChanged(){
return __createUserId != _createUserId;
}
//============================================================
// <T>获得创建用户标识的数据内容。</T>
//
// @return 数据内容
//============================================================
public long createUserId(){
return _createUserId;
}
//============================================================
// <T>设置创建用户标识的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setCreateUserId(long value){
_createUserId = value;
}
//============================================================
// <T>判断创建日期的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isCreateDateChanged(){
return !__createDate.equals(_createDate);
}
//============================================================
// <T>获得创建日期的数据内容。</T>
//
// @return 数据内容
//============================================================
public TDateTime createDate(){
return _createDate;
}
//============================================================
// <T>设置创建日期的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setCreateDate(TDateTime value){
_createDate = value;
}
//============================================================
// <T>判断更新者标识的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isUpdateUserIdChanged(){
return __updateUserId != _updateUserId;
}
//============================================================
// <T>获得更新者标识的数据内容。</T>
//
// @return 数据内容
//============================================================
public long updateUserId(){
return _updateUserId;
}
//============================================================
// <T>设置更新者标识的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setUpdateUserId(long value){
_updateUserId = value;
}
//============================================================
// <T>判断更新时间的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isUpdateDateChanged(){
return !__updateDate.equals(_updateDate);
}
//============================================================
// <T>获得更新时间的数据内容。</T>
//
// @return 数据内容
//============================================================
public TDateTime updateDate(){
return _updateDate;
}
//============================================================
// <T>设置更新时间的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setUpdateDate(TDateTime value){
_updateDate = value;
}
//============================================================
// <T>根据名称获得内容。</T>
//
// @param name 名称
// @return 内容
//============================================================
@Override
public String get(String name){
switch(name){
case "ouid":
return Long.toString(_ouid);
case "ovld":
return RBoolean.toString(_ovld);
case "guid":
return _guid;
case "link_id":
return Long.toString(_linkId);
case "link_date":
return _linkDate.toString();
case "department_total":
return RInteger.toString(_departmentTotal);
case "marketer_total":
return RInteger.toString(_marketerTotal);
case "customer_total":
return RInteger.toString(_customerTotal);
case "investment_total":
return RDouble.toString(_investmentTotal);
case "investment_number_total":
return RInteger.toString(_investmentNumberTotal);
case "redemption_total":
return RDouble.toString(_redemptionTotal);
case "redemption_number_total":
return RInteger.toString(_redemptionNumberTotal);
case "netinvestment_total":
return RDouble.toString(_netinvestmentTotal);
case "interest_total":
return RDouble.toString(_interestTotal);
case "performance_total":
return RDouble.toString(_performanceTotal);
case "create_user_id":
return Long.toString(_createUserId);
case "create_date":
return _createDate.toString();
case "update_user_id":
return Long.toString(_updateUserId);
case "update_date":
return _updateDate.toString();
}
return null;
}
//============================================================
// <T>根据名称设置内容。</T>
//
// @param name 名称
// @param value 内容
//============================================================
@Override
public void set(String name,
String value){
switch(name){
case "ouid":
_ouid = RLong.parse(value);
break;
case "ovld":
_ovld = RBoolean.parse(value);
break;
case "guid":
_guid = value;
break;
case "link_id":
_linkId = RLong.parse(value);
break;
case "link_date":
_linkDate.parse(value);
break;
case "department_total":
_departmentTotal = RInteger.parse(value);
break;
case "marketer_total":
_marketerTotal = RInteger.parse(value);
break;
case "customer_total":
_customerTotal = RInteger.parse(value);
break;
case "investment_total":
_investmentTotal = RDouble.parse(value);
break;
case "investment_number_total":
_investmentNumberTotal = RInteger.parse(value);
break;
case "redemption_total":
_redemptionTotal = RDouble.parse(value);
break;
case "redemption_number_total":
_redemptionNumberTotal = RInteger.parse(value);
break;
case "netinvestment_total":
_netinvestmentTotal = RDouble.parse(value);
break;
case "interest_total":
_interestTotal = RDouble.parse(value);
break;
case "performance_total":
_performanceTotal = RDouble.parse(value);
break;
case "create_user_id":
_createUserId = RLong.parse(value);
break;
case "create_date":
_createDate.parse(value);
break;
case "update_user_id":
_updateUserId = RLong.parse(value);
break;
case "update_date":
_updateDate.parse(value);
break;
}
}
//============================================================
// <T>加载行记录。</T>
//
// @param row 行记录
//============================================================
@Override
public void load(FRow row){
super.load(row);
for(IStringPair pair : row){
// 获得名称
String name = pair.name();
if(RString.isEmpty(name)){
throw new FFatalError("Row format is invalid. (row={1})", row.dump());
}
// 获得内容
String value = pair.value();
// 设置内容
switch(name){
case "ouid":
__ouid = RLong.parse(value);
_ouid = __ouid;
break;
case "ovld":
__ovld = RBoolean.parse(value);
_ovld = __ovld;
break;
case "guid":
__guid = value;
_guid = __guid;
break;
case "link_id":
__linkId = RLong.parse(value);
_linkId = __linkId;
break;
case "link_date":
__linkDate.parse(value);
_linkDate.assign(__linkDate);
break;
case "department_total":
__departmentTotal = RInteger.parse(value);
_departmentTotal = __departmentTotal;
break;
case "marketer_total":
__marketerTotal = RInteger.parse(value);
_marketerTotal = __marketerTotal;
break;
case "customer_total":
__customerTotal = RInteger.parse(value);
_customerTotal = __customerTotal;
break;
case "investment_total":
__investmentTotal = RDouble.parse(value);
_investmentTotal = __investmentTotal;
break;
case "investment_number_total":
__investmentNumberTotal = RInteger.parse(value);
_investmentNumberTotal = __investmentNumberTotal;
break;
case "redemption_total":
__redemptionTotal = RDouble.parse(value);
_redemptionTotal = __redemptionTotal;
break;
case "redemption_number_total":
__redemptionNumberTotal = RInteger.parse(value);
_redemptionNumberTotal = __redemptionNumberTotal;
break;
case "netinvestment_total":
__netinvestmentTotal = RDouble.parse(value);
_netinvestmentTotal = __netinvestmentTotal;
break;
case "interest_total":
__interestTotal = RDouble.parse(value);
_interestTotal = __interestTotal;
break;
case "performance_total":
__performanceTotal = RDouble.parse(value);
_performanceTotal = __performanceTotal;
break;
case "create_user_id":
__createUserId = RLong.parse(value);
_createUserId = __createUserId;
break;
case "create_date":
__createDate.parse(value);
_createDate.assign(__createDate);
break;
case "update_user_id":
__updateUserId = RLong.parse(value);
_updateUserId = __updateUserId;
break;
case "update_date":
__updateDate.parse(value);
_updateDate.assign(__updateDate);
break;
}
}
}
//============================================================
// <T>存储行记录。</T>
//
// @param row 行记录
//============================================================
@Override
public void save(FRow row){
super.load(row);
row.set("ouid", _ouid);
row.set("ovld", _ovld);
row.set("guid", _guid);
row.set("linkId", _linkId);
row.set("linkDate", _linkDate);
row.set("departmentTotal", _departmentTotal);
row.set("marketerTotal", _marketerTotal);
row.set("customerTotal", _customerTotal);
row.set("investmentTotal", _investmentTotal);
row.set("investmentNumberTotal", _investmentNumberTotal);
row.set("redemptionTotal", _redemptionTotal);
row.set("redemptionNumberTotal", _redemptionNumberTotal);
row.set("netinvestmentTotal", _netinvestmentTotal);
row.set("interestTotal", _interestTotal);
row.set("performanceTotal", _performanceTotal);
row.set("createUserId", _createUserId);
row.set("createDate", _createDate);
row.set("updateUserId", _updateUserId);
row.set("updateDate", _updateDate);
}
//============================================================
// <T>保存对照表。</T>
//
// @param map 对照表
//============================================================
@Override
public void saveMap(Map<String, String> map){
super.saveMap(map);
map.put("ouid", RLong.toString(_ouid));
map.put("ovld", RBoolean.toString(_ovld));
map.put("guid", _guid);
map.put("linkId", RLong.toString(_linkId));
map.put("linkDate", _linkDate.format("YYYY-MM-DD HH24:MI:SS"));
map.put("departmentTotal", RInteger.toString(_departmentTotal));
map.put("marketerTotal", RInteger.toString(_marketerTotal));
map.put("customerTotal", RInteger.toString(_customerTotal));
map.put("investmentTotal", RDouble.toString(_investmentTotal));
map.put("investmentNumberTotal", RInteger.toString(_investmentNumberTotal));
map.put("redemptionTotal", RDouble.toString(_redemptionTotal));
map.put("redemptionNumberTotal", RInteger.toString(_redemptionNumberTotal));
map.put("netinvestmentTotal", RDouble.toString(_netinvestmentTotal));
map.put("interestTotal", RDouble.toString(_interestTotal));
map.put("performanceTotal", RDouble.toString(_performanceTotal));
map.put("createUserId", RLong.toString(_createUserId));
map.put("createDate", _createDate.format("YYYY-MM-DD HH24:MI:SS"));
map.put("updateUserId", RLong.toString(_updateUserId));
map.put("updateDate", _updateDate.format("YYYY-MM-DD HH24:MI:SS"));
}
//============================================================
// <T>反序列化数据到内容。</T>
//
// @param input 输入流
//============================================================
@Override
public void unserialize(IDataInput input){
super.unserialize(input);
_ouid = input.readInt64();
_ovld = input.readBoolean();
_guid = input.readString();
_linkId = input.readInt64();
_linkDate.set(input.readInt64());
_departmentTotal = input.readInt32();
_marketerTotal = input.readInt32();
_customerTotal = input.readInt32();
_investmentNumberTotal = input.readInt32();
_redemptionNumberTotal = input.readInt32();
_createUserId = input.readInt64();
_createDate.set(input.readInt64());
_updateUserId = input.readInt64();
_updateDate.set(input.readInt64());
}
//============================================================
// <T>序列化内容到数据。</T>
//
// @param output 输出流
//============================================================
@Override
public void serialize(IDataOutput output){
super.serialize(output);
output.writeInt64(_ouid);
output.writeBoolean(_ovld);
output.writeString(_guid);
output.writeInt64(_linkId);
output.writeInt64(_linkDate.get());
output.writeInt32(_departmentTotal);
output.writeInt32(_marketerTotal);
output.writeInt32(_customerTotal);
output.writeInt32(_investmentNumberTotal);
output.writeInt32(_redemptionNumberTotal);
output.writeInt64(_createUserId);
output.writeInt64(_createDate.get());
output.writeInt64(_updateUserId);
output.writeInt64(_updateDate.get());
}
//============================================================
// <T>复制当前对象。</T>
//
// @param unit 对象
// @return 对象
//============================================================
@Override
public void copy(FLogicUnit logicUnit){
super.copy(logicUnit);
FStatisticsFinancialAmountUnit unit = (FStatisticsFinancialAmountUnit)logicUnit;
unit.setOuid(_ouid);
unit.setOvld(_ovld);
unit.setGuid(_guid);
unit.setLinkId(_linkId);
unit.linkDate().assign(_linkDate);
unit.setDepartmentTotal(_departmentTotal);
unit.setMarketerTotal(_marketerTotal);
unit.setCustomerTotal(_customerTotal);
unit.setInvestmentTotal(_investmentTotal);
unit.setInvestmentNumberTotal(_investmentNumberTotal);
unit.setRedemptionTotal(_redemptionTotal);
unit.setRedemptionNumberTotal(_redemptionNumberTotal);
unit.setNetinvestmentTotal(_netinvestmentTotal);
unit.setInterestTotal(_interestTotal);
unit.setPerformanceTotal(_performanceTotal);
unit.setCreateUserId(_createUserId);
unit.createDate().assign(_createDate);
unit.setUpdateUserId(_updateUserId);
unit.updateDate().assign(_updateDate);
}
//============================================================
// <T>克隆当前对象。</T>
//
// @return 对象
//============================================================
@Override
public FStatisticsFinancialAmountUnit clone(){
FStatisticsFinancialAmountUnit unit = RClass.newInstance(FStatisticsFinancialAmountUnit.class);
copy(unit);
return unit;
}
}
|
UTF-8
|
Java
| 35,003 |
java
|
FStatisticsFinancialAmountUnit.java
|
Java
|
[] | null |
[] |
package org.mo.cloud.data.statistics;
import java.util.Map;
import org.mo.com.collections.FRow;
import org.mo.com.io.IDataInput;
import org.mo.com.io.IDataOutput;
import org.mo.com.lang.FFatalError;
import org.mo.com.lang.IStringPair;
import org.mo.com.lang.RBoolean;
import org.mo.com.lang.RDouble;
import org.mo.com.lang.RInteger;
import org.mo.com.lang.RLong;
import org.mo.com.lang.RString;
import org.mo.com.lang.reflect.RClass;
import org.mo.com.lang.type.TDateTime;
import org.mo.core.aop.face.ASourceMachine;
import org.mo.data.logic.FLogicUnit;
//============================================================
// <T>动态数据表逻辑单元。</T>
//============================================================
@ASourceMachine
public class FStatisticsFinancialAmountUnit
extends FLogicUnit
{
// 存储字段对象标识的定义。
private long __ouid;
// 字段对象标识的定义。
protected long _ouid;
// 存储字段有效性的定义。
private boolean __ovld;
// 字段有效性的定义。
protected boolean _ovld;
// 存储字段对象唯一标识的定义。
private String __guid;
// 字段对象唯一标识的定义。
protected String _guid;
// 存储字段关联编号的定义。
private long __linkId;
// 字段关联编号的定义。
protected long _linkId;
// 存储字段记录时间的定义。
private TDateTime __linkDate = new TDateTime();
// 字段记录时间的定义。
protected TDateTime _linkDate = new TDateTime();
// 存储字段部门总数的定义。
private int __departmentTotal;
// 字段部门总数的定义。
protected int _departmentTotal;
// 存储字段理财师总数的定义。
private int __marketerTotal;
// 字段理财师总数的定义。
protected int _marketerTotal;
// 存储字段客户总数的定义。
private int __customerTotal;
// 字段客户总数的定义。
protected int _customerTotal;
// 存储字段投资总金额的定义。
private double __investmentTotal;
// 字段投资总金额的定义。
protected double _investmentTotal;
// 存储字段投资总次数的定义。
private int __investmentNumberTotal;
// 字段投资总次数的定义。
protected int _investmentNumberTotal;
// 存储字段赎回总金额的定义。
private double __redemptionTotal;
// 字段赎回总金额的定义。
protected double _redemptionTotal;
// 存储字段赎回总次数的定义。
private int __redemptionNumberTotal;
// 字段赎回总次数的定义。
protected int _redemptionNumberTotal;
// 存储字段净投总金额的定义。
private double __netinvestmentTotal;
// 字段净投总金额的定义。
protected double _netinvestmentTotal;
// 存储字段利息总金额的定义。
private double __interestTotal;
// 字段利息总金额的定义。
protected double _interestTotal;
// 存储字段业绩总金额的定义。
private double __performanceTotal;
// 字段业绩总金额的定义。
protected double _performanceTotal;
// 存储字段创建用户标识的定义。
private long __createUserId;
// 字段创建用户标识的定义。
protected long _createUserId;
// 存储字段创建日期的定义。
private TDateTime __createDate = new TDateTime();
// 字段创建日期的定义。
protected TDateTime _createDate = new TDateTime();
// 存储字段更新者标识的定义。
private long __updateUserId;
// 字段更新者标识的定义。
protected long _updateUserId;
// 存储字段更新时间的定义。
private TDateTime __updateDate = new TDateTime();
// 字段更新时间的定义。
protected TDateTime _updateDate = new TDateTime();
//============================================================
// <T>构造动态数据表逻辑单元。</T>
//============================================================
public FStatisticsFinancialAmountUnit(){
}
//============================================================
// <T>判断对象标识的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isOuidChanged(){
return __ouid != _ouid;
}
//============================================================
// <T>获得对象标识的数据内容。</T>
//
// @return 数据内容
//============================================================
public long ouid(){
return _ouid;
}
//============================================================
// <T>设置对象标识的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setOuid(long value){
_ouid = value;
}
//============================================================
// <T>判断有效性的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isOvldChanged(){
return __ovld != _ovld;
}
//============================================================
// <T>获得有效性的数据内容。</T>
//
// @return 数据内容
//============================================================
public boolean ovld(){
return _ovld;
}
//============================================================
// <T>设置有效性的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setOvld(boolean value){
_ovld = value;
}
//============================================================
// <T>判断对象唯一标识的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isGuidChanged(){
return !RString.equals(__guid, _guid);
}
//============================================================
// <T>获得对象唯一标识的数据内容。</T>
//
// @return 数据内容
//============================================================
public String guid(){
return _guid;
}
//============================================================
// <T>设置对象唯一标识的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setGuid(String value){
_guid = value;
}
//============================================================
// <T>判断关联编号的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isLinkIdChanged(){
return __linkId != _linkId;
}
//============================================================
// <T>获得关联编号的数据内容。</T>
//
// @return 数据内容
//============================================================
public long linkId(){
return _linkId;
}
//============================================================
// <T>设置关联编号的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setLinkId(long value){
_linkId = value;
}
//============================================================
// <T>判断记录时间的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isLinkDateChanged(){
return !__linkDate.equals(_linkDate);
}
//============================================================
// <T>获得记录时间的数据内容。</T>
//
// @return 数据内容
//============================================================
public TDateTime linkDate(){
return _linkDate;
}
//============================================================
// <T>设置记录时间的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setLinkDate(TDateTime value){
_linkDate = value;
}
//============================================================
// <T>判断部门总数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isDepartmentTotalChanged(){
return __departmentTotal != _departmentTotal;
}
//============================================================
// <T>获得部门总数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int departmentTotal(){
return _departmentTotal;
}
//============================================================
// <T>设置部门总数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setDepartmentTotal(int value){
_departmentTotal = value;
}
//============================================================
// <T>判断理财师总数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isMarketerTotalChanged(){
return __marketerTotal != _marketerTotal;
}
//============================================================
// <T>获得理财师总数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int marketerTotal(){
return _marketerTotal;
}
//============================================================
// <T>设置理财师总数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setMarketerTotal(int value){
_marketerTotal = value;
}
//============================================================
// <T>判断客户总数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isCustomerTotalChanged(){
return __customerTotal != _customerTotal;
}
//============================================================
// <T>获得客户总数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int customerTotal(){
return _customerTotal;
}
//============================================================
// <T>设置客户总数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setCustomerTotal(int value){
_customerTotal = value;
}
//============================================================
// <T>判断投资总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isInvestmentTotalChanged(){
return __investmentTotal != _investmentTotal;
}
//============================================================
// <T>获得投资总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double investmentTotal(){
return _investmentTotal;
}
//============================================================
// <T>设置投资总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setInvestmentTotal(double value){
_investmentTotal = value;
}
//============================================================
// <T>判断投资总次数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isInvestmentNumberTotalChanged(){
return __investmentNumberTotal != _investmentNumberTotal;
}
//============================================================
// <T>获得投资总次数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int investmentNumberTotal(){
return _investmentNumberTotal;
}
//============================================================
// <T>设置投资总次数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setInvestmentNumberTotal(int value){
_investmentNumberTotal = value;
}
//============================================================
// <T>判断赎回总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isRedemptionTotalChanged(){
return __redemptionTotal != _redemptionTotal;
}
//============================================================
// <T>获得赎回总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double redemptionTotal(){
return _redemptionTotal;
}
//============================================================
// <T>设置赎回总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setRedemptionTotal(double value){
_redemptionTotal = value;
}
//============================================================
// <T>判断赎回总次数的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isRedemptionNumberTotalChanged(){
return __redemptionNumberTotal != _redemptionNumberTotal;
}
//============================================================
// <T>获得赎回总次数的数据内容。</T>
//
// @return 数据内容
//============================================================
public int redemptionNumberTotal(){
return _redemptionNumberTotal;
}
//============================================================
// <T>设置赎回总次数的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setRedemptionNumberTotal(int value){
_redemptionNumberTotal = value;
}
//============================================================
// <T>判断净投总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isNetinvestmentTotalChanged(){
return __netinvestmentTotal != _netinvestmentTotal;
}
//============================================================
// <T>获得净投总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double netinvestmentTotal(){
return _netinvestmentTotal;
}
//============================================================
// <T>设置净投总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setNetinvestmentTotal(double value){
_netinvestmentTotal = value;
}
//============================================================
// <T>判断利息总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isInterestTotalChanged(){
return __interestTotal != _interestTotal;
}
//============================================================
// <T>获得利息总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double interestTotal(){
return _interestTotal;
}
//============================================================
// <T>设置利息总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setInterestTotal(double value){
_interestTotal = value;
}
//============================================================
// <T>判断业绩总金额的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isPerformanceTotalChanged(){
return __performanceTotal != _performanceTotal;
}
//============================================================
// <T>获得业绩总金额的数据内容。</T>
//
// @return 数据内容
//============================================================
public double performanceTotal(){
return _performanceTotal;
}
//============================================================
// <T>设置业绩总金额的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setPerformanceTotal(double value){
_performanceTotal = value;
}
//============================================================
// <T>判断创建用户标识的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isCreateUserIdChanged(){
return __createUserId != _createUserId;
}
//============================================================
// <T>获得创建用户标识的数据内容。</T>
//
// @return 数据内容
//============================================================
public long createUserId(){
return _createUserId;
}
//============================================================
// <T>设置创建用户标识的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setCreateUserId(long value){
_createUserId = value;
}
//============================================================
// <T>判断创建日期的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isCreateDateChanged(){
return !__createDate.equals(_createDate);
}
//============================================================
// <T>获得创建日期的数据内容。</T>
//
// @return 数据内容
//============================================================
public TDateTime createDate(){
return _createDate;
}
//============================================================
// <T>设置创建日期的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setCreateDate(TDateTime value){
_createDate = value;
}
//============================================================
// <T>判断更新者标识的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isUpdateUserIdChanged(){
return __updateUserId != _updateUserId;
}
//============================================================
// <T>获得更新者标识的数据内容。</T>
//
// @return 数据内容
//============================================================
public long updateUserId(){
return _updateUserId;
}
//============================================================
// <T>设置更新者标识的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setUpdateUserId(long value){
_updateUserId = value;
}
//============================================================
// <T>判断更新时间的数据是否改变。</T>
//
// @return 数据内容
//============================================================
public boolean isUpdateDateChanged(){
return !__updateDate.equals(_updateDate);
}
//============================================================
// <T>获得更新时间的数据内容。</T>
//
// @return 数据内容
//============================================================
public TDateTime updateDate(){
return _updateDate;
}
//============================================================
// <T>设置更新时间的数据内容。</T>
//
// @param value 数据内容
//============================================================
public void setUpdateDate(TDateTime value){
_updateDate = value;
}
//============================================================
// <T>根据名称获得内容。</T>
//
// @param name 名称
// @return 内容
//============================================================
@Override
public String get(String name){
switch(name){
case "ouid":
return Long.toString(_ouid);
case "ovld":
return RBoolean.toString(_ovld);
case "guid":
return _guid;
case "link_id":
return Long.toString(_linkId);
case "link_date":
return _linkDate.toString();
case "department_total":
return RInteger.toString(_departmentTotal);
case "marketer_total":
return RInteger.toString(_marketerTotal);
case "customer_total":
return RInteger.toString(_customerTotal);
case "investment_total":
return RDouble.toString(_investmentTotal);
case "investment_number_total":
return RInteger.toString(_investmentNumberTotal);
case "redemption_total":
return RDouble.toString(_redemptionTotal);
case "redemption_number_total":
return RInteger.toString(_redemptionNumberTotal);
case "netinvestment_total":
return RDouble.toString(_netinvestmentTotal);
case "interest_total":
return RDouble.toString(_interestTotal);
case "performance_total":
return RDouble.toString(_performanceTotal);
case "create_user_id":
return Long.toString(_createUserId);
case "create_date":
return _createDate.toString();
case "update_user_id":
return Long.toString(_updateUserId);
case "update_date":
return _updateDate.toString();
}
return null;
}
//============================================================
// <T>根据名称设置内容。</T>
//
// @param name 名称
// @param value 内容
//============================================================
@Override
public void set(String name,
String value){
switch(name){
case "ouid":
_ouid = RLong.parse(value);
break;
case "ovld":
_ovld = RBoolean.parse(value);
break;
case "guid":
_guid = value;
break;
case "link_id":
_linkId = RLong.parse(value);
break;
case "link_date":
_linkDate.parse(value);
break;
case "department_total":
_departmentTotal = RInteger.parse(value);
break;
case "marketer_total":
_marketerTotal = RInteger.parse(value);
break;
case "customer_total":
_customerTotal = RInteger.parse(value);
break;
case "investment_total":
_investmentTotal = RDouble.parse(value);
break;
case "investment_number_total":
_investmentNumberTotal = RInteger.parse(value);
break;
case "redemption_total":
_redemptionTotal = RDouble.parse(value);
break;
case "redemption_number_total":
_redemptionNumberTotal = RInteger.parse(value);
break;
case "netinvestment_total":
_netinvestmentTotal = RDouble.parse(value);
break;
case "interest_total":
_interestTotal = RDouble.parse(value);
break;
case "performance_total":
_performanceTotal = RDouble.parse(value);
break;
case "create_user_id":
_createUserId = RLong.parse(value);
break;
case "create_date":
_createDate.parse(value);
break;
case "update_user_id":
_updateUserId = RLong.parse(value);
break;
case "update_date":
_updateDate.parse(value);
break;
}
}
//============================================================
// <T>加载行记录。</T>
//
// @param row 行记录
//============================================================
@Override
public void load(FRow row){
super.load(row);
for(IStringPair pair : row){
// 获得名称
String name = pair.name();
if(RString.isEmpty(name)){
throw new FFatalError("Row format is invalid. (row={1})", row.dump());
}
// 获得内容
String value = pair.value();
// 设置内容
switch(name){
case "ouid":
__ouid = RLong.parse(value);
_ouid = __ouid;
break;
case "ovld":
__ovld = RBoolean.parse(value);
_ovld = __ovld;
break;
case "guid":
__guid = value;
_guid = __guid;
break;
case "link_id":
__linkId = RLong.parse(value);
_linkId = __linkId;
break;
case "link_date":
__linkDate.parse(value);
_linkDate.assign(__linkDate);
break;
case "department_total":
__departmentTotal = RInteger.parse(value);
_departmentTotal = __departmentTotal;
break;
case "marketer_total":
__marketerTotal = RInteger.parse(value);
_marketerTotal = __marketerTotal;
break;
case "customer_total":
__customerTotal = RInteger.parse(value);
_customerTotal = __customerTotal;
break;
case "investment_total":
__investmentTotal = RDouble.parse(value);
_investmentTotal = __investmentTotal;
break;
case "investment_number_total":
__investmentNumberTotal = RInteger.parse(value);
_investmentNumberTotal = __investmentNumberTotal;
break;
case "redemption_total":
__redemptionTotal = RDouble.parse(value);
_redemptionTotal = __redemptionTotal;
break;
case "redemption_number_total":
__redemptionNumberTotal = RInteger.parse(value);
_redemptionNumberTotal = __redemptionNumberTotal;
break;
case "netinvestment_total":
__netinvestmentTotal = RDouble.parse(value);
_netinvestmentTotal = __netinvestmentTotal;
break;
case "interest_total":
__interestTotal = RDouble.parse(value);
_interestTotal = __interestTotal;
break;
case "performance_total":
__performanceTotal = RDouble.parse(value);
_performanceTotal = __performanceTotal;
break;
case "create_user_id":
__createUserId = RLong.parse(value);
_createUserId = __createUserId;
break;
case "create_date":
__createDate.parse(value);
_createDate.assign(__createDate);
break;
case "update_user_id":
__updateUserId = RLong.parse(value);
_updateUserId = __updateUserId;
break;
case "update_date":
__updateDate.parse(value);
_updateDate.assign(__updateDate);
break;
}
}
}
//============================================================
// <T>存储行记录。</T>
//
// @param row 行记录
//============================================================
@Override
public void save(FRow row){
super.load(row);
row.set("ouid", _ouid);
row.set("ovld", _ovld);
row.set("guid", _guid);
row.set("linkId", _linkId);
row.set("linkDate", _linkDate);
row.set("departmentTotal", _departmentTotal);
row.set("marketerTotal", _marketerTotal);
row.set("customerTotal", _customerTotal);
row.set("investmentTotal", _investmentTotal);
row.set("investmentNumberTotal", _investmentNumberTotal);
row.set("redemptionTotal", _redemptionTotal);
row.set("redemptionNumberTotal", _redemptionNumberTotal);
row.set("netinvestmentTotal", _netinvestmentTotal);
row.set("interestTotal", _interestTotal);
row.set("performanceTotal", _performanceTotal);
row.set("createUserId", _createUserId);
row.set("createDate", _createDate);
row.set("updateUserId", _updateUserId);
row.set("updateDate", _updateDate);
}
//============================================================
// <T>保存对照表。</T>
//
// @param map 对照表
//============================================================
@Override
public void saveMap(Map<String, String> map){
super.saveMap(map);
map.put("ouid", RLong.toString(_ouid));
map.put("ovld", RBoolean.toString(_ovld));
map.put("guid", _guid);
map.put("linkId", RLong.toString(_linkId));
map.put("linkDate", _linkDate.format("YYYY-MM-DD HH24:MI:SS"));
map.put("departmentTotal", RInteger.toString(_departmentTotal));
map.put("marketerTotal", RInteger.toString(_marketerTotal));
map.put("customerTotal", RInteger.toString(_customerTotal));
map.put("investmentTotal", RDouble.toString(_investmentTotal));
map.put("investmentNumberTotal", RInteger.toString(_investmentNumberTotal));
map.put("redemptionTotal", RDouble.toString(_redemptionTotal));
map.put("redemptionNumberTotal", RInteger.toString(_redemptionNumberTotal));
map.put("netinvestmentTotal", RDouble.toString(_netinvestmentTotal));
map.put("interestTotal", RDouble.toString(_interestTotal));
map.put("performanceTotal", RDouble.toString(_performanceTotal));
map.put("createUserId", RLong.toString(_createUserId));
map.put("createDate", _createDate.format("YYYY-MM-DD HH24:MI:SS"));
map.put("updateUserId", RLong.toString(_updateUserId));
map.put("updateDate", _updateDate.format("YYYY-MM-DD HH24:MI:SS"));
}
//============================================================
// <T>反序列化数据到内容。</T>
//
// @param input 输入流
//============================================================
@Override
public void unserialize(IDataInput input){
super.unserialize(input);
_ouid = input.readInt64();
_ovld = input.readBoolean();
_guid = input.readString();
_linkId = input.readInt64();
_linkDate.set(input.readInt64());
_departmentTotal = input.readInt32();
_marketerTotal = input.readInt32();
_customerTotal = input.readInt32();
_investmentNumberTotal = input.readInt32();
_redemptionNumberTotal = input.readInt32();
_createUserId = input.readInt64();
_createDate.set(input.readInt64());
_updateUserId = input.readInt64();
_updateDate.set(input.readInt64());
}
//============================================================
// <T>序列化内容到数据。</T>
//
// @param output 输出流
//============================================================
@Override
public void serialize(IDataOutput output){
super.serialize(output);
output.writeInt64(_ouid);
output.writeBoolean(_ovld);
output.writeString(_guid);
output.writeInt64(_linkId);
output.writeInt64(_linkDate.get());
output.writeInt32(_departmentTotal);
output.writeInt32(_marketerTotal);
output.writeInt32(_customerTotal);
output.writeInt32(_investmentNumberTotal);
output.writeInt32(_redemptionNumberTotal);
output.writeInt64(_createUserId);
output.writeInt64(_createDate.get());
output.writeInt64(_updateUserId);
output.writeInt64(_updateDate.get());
}
//============================================================
// <T>复制当前对象。</T>
//
// @param unit 对象
// @return 对象
//============================================================
@Override
public void copy(FLogicUnit logicUnit){
super.copy(logicUnit);
FStatisticsFinancialAmountUnit unit = (FStatisticsFinancialAmountUnit)logicUnit;
unit.setOuid(_ouid);
unit.setOvld(_ovld);
unit.setGuid(_guid);
unit.setLinkId(_linkId);
unit.linkDate().assign(_linkDate);
unit.setDepartmentTotal(_departmentTotal);
unit.setMarketerTotal(_marketerTotal);
unit.setCustomerTotal(_customerTotal);
unit.setInvestmentTotal(_investmentTotal);
unit.setInvestmentNumberTotal(_investmentNumberTotal);
unit.setRedemptionTotal(_redemptionTotal);
unit.setRedemptionNumberTotal(_redemptionNumberTotal);
unit.setNetinvestmentTotal(_netinvestmentTotal);
unit.setInterestTotal(_interestTotal);
unit.setPerformanceTotal(_performanceTotal);
unit.setCreateUserId(_createUserId);
unit.createDate().assign(_createDate);
unit.setUpdateUserId(_updateUserId);
unit.updateDate().assign(_updateDate);
}
//============================================================
// <T>克隆当前对象。</T>
//
// @return 对象
//============================================================
@Override
public FStatisticsFinancialAmountUnit clone(){
FStatisticsFinancialAmountUnit unit = RClass.newInstance(FStatisticsFinancialAmountUnit.class);
copy(unit);
return unit;
}
}
| 35,003 | 0.424333 | 0.422608 | 1,027 | 30.04479 | 21.737568 | 101 | false | false | 0 | 0 | 0 | 0 | 67 | 0.004109 | 0.356378 | false | false |
3
|
14d91a3fd1eacd7abd6c3e3fb3c56db4dc9de336
| 23,072,564,348,429 |
348fcbdbb1c69604201f3999ad221f2067b2bf6e
|
/BinaryTree.java
|
1fceee44a4deb26b4646127dcb01e5e6c657f7a5
|
[
"MIT"
] |
permissive
|
wardbradt/binary-trees-ward
|
https://github.com/wardbradt/binary-trees-ward
|
3a1686dd170ca2b85c24e87f90eb19e303205861
|
e718b7ac68e2fee8584fb9168bd0d853dcf8c5cb
|
refs/heads/master
| 2021-01-25T09:14:17.562000 | 2017-12-05T16:39:40 | 2017-12-05T16:39:40 | 93,798,163 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Authors: Jimmy Pham, Ward Bradt
* Finish Date: April 12, 2017
*
*/
public class BinaryTree<T>{
private Node<T> root;
public BinaryTree() {
root = null;
}
/**
* Copy constructor
*
* @param r is root
*/
public BinaryTree(Node<T> r) { root = r; }
public Node<T> getRoot() {
return root;
}
public void setRoot(Node<T> node) { root = node; }
/**
* Tells if the <code>BinaryTree</code> has any items in it.
*
* @return if the <code>BinaryTree</code>'s <code>contents == null</code>
*/
public boolean empty() {
return root == null;
}
public void clear() {
root = null;
}
/**
* Add <code>T item</code> to the <code>BinaryTree</code>. At every <code>Node</code>, first checks if the left
* node == null then checks the right node == null. If neither are, it
* goes to the right and checks again.
*
* @param item the T item to be added to the tree
* @return true if T item is added.
*/
public boolean add(T item) {
Queue<Node<T>> nodes = new Queue<>(root);
if (nodes.peek() == null) {
root = new Node<T>(item);
return true;
}
while (true) {
// First check if the left node == null
if (nodes.peek().getLeft() == null) {
return addLeft(nodes.peek(), item);
}
// Then check the right node
else nodes.add(nodes.peek().getLeft());
if (nodes.peek().getRight() == null) {
return addRight(nodes.peek(), item);
}
// Else go the right and repeat (with a DFS), checking left then right nodes.
else nodes.add(nodes.peek().getRight());
nodes.iterator().next();
}
}
public boolean addLeft(Node<T> n, T item) {
if (n.getLeft() == null) {
n.setLeft(new Node<T>(item));
return true;
}
else
return false;
}
public boolean addRight(Node<T>n, T item) {
if (n.getRight() == null) {
n.setRight(new Node<T>(item));
return true;
}
else
return false;
}
/**
* Removes the first instance of <code>T item</code> in a breadth-first traversal.
*
* @param item is the item to be removed
* @throws NullPointerException if item is null or if item is not in the binary tree.
*/
public void remove(T item) throws NullPointerException {
if (item == null) throw new NullPointerException("param item cannot be null!");
Queue<Node<T>> nodes = new Queue<>(root);
while (!nodes.isEmpty()) {
if (nodes.peek().getContents() == item) {
removeHelper(nodes.peek());
return;
}
if (nodes.peek().getLeft() != null)
nodes.add(nodes.peek().getLeft());
if (nodes.peek().getRight() != null) {
nodes.add(nodes.peek().getRight());
}
nodes.iterator().next();
}
// throws exception if tree does not contain item
throw new NullPointerException("item is not in the BinaryTree.");
}
/**
* Finds the <code>Node</code> to swap <code>removed</code> with and swaps those two <code>Node</code>s.
*
* @param removed the <code>Node</code> to remove from the tree
*/
public void removeHelper(Node<T> removed) {
Node<T> swapped = new Node<T>();
// If not at the end of a branch, find the end of a branch.
if (removed.getLeft() != null || removed.getRight() != null) {
swapped = removed.getLeft();
// swapped must be at the end of a branch.
while (swapped != null) {
// If swapped is not at the end of a branch
if (swapped.getLeft() == null || swapped.getRight() == null) {
swapped = swapped.getLeft();
}
}
// Swap swapped and removed.
try {
swapped.setRight(removed.getRight());
} catch (NullPointerException ifNull) {
}
try {
swapped.setLeft(removed.getLeft());
} catch (NullPointerException ifNull) {
}
}
if (removed.getParent() != null && swapped != null) {
if (removed.getParent().getLeft() == removed) {
removed.getParent().setLeft(swapped);
}
else if (removed.getParent().getRight() == removed) {
removed.getParent().setRight(swapped);
}
}
removed.setContents(null);
}
/**
* Determines if any <code>Node</code>s in the tree contain a specified <code>Object</code>.
*
* @param item is the item the method searches for.
* @return if <code>item</code> is in the <code>BinaryTree</code>
*/
public boolean contains(T item) {
if (root.getContents() != item) {
// create binary tree from left and right then create a branched recursion
// to check if each subbranch contains item.
if (root.getLeft() != null) {
BinaryTree<T> left = new BinaryTree<>(root.getLeft());
if (left.contains(item)) return true;
}
if (root.getRight() != null) {
BinaryTree<T> right = new BinaryTree<>(root.getRight());
if (right.contains(item)) return true;
}
return false;
}
return true;
}
/**
* <code>get(T item)</code> searches for an <code>Object</code> in the <code>BinaryTree</code>.
* Received help from
* http://stackoverflow.com/questions/5262308/how-do-implement-a-breadth-first-traversal
*
* @param item is what is being searched for in the <code>BinaryTree</code>
* @return the first breadth-first reference to T item if it is in the BinaryTree
* @throws NullPointerException if item == null or if item is not in the BinaryTree
*/
public Node<T> get(T item) throws NullPointerException {
if (item == null) throw new NullPointerException("parameters cannot be null!");
Queue<Node<T>> nodes = new Queue<>(root);
while (!nodes.isEmpty()) {
if (nodes.peek().getContents() == item)
return nodes.iterator().next();
if (nodes.peek().getLeft() != null)
nodes.add(nodes.peek().getLeft());
if (nodes.peek().getRight() != null)
nodes.add(nodes.peek().getRight());
nodes.iterator().next();
}
throw new NullPointerException("item is not in the BinaryTree.");
}
/**
* Returns a breadth-first <code>Iterable Object</code> of the <code>BinaryTree</code>.
* <code>Queue</code> class implements Iterable<T> using <code>java.util.Iterator</code>
*
* @return a breadth-first iterable object of the tree.
*/
public Queue<T> breadthFirst() {
Queue<T> breadth = new Queue<T>();
Queue<Node<T>> nodes = new Queue<>(root);
// A breadth first traversal in this form never looks at root.
while (!nodes.isEmpty()) {
if (nodes.peek().getContents() != null) {
if (nodes.peek().getLeft() != null) {
nodes.add(nodes.peek().getLeft());
}
if (nodes.peek().getRight() != null)
nodes.add(nodes.peek().getRight());
breadth.add(nodes.iterator().next().getContents());
}
else {
nodes.iterator().next();
}
}
return breadth;
}
/**
* Returns a depth-first iterable object of the branch tree.
* <code>Queue</code> class implements <code>Iterable<T></code> using <code>java.util.Iterator</code>
*
* @return a breadth-first <code>Iterable</code> object of the tree.
*/
public Queue<T> depthFirst() {
Stack<Node<T>> nodes = new Stack<Node<T>>(getRoot());
Queue<T> depth = new Queue<T>(root.getContents());
if (nodes.peek().getLeft() != null) {
depth.addQueue(new BinaryTree<>(nodes.peek().getLeft()).depthFirst());
}
if (nodes.peek().getRight() != null) {
depth.addQueue(new BinaryTree<>(nodes.peek().getRight()).depthFirst());
}
nodes.pop();
return depth;
}
}
|
UTF-8
|
Java
| 8,761 |
java
|
BinaryTree.java
|
Java
|
[
{
"context": "/**\r\n * Authors: Jimmy Pham, Ward Bradt\r\n * Finish Date: April 12, 2017\r\n *\r\n",
"end": 27,
"score": 0.9998679161071777,
"start": 17,
"tag": "NAME",
"value": "Jimmy Pham"
},
{
"context": "/**\r\n * Authors: Jimmy Pham, Ward Bradt\r\n * Finish Date: April 12, 2017\r\n *\r\n */\r\n\r\npubli",
"end": 39,
"score": 0.999864935874939,
"start": 29,
"tag": "NAME",
"value": "Ward Bradt"
}
] | null |
[] |
/**
* Authors: <NAME>, <NAME>
* Finish Date: April 12, 2017
*
*/
public class BinaryTree<T>{
private Node<T> root;
public BinaryTree() {
root = null;
}
/**
* Copy constructor
*
* @param r is root
*/
public BinaryTree(Node<T> r) { root = r; }
public Node<T> getRoot() {
return root;
}
public void setRoot(Node<T> node) { root = node; }
/**
* Tells if the <code>BinaryTree</code> has any items in it.
*
* @return if the <code>BinaryTree</code>'s <code>contents == null</code>
*/
public boolean empty() {
return root == null;
}
public void clear() {
root = null;
}
/**
* Add <code>T item</code> to the <code>BinaryTree</code>. At every <code>Node</code>, first checks if the left
* node == null then checks the right node == null. If neither are, it
* goes to the right and checks again.
*
* @param item the T item to be added to the tree
* @return true if T item is added.
*/
public boolean add(T item) {
Queue<Node<T>> nodes = new Queue<>(root);
if (nodes.peek() == null) {
root = new Node<T>(item);
return true;
}
while (true) {
// First check if the left node == null
if (nodes.peek().getLeft() == null) {
return addLeft(nodes.peek(), item);
}
// Then check the right node
else nodes.add(nodes.peek().getLeft());
if (nodes.peek().getRight() == null) {
return addRight(nodes.peek(), item);
}
// Else go the right and repeat (with a DFS), checking left then right nodes.
else nodes.add(nodes.peek().getRight());
nodes.iterator().next();
}
}
public boolean addLeft(Node<T> n, T item) {
if (n.getLeft() == null) {
n.setLeft(new Node<T>(item));
return true;
}
else
return false;
}
public boolean addRight(Node<T>n, T item) {
if (n.getRight() == null) {
n.setRight(new Node<T>(item));
return true;
}
else
return false;
}
/**
* Removes the first instance of <code>T item</code> in a breadth-first traversal.
*
* @param item is the item to be removed
* @throws NullPointerException if item is null or if item is not in the binary tree.
*/
public void remove(T item) throws NullPointerException {
if (item == null) throw new NullPointerException("param item cannot be null!");
Queue<Node<T>> nodes = new Queue<>(root);
while (!nodes.isEmpty()) {
if (nodes.peek().getContents() == item) {
removeHelper(nodes.peek());
return;
}
if (nodes.peek().getLeft() != null)
nodes.add(nodes.peek().getLeft());
if (nodes.peek().getRight() != null) {
nodes.add(nodes.peek().getRight());
}
nodes.iterator().next();
}
// throws exception if tree does not contain item
throw new NullPointerException("item is not in the BinaryTree.");
}
/**
* Finds the <code>Node</code> to swap <code>removed</code> with and swaps those two <code>Node</code>s.
*
* @param removed the <code>Node</code> to remove from the tree
*/
public void removeHelper(Node<T> removed) {
Node<T> swapped = new Node<T>();
// If not at the end of a branch, find the end of a branch.
if (removed.getLeft() != null || removed.getRight() != null) {
swapped = removed.getLeft();
// swapped must be at the end of a branch.
while (swapped != null) {
// If swapped is not at the end of a branch
if (swapped.getLeft() == null || swapped.getRight() == null) {
swapped = swapped.getLeft();
}
}
// Swap swapped and removed.
try {
swapped.setRight(removed.getRight());
} catch (NullPointerException ifNull) {
}
try {
swapped.setLeft(removed.getLeft());
} catch (NullPointerException ifNull) {
}
}
if (removed.getParent() != null && swapped != null) {
if (removed.getParent().getLeft() == removed) {
removed.getParent().setLeft(swapped);
}
else if (removed.getParent().getRight() == removed) {
removed.getParent().setRight(swapped);
}
}
removed.setContents(null);
}
/**
* Determines if any <code>Node</code>s in the tree contain a specified <code>Object</code>.
*
* @param item is the item the method searches for.
* @return if <code>item</code> is in the <code>BinaryTree</code>
*/
public boolean contains(T item) {
if (root.getContents() != item) {
// create binary tree from left and right then create a branched recursion
// to check if each subbranch contains item.
if (root.getLeft() != null) {
BinaryTree<T> left = new BinaryTree<>(root.getLeft());
if (left.contains(item)) return true;
}
if (root.getRight() != null) {
BinaryTree<T> right = new BinaryTree<>(root.getRight());
if (right.contains(item)) return true;
}
return false;
}
return true;
}
/**
* <code>get(T item)</code> searches for an <code>Object</code> in the <code>BinaryTree</code>.
* Received help from
* http://stackoverflow.com/questions/5262308/how-do-implement-a-breadth-first-traversal
*
* @param item is what is being searched for in the <code>BinaryTree</code>
* @return the first breadth-first reference to T item if it is in the BinaryTree
* @throws NullPointerException if item == null or if item is not in the BinaryTree
*/
public Node<T> get(T item) throws NullPointerException {
if (item == null) throw new NullPointerException("parameters cannot be null!");
Queue<Node<T>> nodes = new Queue<>(root);
while (!nodes.isEmpty()) {
if (nodes.peek().getContents() == item)
return nodes.iterator().next();
if (nodes.peek().getLeft() != null)
nodes.add(nodes.peek().getLeft());
if (nodes.peek().getRight() != null)
nodes.add(nodes.peek().getRight());
nodes.iterator().next();
}
throw new NullPointerException("item is not in the BinaryTree.");
}
/**
* Returns a breadth-first <code>Iterable Object</code> of the <code>BinaryTree</code>.
* <code>Queue</code> class implements Iterable<T> using <code>java.util.Iterator</code>
*
* @return a breadth-first iterable object of the tree.
*/
public Queue<T> breadthFirst() {
Queue<T> breadth = new Queue<T>();
Queue<Node<T>> nodes = new Queue<>(root);
// A breadth first traversal in this form never looks at root.
while (!nodes.isEmpty()) {
if (nodes.peek().getContents() != null) {
if (nodes.peek().getLeft() != null) {
nodes.add(nodes.peek().getLeft());
}
if (nodes.peek().getRight() != null)
nodes.add(nodes.peek().getRight());
breadth.add(nodes.iterator().next().getContents());
}
else {
nodes.iterator().next();
}
}
return breadth;
}
/**
* Returns a depth-first iterable object of the branch tree.
* <code>Queue</code> class implements <code>Iterable<T></code> using <code>java.util.Iterator</code>
*
* @return a breadth-first <code>Iterable</code> object of the tree.
*/
public Queue<T> depthFirst() {
Stack<Node<T>> nodes = new Stack<Node<T>>(getRoot());
Queue<T> depth = new Queue<T>(root.getContents());
if (nodes.peek().getLeft() != null) {
depth.addQueue(new BinaryTree<>(nodes.peek().getLeft()).depthFirst());
}
if (nodes.peek().getRight() != null) {
depth.addQueue(new BinaryTree<>(nodes.peek().getRight()).depthFirst());
}
nodes.pop();
return depth;
}
}
| 8,753 | 0.521288 | 0.519804 | 245 | 33.759182 | 27.336512 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false |
3
|
5fe6aa2d9e3bbb6065a69280a9a8093fc092079f
| 16,939,351,017,168 |
30daaa1eac73dec52a6826d85e263f4d6b19312a
|
/app/src/main/java/st/teamcataly/turistademanila/customview/ReportView.java
|
8d9616c13607810d49023a3fe06b91edd52292f7
|
[
"Apache-2.0"
] |
permissive
|
ac-opensource/tourista-de-manila
|
https://github.com/ac-opensource/tourista-de-manila
|
cb1d0bd81db143d8e75745d4db021bb0186e6081
|
021185f42a35739e8ae287b55997b1b23102ee47
|
refs/heads/master
| 2021-01-20T04:18:38.070000 | 2017-09-19T11:22:37 | 2017-09-19T11:22:37 | 101,386,112 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package st.teamcataly.turistademanila.customview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.adroitandroid.chipcloud.ChipCloud;
import com.adroitandroid.chipcloud.ChipListener;
import com.airbnb.epoxy.ModelProp;
import com.airbnb.epoxy.ModelView;
import st.teamcataly.turistademanila.R;
import st.teamcataly.turistademanila.touristspots.TouristSpotsController;
@ModelView(defaultLayout = R.layout.report_view)
public class ReportView extends LinearLayout {
private ChipCloud chipCloud;
private String[] filter = new String[]{
"on going",
"travel report"
};
public ReportView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setOrientation(VERTICAL);
View view = inflate(getContext(), R.layout.tag_cloud, this);
chipCloud = (ChipCloud) view.findViewById(R.id.chipCloud);
((TextView) view.findViewById(R.id.title)).setText("View Type");
chipCloud.addChips(filter);
}
@ModelProp(options = ModelProp.Option.DoNotHash)
public void setListener(TouristSpotsController.AdapterCallbacks adapterCallbacks) {
chipCloud.setChipListener(new ChipListener() {
@Override
public void chipSelected(int i) {
if (adapterCallbacks != null) {
adapterCallbacks.onChipClicked(filter[i]);
}
}
@Override
public void chipDeselected(int i) {
}
});
}
}
|
UTF-8
|
Java
| 1,667 |
java
|
ReportView.java
|
Java
|
[] | null |
[] |
package st.teamcataly.turistademanila.customview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.adroitandroid.chipcloud.ChipCloud;
import com.adroitandroid.chipcloud.ChipListener;
import com.airbnb.epoxy.ModelProp;
import com.airbnb.epoxy.ModelView;
import st.teamcataly.turistademanila.R;
import st.teamcataly.turistademanila.touristspots.TouristSpotsController;
@ModelView(defaultLayout = R.layout.report_view)
public class ReportView extends LinearLayout {
private ChipCloud chipCloud;
private String[] filter = new String[]{
"on going",
"travel report"
};
public ReportView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setOrientation(VERTICAL);
View view = inflate(getContext(), R.layout.tag_cloud, this);
chipCloud = (ChipCloud) view.findViewById(R.id.chipCloud);
((TextView) view.findViewById(R.id.title)).setText("View Type");
chipCloud.addChips(filter);
}
@ModelProp(options = ModelProp.Option.DoNotHash)
public void setListener(TouristSpotsController.AdapterCallbacks adapterCallbacks) {
chipCloud.setChipListener(new ChipListener() {
@Override
public void chipSelected(int i) {
if (adapterCallbacks != null) {
adapterCallbacks.onChipClicked(filter[i]);
}
}
@Override
public void chipDeselected(int i) {
}
});
}
}
| 1,667 | 0.671266 | 0.671266 | 56 | 28.785715 | 23.125214 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
47ab9306ec000a52eeeba473cf92fcdc9c9c186e
| 7,224,135,010,943 |
ec2deb507e6da0382257ca7d893464cb8a82ea1f
|
/src/main/java/com/demo/convert/numbers/facade/NumberToWordFacade.java
|
bfe4e7279934992a29da6e909ba99fbcedf3447b
|
[] |
no_license
|
bibhudendumishra/Test
|
https://github.com/bibhudendumishra/Test
|
aa23f1d0c5fb503156e081ca6c38fb10c4acbf67
|
81f7c067d3b7d3f60e766e2ba14016f51ae6062a
|
refs/heads/master
| 2021-07-07T07:30:12.966000 | 2019-05-28T13:02:42 | 2019-05-28T13:02:42 | 188,844,941 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.demo.convert.numbers.facade;
import com.demo.convert.numbers.business.impl.NumberWordConverBLImpl;
import com.demo.convert.numbers.dao.impl.NumberDaoImpl;
import com.demo.convert.numbers.exception.NumberExceptionMessage;
import com.demo.convert.numbers.exception.NumberRuntimeException;
import com.demo.convert.numbers.model.Number;
import com.demo.convert.numbers.service.WordConverter;
import com.demo.convert.numbers.service.impl.WordConverterService;
import com.demo.convert.numbers.utilities.Constants;
import com.demo.convert.numbers.validator.NumberValidator;
import com.demo.convert.numbers.validator.NumberValidatorImpl;
public class NumberToWordFacade {
private WordConverter wordConverter;
public String ConvertToWording(String number) throws NumberRuntimeException, NumberExceptionMessage {
if(null==number) return Constants.INVALID_NULL_INPUT;
////////////////////////////////////////////////////////////////
// Validate Input
////////////////////////////////////////////////////////////////
NumberValidator numberValidator = new NumberValidatorImpl(number);
String message = numberValidator.validate();
if(message.equals(Constants.SUCCESS)) {
this.wordConverter = new WordConverterService(new NumberWordConverBLImpl(new NumberDaoImpl(),new Number(number.replace(",", ""))));
return this.wordConverter.convertToWord();
}
return message;
}
public WordConverter getWordConverter() {
return wordConverter;
}
public void setWordConverter(WordConverter wordConverter) {
this.wordConverter = wordConverter;
}
}
|
UTF-8
|
Java
| 1,624 |
java
|
NumberToWordFacade.java
|
Java
|
[] | null |
[] |
package com.demo.convert.numbers.facade;
import com.demo.convert.numbers.business.impl.NumberWordConverBLImpl;
import com.demo.convert.numbers.dao.impl.NumberDaoImpl;
import com.demo.convert.numbers.exception.NumberExceptionMessage;
import com.demo.convert.numbers.exception.NumberRuntimeException;
import com.demo.convert.numbers.model.Number;
import com.demo.convert.numbers.service.WordConverter;
import com.demo.convert.numbers.service.impl.WordConverterService;
import com.demo.convert.numbers.utilities.Constants;
import com.demo.convert.numbers.validator.NumberValidator;
import com.demo.convert.numbers.validator.NumberValidatorImpl;
public class NumberToWordFacade {
private WordConverter wordConverter;
public String ConvertToWording(String number) throws NumberRuntimeException, NumberExceptionMessage {
if(null==number) return Constants.INVALID_NULL_INPUT;
////////////////////////////////////////////////////////////////
// Validate Input
////////////////////////////////////////////////////////////////
NumberValidator numberValidator = new NumberValidatorImpl(number);
String message = numberValidator.validate();
if(message.equals(Constants.SUCCESS)) {
this.wordConverter = new WordConverterService(new NumberWordConverBLImpl(new NumberDaoImpl(),new Number(number.replace(",", ""))));
return this.wordConverter.convertToWord();
}
return message;
}
public WordConverter getWordConverter() {
return wordConverter;
}
public void setWordConverter(WordConverter wordConverter) {
this.wordConverter = wordConverter;
}
}
| 1,624 | 0.722291 | 0.722291 | 43 | 35.767441 | 31.615301 | 134 | false | false | 0 | 0 | 0 | 0 | 64 | 0.078818 | 1.511628 | false | false |
3
|
2d931f344c3fd5bb0902a4a6b7b7699eb324b3b8
| 28,441,273,489,503 |
18a4c1f72720be81609d94fb4ff1b9e7c2e086d2
|
/src/main/java/com/fanyi/oa/pojo/Customer.java
|
da7b24e93c86327893cafad9354f1783a0789332
|
[] |
no_license
|
GentelBai/oaaa
|
https://github.com/GentelBai/oaaa
|
7575cc2c512017b05e38b8c33a216de4572635ad
|
9940e8d42bcbae4919a9ac17cf0f20abf047b8a9
|
refs/heads/master
| 2020-06-20T04:21:49.523000 | 2019-07-18T02:58:40 | 2019-07-18T02:58:40 | 196,991,150 | 0 | 0 | null | false | 2019-10-31T06:49:57 | 2019-07-15T12:06:49 | 2019-07-18T02:59:12 | 2019-10-31T06:49:54 | 492 | 0 | 0 | 1 |
JavaScript
| false | false |
package com.fanyi.oa.pojo;
import java.io.Serializable;
/**
* 客户信息
*
* @author Administrator
* @version 1.0
* @created 09-十月-2016 10:19:20
*/
public class Customer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 客户id
*/
private int cust_id;
/**
* 客户姓名
*/
private String cust_name;
/**
* 0女;1男
*/
private String sex;
/**
* 年龄
*/
private String age;
/**
* 客户电话
*/
private String phone;
/**
* 所属店铺ID
*/
private String shop_id;
private String shop_name;// 新增店铺名称
/**
* 区域代码
*/
private String area_id;
private String area_name;// 新增区域名称
private String province_id;
private String province_name;// 新增省份名称
private String address;
/**
* 指派咨询师(主)
*/
private String main_teacher;
private String main_name;// 新增住咨询师名称
/**
* 咨询师(次)
*/
private String else_teacher;
private String else_name;
/**
* 总监
*/
private String director;
private String director_name;// 总监名称
/**
* 0老客户;1新客户
*/
private String flag;
/**
* 客户识别码
*/
private String cust_code;
/**
* 上一级客户识别码
*/
private String up_cust_code;
/**
* 主要负责人
*/
private String principal;
/**
* 抄送者
*/
private String copyto;
/**
* 1.远程咨询;2.积分系统;3.crm
*/
private String cust_sourse;
private String rank;// 新增级别字段A,B,C级
private String state;// 新增字段,0意客户;1.成单客户
/**
* 开发者
*/
private String developer;
private String developer_name;
private String insert_user;
private String insert_time;
private String update_user;
private String update_time;
private String filename;// 新增字段
private String url;// 客户照片路径
private String next_visitime;// 下次回访时间(新增)
private String distanceTime;// 下次回访时间与当前时间
// 0:已删除1.正常
private String isenabled;//
/**
* 客户生日
*/
private String birthday;// 需新增字段
private String daysBetween;// 新建客户与当前日期的相差的天数
public String getIsenabled() {
return isenabled;
}
public void setIsenabled(String isenabled) {
this.isenabled = isenabled;
}
public Customer() {
}
public void finalize() throws Throwable {
}
public int getCust_id() {
return cust_id;
}
public void setCust_id(int cust_id) {
this.cust_id = cust_id;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getArea_id() {
return area_id;
}
public void setArea_id(String area_id) {
this.area_id = area_id;
}
public String getProvince_id() {
return province_id;
}
public void setProvince_id(String province_id) {
this.province_id = province_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMain_teacher() {
return main_teacher;
}
public void setMain_teacher(String main_teacher) {
this.main_teacher = main_teacher;
}
public String getElse_teacher() {
return else_teacher;
}
public void setElse_teacher(String else_teacher) {
this.else_teacher = else_teacher;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getCust_code() {
return cust_code;
}
public void setCust_code(String cust_code) {
this.cust_code = cust_code;
}
public String getUp_cust_code() {
return up_cust_code;
}
public void setUp_cust_code(String up_cust_code) {
this.up_cust_code = up_cust_code;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public String getCopyto() {
return copyto;
}
public void setCopyto(String copyto) {
this.copyto = copyto;
}
public String getCust_sourse() {
return cust_sourse;
}
public void setCust_sourse(String cust_sourse) {
this.cust_sourse = cust_sourse;
}
public String getInsert_user() {
return insert_user;
}
public void setInsert_user(String insert_user) {
this.insert_user = insert_user;
}
public String getInsert_time() {
return insert_time;
}
public void setInsert_time(String insert_time) {
this.insert_time = insert_time;
}
public String getUpdate_user() {
return update_user;
}
public void setUpdate_user(String update_user) {
this.update_user = update_user;
}
public String getUpdate_time() {
return update_time;
}
public void setUpdate_time(String update_time) {
this.update_time = update_time;
}
public String getShop_id() {
return shop_id;
}
public void setShop_id(String shop_id) {
this.shop_id = shop_id;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getShop_name() {
return shop_name;
}
public void setShop_name(String shop_name) {
this.shop_name = shop_name;
}
public String getArea_name() {
return area_name;
}
public void setArea_name(String area_name) {
this.area_name = area_name;
}
public String getProvince_name() {
return province_name;
}
public void setProvince_name(String province_name) {
this.province_name = province_name;
}
public String getMain_name() {
return main_name;
}
public void setMain_name(String main_name) {
this.main_name = main_name;
}
public String getElse_name() {
return else_name;
}
public void setElse_name(String else_name) {
this.else_name = else_name;
}
public String getDirector_name() {
return director_name;
}
public void setDirector_name(String director_name) {
this.director_name = director_name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getNext_visitime() {
return next_visitime;
}
public void setNext_visitime(String next_visitime) {
this.next_visitime = next_visitime;
}
public String getDistanceTime() {
return distanceTime;
}
public void setDistanceTime(String distanceTime) {
this.distanceTime = distanceTime;
}
public String getDeveloper() {
return developer;
}
public void setDeveloper(String developer) {
this.developer = developer;
}
public String getDeveloper_name() {
return developer_name;
}
public void setDeveloper_name(String developer_name) {
this.developer_name = developer_name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getDaysBetween() {
return daysBetween;
}
public void setDaysBetween(String daysBetween) {
this.daysBetween = daysBetween;
}
}
|
UTF-8
|
Java
| 7,564 |
java
|
Customer.java
|
Java
|
[
{
"context": " java.io.Serializable;\n\n/**\n * 客户信息\n * \n * @author Administrator\n * @version 1.0\n * @created 09-十月-2016 10:19:20\n ",
"end": 98,
"score": 0.9713110327720642,
"start": 85,
"tag": "NAME",
"value": "Administrator"
}
] | null |
[] |
package com.fanyi.oa.pojo;
import java.io.Serializable;
/**
* 客户信息
*
* @author Administrator
* @version 1.0
* @created 09-十月-2016 10:19:20
*/
public class Customer implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 客户id
*/
private int cust_id;
/**
* 客户姓名
*/
private String cust_name;
/**
* 0女;1男
*/
private String sex;
/**
* 年龄
*/
private String age;
/**
* 客户电话
*/
private String phone;
/**
* 所属店铺ID
*/
private String shop_id;
private String shop_name;// 新增店铺名称
/**
* 区域代码
*/
private String area_id;
private String area_name;// 新增区域名称
private String province_id;
private String province_name;// 新增省份名称
private String address;
/**
* 指派咨询师(主)
*/
private String main_teacher;
private String main_name;// 新增住咨询师名称
/**
* 咨询师(次)
*/
private String else_teacher;
private String else_name;
/**
* 总监
*/
private String director;
private String director_name;// 总监名称
/**
* 0老客户;1新客户
*/
private String flag;
/**
* 客户识别码
*/
private String cust_code;
/**
* 上一级客户识别码
*/
private String up_cust_code;
/**
* 主要负责人
*/
private String principal;
/**
* 抄送者
*/
private String copyto;
/**
* 1.远程咨询;2.积分系统;3.crm
*/
private String cust_sourse;
private String rank;// 新增级别字段A,B,C级
private String state;// 新增字段,0意客户;1.成单客户
/**
* 开发者
*/
private String developer;
private String developer_name;
private String insert_user;
private String insert_time;
private String update_user;
private String update_time;
private String filename;// 新增字段
private String url;// 客户照片路径
private String next_visitime;// 下次回访时间(新增)
private String distanceTime;// 下次回访时间与当前时间
// 0:已删除1.正常
private String isenabled;//
/**
* 客户生日
*/
private String birthday;// 需新增字段
private String daysBetween;// 新建客户与当前日期的相差的天数
public String getIsenabled() {
return isenabled;
}
public void setIsenabled(String isenabled) {
this.isenabled = isenabled;
}
public Customer() {
}
public void finalize() throws Throwable {
}
public int getCust_id() {
return cust_id;
}
public void setCust_id(int cust_id) {
this.cust_id = cust_id;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getArea_id() {
return area_id;
}
public void setArea_id(String area_id) {
this.area_id = area_id;
}
public String getProvince_id() {
return province_id;
}
public void setProvince_id(String province_id) {
this.province_id = province_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMain_teacher() {
return main_teacher;
}
public void setMain_teacher(String main_teacher) {
this.main_teacher = main_teacher;
}
public String getElse_teacher() {
return else_teacher;
}
public void setElse_teacher(String else_teacher) {
this.else_teacher = else_teacher;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getCust_code() {
return cust_code;
}
public void setCust_code(String cust_code) {
this.cust_code = cust_code;
}
public String getUp_cust_code() {
return up_cust_code;
}
public void setUp_cust_code(String up_cust_code) {
this.up_cust_code = up_cust_code;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public String getCopyto() {
return copyto;
}
public void setCopyto(String copyto) {
this.copyto = copyto;
}
public String getCust_sourse() {
return cust_sourse;
}
public void setCust_sourse(String cust_sourse) {
this.cust_sourse = cust_sourse;
}
public String getInsert_user() {
return insert_user;
}
public void setInsert_user(String insert_user) {
this.insert_user = insert_user;
}
public String getInsert_time() {
return insert_time;
}
public void setInsert_time(String insert_time) {
this.insert_time = insert_time;
}
public String getUpdate_user() {
return update_user;
}
public void setUpdate_user(String update_user) {
this.update_user = update_user;
}
public String getUpdate_time() {
return update_time;
}
public void setUpdate_time(String update_time) {
this.update_time = update_time;
}
public String getShop_id() {
return shop_id;
}
public void setShop_id(String shop_id) {
this.shop_id = shop_id;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getShop_name() {
return shop_name;
}
public void setShop_name(String shop_name) {
this.shop_name = shop_name;
}
public String getArea_name() {
return area_name;
}
public void setArea_name(String area_name) {
this.area_name = area_name;
}
public String getProvince_name() {
return province_name;
}
public void setProvince_name(String province_name) {
this.province_name = province_name;
}
public String getMain_name() {
return main_name;
}
public void setMain_name(String main_name) {
this.main_name = main_name;
}
public String getElse_name() {
return else_name;
}
public void setElse_name(String else_name) {
this.else_name = else_name;
}
public String getDirector_name() {
return director_name;
}
public void setDirector_name(String director_name) {
this.director_name = director_name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getNext_visitime() {
return next_visitime;
}
public void setNext_visitime(String next_visitime) {
this.next_visitime = next_visitime;
}
public String getDistanceTime() {
return distanceTime;
}
public void setDistanceTime(String distanceTime) {
this.distanceTime = distanceTime;
}
public String getDeveloper() {
return developer;
}
public void setDeveloper(String developer) {
this.developer = developer;
}
public String getDeveloper_name() {
return developer_name;
}
public void setDeveloper_name(String developer_name) {
this.developer_name = developer_name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getDaysBetween() {
return daysBetween;
}
public void setDaysBetween(String daysBetween) {
this.daysBetween = daysBetween;
}
}
| 7,564 | 0.679366 | 0.675751 | 450 | 14.984445 | 15.749913 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.2 | false | false |
3
|
45f6971de7cfd53189dd68f7cc676d1ddcebbbab
| 11,038,065,957,360 |
6ddc7090b75f0a74acabe292832f930877ccaa1b
|
/src/main/java/io/github/ilyazinkovich/caching/alternative/RedisCacheable.java
|
360edd76f5e4b85fc2da66bd91ac75389089f3ad
|
[] |
no_license
|
IlyaZinkovich/caching-without-compromises
|
https://github.com/IlyaZinkovich/caching-without-compromises
|
0e10e3a5a5c4d5c2bee8e3802f146e1d6b985d76
|
3077409659efdc18d82a4938a0f16edcb182110e
|
refs/heads/master
| 2020-05-04T21:31:25.402000 | 2019-04-07T16:40:00 | 2019-04-07T16:40:00 | 179,479,446 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.github.ilyazinkovich.caching.alternative;
import io.lettuce.core.api.async.RedisAsyncCommands;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RedisCacheable<T> implements Cacheable<T> {
private static final Logger log = LoggerFactory.getLogger(RedisCacheable.class);
private final RedisAsyncCommands<String, String> redis;
private final Serializer<T> jsonSerializable;
private final String cacheName;
RedisCacheable(
RedisAsyncCommands<String, String> redis,
Serializer<T> jsonSerializable, final String cacheName) {
this.redis = redis;
this.jsonSerializable = jsonSerializable;
this.cacheName = cacheName;
}
@Override
public CompletableFuture<T> getCachedOrLoad(
String key, Supplier<CompletableFuture<T>> loader) {
return getCached(key).thenCompose(cachedValue ->
deserialize(cachedValue).orElseGet(() -> loadAndCache(key, loader)));
}
private CompletableFuture<Optional<String>> getCached(
String key) {
return redis.get(toRedisKey(key))
.toCompletableFuture()
.thenApply(Optional::ofNullable)
.exceptionally(error -> {
log.warn("Unable to get cached value for key {} in cache {}.",
key, cacheName, error);
return Optional.empty();
});
}
private Optional<CompletableFuture<T>> deserialize(
Optional<String> cachedValue) {
return cachedValue
.flatMap(jsonSerializable::fromJson)
.map(CompletableFuture::completedFuture);
}
private CompletableFuture<T> loadAndCache(
String key, Supplier<CompletableFuture<T>> loader) {
return loader.get().thenCompose(value -> cache(key, value));
}
private CompletionStage<T> cache(String key, T value) {
return redis.set(toRedisKey(key), jsonSerializable.toJson(value))
.thenApply(result -> value)
.exceptionally(error -> {
log.warn("Unable to cache value {} for key {} in cache {}.",
value, key, cacheName, error);
return value;
});
}
private String toRedisKey(final String key) {
return String.format("%s:%s", cacheName, key);
}
}
|
UTF-8
|
Java
| 2,326 |
java
|
RedisCacheable.java
|
Java
|
[
{
"context": "package io.github.ilyazinkovich.caching.alternative;\n\nimport io.lettuce.core.api.",
"end": 31,
"score": 0.9996644258499146,
"start": 18,
"tag": "USERNAME",
"value": "ilyazinkovich"
}
] | null |
[] |
package io.github.ilyazinkovich.caching.alternative;
import io.lettuce.core.api.async.RedisAsyncCommands;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RedisCacheable<T> implements Cacheable<T> {
private static final Logger log = LoggerFactory.getLogger(RedisCacheable.class);
private final RedisAsyncCommands<String, String> redis;
private final Serializer<T> jsonSerializable;
private final String cacheName;
RedisCacheable(
RedisAsyncCommands<String, String> redis,
Serializer<T> jsonSerializable, final String cacheName) {
this.redis = redis;
this.jsonSerializable = jsonSerializable;
this.cacheName = cacheName;
}
@Override
public CompletableFuture<T> getCachedOrLoad(
String key, Supplier<CompletableFuture<T>> loader) {
return getCached(key).thenCompose(cachedValue ->
deserialize(cachedValue).orElseGet(() -> loadAndCache(key, loader)));
}
private CompletableFuture<Optional<String>> getCached(
String key) {
return redis.get(toRedisKey(key))
.toCompletableFuture()
.thenApply(Optional::ofNullable)
.exceptionally(error -> {
log.warn("Unable to get cached value for key {} in cache {}.",
key, cacheName, error);
return Optional.empty();
});
}
private Optional<CompletableFuture<T>> deserialize(
Optional<String> cachedValue) {
return cachedValue
.flatMap(jsonSerializable::fromJson)
.map(CompletableFuture::completedFuture);
}
private CompletableFuture<T> loadAndCache(
String key, Supplier<CompletableFuture<T>> loader) {
return loader.get().thenCompose(value -> cache(key, value));
}
private CompletionStage<T> cache(String key, T value) {
return redis.set(toRedisKey(key), jsonSerializable.toJson(value))
.thenApply(result -> value)
.exceptionally(error -> {
log.warn("Unable to cache value {} for key {} in cache {}.",
value, key, cacheName, error);
return value;
});
}
private String toRedisKey(final String key) {
return String.format("%s:%s", cacheName, key);
}
}
| 2,326 | 0.696045 | 0.695185 | 70 | 32.228573 | 23.322687 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.628571 | false | false |
3
|
e6b51fd37b634ca7cde09f78554cf24bdda0ea46
| 39,238,821,248,963 |
2975f338bd93a50c79fba7a287a2da3463f46a39
|
/src/main/java/m21_Strategy/StrategyImplB.java
|
1ce255a5dc5d40c9dedf80bb85fe75510540aa77
|
[] |
no_license
|
fyjjpe/design_mode_test
|
https://github.com/fyjjpe/design_mode_test
|
127650e18301d785cf951958dfdb569259a992bc
|
72aa522460c5350f4e00ba7b01df9d74eee645e0
|
refs/heads/master
| 2021-05-09T22:24:25.385000 | 2018-02-22T08:28:15 | 2018-02-22T08:28:15 | 118,749,571 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package m21_Strategy;
/**
* Created by yuanjie.fang on 2018/2/22.
*/
public class StrategyImplB implements Strategy {
public void strategyInterface() {
System.out.println("实现类B");
}
}
|
UTF-8
|
Java
| 209 |
java
|
StrategyImplB.java
|
Java
|
[
{
"context": "package m21_Strategy;\n\n/**\n * Created by yuanjie.fang on 2018/2/22.\n */\npublic class StrategyImplB impl",
"end": 53,
"score": 0.9558846354484558,
"start": 41,
"tag": "NAME",
"value": "yuanjie.fang"
}
] | null |
[] |
package m21_Strategy;
/**
* Created by yuanjie.fang on 2018/2/22.
*/
public class StrategyImplB implements Strategy {
public void strategyInterface() {
System.out.println("实现类B");
}
}
| 209 | 0.669951 | 0.625616 | 10 | 19.299999 | 18.050207 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false |
3
|
fd571df370cfb30d03f847b62aa17c07d5004631
| 37,228,776,560,043 |
deed52e2673dd15e5e4abe45fbc6f65b380568eb
|
/reformcloud-global/reformcloud-api/reformcloud-api-velocity/src/main/java/systems/reformcloud/commands/CommandJumpto.java
|
4ac587a77ec65a39e1d369d7dea79631c0d98746
|
[
"Apache-2.0"
] |
permissive
|
robertschuck/reformcloud
|
https://github.com/robertschuck/reformcloud
|
24523dd7063f8ceab5dc3b680f732296782b067e
|
a7563fa72b14041421dc6bacc9137d1fa0ad897c
|
refs/heads/master
| 2020-07-15T10:07:20.219000 | 2019-07-29T15:25:18 | 2019-07-29T15:25:18 | 205,539,389 | 0 | 0 |
Apache-2.0
| true | 2019-08-31T12:07:28 | 2019-08-31T12:07:28 | 2019-08-15T01:59:04 | 2019-08-24T13:05:57 | 8,722 | 0 | 0 | 0 | null | false | false |
/*
Copyright © 2018 Pasqual K. | All rights reserved
*/
package systems.reformcloud.commands;
import com.velocitypowered.api.command.Command;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.Player;
import net.kyori.text.TextComponent;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.optional.qual.MaybePresent;
import systems.reformcloud.ReformCloudAPIVelocity;
import systems.reformcloud.bootstrap.VelocityBootstrap;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* @author _Klaro | Pasqual K. / created on 09.12.2018
*/
public final class CommandJumpto implements Command {
@Override
public void execute(@MaybePresent CommandSource commandSource,
@NonNull @MaybePresent String[] strings) {
if (!(commandSource instanceof Player)) {
return;
}
final Player proxiedPlayer = (Player) commandSource;
if (!proxiedPlayer.hasPermission("reformcloud.command.jumpto")) {
return;
}
if (strings.length == 1) {
if (!this.isServerRegistered(strings[0]) &&
VelocityBootstrap.getInstance().getProxyServer().getPlayer(strings[0]).orElse(null)
== null) {
commandSource.sendMessage(
TextComponent.of(ReformCloudAPIVelocity.getInstance().getInternalCloudNetwork()
.getMessage("internal-api-bungee-command-jumpto-server-player-not-found")));
return;
}
if (VelocityBootstrap.getInstance().getProxyServer().getPlayer(strings[0]).orElse(null)
!= null) {
proxiedPlayer.createConnectionRequest(
VelocityBootstrap.getInstance().getProxyServer().getServer(VelocityBootstrap
.getInstance().getProxyServer().getPlayer(strings[0]).get()
.getCurrentServer().get().getServerInfo().getName()).get()).connect();
proxiedPlayer.sendMessage(TextComponent
.of(ReformCloudAPIVelocity.getInstance().getInternalCloudNetwork()
.getMessage("internal-api-bungee-command-jumpto-success")));
return;
}
if (this.isServerRegistered(strings[0])) {
proxiedPlayer.createConnectionRequest(
VelocityBootstrap.getInstance().getProxyServer().getServer(strings[0]).get())
.connect();
proxiedPlayer.sendMessage(TextComponent
.of(ReformCloudAPIVelocity.getInstance().getInternalCloudNetwork()
.getMessage("internal-api-bungee-command-jumpto-success")));
}
}
}
@Override
public boolean hasPermission(CommandSource source, @NonNull String[] args) {
return source.getPermissionValue("reformcloud.command.jumpto").asBoolean();
}
@Override
public @MaybePresent List<String> suggest(@MaybePresent CommandSource source,
@NonNull @MaybePresent String[] currentArgs) {
if (!source.hasPermission("reformcloud.command.jumpto")) {
return new LinkedList<>();
}
StringBuilder stringBuilder = new StringBuilder();
Arrays.stream(currentArgs).forEach(stringBuilder::append);
LinkedList<String> iterable = new LinkedList<>();
ReformCloudAPIVelocity.getInstance().getInternalCloudNetwork().getServerProcessManager()
.getRegisteredServerNameProcesses().stream()
.filter(e -> e.startsWith(stringBuilder.substring(0))).forEach(iterable::add);
VelocityBootstrap.getInstance().getProxyServer().getAllPlayers().stream()
.filter(e -> e.getUsername().startsWith(stringBuilder.substring(0)))
.forEach(e -> iterable.add(e.getUsername()));
return iterable;
}
private boolean isServerRegistered(String name) {
return VelocityBootstrap.getInstance().getProxyServer().getAllServers()
.stream()
.anyMatch(e -> e.getServerInfo().getName().equals(name));
}
}
|
UTF-8
|
Java
| 4,193 |
java
|
CommandJumpto.java
|
Java
|
[
{
"context": "/*\n Copyright © 2018 Pasqual K. | All rights reserved\n */\n\npackage systems.reform",
"end": 31,
"score": 0.999078631401062,
"start": 22,
"tag": "NAME",
"value": "Pasqual K"
},
{
"context": "LinkedList;\nimport java.util.List;\n\n/**\n * @author _Klaro | Pasqual K. / created on 09.12.2018\n */\n\npublic ",
"end": 613,
"score": 0.9989444613456726,
"start": 607,
"tag": "USERNAME",
"value": "_Klaro"
},
{
"context": "t;\nimport java.util.List;\n\n/**\n * @author _Klaro | Pasqual K. / created on 09.12.2018\n */\n\npublic final class C",
"end": 625,
"score": 0.989429235458374,
"start": 616,
"tag": "NAME",
"value": "Pasqual K"
}
] | null |
[] |
/*
Copyright © 2018 <NAME>. | All rights reserved
*/
package systems.reformcloud.commands;
import com.velocitypowered.api.command.Command;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.Player;
import net.kyori.text.TextComponent;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.optional.qual.MaybePresent;
import systems.reformcloud.ReformCloudAPIVelocity;
import systems.reformcloud.bootstrap.VelocityBootstrap;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* @author _Klaro | <NAME>. / created on 09.12.2018
*/
public final class CommandJumpto implements Command {
@Override
public void execute(@MaybePresent CommandSource commandSource,
@NonNull @MaybePresent String[] strings) {
if (!(commandSource instanceof Player)) {
return;
}
final Player proxiedPlayer = (Player) commandSource;
if (!proxiedPlayer.hasPermission("reformcloud.command.jumpto")) {
return;
}
if (strings.length == 1) {
if (!this.isServerRegistered(strings[0]) &&
VelocityBootstrap.getInstance().getProxyServer().getPlayer(strings[0]).orElse(null)
== null) {
commandSource.sendMessage(
TextComponent.of(ReformCloudAPIVelocity.getInstance().getInternalCloudNetwork()
.getMessage("internal-api-bungee-command-jumpto-server-player-not-found")));
return;
}
if (VelocityBootstrap.getInstance().getProxyServer().getPlayer(strings[0]).orElse(null)
!= null) {
proxiedPlayer.createConnectionRequest(
VelocityBootstrap.getInstance().getProxyServer().getServer(VelocityBootstrap
.getInstance().getProxyServer().getPlayer(strings[0]).get()
.getCurrentServer().get().getServerInfo().getName()).get()).connect();
proxiedPlayer.sendMessage(TextComponent
.of(ReformCloudAPIVelocity.getInstance().getInternalCloudNetwork()
.getMessage("internal-api-bungee-command-jumpto-success")));
return;
}
if (this.isServerRegistered(strings[0])) {
proxiedPlayer.createConnectionRequest(
VelocityBootstrap.getInstance().getProxyServer().getServer(strings[0]).get())
.connect();
proxiedPlayer.sendMessage(TextComponent
.of(ReformCloudAPIVelocity.getInstance().getInternalCloudNetwork()
.getMessage("internal-api-bungee-command-jumpto-success")));
}
}
}
@Override
public boolean hasPermission(CommandSource source, @NonNull String[] args) {
return source.getPermissionValue("reformcloud.command.jumpto").asBoolean();
}
@Override
public @MaybePresent List<String> suggest(@MaybePresent CommandSource source,
@NonNull @MaybePresent String[] currentArgs) {
if (!source.hasPermission("reformcloud.command.jumpto")) {
return new LinkedList<>();
}
StringBuilder stringBuilder = new StringBuilder();
Arrays.stream(currentArgs).forEach(stringBuilder::append);
LinkedList<String> iterable = new LinkedList<>();
ReformCloudAPIVelocity.getInstance().getInternalCloudNetwork().getServerProcessManager()
.getRegisteredServerNameProcesses().stream()
.filter(e -> e.startsWith(stringBuilder.substring(0))).forEach(iterable::add);
VelocityBootstrap.getInstance().getProxyServer().getAllPlayers().stream()
.filter(e -> e.getUsername().startsWith(stringBuilder.substring(0)))
.forEach(e -> iterable.add(e.getUsername()));
return iterable;
}
private boolean isServerRegistered(String name) {
return VelocityBootstrap.getInstance().getProxyServer().getAllServers()
.stream()
.anyMatch(e -> e.getServerInfo().getName().equals(name));
}
}
| 4,187 | 0.645992 | 0.640983 | 103 | 39.699028 | 32.488335 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.349515 | false | false |
3
|
c7cd54bdae8f55dbaac710ba756f8d4c1a266027
| 38,826,504,382,328 |
15a1316ccd03b0eabc5d901c96b6e75cef34d28a
|
/transport-base/src/main/java/com/gistandard/transport/base/entity/dao/MobileScheduSubOrderDao.java
|
06d82865271c7ead0f865f7744411b2922f1116b
|
[] |
no_license
|
bellmit/GistandardTransport
|
https://github.com/bellmit/GistandardTransport
|
fedfe6d1d9925900968f91b97570d21442b8ae0e
|
44130d832612adb72f153cb41977857eea551859
|
refs/heads/master
| 2022-02-20T20:03:09.729000 | 2017-09-14T09:35:28 | 2017-09-14T09:35:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.gistandard.transport.base.entity.dao;
import com.gistandard.transport.base.annotation.MyBatisRepository;
import com.gistandard.transport.base.entity.bean.MobileScheduSubOrder;
@MyBatisRepository
public interface MobileScheduSubOrderDao {
int deleteByPrimaryKey(Integer id);
int insert(MobileScheduSubOrder record);
int insertSelective(MobileScheduSubOrder record);
MobileScheduSubOrder selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(MobileScheduSubOrder record);
int updateByPrimaryKey(MobileScheduSubOrder record);
}
|
UTF-8
|
Java
| 576 |
java
|
MobileScheduSubOrderDao.java
|
Java
|
[] | null |
[] |
package com.gistandard.transport.base.entity.dao;
import com.gistandard.transport.base.annotation.MyBatisRepository;
import com.gistandard.transport.base.entity.bean.MobileScheduSubOrder;
@MyBatisRepository
public interface MobileScheduSubOrderDao {
int deleteByPrimaryKey(Integer id);
int insert(MobileScheduSubOrder record);
int insertSelective(MobileScheduSubOrder record);
MobileScheduSubOrder selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(MobileScheduSubOrder record);
int updateByPrimaryKey(MobileScheduSubOrder record);
}
| 576 | 0.828125 | 0.828125 | 18 | 31.055555 | 27.027706 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
3
|
11a92fac81b089d0bb8feb08c36326dd01442a92
| 23,965,917,511,983 |
2753311aa10600d5ffde7d5bd1f050b5f1d71d68
|
/src/main/java/by/sazanchuk/finalTask/service/ServiceInvocationHandlerImpl.java
|
233b639607e4e576512eac4d580da2fea151a17d
|
[] |
no_license
|
dianasaz/PetClinic
|
https://github.com/dianasaz/PetClinic
|
770d432fbb605a1ce62c4234ff6074f066a6687d
|
d8ac658046a9b8b5cbc60f38a55901c98a9e637d
|
refs/heads/master
| 2022-07-05T09:59:34.841000 | 2020-05-14T15:53:46 | 2020-05-14T15:53:46 | 233,541,206 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package by.sazanchuk.finalTask.service;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import by.sazanchuk.finalTask.dao.DaoException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* The type Service invocation handler.
*/
public class ServiceInvocationHandlerImpl implements InvocationHandler {
private static Logger logger = LogManager.getLogger(ServiceInvocationHandlerImpl.class);
private ServiceImpl service;
/**
* Instantiates a new Service invocation handler.
*
* @param service the service
*/
public ServiceInvocationHandlerImpl(ServiceImpl service) {
this.service = service;
}
@Override
public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
try {
Object result = method.invoke(service, arguments);
service.transaction.commit();
return result;
} catch(DaoException e) {
rollback(method);
throw e;
} catch(InvocationTargetException e) {
rollback(method);
throw e.getCause();
}
}
private void rollback(Method method) {
try {
service.transaction.rollback();
} catch(DaoException e) {
logger.warn("It is impossible to rollback transaction", e);
}
}
}
|
UTF-8
|
Java
| 1,456 |
java
|
ServiceInvocationHandlerImpl.java
|
Java
|
[] | null |
[] |
package by.sazanchuk.finalTask.service;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import by.sazanchuk.finalTask.dao.DaoException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* The type Service invocation handler.
*/
public class ServiceInvocationHandlerImpl implements InvocationHandler {
private static Logger logger = LogManager.getLogger(ServiceInvocationHandlerImpl.class);
private ServiceImpl service;
/**
* Instantiates a new Service invocation handler.
*
* @param service the service
*/
public ServiceInvocationHandlerImpl(ServiceImpl service) {
this.service = service;
}
@Override
public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
try {
Object result = method.invoke(service, arguments);
service.transaction.commit();
return result;
} catch(DaoException e) {
rollback(method);
throw e;
} catch(InvocationTargetException e) {
rollback(method);
throw e.getCause();
}
}
private void rollback(Method method) {
try {
service.transaction.rollback();
} catch(DaoException e) {
logger.warn("It is impossible to rollback transaction", e);
}
}
}
| 1,456 | 0.663462 | 0.662088 | 50 | 28.1 | 24.307405 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46 | false | false |
3
|
94255ce27a6b2f9751698f35d0526a3ad3299003
| 23,965,917,514,413 |
2ec905b5b130bed2aa6f1f37591317d80b7ce70d
|
/ihmc-common-walking-control-modules/src/test/java/us/ihmc/commonWalkingControlModules/momentumBasedController/MomentumControlTestTools.java
|
192d84bb0e3d4e6ddbe78d2301ad64e10405d2a1
|
[
"Apache-2.0"
] |
permissive
|
ihmcrobotics/ihmc-open-robotics-software
|
https://github.com/ihmcrobotics/ihmc-open-robotics-software
|
dbb1f9d7a4eaf01c08068b7233d1b01d25c5d037
|
42a4e385af75e8e13291d6156a5c7bebebbecbfd
|
refs/heads/develop
| 2023-09-01T18:18:14.623000 | 2023-09-01T14:16:26 | 2023-09-01T14:16:26 | 50,613,360 | 227 | 91 | null | false | 2023-01-25T21:39:35 | 2016-01-28T21:00:16 | 2023-01-23T10:08:40 | 2023-01-25T21:39:32 | 980,849 | 195 | 77 | 30 |
Java
| false | false |
package us.ihmc.commonWalkingControlModules.momentumBasedController;
import static us.ihmc.robotics.Assert.*;
import java.util.Collection;
import java.util.Map;
import us.ihmc.commonWalkingControlModules.bipedSupportPolygons.PlaneContactState;
import us.ihmc.commonWalkingControlModules.controlModules.CenterOfPressureResolver;
import us.ihmc.euclid.referenceFrame.FrameConvexPolygon2D;
import us.ihmc.euclid.referenceFrame.FramePoint2D;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.euclid.referenceFrame.interfaces.FrameVertex2DSupplier;
import us.ihmc.mecano.algorithms.InverseDynamicsCalculator;
import us.ihmc.mecano.multiBodySystem.SixDoFJoint;
import us.ihmc.mecano.multiBodySystem.interfaces.RigidBodyBasics;
import us.ihmc.mecano.spatial.SpatialForce;
import us.ihmc.mecano.spatial.Wrench;
import us.ihmc.mecano.tools.MecanoTestTools;
import us.ihmc.robotics.contactable.ContactablePlaneBody;
/**
* @author twan
* Date: 5/7/13
*/
public class MomentumControlTestTools
{
public static void assertWrenchesSumUpToMomentumDot(Collection<Wrench> externalWrenches, SpatialForce desiredCentroidalMomentumRate, double gravityZ,
double mass, ReferenceFrame centerOfMassFrame, double epsilon)
{
SpatialForce totalWrench = new SpatialForce(centerOfMassFrame);
Wrench tempWrench = new Wrench();
for (Wrench wrench : externalWrenches)
{
tempWrench.setIncludingFrame(wrench);
tempWrench.changeFrame(centerOfMassFrame);
totalWrench.add(tempWrench);
}
Wrench gravitationalWrench = new Wrench(centerOfMassFrame, centerOfMassFrame);
gravitationalWrench.setLinearPartZ(-mass * gravityZ);
totalWrench.add(gravitationalWrench);
MecanoTestTools.assertSpatialForceEquals(desiredCentroidalMomentumRate, totalWrench, epsilon);
}
public static void assertWrenchesInFrictionCones(Map<RigidBodyBasics, Wrench> externalWrenches,
Map<ContactablePlaneBody, ? extends PlaneContactState> contactStates, double coefficientOfFriction)
{
CenterOfPressureResolver centerOfPressureResolver = new CenterOfPressureResolver();
for (ContactablePlaneBody contactablePlaneBody : contactStates.keySet())
{
Wrench wrench = externalWrenches.get(contactablePlaneBody.getRigidBody());
PlaneContactState contactState = contactStates.get(contactablePlaneBody);
ReferenceFrame planeFrame = contactState.getPlaneFrame();
wrench.changeFrame(planeFrame);
double fZ = wrench.getLinearPartZ();
assertTrue(fZ > 0.0);
double fT = Math.hypot(wrench.getLinearPartX(), wrench.getLinearPartY());
assertTrue(fT / fZ < coefficientOfFriction);
FramePoint2D cop = new FramePoint2D(planeFrame);
centerOfPressureResolver.resolveCenterOfPressureAndNormalTorque(cop, wrench, planeFrame);
FrameConvexPolygon2D supportPolygon = new FrameConvexPolygon2D(FrameVertex2DSupplier.asFrameVertex2DSupplier(contactState.getContactFramePoints2dInContactCopy()));
assertTrue(supportPolygon.isPointInside(cop));
}
}
public static void assertRootJointWrenchZero(Map<RigidBodyBasics, Wrench> externalWrenches, SixDoFJoint rootJoint, double gravityZ, double epsilon)
{
InverseDynamicsCalculator inverseDynamicsCalculator = new InverseDynamicsCalculator(rootJoint.getPredecessor());
inverseDynamicsCalculator.setGravitionalAcceleration(-gravityZ);
for (RigidBodyBasics rigidBody : externalWrenches.keySet())
{
Wrench externalWrench = externalWrenches.get(rigidBody);
externalWrench.changeFrame(rigidBody.getBodyFixedFrame());
inverseDynamicsCalculator.setExternalWrench(rigidBody, externalWrench);
}
inverseDynamicsCalculator.compute();
Wrench wrench = new Wrench();
wrench.setIncludingFrame(rootJoint.getJointWrench());
SpatialForce zeroWrench = new SpatialForce(wrench.getReferenceFrame());
MecanoTestTools.assertSpatialForceEquals(wrench, zeroWrench, epsilon);
}
}
|
UTF-8
|
Java
| 4,082 |
java
|
MomentumControlTestTools.java
|
Java
|
[
{
"context": ".contactable.ContactablePlaneBody;\n\n/**\n * @author twan\n * Date: 5/7/13\n */\npublic class Momentum",
"end": 947,
"score": 0.9965143203735352,
"start": 943,
"tag": "USERNAME",
"value": "twan"
}
] | null |
[] |
package us.ihmc.commonWalkingControlModules.momentumBasedController;
import static us.ihmc.robotics.Assert.*;
import java.util.Collection;
import java.util.Map;
import us.ihmc.commonWalkingControlModules.bipedSupportPolygons.PlaneContactState;
import us.ihmc.commonWalkingControlModules.controlModules.CenterOfPressureResolver;
import us.ihmc.euclid.referenceFrame.FrameConvexPolygon2D;
import us.ihmc.euclid.referenceFrame.FramePoint2D;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.euclid.referenceFrame.interfaces.FrameVertex2DSupplier;
import us.ihmc.mecano.algorithms.InverseDynamicsCalculator;
import us.ihmc.mecano.multiBodySystem.SixDoFJoint;
import us.ihmc.mecano.multiBodySystem.interfaces.RigidBodyBasics;
import us.ihmc.mecano.spatial.SpatialForce;
import us.ihmc.mecano.spatial.Wrench;
import us.ihmc.mecano.tools.MecanoTestTools;
import us.ihmc.robotics.contactable.ContactablePlaneBody;
/**
* @author twan
* Date: 5/7/13
*/
public class MomentumControlTestTools
{
public static void assertWrenchesSumUpToMomentumDot(Collection<Wrench> externalWrenches, SpatialForce desiredCentroidalMomentumRate, double gravityZ,
double mass, ReferenceFrame centerOfMassFrame, double epsilon)
{
SpatialForce totalWrench = new SpatialForce(centerOfMassFrame);
Wrench tempWrench = new Wrench();
for (Wrench wrench : externalWrenches)
{
tempWrench.setIncludingFrame(wrench);
tempWrench.changeFrame(centerOfMassFrame);
totalWrench.add(tempWrench);
}
Wrench gravitationalWrench = new Wrench(centerOfMassFrame, centerOfMassFrame);
gravitationalWrench.setLinearPartZ(-mass * gravityZ);
totalWrench.add(gravitationalWrench);
MecanoTestTools.assertSpatialForceEquals(desiredCentroidalMomentumRate, totalWrench, epsilon);
}
public static void assertWrenchesInFrictionCones(Map<RigidBodyBasics, Wrench> externalWrenches,
Map<ContactablePlaneBody, ? extends PlaneContactState> contactStates, double coefficientOfFriction)
{
CenterOfPressureResolver centerOfPressureResolver = new CenterOfPressureResolver();
for (ContactablePlaneBody contactablePlaneBody : contactStates.keySet())
{
Wrench wrench = externalWrenches.get(contactablePlaneBody.getRigidBody());
PlaneContactState contactState = contactStates.get(contactablePlaneBody);
ReferenceFrame planeFrame = contactState.getPlaneFrame();
wrench.changeFrame(planeFrame);
double fZ = wrench.getLinearPartZ();
assertTrue(fZ > 0.0);
double fT = Math.hypot(wrench.getLinearPartX(), wrench.getLinearPartY());
assertTrue(fT / fZ < coefficientOfFriction);
FramePoint2D cop = new FramePoint2D(planeFrame);
centerOfPressureResolver.resolveCenterOfPressureAndNormalTorque(cop, wrench, planeFrame);
FrameConvexPolygon2D supportPolygon = new FrameConvexPolygon2D(FrameVertex2DSupplier.asFrameVertex2DSupplier(contactState.getContactFramePoints2dInContactCopy()));
assertTrue(supportPolygon.isPointInside(cop));
}
}
public static void assertRootJointWrenchZero(Map<RigidBodyBasics, Wrench> externalWrenches, SixDoFJoint rootJoint, double gravityZ, double epsilon)
{
InverseDynamicsCalculator inverseDynamicsCalculator = new InverseDynamicsCalculator(rootJoint.getPredecessor());
inverseDynamicsCalculator.setGravitionalAcceleration(-gravityZ);
for (RigidBodyBasics rigidBody : externalWrenches.keySet())
{
Wrench externalWrench = externalWrenches.get(rigidBody);
externalWrench.changeFrame(rigidBody.getBodyFixedFrame());
inverseDynamicsCalculator.setExternalWrench(rigidBody, externalWrench);
}
inverseDynamicsCalculator.compute();
Wrench wrench = new Wrench();
wrench.setIncludingFrame(rootJoint.getJointWrench());
SpatialForce zeroWrench = new SpatialForce(wrench.getReferenceFrame());
MecanoTestTools.assertSpatialForceEquals(wrench, zeroWrench, epsilon);
}
}
| 4,082 | 0.775355 | 0.771436 | 91 | 43.857143 | 38.811058 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.78022 | false | false |
3
|
7b576e5a000c4d94f8b66de687da16b811e0cf74
| 2,748,779,076,479 |
2c93fa0b266d392a601fc4408135f2430c667a49
|
/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/validation/TimeFormatValidation.java
|
e4f8ff51e8dea442eeac9407053287fdbc86c059
|
[
"Apache-2.0"
] |
permissive
|
jbeecham/ovirt-engine
|
https://github.com/jbeecham/ovirt-engine
|
5d79080d2f5627229e6551fee78882f9f9a6e3bc
|
3e76a8d3b970a963cedd84bcb3c7425b8484cf26
|
refs/heads/master
| 2021-01-01T17:15:29.961000 | 2012-10-25T14:41:57 | 2012-10-26T08:56:22 | 10,623,147 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.ovirt.engine.ui.uicommonweb.validation;
import org.ovirt.engine.core.compat.CultureInfo;
import org.ovirt.engine.core.compat.DateTime;
import org.ovirt.engine.core.compat.DateTimeStyles;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import java.util.Date;
@SuppressWarnings("unused")
public class TimeFormatValidation implements IValidation
{
@Override
public ValidationResult Validate(Object value)
{
ValidationResult result = new ValidationResult();
if (value != null && value instanceof String && !((String) value).equals("")) //$NON-NLS-1$
{
CultureInfo ci = CultureInfo.CurrentCulture;
Date dtValue = new Date(0);
RefObject<Date> tempRef_dtValue = new RefObject<Date>(dtValue);
boolean tempVar =
!DateTime.TryParseExact((String) value, "t", //$NON-NLS-1$
ci.DateTimeFormat,
DateTimeStyles.None,
tempRef_dtValue);
dtValue = tempRef_dtValue.argvalue;
if (tempVar)
{
result.setSuccess(false);
result.getReasons().add(ConstantsManager.getInstance()
.getConstants()
.theFieldMustContainTimeValueInvalidReason());
}
}
return result;
}
}
|
UTF-8
|
Java
| 1,445 |
java
|
TimeFormatValidation.java
|
Java
|
[] | null |
[] |
package org.ovirt.engine.ui.uicommonweb.validation;
import org.ovirt.engine.core.compat.CultureInfo;
import org.ovirt.engine.core.compat.DateTime;
import org.ovirt.engine.core.compat.DateTimeStyles;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import java.util.Date;
@SuppressWarnings("unused")
public class TimeFormatValidation implements IValidation
{
@Override
public ValidationResult Validate(Object value)
{
ValidationResult result = new ValidationResult();
if (value != null && value instanceof String && !((String) value).equals("")) //$NON-NLS-1$
{
CultureInfo ci = CultureInfo.CurrentCulture;
Date dtValue = new Date(0);
RefObject<Date> tempRef_dtValue = new RefObject<Date>(dtValue);
boolean tempVar =
!DateTime.TryParseExact((String) value, "t", //$NON-NLS-1$
ci.DateTimeFormat,
DateTimeStyles.None,
tempRef_dtValue);
dtValue = tempRef_dtValue.argvalue;
if (tempVar)
{
result.setSuccess(false);
result.getReasons().add(ConstantsManager.getInstance()
.getConstants()
.theFieldMustContainTimeValueInvalidReason());
}
}
return result;
}
}
| 1,445 | 0.601384 | 0.599308 | 42 | 33.404762 | 25.880733 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false |
3
|
a7ecc8fff790b090e75d18db070de11540e77c9d
| 22,892,175,695,357 |
00d82d5737250f24f1211bf2b39a170320c0f598
|
/src/main/java/ndesilets/wstest/models/APIJobCompletion.java
|
5432d1757638c26596600432c24b51d53e463612
|
[] |
no_license
|
ndesilets/ws-test
|
https://github.com/ndesilets/ws-test
|
af17409eee93bd3c3b236f0560a8ab4ea681da4d
|
70c10be0bb5149e83589487cb359315516fabbce
|
refs/heads/master
| 2020-04-08T19:08:48.850000 | 2018-11-29T19:03:42 | 2018-11-29T19:03:42 | 159,642,133 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ndesilets.wstest.models;
public class APIJobCompletion {
private Job job;
private String status;
public APIJobCompletion(Job job, String status) {
this.job = job;
this.status = status;
}
public Job getJob() {
return job;
}
public String getStatus() {
return status;
}
}
|
UTF-8
|
Java
| 346 |
java
|
APIJobCompletion.java
|
Java
|
[] | null |
[] |
package ndesilets.wstest.models;
public class APIJobCompletion {
private Job job;
private String status;
public APIJobCompletion(Job job, String status) {
this.job = job;
this.status = status;
}
public Job getJob() {
return job;
}
public String getStatus() {
return status;
}
}
| 346 | 0.606936 | 0.606936 | 19 | 17.210526 | 14.724054 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false |
3
|
8b5232a614a796d1fea5d2666deb925408989a38
| 25,254,407,707,887 |
6b102ab7fec59a757af76d17ea81e998525424e6
|
/CMUPayWebPay/src/main/java/com/huateng/bean/AliData.java
|
7e62b25d2ad5f4d8c64358ec805bb37e5f198b4e
|
[] |
no_license
|
justfordream/my-2
|
https://github.com/justfordream/my-2
|
a52516b87de9321916c0f111328fe1ced17e3549
|
e7b2d1003afbd5df8351342692e94a11b7ec15c5
|
refs/heads/master
| 2016-08-10T13:48:44.772000 | 2015-06-01T15:40:45 | 2015-06-01T15:40:45 | 36,330,084 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.huateng.bean;
import java.util.HashMap;
import java.util.Map;
/**
* 支付宝返回参数
*
* @author Administrator
*
*/
public class AliData {
// 成功标识
private String is_success;
// 签名方式
private String sign_type;
// 签名
private String sign;
// 商户网站唯一订单号
private String out_trade_no;
// 商品名称
private String subject;
// 支付类型
private String payment_type;
// 接口名称
private String exterface;
// 支付宝交易号
private String trade_no;
// 交易状态
private String trade_status;
// 通知校验ID
private String notify_id;
// 通知时间
private String notify_time;
// 通知类型
private String notify_type;
// 卖家支付宝账号
private String seller_email;
// 买家支付宝账号
private String buyer_email;
// 卖家支付宝账户号
private String seller_id;
// 买家支付宝账户号
private String buyer_id;
// 交易金额
private String total_fee;
// 商品描述
private String body;
// 公用回传参数
private String extra_common_param;
// 信用支付购票员的代理人ID
private String agent_user_id;
// ******************
private String serverURL;
private String backURL;
private String status;
private String errorMsg;
public String getIs_success() {
return is_success;
}
public void setIs_success(String is_success) {
this.is_success = is_success;
}
public String getSign_type() {
return sign_type;
}
public void setSign_type(String sign_type) {
this.sign_type = sign_type;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getPayment_type() {
return payment_type;
}
public void setPayment_type(String payment_type) {
this.payment_type = payment_type;
}
public String getExterface() {
return exterface;
}
public void setExterface(String exterface) {
this.exterface = exterface;
}
public String getTrade_no() {
return trade_no;
}
public void setTrade_no(String trade_no) {
this.trade_no = trade_no;
}
public String getTrade_status() {
return trade_status;
}
public void setTrade_status(String trade_status) {
this.trade_status = trade_status;
}
public String getNotify_id() {
return notify_id;
}
public void setNotify_id(String notify_id) {
this.notify_id = notify_id;
}
public String getNotify_time() {
return notify_time;
}
public void setNotify_time(String notify_time) {
this.notify_time = notify_time;
}
public String getNotify_type() {
return notify_type;
}
public void setNotify_type(String notify_type) {
this.notify_type = notify_type;
}
public String getSeller_email() {
return seller_email;
}
public void setSeller_email(String seller_email) {
this.seller_email = seller_email;
}
public String getBuyer_email() {
return buyer_email;
}
public void setBuyer_email(String buyer_email) {
this.buyer_email = buyer_email;
}
public String getSeller_id() {
return seller_id;
}
public void setSeller_id(String seller_id) {
this.seller_id = seller_id;
}
public String getBuyer_id() {
return buyer_id;
}
public void setBuyer_id(String buyer_id) {
this.buyer_id = buyer_id;
}
public String getTotal_fee() {
return total_fee;
}
public void setTotal_fee(String total_fee) {
this.total_fee = total_fee;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getExtra_common_param() {
return extra_common_param;
}
public void setExtra_common_param(String extra_common_param) {
this.extra_common_param = extra_common_param;
}
public String getAgent_user_id() {
return agent_user_id;
}
public void setAgent_user_id(String agent_user_id) {
this.agent_user_id = agent_user_id;
}
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}
public String getBackURL() {
return backURL;
}
public void setBackURL(String backURL) {
this.backURL = backURL;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
@Override
public String toString() {
return "AliData [is_success=" + is_success + ", sign_type=" + sign_type
+ ", sign=" + sign + ", out_trade_no=" + out_trade_no
+ ", subject=" + subject + ", payment_type=" + payment_type
+ ", exterface=" + exterface + ", trade_no=" + trade_no
+ ", trade_status=" + trade_status + ", notify_id=" + notify_id
+ ", notify_time=" + notify_time + ", notify_type="
+ notify_type + ", seller_email=" + seller_email
+ ", buyer_email=" + buyer_email + ", seller_id=" + seller_id
+ ", buyer_id=" + buyer_id + ", total_fee=" + total_fee
+ ", body=" + body + ", extra_common_param="
+ extra_common_param + ", agent_user_id=" + agent_user_id
+ ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
+ ", toString()=" + super.toString() + "]";
}
public Map<String, String> assemlyPayPlainMap() {
Map<String, String> plainMap = new HashMap<String, String>();
plainMap.put("is_success", is_success);
plainMap.put("sign_type", sign_type);
plainMap.put("sign", sign);
plainMap.put("out_trade_no", out_trade_no);
plainMap.put("subject", subject);
plainMap.put("payment_type", payment_type);
plainMap.put("exterface", exterface);
plainMap.put("trade_no", trade_no);
plainMap.put("trade_status", trade_status);
plainMap.put("notify_id", notify_id);
plainMap.put("notify_time", notify_time);
plainMap.put("notify_type", notify_type);
plainMap.put("seller_email", seller_email);
plainMap.put("buyer_email", buyer_email);
plainMap.put("seller_id", seller_id);
plainMap.put("buyer_id", buyer_id);
plainMap.put("total_fee", total_fee);
plainMap.put("body", body);
plainMap.put("extra_common_param", extra_common_param);
plainMap.put("agent_user_id", agent_user_id);
return plainMap;
}
}
|
UTF-8
|
Java
| 6,440 |
java
|
AliData.java
|
Java
|
[
{
"context": "port java.util.Map;\n\n/**\n * 支付宝返回参数\n * \n * @author Administrator\n * \n */\npublic class AliData {\n\n\t// 成功标识\n\tprivate",
"end": 119,
"score": 0.9882558584213257,
"start": 106,
"tag": "NAME",
"value": "Administrator"
}
] | null |
[] |
package com.huateng.bean;
import java.util.HashMap;
import java.util.Map;
/**
* 支付宝返回参数
*
* @author Administrator
*
*/
public class AliData {
// 成功标识
private String is_success;
// 签名方式
private String sign_type;
// 签名
private String sign;
// 商户网站唯一订单号
private String out_trade_no;
// 商品名称
private String subject;
// 支付类型
private String payment_type;
// 接口名称
private String exterface;
// 支付宝交易号
private String trade_no;
// 交易状态
private String trade_status;
// 通知校验ID
private String notify_id;
// 通知时间
private String notify_time;
// 通知类型
private String notify_type;
// 卖家支付宝账号
private String seller_email;
// 买家支付宝账号
private String buyer_email;
// 卖家支付宝账户号
private String seller_id;
// 买家支付宝账户号
private String buyer_id;
// 交易金额
private String total_fee;
// 商品描述
private String body;
// 公用回传参数
private String extra_common_param;
// 信用支付购票员的代理人ID
private String agent_user_id;
// ******************
private String serverURL;
private String backURL;
private String status;
private String errorMsg;
public String getIs_success() {
return is_success;
}
public void setIs_success(String is_success) {
this.is_success = is_success;
}
public String getSign_type() {
return sign_type;
}
public void setSign_type(String sign_type) {
this.sign_type = sign_type;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getPayment_type() {
return payment_type;
}
public void setPayment_type(String payment_type) {
this.payment_type = payment_type;
}
public String getExterface() {
return exterface;
}
public void setExterface(String exterface) {
this.exterface = exterface;
}
public String getTrade_no() {
return trade_no;
}
public void setTrade_no(String trade_no) {
this.trade_no = trade_no;
}
public String getTrade_status() {
return trade_status;
}
public void setTrade_status(String trade_status) {
this.trade_status = trade_status;
}
public String getNotify_id() {
return notify_id;
}
public void setNotify_id(String notify_id) {
this.notify_id = notify_id;
}
public String getNotify_time() {
return notify_time;
}
public void setNotify_time(String notify_time) {
this.notify_time = notify_time;
}
public String getNotify_type() {
return notify_type;
}
public void setNotify_type(String notify_type) {
this.notify_type = notify_type;
}
public String getSeller_email() {
return seller_email;
}
public void setSeller_email(String seller_email) {
this.seller_email = seller_email;
}
public String getBuyer_email() {
return buyer_email;
}
public void setBuyer_email(String buyer_email) {
this.buyer_email = buyer_email;
}
public String getSeller_id() {
return seller_id;
}
public void setSeller_id(String seller_id) {
this.seller_id = seller_id;
}
public String getBuyer_id() {
return buyer_id;
}
public void setBuyer_id(String buyer_id) {
this.buyer_id = buyer_id;
}
public String getTotal_fee() {
return total_fee;
}
public void setTotal_fee(String total_fee) {
this.total_fee = total_fee;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getExtra_common_param() {
return extra_common_param;
}
public void setExtra_common_param(String extra_common_param) {
this.extra_common_param = extra_common_param;
}
public String getAgent_user_id() {
return agent_user_id;
}
public void setAgent_user_id(String agent_user_id) {
this.agent_user_id = agent_user_id;
}
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}
public String getBackURL() {
return backURL;
}
public void setBackURL(String backURL) {
this.backURL = backURL;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
@Override
public String toString() {
return "AliData [is_success=" + is_success + ", sign_type=" + sign_type
+ ", sign=" + sign + ", out_trade_no=" + out_trade_no
+ ", subject=" + subject + ", payment_type=" + payment_type
+ ", exterface=" + exterface + ", trade_no=" + trade_no
+ ", trade_status=" + trade_status + ", notify_id=" + notify_id
+ ", notify_time=" + notify_time + ", notify_type="
+ notify_type + ", seller_email=" + seller_email
+ ", buyer_email=" + buyer_email + ", seller_id=" + seller_id
+ ", buyer_id=" + buyer_id + ", total_fee=" + total_fee
+ ", body=" + body + ", extra_common_param="
+ extra_common_param + ", agent_user_id=" + agent_user_id
+ ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
+ ", toString()=" + super.toString() + "]";
}
public Map<String, String> assemlyPayPlainMap() {
Map<String, String> plainMap = new HashMap<String, String>();
plainMap.put("is_success", is_success);
plainMap.put("sign_type", sign_type);
plainMap.put("sign", sign);
plainMap.put("out_trade_no", out_trade_no);
plainMap.put("subject", subject);
plainMap.put("payment_type", payment_type);
plainMap.put("exterface", exterface);
plainMap.put("trade_no", trade_no);
plainMap.put("trade_status", trade_status);
plainMap.put("notify_id", notify_id);
plainMap.put("notify_time", notify_time);
plainMap.put("notify_type", notify_type);
plainMap.put("seller_email", seller_email);
plainMap.put("buyer_email", buyer_email);
plainMap.put("seller_id", seller_id);
plainMap.put("buyer_id", buyer_id);
plainMap.put("total_fee", total_fee);
plainMap.put("body", body);
plainMap.put("extra_common_param", extra_common_param);
plainMap.put("agent_user_id", agent_user_id);
return plainMap;
}
}
| 6,440 | 0.672142 | 0.672142 | 317 | 18.589905 | 18.504215 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.511041 | false | false |
3
|
74fe4e3891556a067c0d59685a2ef5b5b6b5cf82
| 32,229,434,595,995 |
ec41644f07f764bab56198a203e754f3f88c4bcd
|
/Interpret/Interpret8/MyConstructor.java
|
bcbd0f01faf4c48e829f2c24ca240473a27c339e
|
[] |
no_license
|
ko-haneda/Java2013
|
https://github.com/ko-haneda/Java2013
|
b5cc5da4bf6eb91df778a69957bcb3268929958f
|
b7aeaea08ec64fd7826cc29603feab60ec7d63f4
|
refs/heads/master
| 2020-12-24T16:14:58.625000 | 2014-08-07T15:18:36 | 2014-08-07T15:18:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Interpret8;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Comparator;
public class MyConstructor {
//クラス名(引数str)からコンストラクタの一覧を取得
public static Constructor<?>[] getConstructors(String str) throws SecurityException, ClassNotFoundException {
return Class.forName(str).getDeclaredConstructors();
}
//指定されたコンストラクタ(引数con)を呼び出し、インスタンスを生成する。
//コンストラクタに必要な引数(input)
public static Object newConstructor(Constructor<?> con, String input) throws InstantiationException, IllegalAccessException, InvocationTargetException{
String[] inputs = input.split(",");
con.setAccessible(true);
Type[] types = con.getGenericParameterTypes();
if(types.length == 0){
return con.newInstance();
}
if(types.length != types.length){
System.out.println("引数の数が異なります。");
}
Object[] params = new Object[inputs.length];
int i = 0;
for (Type type : types) {
params[i] = Interpret.createObject(type, inputs[i++]);
}
return con.newInstance(params);
}
public static String getSimpleName(Constructor<?> c){
StringBuffer sb = new StringBuffer();
int m = c.getModifiers();
if(Modifier.isPublic(m)) sb.append("public ");
if(Modifier.isProtected(m)) sb.append("protected ");
if(Modifier.isPrivate(m)) sb.append("private ");
if(Modifier.isStatic(m)) sb.append("static ");
if(Modifier.isFinal(m)) sb.append("final ");
sb.append(c.getDeclaringClass().getSimpleName());
Class<?> []cl = c.getParameterTypes();
sb.append("(");
int i = 0;
for(Class<?> cla: cl){
if(i++ != 0) sb.append(" ,");
sb.append(cla.getSimpleName());
}
sb.append(")");
return sb.toString();
}
static class ConstructorComparator implements Comparator<Constructor<?>> {
public int compare(Constructor<?> c1, Constructor<?> c2) {
int comp = c1.getParameterTypes().length - c2.getParameterTypes().length;
if(comp != 0) return comp;
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
for(Class<?> c: c1.getParameterTypes()) sb1.append(c.getSimpleName().toLowerCase());
for(Class<?> c: c2.getParameterTypes()) sb2.append(c.getSimpleName().toLowerCase());
return sb1.toString().compareTo(sb2.toString());
}
}
}
|
UTF-8
|
Java
| 2,461 |
java
|
MyConstructor.java
|
Java
|
[] | null |
[] |
package Interpret8;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.Comparator;
public class MyConstructor {
//クラス名(引数str)からコンストラクタの一覧を取得
public static Constructor<?>[] getConstructors(String str) throws SecurityException, ClassNotFoundException {
return Class.forName(str).getDeclaredConstructors();
}
//指定されたコンストラクタ(引数con)を呼び出し、インスタンスを生成する。
//コンストラクタに必要な引数(input)
public static Object newConstructor(Constructor<?> con, String input) throws InstantiationException, IllegalAccessException, InvocationTargetException{
String[] inputs = input.split(",");
con.setAccessible(true);
Type[] types = con.getGenericParameterTypes();
if(types.length == 0){
return con.newInstance();
}
if(types.length != types.length){
System.out.println("引数の数が異なります。");
}
Object[] params = new Object[inputs.length];
int i = 0;
for (Type type : types) {
params[i] = Interpret.createObject(type, inputs[i++]);
}
return con.newInstance(params);
}
public static String getSimpleName(Constructor<?> c){
StringBuffer sb = new StringBuffer();
int m = c.getModifiers();
if(Modifier.isPublic(m)) sb.append("public ");
if(Modifier.isProtected(m)) sb.append("protected ");
if(Modifier.isPrivate(m)) sb.append("private ");
if(Modifier.isStatic(m)) sb.append("static ");
if(Modifier.isFinal(m)) sb.append("final ");
sb.append(c.getDeclaringClass().getSimpleName());
Class<?> []cl = c.getParameterTypes();
sb.append("(");
int i = 0;
for(Class<?> cla: cl){
if(i++ != 0) sb.append(" ,");
sb.append(cla.getSimpleName());
}
sb.append(")");
return sb.toString();
}
static class ConstructorComparator implements Comparator<Constructor<?>> {
public int compare(Constructor<?> c1, Constructor<?> c2) {
int comp = c1.getParameterTypes().length - c2.getParameterTypes().length;
if(comp != 0) return comp;
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
for(Class<?> c: c1.getParameterTypes()) sb1.append(c.getSimpleName().toLowerCase());
for(Class<?> c: c2.getParameterTypes()) sb2.append(c.getSimpleName().toLowerCase());
return sb1.toString().compareTo(sb2.toString());
}
}
}
| 2,461 | 0.708207 | 0.700391 | 68 | 32.85294 | 28.152559 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.411765 | false | false |
3
|
0318c2a8839d77045438f0bdf7fe53cba95b84e7
| 32,229,434,593,944 |
8592849772932f3dc2e377db80ab5a23c02386a0
|
/src/ua/org/ao/andreyzarazka/network/TestURLConnection.java
|
d0fe9d229c1f6e11209d6ba9d5db8f84efc2f5a5
|
[] |
no_license
|
zar1k/Schildt
|
https://github.com/zar1k/Schildt
|
fa33b33dc4f7a6825df659681ed3333f27ff835e
|
7406814b56a5b490ad885633dd543aabe48933d4
|
refs/heads/master
| 2016-08-07T13:03:30.989000 | 2015-09-19T08:00:14 | 2015-09-19T08:00:14 | 42,668,400 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ua.org.ao.andreyzarazka.network;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TestURLConnection {
public static void main(String[] args) throws IOException {
List<String> listOfSites = new ArrayList<>();
listOfSites.add("http://www.google.com");
listOfSites.add("http://dou.ua");
listOfSites.add("https://www.gismeteo.ua");
listOfSites.add("http://imhonet.ru");
listOfSites.add("http://habrahabr.ru");
listOfSites.add("http://www.quizful.net/test");
listOfSites.add("http://www.mkyong.com");
listOfSites.add("http://online.orfo.ru");
listOfSites.add("https://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%B3%D0%BB%D0%B0%D0%B2%D0%BD%D0%B0%D1%8F_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0");
listOfSites.add("http://sfw.so");
URL url;
int counter = 0;
for (String site : listOfSites) {
System.out.printf("%s%d %s\n", "№", ++counter, site);
url = new URL(site);
URLConnection urlConnection = url.openConnection();
System.out.printf("%-28s %s\n", "Протокол:", url.getProtocol());
System.out.printf("%-28s %s\n", "Порт:", url.getPort());
System.out.printf("%-28s %s\n", "Хост:", url.getHost());
System.out.printf("%-28s %s\n", "Файл:", url.getFile());
System.out.printf("%-28s %s\n", "Полная форма:", url.toExternalForm());
// Получить дату
long date = urlConnection.getDate();
if (date == 0) {
System.out.printf("%s\n", "Сведения о дате отсутствуют.");
} else {
System.out.printf("%-28s %s\n", "Дата:", new Date(date));
}
// Получить тип содержимого
System.out.printf("%-28s %s\n", "Тип содержимого:", urlConnection.getContentType());
// Дата срока действия ресурса
date = urlConnection.getExpiration();
if (date == 0) {
System.out.printf("%s\n", "Свединия о сроке действия отсутствуют.");
} else {
System.out.printf("%-28s %s\n", "Срок действия истекает:", new Date(date));
}
// Получить дату последней модификации
date = urlConnection.getLastModified();
if (date == 0) {
System.out.printf("%s\n", "Свединия о дате последней модификации отсутствуют.");
} else {
System.out.printf("%-28s %s\n", "Дата последней модификации:", new Date(date));
}
// Получить длину содержимого
long contentLength = urlConnection.getContentLength();
if (contentLength == -1) {
System.out.printf("%s\n", "Длина содержимого недоступна.");
} else {
System.out.printf("%-28s %d\n\n", "Длина содержимого:", contentLength);
}
// Получить содержимое
if (contentLength != 0) {
int c;
System.out.printf("%35s\n", "Содержимое");
InputStream input = urlConnection.getInputStream();
while ((c = input.read()) != -1) {
System.out.printf("%s", (char) c);
}
input.close();
System.out.println();
} else {
System.out.printf("%s\n", "Содержимое недоступно.");
}
System.out.println();
}
}
}
|
UTF-8
|
Java
| 4,040 |
java
|
TestURLConnection.java
|
Java
|
[] | null |
[] |
package ua.org.ao.andreyzarazka.network;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TestURLConnection {
public static void main(String[] args) throws IOException {
List<String> listOfSites = new ArrayList<>();
listOfSites.add("http://www.google.com");
listOfSites.add("http://dou.ua");
listOfSites.add("https://www.gismeteo.ua");
listOfSites.add("http://imhonet.ru");
listOfSites.add("http://habrahabr.ru");
listOfSites.add("http://www.quizful.net/test");
listOfSites.add("http://www.mkyong.com");
listOfSites.add("http://online.orfo.ru");
listOfSites.add("https://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%B3%D0%BB%D0%B0%D0%B2%D0%BD%D0%B0%D1%8F_%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0");
listOfSites.add("http://sfw.so");
URL url;
int counter = 0;
for (String site : listOfSites) {
System.out.printf("%s%d %s\n", "№", ++counter, site);
url = new URL(site);
URLConnection urlConnection = url.openConnection();
System.out.printf("%-28s %s\n", "Протокол:", url.getProtocol());
System.out.printf("%-28s %s\n", "Порт:", url.getPort());
System.out.printf("%-28s %s\n", "Хост:", url.getHost());
System.out.printf("%-28s %s\n", "Файл:", url.getFile());
System.out.printf("%-28s %s\n", "Полная форма:", url.toExternalForm());
// Получить дату
long date = urlConnection.getDate();
if (date == 0) {
System.out.printf("%s\n", "Сведения о дате отсутствуют.");
} else {
System.out.printf("%-28s %s\n", "Дата:", new Date(date));
}
// Получить тип содержимого
System.out.printf("%-28s %s\n", "Тип содержимого:", urlConnection.getContentType());
// Дата срока действия ресурса
date = urlConnection.getExpiration();
if (date == 0) {
System.out.printf("%s\n", "Свединия о сроке действия отсутствуют.");
} else {
System.out.printf("%-28s %s\n", "Срок действия истекает:", new Date(date));
}
// Получить дату последней модификации
date = urlConnection.getLastModified();
if (date == 0) {
System.out.printf("%s\n", "Свединия о дате последней модификации отсутствуют.");
} else {
System.out.printf("%-28s %s\n", "Дата последней модификации:", new Date(date));
}
// Получить длину содержимого
long contentLength = urlConnection.getContentLength();
if (contentLength == -1) {
System.out.printf("%s\n", "Длина содержимого недоступна.");
} else {
System.out.printf("%-28s %d\n\n", "Длина содержимого:", contentLength);
}
// Получить содержимое
if (contentLength != 0) {
int c;
System.out.printf("%35s\n", "Содержимое");
InputStream input = urlConnection.getInputStream();
while ((c = input.read()) != -1) {
System.out.printf("%s", (char) c);
}
input.close();
System.out.println();
} else {
System.out.printf("%s\n", "Содержимое недоступно.");
}
System.out.println();
}
}
}
| 4,040 | 0.536264 | 0.518407 | 91 | 39 | 29.288635 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.879121 | false | false |
3
|
f98840efb5903b1ecbfab653c62a580a75eec4e4
| 1,288,490,202,819 |
f26b3110e0fe457ff4b8947cf7a42603ab5d3193
|
/src/main/java/com/yvaldm/samples/structures/deque/DequeSample.java
|
eeff785d1fbd811754f8152a3534f9f69edadfd7
|
[] |
no_license
|
yvaldm/code-samples
|
https://github.com/yvaldm/code-samples
|
bfd52b66836857eae460f6906a965547b4f93c35
|
b6a6647bf274645d01985aff19146878abfe5d80
|
refs/heads/master
| 2020-01-15T23:49:30.706000 | 2019-07-11T19:51:22 | 2019-07-11T19:51:22 | 86,186,426 | 0 | 0 | null | false | 2019-11-13T03:12:32 | 2017-03-25T20:28:35 | 2019-07-11T19:51:30 | 2019-11-13T03:12:30 | 50 | 0 | 0 | 1 |
Java
| false | false |
package com.yvaldm.samples.structures.deque;
import java.util.ArrayDeque;
public class DequeSample {
// quiz deque
public static void main(String[] args) {
ArrayDeque<String> greetings = new ArrayDeque<String>();
greetings.push("hello");
greetings.push("hi");
greetings.push("ola");
// Pops an element from the stack represented by this deque.
// In other words, removes and returns the first element of this deque.
String pop = greetings.pop();
System.out.println("first element: " + pop);
// Retrieves, but does not remove, the head of the queue represented by
// this deque, or returns {@code null} if this deque is empty.
greetings.peek();
while (greetings.peek() != null) {
System.out.println(greetings.pop());
}
}
}
|
UTF-8
|
Java
| 859 |
java
|
DequeSample.java
|
Java
|
[] | null |
[] |
package com.yvaldm.samples.structures.deque;
import java.util.ArrayDeque;
public class DequeSample {
// quiz deque
public static void main(String[] args) {
ArrayDeque<String> greetings = new ArrayDeque<String>();
greetings.push("hello");
greetings.push("hi");
greetings.push("ola");
// Pops an element from the stack represented by this deque.
// In other words, removes and returns the first element of this deque.
String pop = greetings.pop();
System.out.println("first element: " + pop);
// Retrieves, but does not remove, the head of the queue represented by
// this deque, or returns {@code null} if this deque is empty.
greetings.peek();
while (greetings.peek() != null) {
System.out.println(greetings.pop());
}
}
}
| 859 | 0.619325 | 0.619325 | 30 | 27.633333 | 26.110641 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false |
3
|
082ef0ab0a69bcf8777ce8f745e10ed37e5f1e99
| 841,813,599,549 |
ac233e0e51fc315846f5c1e3b85d061dda7048d7
|
/backend/src/main/java/com/chenym/pig/service/SysMenuService.java
|
bf6998e9f9f54806af58e58c5a6554f3190e38a1
|
[
"MIT"
] |
permissive
|
a0953245782/pig-admin
|
https://github.com/a0953245782/pig-admin
|
8e1ee1c1803eda99ae8ed561552cfb00cb5c89a7
|
d7a323fbb88a9d2c73a6d34a562eae36f675894f
|
refs/heads/master
| 2022-08-01T06:30:51.201000 | 2021-01-11T03:32:09 | 2021-01-11T03:32:09 | 180,356,738 | 8 | 5 |
MIT
| false | 2022-07-07T04:20:23 | 2019-04-09T11:57:37 | 2021-11-17T16:32:28 | 2022-07-07T04:20:20 | 2,417 | 4 | 2 | 2 |
Java
| false | false |
package com.chenym.pig.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chenym.pig.model.SysMenu;
import com.chenym.pig.utils.R;
import com.chenym.pig.vo.MenuVO;
import java.util.List;
public interface SysMenuService extends IService<SysMenu> {
List<MenuVO> findMenuByRoleId(Integer roleId);
/**
* 级联删除菜单
*
* @param id 菜单ID
* @return 成功、失败
*/
R removeMenuById(Integer id);
/**
* 更新菜单信息
*
* @param sysMenu 菜单信息
* @return 成功、失败
*/
Boolean updateMenuById(SysMenu sysMenu);
}
|
UTF-8
|
Java
| 666 |
java
|
SysMenuService.java
|
Java
|
[] | null |
[] |
package com.chenym.pig.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chenym.pig.model.SysMenu;
import com.chenym.pig.utils.R;
import com.chenym.pig.vo.MenuVO;
import java.util.List;
public interface SysMenuService extends IService<SysMenu> {
List<MenuVO> findMenuByRoleId(Integer roleId);
/**
* 级联删除菜单
*
* @param id 菜单ID
* @return 成功、失败
*/
R removeMenuById(Integer id);
/**
* 更新菜单信息
*
* @param sysMenu 菜单信息
* @return 成功、失败
*/
Boolean updateMenuById(SysMenu sysMenu);
}
| 666 | 0.629508 | 0.629508 | 30 | 18.333334 | 17.88171 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false |
3
|
0c9d7107a081606f113116a6d0109ac1451b11b4
| 25,933,012,542,883 |
add7b95a7e7d6df52a1b8d16582acf601cbd9831
|
/src/cezeri/image_processing/ImageProcess.java
|
7942c9c672e516df9bd27e947a47001736c2c5b0
|
[] |
no_license
|
hakmesyo/open-cezeri-library
|
https://github.com/hakmesyo/open-cezeri-library
|
67abf76a6874a054e20cd50a4313cf06ad1f38c1
|
cab3a341b193d9b40e7c1aa01ec533ae417cc244
|
refs/heads/master
| 2022-01-17T23:46:42.413000 | 2022-01-13T20:44:00 | 2022-01-13T20:44:00 | 30,397,340 | 19 | 10 | null | false | 2020-12-13T12:35:12 | 2015-02-06T05:48:13 | 2020-11-17T00:34:29 | 2020-11-03T07:02:02 | 344,218 | 10 | 4 | 1 |
Java
| false | false |
/**
* TODO: ImageProcess ve diğer core classlardaki tüm işlemler parametre olarak
* double[][] almalı.
*
* ****************************************************************************
* OpenCV komutlarını çağıran harici uygulamalarda
* System.loadLibrary(Core.NATIVE_LIBRARY_NAME); eklenmeli ve 64 bit jar add jar
* ile eklendikten sonra dll dosyası da kök dizinde bulunmalı
* ****************************************************************************
*/
package cezeri.image_processing;
import cezeri.factory.FactoryNormalization;
import cezeri.factory.FactoryStatistic;
import cezeri.factory.FactorySimilarityDistance;
import cezeri.factory.FactoryUtils;
import cezeri.types.TRoi;
import cezeri.types.TGrayPixel;
import cezeri.types.TWord;
import cezeri.machine_learning.extraction.FeatureExtractionLBP;
import cezeri.matrix.CMatrix;
import cezeri.matrix.CPoint;
import cezeri.matrix.CRectangle;
import cezeri.factory.FactoryMatrix;
import cezeri.utils.*;
import com.jhlabs.composite.ColorDodgeComposite;
import com.jhlabs.image.AverageFilter;
import com.jhlabs.image.GaussianFilter;
import com.jhlabs.image.GrayscaleFilter;
import com.jhlabs.image.InvertFilter;
import com.jhlabs.image.MotionBlurFilter;
import com.jhlabs.image.MotionBlurOp;
import com.jhlabs.image.PointFilter;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOInvalidTreeException;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.GrayFilter;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import org.opencv.objdetect.CascadeClassifier;
/**
*
* @author venap3
*/
public final class ImageProcess {
static{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
/**
* Conversion from RGB space to LAB space (CIE)
*
* @param R
* @param G
* @param B
* @return
*/
public static double[] rgbToLab(int R, int G, int B) {
double r, g, b, X, Y, Z, xr, yr, zr;
// D65/2°
double Xr = 95.047;
double Yr = 100.0;
double Zr = 108.883;
// --------- RGB to XYZ ---------//
r = R / 255.0;
g = G / 255.0;
b = B / 255.0;
if (r > 0.04045) {
r = Math.pow((r + 0.055) / 1.055, 2.4);
} else {
r = r / 12.92;
}
if (g > 0.04045) {
g = Math.pow((g + 0.055) / 1.055, 2.4);
} else {
g = g / 12.92;
}
if (b > 0.04045) {
b = Math.pow((b + 0.055) / 1.055, 2.4);
} else {
b = b / 12.92;
}
r *= 100;
g *= 100;
b *= 100;
X = 0.4124 * r + 0.3576 * g + 0.1805 * b;
Y = 0.2126 * r + 0.7152 * g + 0.0722 * b;
Z = 0.0193 * r + 0.1192 * g + 0.9505 * b;
// --------- XYZ to Lab --------- //
xr = X / Xr;
yr = Y / Yr;
zr = Z / Zr;
if (xr > 0.008856) {
xr = (float) Math.pow(xr, 1 / 3.);
} else {
xr = (float) ((7.787 * xr) + 16 / 116.0);
}
if (yr > 0.008856) {
yr = (float) Math.pow(yr, 1 / 3.);
} else {
yr = (float) ((7.787 * yr) + 16 / 116.0);
}
if (zr > 0.008856) {
zr = (float) Math.pow(zr, 1 / 3.);
} else {
zr = (float) ((7.787 * zr) + 16 / 116.0);
}
double[] lab = new double[3];
lab[0] = (116 * yr) - 16;
lab[1] = 500 * (xr - yr);
lab[2] = 200 * (yr - zr);
return lab;
}
/**
* Canny Edge Detector
*
* @param d : inputImage
* @return BufferedImage
*/
public static double[][] edgeDetectionCanny(double[][] d) {
float lowThreshold = 0.3f;
float highTreshold = 1.0f;
float gaussianKernelRadious = 2.5f;
int guassianKernelWidth = 3;
boolean isContrastNormalized = false;
BufferedImage currBufferedImage = ImageProcess.pixelsToImageGray(d);
currBufferedImage = edgeDetectionCanny(currBufferedImage, lowThreshold, highTreshold, gaussianKernelRadious, guassianKernelWidth, isContrastNormalized);
currBufferedImage = toGrayLevel(currBufferedImage);
return imageToPixelsDouble(currBufferedImage);
}
public static BufferedImage edgeDetectionCannyAsImage(double[][] d) {
float lowThreshold = 0.3f;
float highTreshold = 1.0f;
float gaussianKernelRadious = 2.5f;
int guassianKernelWidth = 3;
boolean isContrastNormalized = false;
BufferedImage currBufferedImage = ImageProcess.pixelsToImageGray(d);
currBufferedImage = edgeDetectionCanny(currBufferedImage, lowThreshold, highTreshold, gaussianKernelRadious, guassianKernelWidth, isContrastNormalized);
currBufferedImage = toGrayLevel(currBufferedImage);
return currBufferedImage;
}
public static double[][] edgeDetectionCanny(BufferedImage img) {
float lowThreshold = 0.3f;
float highTreshold = 1.0f;
float gaussianKernelRadious = 2.5f;
int guassianKernelWidth = 3;
boolean isContrastNormalized = false;
BufferedImage currBufferedImage = edgeDetectionCanny(img, lowThreshold, highTreshold, gaussianKernelRadious, guassianKernelWidth, isContrastNormalized);
return imageToPixelsDouble(currBufferedImage);
}
public static Mat ocv_edgeDetectionCanny(Mat imageGray) {
Mat imageCanny = new Mat();
Imgproc.Canny(imageGray, imageCanny, 10, 100, 3, true);
return imageCanny;
}
public static BufferedImage ocv_edgeDetectionCanny(BufferedImage img) {
Mat imageGray = ocv_img2Mat(img);
Mat imageCanny = new Mat();
Imgproc.Canny(imageGray, imageCanny, 10, 100, 3, true);
return ocv_mat2Img(imageCanny);
}
public static Mat ocv_blendImagesMat(Mat img1, Mat img2) {
Mat dst = new Mat();
Core.addWeighted(img1, 0.5, img2, 0.5, 0.0, dst);
return dst;
}
public static Mat ocv_blendImagesMat(BufferedImage img1, BufferedImage img2) {
Mat src1 = ImageProcess.ocv_img2Mat(img1);
Mat src2 = ImageProcess.ocv_img2Mat(img2);
Mat dst = new Mat();
Core.addWeighted(src1, 0.5, src2, 0.5, 0.0, dst);
return dst;
}
public static BufferedImage ocv_blendImagesBuffered(BufferedImage img1, BufferedImage img2) {
Mat src1 = ImageProcess.ocv_img2Mat(img1);
Mat src2 = ImageProcess.ocv_img2Mat(img2);
Mat dst = new Mat();
Core.addWeighted(src1, 0.5, src2, 0.5, 0.0, dst);
BufferedImage bf_3 = ImageProcess.ocv_mat2Img(dst);
return bf_3;
}
public static BufferedImage ocv_edgeDetectionCanny(double[][] d) {
BufferedImage img = pixelsToImageGray(d);
Mat imageGray = ocv_img2Mat(img);
Mat imageCanny = new Mat();
// Imgproc.Canny(imageGray, imageCanny, 10, 100, 3, true);
Imgproc.Canny(imageGray, imageCanny, 10, 150, 3, true);
return ocv_mat2Img(imageCanny);
}
public static double[][] ocv_edgeDetectionCanny2D(BufferedImage img) {
Mat imageGray = ocv_img2Mat(img);
Mat imageCanny = new Mat();
// Imgproc.Canny(imageGray, imageCanny, 50, 200, 3, true);
// Imgproc.Canny(imageGray, imageCanny, 20, 150, 3, true);
// Imgproc.Canny(imageGray, imageCanny, 20, 100, 3, true);
Imgproc.Canny(imageGray, imageCanny, 50, 100, 3, true);
double[][] ret = imageToPixelsDouble(ocv_mat2Img(imageCanny));
return ret;
}
/**
* Musa Edge Detector
*
* @param d: inputImage
* @param thr: threshold double value
* @return
*/
public static double[][] edgeDetectionMusa(double[][] d, int thr) {
// double thr=30;
double[][] a1 = FactoryUtils.shiftOnRow(d, 1);
double[][] a2 = FactoryUtils.shiftOnRow(d, -1);
double[][] a3 = FactoryUtils.shiftOnColumn(d, 1);
double[][] a4 = FactoryUtils.shiftOnColumn(d, -1);
double[][] ret1 = FactoryUtils.subtractWithThreshold(d, a1, thr);
double[][] ret2 = FactoryUtils.subtractWithThreshold(d, a2, thr);
double[][] ret3 = FactoryUtils.subtractWithThreshold(d, a3, thr);
double[][] ret4 = FactoryUtils.subtractWithThreshold(d, a4, thr);
double[][] retx = FactoryUtils.add(ret1, ret2);
double[][] rety = FactoryUtils.add(ret3, ret4);
double[][] ret = FactoryUtils.add(retx, rety);
// double[][] ret=FactoryUtils.add(ret1,ret3);
return ret;
}
/**
* Canny Edge Detector
*
* @param d : inputImage
* @param lowThreshold: default value is 0.3f
* @param highTreshold:default value is 1.0f
* @param gaussianKernelRadious:default value is 2.5f
* @param guassianKernelWidth:default value is 3
* @param isContrastNormalized : default false
* @return BufferedImage
*/
public static int[][] edgeDetectionCanny(
double[][] d,
float lowThreshold,
float highTreshold,
float gaussianKernelRadious,
int guassianKernelWidth,
boolean isContrastNormalized) {
BufferedImage currBufferedImage = ImageProcess.pixelsToImageGray(d);
currBufferedImage = edgeDetectionCanny(currBufferedImage, lowThreshold, highTreshold, gaussianKernelRadious, guassianKernelWidth, isContrastNormalized);
return imageToPixelsInt(currBufferedImage);
}
/**
* Canny Edge Detector
*
* @param img : inputImage
* @param lowThreshold: default value is 0.3f
* @param highTreshold:default value is 1.0f
* @param gaussianKernelRadious:default value is 2.5f
* @param guassianKernelWidth:default value is 3
* @param isContrastNormalized : default false
* @return BufferedImage
*/
public static BufferedImage edgeDetectionCanny(
BufferedImage img,
float lowThreshold,
float highTreshold,
float gaussianKernelRadious,
int guassianKernelWidth,
boolean isContrastNormalized) {
BufferedImage currBufferedImage = img;
CannyEdgeDetector detector = new CannyEdgeDetector();
detector.setLowThreshold(lowThreshold);
detector.setHighThreshold(highTreshold);
detector.setGaussianKernelRadius(gaussianKernelRadious);
detector.setGaussianKernelWidth(guassianKernelWidth);
detector.setContrastNormalized(isContrastNormalized);
detector.setSourceImage(currBufferedImage);
detector.process();
currBufferedImage = detector.getEdgesImage();
return ImageProcess.rgb2gray(currBufferedImage);
}
public static BufferedImage isolateChannel(BufferedImage image, String channel) {
BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
int iAlpha = 0;
int iRed = 0;
int iGreen = 0;
int iBlue = 0;
int newPixel = 0;
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
int rgb = image.getRGB(i, j);
newPixel = 0;
iAlpha = rgb >> 24 & 0xff;
iRed = rgb >> 16 & 0xff;
iGreen = rgb >> 8 & 0xff;
iBlue = rgb & 0xff;
if (channel.equals("red")) {
// Tevafuk için eklenmişti
// if (iRed > 110 && iRed < 220 && iGreen > 20 && iGreen < 110 && iBlue > 20 && iBlue < 110) {
// newPixel = 0 | 170 << 16;
// } else {
// newPixel = 0;
// }
newPixel = newPixel | iRed << 16;
}
if (channel.equals("green")) {
newPixel = newPixel | iGreen << 8;
}
if (channel.equals("blue")) {
newPixel = newPixel | iBlue;
}
result.setRGB(i, j, newPixel);
}
}
return result;
}
public static BufferedImage showRedPixels(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
BufferedImage redImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Color color;
int t = 140;
//int[] pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
//yaz(pixels);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//int pp = img.getRGB(x, y);
// printPixelARGB(pp);
Color cl = new Color(img.getRGB(x, y));
int r = cl.getRed();
int g = cl.getGreen();
int b = cl.getBlue();
// float[] hsv = new float[3];
// hsv = cl.RGBtoHSB(r, g, b, hsv);
// int q = 15;
// if (hsv[0] * 360 > 345 || hsv[0] * 360 < 15) {
// //yaz("red:" + (hsv[0] * 360));
// }else{
// yaz("bulmadi");
// }
//
yaz("rgb:" + r + "," + g + "," + b);
// if (red == green && red == blue) {
// color = new Color(0, 0, 0);
// } else if (red > t && green < t && blue < t) {
// color = new Color(255, 0, 0);
// } else {
// color = new Color(0, 0, 0);
// }
//
// redImage.setRGB(x, y, color.getRGB());
}
}
return redImage;
}
public static void printPixelARGB(int pixel) {
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
System.out.println("argb: " + alpha + ", " + red + ", " + green + ", " + blue);
}
public static BufferedImage changeToRedMonochrome(BufferedImage grayImage) {
int width = grayImage.getWidth();
int height = grayImage.getHeight();
BufferedImage redImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Color grayColor = new Color(grayImage.getRGB(x, y));
int gray = grayColor.getRed();
int red = (gray > 127) ? 255 : gray / 2;
int blue = (gray > 127) ? gray / 2 : 0;
int green = (gray > 127) ? gray / 2 : 0;
Color redColor = new Color(red, blue, green);
redImage.setRGB(x, y, redColor.getRGB());
}
}
return redImage;
}
public static BufferedImage DCT(BufferedImage bimg) {
final int N = 8; // Block size
int nrows, ncols, m, n, x, y, u, v, img[][], in[][];
double dct[][], sum, au, av;
double n1 = Math.sqrt(1.0 / N), n2 = Math.sqrt(2.0 / N);
img = imageToPixelsInt(bimg);
nrows = img.length;
ncols = img[0].length;
if (nrows % N != 0 || ncols % N != 0) {
System.out.println("Nrows and ncols should be 8's power");
return bimg;
// System.exit(0);
}
in = new int[nrows][ncols];
dct = new double[nrows][ncols];
// For each NxN block[m,n]
for (m = 0; m < nrows; m += N) {
for (n = 0; n < ncols; n += N) {
// For each pixel[u,v] in block[m,n]
for (u = m; u < m + N; u++) {
au = (u == m) ? n1 : n2;
for (v = n; v < n + N; v++) {
av = (v == n) ? n1 : n2;
// Sum up all pixels in the block
for (x = m, sum = 0; x < m + N; x++) {
for (y = n; y < n + N; y++) {
in[x][y] = img[x][y] - 128; // Subtract by 128
sum += in[x][y] * Math.cos((2 * (x - m) + 1) * (u - m) * Math.PI / (2 * N))
* Math.cos((2 * (y - n) + 1) * (v - n) * Math.PI / (2 * N));
}
}
dct[u][v] = au * av * sum;
} // for v
} // for u
} // for n
} // for m
return ImageProcess.pixelsToImageGray(FactoryUtils.toIntArray2D(dct));
}
public static BufferedImage cropImage(BufferedImage src, CRectangle rect) {
if (src.getType() == BufferedImage.TYPE_BYTE_GRAY) {
return src.getSubimage(rect.column, rect.row, rect.width, rect.height);
} else {
return toBGR(src.getSubimage(rect.column, rect.row, rect.width, rect.height));
}
// BufferedImage dest = clone(src);
// try {
// src = src.getSubimage(rect.column, rect.row, rect.width, rect.height);
// } catch (Exception ex) {
// Logger.getLogger(ImageProcess.class.getName()).log(Level.SEVERE, null, ex);
// }
// return dest;
}
public static BufferedImage convertImageToPencilSketch(BufferedImage src) {
PointFilter grayScaleFilter = new GrayscaleFilter();
BufferedImage grayScale = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
grayScaleFilter.filter(src, grayScale);
//inverted gray scale
BufferedImage inverted = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
PointFilter invertFilter = new InvertFilter();
invertFilter.filter(grayScale, inverted);
//gaussian blurr
GaussianFilter gaussianFilter = new GaussianFilter(20);
BufferedImage gaussianFiltered = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
gaussianFilter.filter(inverted, gaussianFiltered);
//color dodge
ColorDodgeComposite cdc = new ColorDodgeComposite(1.0f);
CompositeContext cc = cdc.createContext(inverted.getColorModel(), grayScale.getColorModel(), null);
Raster invertedR = gaussianFiltered.getRaster();
Raster grayScaleR = grayScale.getRaster();
BufferedImage composite = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
WritableRaster colorDodgedR = composite.getRaster();
cc.compose(invertedR, grayScaleR, colorDodgedR);
//==================================
return composite;
}
public static boolean lookNeighbourPixels(int[][] img, Point p, int r) {
ArrayList<Point> lst = getWindowEdgePixelPositions(img, p, r);
for (Point pt : lst) {
if (img[pt.x][pt.y] != 127 && img[pt.x][pt.y] != 0) {
p.x = pt.x;
p.y = pt.y;
//yaz("konumlandı: p.x:"+p.x+" p.y:"+p.y);
return true;
}
}
return false;
}
public static ArrayList<Point> getWindowEdgePixelPositions(int[][] img, Point p, int r) {
Point m = new Point();
m.x = p.x - r;
m.y = p.y - r;
Point pt = null;
ArrayList<Point> lst = new ArrayList<Point>();
if (m.x <= 0 || m.y <= 0 || m.x + 2 * r >= img.length || m.y + 2 * r >= img[0].length) {
return lst;
}
for (int i = 0; i < 2 * r + 1; i++) {
for (int j = 0; j < 2 * r + 1; j++) {
pt = new Point(m.x + j, m.y + i);
lst.add(pt);
}
}
lst = FactoryUtils.shuffleList(lst);
return lst;
}
/**
* return Alpha, Red, Green and Blue values of original RGB image
*
* @param image
* @return
*/
public static int[][][] imageToPixelsColorInt(BufferedImage image) {
int numRows = image.getHeight();
int numCols = image.getWidth();
// Now we make our array.
int[][][] pixels = new int[numRows][numCols][4];
// int[] outputChannels=new int[4];
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
// image.getRaster().getPixel(col,row,outputChannels);
// pixels[row][col]=outputChannels;
Color c = new Color(image.getRGB(col, row));
pixels[row][col][0] = c.getAlpha(); // Alpha
pixels[row][col][1] = c.getRed(); // Red
pixels[row][col][2] = c.getGreen(); // Green
pixels[row][col][3] = c.getBlue(); // Blue
}
}
return pixels;
}
/**
* return Alpha, Red, Green and Blue values of original RGB image
*
* @param image
* @return
*/
public static double[][][] imageToPixelsColorDouble(BufferedImage image) {
int numRows = image.getHeight();
int numCols = image.getWidth();
// Now we make our array.
double[][][] pixels = new double[numRows][numCols][4];
// double[] outputChannels=new double[4];
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
// image.getRaster().getPixel(col,row,outputChannels);
// pixels[row][col]=outputChannels;
Color c = new Color(image.getRGB(col, row));
pixels[row][col][0] = c.getAlpha(); // Alpha
pixels[row][col][1] = c.getRed(); // Red
pixels[row][col][2] = c.getGreen(); // Green
pixels[row][col][3] = c.getBlue(); // Blue
}
}
return pixels;
}
/**
* return Alpha, Red, Green and Blue values of original RGB image
*
* @param image
* @return
*/
public static int[][][] imageToPixelsColorIntV2(BufferedImage image) {
// Java's peculiar way of extracting pixels is to give them
// back as a one-dimensional array from which we will construct
// our version.
int numRows = image.getHeight();
int numCols = image.getWidth();
int[] oneDPixels = new int[numRows * numCols];
// This will place the pixels in oneDPixels[]. Each int in
// oneDPixels has 4 bytes containing the 4 pieces we need.
PixelGrabber grabber = new PixelGrabber(image, 0, 0, numCols, numRows,
oneDPixels, 0, numCols);
try {
grabber.grabPixels(0);
} catch (InterruptedException e) {
System.out.println(e);
}
// Now we make our array.
int[][][] pixels = new int[numRows][numCols][4];
for (int row = 0; row < numRows; row++) {
// First extract a row of int's from the right place.
int[] aRow = new int[numCols];
for (int col = 0; col < numCols; col++) {
int element = row * numCols + col;
aRow[col] = oneDPixels[element];
}
// In Java, the most significant byte is the alpha value,
// followed by R, then G, then B. Thus, to extract the alpha
// value, we shift by 24 and make sure we extract only that byte.
for (int col = 0; col < numCols; col++) {
pixels[row][col][0] = (aRow[col] >> 24) & 0xFF; // Alpha
pixels[row][col][1] = (aRow[col] >> 16) & 0xFF; // Red
pixels[row][col][2] = (aRow[col] >> 8) & 0xFF; // Green
pixels[row][col][3] = (aRow[col]) & 0xFF; // Blue
}
}
return pixels;
}
/**
* return Alpha, Red, Green and Blue values of original RGB image
*
* @param image
* @return
*/
public static double[][][] imageToPixelsColorDoubleFaster(BufferedImage image) {
// Java's peculiar way of extracting pixels is to give them
// back as a one-dimensional array from which we will construct
// our version.
int numRows = image.getHeight();
int numCols = image.getWidth();
int[] oneDPixels = new int[numRows * numCols];
// This will place the pixels in oneDPixels[]. Each int in
// oneDPixels has 4 bytes containing the 4 pieces we need.
PixelGrabber grabber = new PixelGrabber(image, 0, 0, numCols, numRows,
oneDPixels, 0, numCols);
try {
grabber.grabPixels(0);
} catch (InterruptedException e) {
System.out.println(e);
}
// Now we make our array.
double[][][] pixels = new double[4][numRows][numCols];
for (int row = 0; row < numRows; row++) {
// First extract a row of int's from the right place.
int[] aRow = new int[numCols];
for (int col = 0; col < numCols; col++) {
int element = row * numCols + col;
aRow[col] = oneDPixels[element];
}
// In Java, the most significant byte is the alpha value,
// followed by R, then G, then B. Thus, to extract the alpha
// value, we shift by 24 and make sure we extract only that byte.
for (int col = 0; col < numCols; col++) {
pixels[0][row][col] = (aRow[col] >> 24) & 0xFF; // Alpha
pixels[1][row][col] = (aRow[col] >> 16) & 0xFF; // Red
pixels[2][row][col] = (aRow[col] >> 8) & 0xFF; // Green
pixels[3][row][col] = (aRow[col]) & 0xFF; // Blue
}
}
return pixels;
}
public static BufferedImage pixelsToImageColor(int[][][] pixels) {
int numRows = pixels.length;
int numCols = pixels[0].length;
int[] oneDPixels = new int[numRows * numCols];
int index = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
oneDPixels[index] = ((pixels[row][col][0] << 24) & 0xFF000000)
| ((pixels[row][col][1] << 16) & 0x00FF0000)
| ((pixels[row][col][2] << 8) & 0x0000FF00)
| ((pixels[row][col][3]) & 0x000000FF);
index++;
}
}
// The MemoryImageSource class is an ImageProducer that can
// build an image out of 1D pixels. Then, rather confusingly,
// the createImage() method, inherited from Component, is used
// to make the actual Image instance. This is simply Java's
// confusing, roundabout way. An alternative is to use the
// Raster models provided in BufferedImage.
MemoryImageSource imSource = new MemoryImageSource(numCols, numRows, oneDPixels, 0, numCols);
Image imG = Toolkit.getDefaultToolkit().createImage(imSource);
BufferedImage I = imageToBufferedImage(imG);
return I;
}
public static BufferedImage pixelsToImageColor(double[][][] pixels) {
int numRows = pixels.length;
int numCols = pixels[0].length;
int[] oneDPixels = new int[numRows * numCols];
int index = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
oneDPixels[index] = (((int) pixels[row][col][0] << 24) & 0xFF000000)
| (((int) pixels[row][col][1] << 16) & 0x00FF0000)
| (((int) pixels[row][col][2] << 8) & 0x0000FF00)
| (((int) pixels[row][col][3]) & 0x000000FF);
index++;
}
}
// The MemoryImageSource class is an ImageProducer that can
// build an image out of 1D pixels. Then, rather confusingly,
// the createImage() method, inherited from Component, is used
// to make the actual Image instance. This is simply Java's
// confusing, roundabout way. An alternative is to use the
// Raster models provided in BufferedImage.
MemoryImageSource imSource = new MemoryImageSource(numCols, numRows, oneDPixels, 0, numCols);
Image imG = Toolkit.getDefaultToolkit().createImage(imSource);
BufferedImage I = imageToBufferedImage(imG);
return I;
}
public static BufferedImage pixelsToImageColor(double[][] pixels) {
int numRows = pixels.length;
int numCols = pixels[0].length;
int[] oneDPixels = new int[numRows * numCols];
int index = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
oneDPixels[index] = (int) pixels[row][col];
index++;
}
}
// The MemoryImageSource class is an ImageProducer that can
// build an image out of 1D pixels. Then, rather confusingly,
// the createImage() method, inherited from Component, is used
// to make the actual Image instance. This is simply Java's
// confusing, roundabout way. An alternative is to use the
// Raster models provided in BufferedImage.
MemoryImageSource imSource = new MemoryImageSource(numCols, numRows, oneDPixels, 0, numCols);
Image imG = Toolkit.getDefaultToolkit().createImage(imSource);
BufferedImage I = imageToBufferedImage(imG);
return I;
}
public static BufferedImage pixelsToImageColorArgbFormat(double[][][] pixels) {
int numRows = pixels[0].length;
int numCols = pixels[0][0].length;
int[] oneDPixels = new int[numRows * numCols];
int index = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
oneDPixels[index] = (((int) pixels[0][row][col] << 24) & 0xFF000000)
| (((int) pixels[1][row][col] << 16) & 0x00FF0000)
| (((int) pixels[2][row][col] << 8) & 0x0000FF00)
| (((int) pixels[3][row][col]) & 0x000000FF);
index++;
}
}
// The MemoryImageSource class is an ImageProducer that can
// build an image out of 1D pixels. Then, rather confusingly,
// the createImage() method, inherited from Component, is used
// to make the actual Image instance. This is simply Java's
// confusing, roundabout way. An alternative is to use the
// Raster models provided in BufferedImage.
MemoryImageSource imSource = new MemoryImageSource(numCols, numRows, oneDPixels, 0, numCols);
Image imG = Toolkit.getDefaultToolkit().createImage(imSource);
BufferedImage I = imageToBufferedImage(imG);
return I;
}
public static byte[] getBytes(BufferedImage img) {
return ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
}
public static int[][] convertTo2DWithoutUsingGetRGB(BufferedImage image) {
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
public static double[][] convertBufferedImageTo2D(BufferedImage image) {
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
double[][] result = new double[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
public static BufferedImage readImage(String fileName) {
try {
return ImageIO.read(new File(fileName));
} catch (IOException ex) {
Logger.getLogger(ImageProcess.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static double[][] bufferedImageToArray2D(BufferedImage img) {
double[][] ret = null;
if (img.getColorModel().getNumComponents() == 4) {
img = convertToBufferedImageTypes(img, 5);
ret = convertBufferedImageTo2D(img);
// WritableRaster raster = img.getRaster();
// DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
// byte[] d = data.getData();
// double[] r = FactoryUtils.byte2Double(d);
// double[] t = new double[r.length / 4];
// int size = t.length;
// for (int i = 0; i < size; i++) {
// t[i] = (int) ((r[4 * i + 1] + r[4 * i + 2] + r[4 * i + 3]) / 3);
// }
// ret = FactoryMatrix.reshapeBasedOnRows(t, img.getHeight(), img.getWidth());
// return ret;
} else if (img.getColorModel().getNumComponents() == 1 && !img.getColorModel().hasAlpha()) {
// int w=img.getWidth();
// int h=img.getHeight();
// byte[] imageBytes=new byte[w*h];
// img.getRaster().setDataElements(0, 0, w, h, imageBytes);
WritableRaster raster = img.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] d = data.getData();
double[] r = FactoryUtils.byte2Double(d);
if (r.length != img.getWidth() * img.getHeight()) {
System.out.println("farklı");
}
ret = FactoryMatrix.reshapeBasedOnRows(r, img.getHeight(), img.getWidth());
return ret;
} else if (img.getColorModel().getNumComponents() == 3 && !img.getColorModel().hasAlpha()) {
img = convertToBufferedImageTypes(img, 5);
ret = convertBufferedImageTo2D(img);
// WritableRaster raster = img.getRaster();
// DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
// int[] rgb = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
//
// byte[] d = data.getData();
// double[] r = FactoryUtils.byte2Double(d);
// double[] t = new double[r.length / 3];
// int size = t.length;
// for (int i = 0; i < size; i++) {
// t[i] = (int) ((r[3 * i] + r[3 * i + 1] + r[3 * i + 2]) / 3);
// }
// ret = FactoryMatrix.reshapeBasedOnRows(t, img.getHeight(), img.getWidth());
return ret;
}
return ret;
}
public static double[][][] bufferedImageToArray3D(BufferedImage img) {
double[][][] ret = null;
if (img.getColorModel().getNumComponents() == 1 && !img.getColorModel().hasAlpha()) {
throw new ArithmeticException("BufferedImage has not rgba channels");
} else if (img.getColorModel().getNumComponents() == 3 && !img.getColorModel().hasAlpha()) {
WritableRaster raster = img.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] d = data.getData();
double[] q = FactoryUtils.byte2Double(d);
double[] r = new double[q.length / 3];
double[] g = new double[q.length / 3];
double[] b = new double[q.length / 3];
int size = r.length;
for (int i = 0; i < size; i++) {
r[i] = q[3 * i];
g[i] = q[3 * i + 1];
b[i] = q[3 * i + 2];
}
double[][] rr = FactoryMatrix.reshape(r, img.getHeight(), img.getWidth());
double[][] gg = FactoryMatrix.reshape(g, img.getHeight(), img.getWidth());
double[][] bb = FactoryMatrix.reshape(b, img.getHeight(), img.getWidth());
ret = new double[3][][];
ret[0] = rr;
ret[1] = gg;
ret[2] = bb;
return ret;
}
return ret;
}
public static int[][] imageToPixelsInt(BufferedImage img) {
double[][] d = imageToPixelsDouble(img);
int[][] original = FactoryUtils.toIntArray2D(d);
return original;
}
public static double[][] imageToPixelsDouble(BufferedImage img) {
// if (img == null) {
// return null;
// }
// double[][] original = new double[img.getHeight()][img.getWidth()]; // where we'll put the image
// if ((img.getType() == BufferedImage.TYPE_CUSTOM)
// || (img.getType() == BufferedImage.TYPE_INT_RGB)
// || (img.getType() == BufferedImage.TYPE_INT_ARGB)
// || (img.getType() == BufferedImage.TYPE_3BYTE_BGR)
// || (img.getType() == BufferedImage.TYPE_4BYTE_ABGR)) {
// for (int i = 0; i < img.getHeight(); i++) {
// for (int j = 0; j < img.getWidth(); j++) {
// original[i][j] = img.getRGB(j, i);
// }
// }
// } else {
// Raster image_raster = img.getData();
// //get pixel by pixel
// int[] pixel = new int[1];
// int[] buffer = new int[1];
//
// // declaring the size of arrays
// original = new double[img.getHeight()][img.getWidth()];
//
// //get the image in the array
// for (int i = 0; i < img.getHeight(); i++) {
// for (int j = 0; j < img.getWidth(); j++) {
// pixel = image_raster.getPixel(j, i, buffer);
// original[i][j] = pixel[0];
// }
// }
// }
// return original;
return bufferedImageToArray2D(img);
}
public static int[][] imageToPixels255_CIZ(BufferedImage img) {
return imageToPixelsInt(img);
// MediaTracker mt = new MediaTracker(null);
// mt.addImage(img, 0);
// try {
// mt.waitForID(0);
// } catch (Exception e) {
// // TODO: handle exception
// }
//
// int w = img.getWidth();
// int h = img.getHeight();
// //System.out.println("w:"+w+" h:"+h);
// int pixels[] = new int[w * h];
// int fpixels[] = new int[w * h];
// int dpixel[][] = new int[w][h];
// PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
// try {
// pg.grabPixels();
// } catch (Exception e) {
// // TODO: handle exception
// }
// int red = (pixels[0] >> 16 & 0xff);
// int green = pixels[0] >> 8 & 0xff;
// int blue = pixels[0] & 0xff;
//
// if (red == green && red == blue) {
// for (int i = 0; i < pixels.length; i++) {
// fpixels[i] = pixels[i] & 0xff;
// }
// } else {
// for (int i = 0; i < pixels.length; i++) {
// int r = pixels[i] >> 16 & 0xff;
// int g = pixels[i] >> 8 & 0xff;
// int b = pixels[i] & 0xff;
// int y = (int) (0.33000000000000002D * (double) r + 0.56000000000000005D * (double) g + 0.11D * (double) b);
// fpixels[i] = y;
//// fpixels[i] = pixels[i];
// }
// }
// int k = 0;
// for (int i = 0; i < h; i++) {
// for (int j = 0; j < w; j++) {
// dpixel[j][i] = fpixels[k];
// k++;
// }
// }
//
// return dpixel;
}
public static int[] imageToPixelsTo1D(BufferedImage img) {
return FactoryUtils.toIntArray1D(imageToPixelsInt(img));
}
public static int[][] imageToPixelsROI(BufferedImage img, Rectangle roi) {
MediaTracker mt = new MediaTracker(null);
mt.addImage(img, 0);
try {
mt.waitForID(0);
} catch (Exception e) {
// TODO: handle exception
}
int w = img.getWidth();
int h = img.getHeight();
//System.out.println("w:"+w+" h:"+h);
int pixels[] = new int[w * h];
int fpixels[] = new int[w * h];
int dpixel[][] = new int[roi.width][roi.height];
PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
try {
pg.grabPixels();
} catch (Exception e) {
// TODO: handle exception
}
int cnt = 0;
int py = 0;
for (int i = roi.y * w + roi.x; i < (roi.y + roi.height) * w + roi.x; i++) {
if (cnt < roi.width) {
int r = pixels[i] >> 16 & 0xff;
int g = pixels[i] >> 8 & 0xff;
int b = pixels[i] >> 0 & 0xff;
int y = (int) (0.33000000000000002D * (double) r + 0.56000000000000005D * (double) g + 0.11D * (double) b);
dpixel[cnt][py] = y;
cnt++;
} else {
cnt = 0;
i = i + w - roi.width;
py++;
}
}
return dpixel;
}
public static BufferedImage imageToBufferedImage(Image im) {
BufferedImage bi = new BufferedImage(im.getWidth(null), im.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();
return bi;
}
public static BufferedImage pixelsToImageGray(int dizi[][]) {
int[] pixels = FactoryUtils.toIntArray1D(dizi);
int h = dizi.length;
int w = dizi[0].length;
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
WritableRaster raster = image.getRaster();
raster.setPixels(0, 0, w, h, pixels);
return image;
}
public static BufferedImage pixelsToImageGray(double dizi[][]) {
int[] pixels = FactoryUtils.toIntArray1DBasedOnRows(dizi);
int h = dizi.length;
int w = dizi[0].length;
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
WritableRaster raster = image.getRaster();
raster.setPixels(0, 0, w, h, pixels);
return image;
}
public static BufferedImage pixelsToBufferedImage255_CIZ(int dizi[][]) {
int w = dizi.length;
int h = dizi[0].length;
int ai[] = new int[w * h];
int aix[] = new int[w * h];
int k = 0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
ai[k] = dizi[j][i];
aix[k] = (0xff000000 | ai[k] << 16 | ai[k] << 8 | ai[k]);
k++;
}
}
Image imG = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, aix, 0, w));
BufferedImage myImage = imageToBufferedImage(imG);
return myImage;
}
// public static BufferedImage toGrayLevel(BufferedImage img) {
// return rgb2gray(img);
// }
public static BufferedImage rgb2hsv(BufferedImage img) {
int[][][] ret = convertHSV(img);
BufferedImage rimg = pixelsToImageColor(ret);
return rimg;
}
public static BufferedImage hsv2rgb(BufferedImage img) {
int[][][] d = imageToPixelsColorInt(img);
int nr = d.length;
int nc = d[0].length;
int ch = d[0][0].length;
int[][][] ret = new int[nr][nc][ch];
int red, green, blue;
float hue, saturation, brightness;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
hue = d[i][j][1] / 255.0f;
saturation = d[i][j][2] / 255.0f;
brightness = d[i][j][3] / 255.0f;
int rgb = Color.HSBtoRGB(hue, saturation, brightness);
red = (rgb >> 16) & 0xFF;
green = (rgb >> 8) & 0xFF;
blue = rgb & 0xFF;
ret[i][j][0] = 255;//alpha channel
ret[i][j][1] = red;
ret[i][j][2] = green;
ret[i][j][3] = blue;
}
}
BufferedImage rimg = pixelsToImageColor(ret);
return rimg;
}
public static BufferedImage toHSVColorSpace(BufferedImage img) {
return rgb2hsv(img);
}
public static BufferedImage getHueChannel(BufferedImage img) {
int[][][] ret = convertHSV(img);
int[][] d = new int[ret.length][ret[0].length];
for (int i = 0; i < ret.length; i++) {
for (int j = 0; j < ret[0].length; j++) {
d[i][j] = ret[i][j][1];
}
}
BufferedImage bf = ImageProcess.pixelsToImageGray(d);
return bf;
}
public static BufferedImage getSaturationChannel(BufferedImage img) {
int[][][] ret = convertHSV(img);
int[][] d = new int[ret.length][ret[0].length];
for (int i = 0; i < ret.length; i++) {
for (int j = 0; j < ret[0].length; j++) {
d[i][j] = ret[i][j][2];
}
}
BufferedImage bf = ImageProcess.pixelsToImageGray(d);
return bf;
}
public static BufferedImage getValueChannel(BufferedImage img) {
int[][][] ret = convertHSV(img);
int[][] d = new int[ret.length][ret[0].length];
for (int i = 0; i < ret.length; i++) {
for (int j = 0; j < ret[0].length; j++) {
d[i][j] = ret[i][j][3];
}
}
BufferedImage bf = ImageProcess.pixelsToImageGray(d);
return bf;
}
public static int[][][] convertHSV(BufferedImage img) {
int[][][] d = imageToPixelsColorInt(img);
int[][][] ret = new int[d.length][d[0].length][d[0][0].length];
int n = 255;
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
int[] val = FactoryMatrix.clone(d[i][j]);
float[] q = toHSV(val[1], val[2], val[3]);
val[1] = (int) (q[0] * n);
val[2] = (int) (q[1] * n);
val[3] = (int) (q[2] * n);
ret[i][j] = val;
}
}
return ret;
}
public static float[] toHSV(int red, int green, int blue) {
float[] hsv = new float[3];
hsv = Color.RGBtoHSB(red, green, blue, null);
return hsv;
}
public static float[] rgb2hsv(int red, int green, int blue) {
return toHSV(red, green, blue);
}
public static float[] toRGB(int hue, int sat, int val) {
float[] rgb = new float[3];
int n = Color.HSBtoRGB(hue, sat, val);
return rgb;
}
public static BufferedImage rgb2gray(BufferedImage img) {
return toGrayLevel(img);
}
public static BufferedImage ocv_rgb2gray(BufferedImage img) {
Mat rgbImage = ocv_img2Mat(img);
Mat imageGray = new Mat();
if (img.getType()==0 || img.getType()==1) {
Imgproc.cvtColor(rgbImage, imageGray, Imgproc.COLOR_RGB2GRAY);
}else if (img.getType()==4){
Imgproc.cvtColor(rgbImage, imageGray, Imgproc.COLOR_BGR2GRAY);
}
return ocv_mat2Img(imageGray);
}
public static BufferedImage ocv_rgb2RedChannel(BufferedImage img) {
Mat rgbImage = ocv_img2Mat(img);
ArrayList<Mat> bgr=new ArrayList();
Core.split(rgbImage, bgr);
int type = bgr.get(2).type();
System.out.println("type = " + type);
Mat imageRed = new Mat();
if (img.getType()==0 || img.getType()==1) {
Imgproc.cvtColor(bgr.get(2), imageRed, Imgproc.COLOR_GRAY2RGB);
}else if (img.getType()==4){
Imgproc.cvtColor(bgr.get(2), imageRed, Imgproc.COLOR_GRAY2BGR);
}
return ocv_mat2Img(imageRed);
}
public static BufferedImage ocv_rgb2gray(Mat rgbImage) {
Mat imageGray = new Mat();
Imgproc.cvtColor(rgbImage, imageGray, Imgproc.COLOR_BGR2GRAY);
return ocv_mat2Img(imageGray);
}
public static Mat ocv_rgb2grayMat(Mat rgbImage) {
Mat imageGray = new Mat();
Imgproc.cvtColor(rgbImage, imageGray, Imgproc.COLOR_BGR2GRAY);
return imageGray;
}
public static BufferedImage ocv_mat2Img(Mat m) {
int type = BufferedImage.TYPE_BYTE_GRAY;
if (m.channels() > 1) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels() * m.cols() * m.rows();
byte[] b = new byte[bufferSize];
m.get(0, 0, b); // get all the pixels
BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return image;
}
public static Mat ocv_img2Mat(BufferedImage in) {
if (in.getType() == BufferedImage.TYPE_INT_RGB) {
Mat out;
byte[] data;
int r, g, b;
out = new Mat(in.getHeight(), in.getWidth(), CvType.CV_8UC3);
data = new byte[in.getWidth() * in.getHeight() * (int) out.elemSize()];
int[] dataBuff = in.getRGB(0, 0, in.getWidth(), in.getHeight(), null, 0, in.getWidth());
for (int i = 0; i < dataBuff.length; i++) {
data[i * 3] = (byte) ((dataBuff[i] >> 0) & 0xFF);
data[i * 3 + 1] = (byte) ((dataBuff[i] >> 8) & 0xFF);
data[i * 3 + 2] = (byte) ((dataBuff[i] >> 16) & 0xFF);
}
return out;
}
byte[] pixels = ((DataBufferByte) in.getRaster().getDataBuffer()).getData();
Mat mat = null;
if (in.getType() == BufferedImage.TYPE_BYTE_GRAY) {
mat = new Mat(in.getHeight(), in.getWidth(), CvType.CV_8UC1);
} else {
mat = new Mat(in.getHeight(), in.getWidth(), CvType.CV_8UC3);
}
mat.put(0, 0, pixels);
return mat;
}
public static double[][] rgb2gray2D(BufferedImage img) {
// BufferedImage retImg = toNewColorSpace(img, BufferedImage.TYPE_BYTE_GRAY);
BufferedImage retImg = toGrayLevel(img);
double[][] ret = imageToPixelsDouble(retImg);
return ret;
}
private static void yaz(int[] p) {
for (int i = 0; i < p.length; i++) {
System.out.println(p[i]);
}
}
private static void yaz(String s) {
System.out.println(s);
}
public static BufferedImage getHistogramImage(int[] lbp) {
lbp = FactoryNormalization.normalizeMinMax(lbp);
BufferedImage img = new BufferedImage(lbp.length * 10, 300, BufferedImage.TYPE_BYTE_GRAY);
Graphics gr = img.getGraphics();
gr.setColor(Color.white);
int w = img.getWidth();
int h = img.getHeight();
int a = 20;
gr.drawRect(a, a, w - 2 * a, h - 2 * a);
return img;
}
// public static BufferedImage getHistogramImage(BufferedImage imgx) {
// int[] hist=getHistogramData(imgx);
// BufferedImage img = new BufferedImage(hist.length * 10, 300, BufferedImage.TYPE_BYTE_GRAY);
// Graphics gr = img.getGraphics();
// gr.setColor(Color.white);
// int w = img.getWidth();
// int h = img.getHeight();
// int a = 20;
// gr.drawRect(a, a, w - 2 * a, h - 2 * a);
// return img;
// }
public static int[] getHistogram(BufferedImage imgx) {
int[] d = imageToPixelsTo1D(imgx);
int[] ret = new int[256];
for (int i = 0; i < 256; i++) {
for (int j = 0; j < d.length; j++) {
if (d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
// public static CMatrix getHistogram(BufferedImage imgx) {
// CMatrix cm;
// int[] d = imageToPixels255_1D(imgx);
// int[] returnedValue = getHistogram(d);
// cm = CMatrix.getInstance(returnedValue);
// return cm;
// }
/**
* 8 bit gray level histogram
*
* @param d
* @return
*/
public static int[] getHistogram(int[] d) {
int[] ret = new int[256];
for (int i = 0; i < 256; i++) {
for (int j = 0; j < d.length; j++) {
if (d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
/**
* N bins of histogram
*
* @param d
* @return
*/
public static int[] getHistogram(int[] d, int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < d.length; j++) {
if (d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
public static int[] getHistogram(double[][] p) {
double[] d = FactoryUtils.toDoubleArray1D(p);
int[] ret = new int[256];
for (int i = 0; i < 256; i++) {
for (int j = 0; j < d.length; j++) {
if ((int) d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
public static int[] getHistogram(int[][] p) {
int[] d = FactoryUtils.toIntArray1D(p);
int[] ret = new int[256];
for (int i = 0; i < 256; i++) {
for (int j = 0; j < d.length; j++) {
if ((int) d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
public static CMatrix getHistogramRed(CMatrix cm) {
int[] d = cm.getRedChannelColor().toIntArray1D();
int[] ret = ImageProcess.getHistogram(d);
cm = CMatrix.getInstance(ret).transpose();
return cm;
}
public static CMatrix getHistogramGreen(CMatrix cm) {
int[] d = cm.getGreenChannelColor().toIntArray1D();
int[] ret = ImageProcess.getHistogram(d);
cm = CMatrix.getInstance(ret).transpose();
return cm;
}
public static CMatrix getHistogramBlue(CMatrix cm) {
int[] d = cm.getBlueChannelColor().toIntArray1D();
int[] ret = ImageProcess.getHistogram(d);
cm = CMatrix.getInstance(ret).transpose();
return cm;
}
public static CMatrix getHistogramAlpha(CMatrix cm) {
int[] d = cm.getAlphaChannelColor().toIntArray1D();
int[] ret = ImageProcess.getHistogram(d);
cm = CMatrix.getInstance(ret).transpose();
return cm;
}
public static CMatrix getHistogram(CMatrix cm) {
if (cm.getImage().getType() == BufferedImage.TYPE_BYTE_GRAY) {
short[] d = cm.toShortArray1D();
double[] ret = FactoryMatrix.getHistogram(d, 256);
cm.setArray(ret);
cm = cm.transpose();
} else {
int[][][] d = imageToPixelsColorInt(cm.getImage());
double[][] ret = FactoryMatrix.getHistogram(d, 256);
cm.setArray(ret);
}
cm.name += "|" + "Histogram";
return cm;
}
public static BufferedImage revert(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int p = img.getRGB(x, y);
int a = (p >> 24) & 0xff;
int r = (p >> 16) & 0xff;
int g = (p >> 8) & 0xff;
int b = p & 0xff;
r = 255 - r;
g = 255 - g;
b = 255 - b;
p = (a << 24) | (r << 16) | (g << 8) | b;
img.setRGB(x, y, p);
}
}
return img;
// BufferedImage ret = null;
// int[][] d = imageToPixelsInt(img);
// int[][] q = new int[d.length][d[0].length];
// for (int i = 0; i < d.length; i++) {
// for (int j = 0; j < d[0].length; j++) {
// q[i][j] = Math.abs(255 - d[i][j]);
// }
// }
// ret = ImageProcess.pixelsToImageGray(q);
// return ret;
}
/**
* resize the image to desired width and height value by using
* Image.SCALE_SMOOTH format
*
* @param src:BufferedImage
* @param w:width
* @param h:height
* @return
*/
public static BufferedImage resize(BufferedImage src, int w, int h) {
//// Image tmp = img.getScaledInstance(w, h, Image.SCALE_FAST);
// Image tmp = img.getScaledInstance(w, h, Image.SCALE_SMOOTH);
//// Image tmp = img.getScaledInstance(w, h, Image.SCALE_REPLICATE);
// BufferedImage dimg = new BufferedImage(w, h, img.getType());
// Graphics2D g2d = dimg.createGraphics();
// g2d.drawImage(tmp, 0, 0, null);
// g2d.dispose();
// return dimg;
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
Graphics2D g2 = resizedImg.createGraphics();
// g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(src, 0, 0, w, h, null);
g2.dispose();
BufferedImage img = new BufferedImage(w, h, src.getType());
g2 = img.createGraphics();
g2.drawImage(resizedImg, 0, 0, w, h, null);
g2.dispose();
return img;
}
public static BufferedImage resizeSmooth(BufferedImage src, int w, int h) {
Image img = src.getScaledInstance(w, h, BufferedImage.SCALE_SMOOTH);
BufferedImage ret = toBufferedImage(img);
return ret;
}
/**
* Resizes an image using a Graphics2D object backed by a BufferedImage.
*
* @param src - source image to scale
* @param w - desired width
* @param h - desired height
* @return - the new resized image
*/
public static BufferedImage resizeAspectRatio(BufferedImage src, int w, int h) {
int finalw = w;
int finalh = h;
double factor = 1.0d;
if (src.getWidth() > src.getHeight()) {
factor = ((double) src.getHeight() / (double) src.getWidth());
finalh = (int) (finalw * factor);
} else {
factor = ((double) src.getWidth() / (double) src.getHeight());
finalw = (int) (finalh * factor);
}
BufferedImage resizedImg = new BufferedImage(finalw, finalh, BufferedImage.TRANSLUCENT);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(src, 0, 0, finalw, finalh, null);
g2.dispose();
BufferedImage img = new BufferedImage(finalw, finalh, BufferedImage.TYPE_3BYTE_BGR);
g2 = img.createGraphics();
g2.drawImage(resizedImg, 0, 0, finalw, finalh, null);
g2.dispose();
// return resizedImg;
return img;
}
public static BufferedImage rotateImage(BufferedImage img, double theta) {
double radians = theta * Math.PI / 180;
AffineTransform transform = new AffineTransform();
transform.rotate(radians, img.getWidth() / 2, img.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
BufferedImage newImage = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
img = op.filter(img, newImage);
return newImage;
}
public static BufferedImage rotateImage(BufferedImage img, CPoint cp, double theta) {
double radians = theta * Math.PI / 180;
AffineTransform transform = new AffineTransform();
transform.rotate(radians, cp.column, cp.row);
AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
BufferedImage newImage = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
img = op.filter(img, newImage);
return newImage;
}
public static ArrayList<TRoi> getSpecialROIPositions(BufferedImage img) {
ArrayList<TRoi> pos = new ArrayList<>();
int[][] m = imageToPixelsInt(img);
m = binarizeImage(m);
m = FactoryUtils.transpose(m);
int hImg = m.length;
//each page of Quran is made up of 15 rows
int hRow = hImg / 15;
for (int i = 0; i < 15; i++) {
addPosForEachRow(m, pos, i, hRow);
}
return pos;
}
private static int[][] binarizeImage(int[][] m) {
int[][] ret = new int[m.length][m[0].length];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
if (m[i][j] > 0) {
ret[i][j] = 255;
}
}
}
return ret;
}
private static void addPosForEachRow(int[][] m, ArrayList<TRoi> pl, int n, int hRow) {
CPoint p1 = new CPoint(n * hRow, 0);
CPoint p2 = new CPoint(n * hRow + hRow, m[0].length);
int[][] subMatrix = FactoryUtils.getSubMatrix(m, p1, p2);
int[] prjMatrix = FactoryUtils.getProjectedMatrixOnX(subMatrix);
TWord[] points = FactoryUtils.getPoints(prjMatrix);
for (int i = 0; i < points.length; i++) {
Point p = new Point(n * hRow + hRow / 2, points[i].centerPos);
TRoi roi = new TRoi();
roi.cp = p;
roi.width = points[i].width;
pl.add(roi);
//yaz((n + 1) + ".satır da "+(i+1)+". yer"+" pos:"+p.x+","+p.y);
}
}
private static double checkWindowDensity(int[][] m, int x, int y, int dx) {
int w = 30;
int h = 30 - dx;
CPoint p1 = new CPoint(x, y);
CPoint p2 = new CPoint(x + h, y + w);
int[][] subMatrix = FactoryUtils.getSubMatrix(m, p1, p2);
// double mean = Utils.getMeanValue(subMatrix);
double mean = FactoryUtils.getPixelCount(subMatrix);
yaz("roi pos:" + x + "," + y + " mean:" + mean);
return mean;
}
/**
* 16.04.2014 Musa Ataş Bir imgenin çerisinde küçük bir imgeyi correlation
* coefficient tabanlı arar, en iyi correlation coefficient değerine sahip
* koordinatı geri gönderir.
*/
public static Point getPositionOfSubImageFromParentImage(int[][] parentImg, int[][] subImg, String filterType) {
Point ret = new Point();
ArrayList<TGrayPixel> cr = null;
if (filterType.equals("DirectCorrelationBased")) {
cr = performConvolveOperationForCorrelation(parentImg, subImg);
}
if (filterType.equals("LBP")) {
cr = performConvolveOperationForLBP(parentImg, subImg);
}
for (int i = 0; i < 10; i++) {
FactoryUtils.yaz(cr.get(i).toString());
}
return ret;
}
private static double[] to1D(int[][] parentImg) {
int index = -1;
double[] d = new double[parentImg.length * parentImg[0].length];
for (int i = 0; i < parentImg.length; i++) {
for (int j = 0; j < parentImg[0].length; j++) {
d[++index] = parentImg[i][j] * 1.0;
}
}
return d;
}
private static ArrayList<TGrayPixel> performConvolveOperationForCorrelation(int[][] parentImg, int[][] subImg) {
return getPossiblePixelsAfterConvolution(parentImg, subImg, "PearsonCorrelationCoefficient");
}
private static ArrayList<TGrayPixel> performConvolveOperationForLBP(int[][] parentImg, int[][] subImg) {
return getPossiblePixelsAfterConvolution(parentImg, subImg, "LBP");
}
public static ArrayList<TGrayPixel> getPossiblePixelsAfterConvolution(int[][] parentImg, int[][] subImg, String filterType) {
ArrayList<TGrayPixel> ret = new ArrayList<TGrayPixel>();
int pw = parentImg.length;
int ph = parentImg[0].length;
int sw = subImg.length;
int sh = subImg[0].length;
FactoryUtils.yazln("pw:" + pw + " ph:" + ph + " sw:" + sw + " sh:" + sh);
double[] m2 = to1D(subImg);
double[] m1 = null;
for (int i = sw / 2; i < pw - sw; i++) {
for (int j = sh / 2; j < ph - sh; j++) {
//Utils.yaz("i:"+i+" j:"+j);
int[][] d = FactoryUtils.getSubMatrix(parentImg, new CPoint(i, j), new CPoint(i + sw, j + sh));
m1 = to1D(d);
double cor = 0;
if (filterType.equals("PearsonCorrelationCoefficient")) {
cor = FactoryStatistic.PEARSON(m1, m2);
}
if (filterType.equals("LBP")) {
int[] subImgLBP = FeatureExtractionLBP.getLBP(subImg, true);
int[] parentImgLBP = FeatureExtractionLBP.getLBP(d, true);
//cor = Distance.getCorrelationCoefficientDistance(Utils.to2DArrayDouble(subImgLBP),Utilto2DArrayDoubleay(parentImgLBP));
cor = FactorySimilarityDistance.getEuclideanDistance(FactoryUtils.toDoubleArray1D(subImgLBP), FactoryUtils.toDoubleArray1D(parentImgLBP));
}
// if (cor > 0.85) {
// Utils.yazln("high Correlation:" + cor + " coordinates:" + i + ":" + j);
// Utils.yaz("M1=");
// Utils.yaz(m1);
// Utils.yaz("M2=");
// Utils.yaz(m2);
// }
TGrayPixel gp = new TGrayPixel();
gp.corValue = cor;
gp.x = i;
gp.y = j;
ret.add(gp);
}
}
Collections.sort(ret, new CustomComparatorForGrayPixelCorrelation());
return ret;
}
public static int[][] getAbsoluteMatrixDifferenceWithROI(int[][] m_prev, int[][] m_curr, Rectangle r) {
int[][] ret = new int[r.width][r.height];
int k = 0;
int l = 0;
for (int i = r.x; i < r.x + r.width - 1; i++) {
l = 0;
for (int j = r.y; j < r.y + r.height - 1; j++) {
int a = Math.abs(m_prev[i][j] - m_curr[i][j]);
ret[k][l++] = (a < 20) ? 0 : a;
}
k++;
}
return ret;
}
public static int[][] segmentImageDifference(int[][] m, int size) {
int w = m.length;
int h = m[0].length;
int nx = w / size;
int ny = h / size;
int[][] segM = new int[nx][ny];
int[][] v = new int[size][size];
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
v = cropMatrix(m, new Rectangle(i * size, j * size, size, size));
segM[i][j] = (int) FactoryUtils.getMean(v);
}
}
return segM;
}
public static int[][] cropMatrix(int[][] m, Rectangle r) {
int[][] ret = new int[r.width][r.height];
int k = 0;
int l = 0;
for (int i = r.x; i < r.x + r.width - 1; i++) {
l = 0;
for (int j = r.y; j < r.y + r.height - 1; j++) {
ret[k][l++] = m[i][j];
}
k++;
}
return ret;
}
public static CPoint getCenterOfGravityGray(BufferedImage img) {
int[][] m = imageToPixelsInt(img);
return ImageProcess.getCenterOfGravityGray(m);
}
public static CPoint getCenterOfGravityGray(BufferedImage img, boolean isShowCenter) {
int[][] m = null;
if (img.getType() != BufferedImage.TYPE_BYTE_GRAY) {
BufferedImage temp = rgb2gray(img);
m = imageToPixelsInt(temp);
} else {
m = imageToPixelsInt(img);
}
CPoint cp = ImageProcess.getCenterOfGravityGray(m);
if (isShowCenter) {
img = fillRectangle(img, cp.row - 2, cp.column - 2, 5, 5, Color.black);
}
return cp;
}
public static CPoint getCenterOfGravityColor(BufferedImage img, boolean isShowCenter) {
int[][][] m = null;
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
System.err.println("You should not use gray level image for this particular case");
return new CPoint();
} else {
m = imageToPixelsColorInt(img);
}
BufferedImage red = ImageProcess.getRedChannelGray(img);
BufferedImage green = ImageProcess.getGreenChannelGray(img);
BufferedImage blue = ImageProcess.getRedChannelGray(img);
CPoint cpRed = ImageProcess.getCenterOfGravityGray(red);
CPoint cpGreen = ImageProcess.getCenterOfGravityGray(green);
CPoint cpBlue = ImageProcess.getCenterOfGravityGray(blue);
CPoint cp = new CPoint();
cp.row = (int) ((cpRed.row + cpGreen.row + cpBlue.row) / 3.0);
cp.column = (int) ((cpRed.column + cpGreen.column + cpBlue.column) / 3.0);
if (isShowCenter) {
img = fillRectangle(img, cp.row - 2, cp.column - 2, 5, 5, Color.red);
}
return cp;
}
public static CPoint getCenterOfGravityGray(int[][] m) {
int w = m.length;
int h = m[0].length;
int sumX = 0;
int sumY = 0;
int np = 0;
CPoint cp = new CPoint();
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (m[i][j] > 0) {
sumX += i;
sumY += j;
np++;
}
}
}
double pr = 0;
double pc = 0;
if (np != 0) {
pr = sumX * 1.0 / np;
pc = sumY * 1.0 / np;
cp.row = (int) pr;
cp.column = (int) pc;
}
return cp;
}
public static int[][] getCenterOfGravityCiz(int[][] m) {
int w = m.length;
int h = m[0].length;
int[][] ret = new int[w][h];
int sumX = 0;
int sumY = 0;
int np = 0;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (m[i][j] > 0) {
sumX += i;
sumY += j;
np++;
}
}
}
//avoid division by zero
double px = 0;
double py = 0;
if (np != 0) {
px = sumX * 1.0 / np;
py = sumY * 1.0 / np;
ret[(int) px][(int) py] = 255;
//writeToFile((int) px * zoom, 400 - (int) py * zoom, ++ID);
}
return ret;
}
public static CPoint getCenterOfGravityGray(double[][] m) {
int w = m.length;
int h = m[0].length;
int sumX = 0;
int sumY = 0;
int np = 0;
CPoint cp = new CPoint();
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (m[i][j] > 0) {
sumX += i;
sumY += j;
np++;
}
}
}
double pr = 0;
double pc = 0;
if (np != 0) {
pr = sumX * 1.0 / np;
pc = sumY * 1.0 / np;
cp.row = (int) pr;
cp.column = (int) pc;
}
return cp;
}
public static double getInverseDiffMoment(int[][] img) {
int col = img.length;
int row = img[0].length;
double IDF = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
IDF += img[i][j] / (1 + (i - j) * (i - j));
}
}
return IDF;
}
public static double getInverseDiffMoment(BufferedImage img) {
int[][] d = imageToPixelsInt(img);
return getInverseDiffMoment(d);
}
public static double getInverseDiffMoment(double[][] img) {
int col = img.length;
int row = img[0].length;
double IDF = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
IDF += img[i][j] / (1 + (i - j) * (i - j));
}
}
return IDF;
}
public static double getContrast(BufferedImage img) {
int[][] d = imageToPixelsInt(img);
return getContrast(d);
}
public static double getContrast(int[][] img) {
int col = img.length;
int row = img[0].length;
double contrast = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
contrast += img[i][j] * ((i - j) * (i - j));
}
}
return contrast;
}
public static double getContrast(double[][] img) {
int col = img.length;
int row = img[0].length;
double contrast = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
contrast += img[i][j] * ((i - j) * (i - j));
}
}
return contrast;
}
public static double getEntropy(int[][] img) {
int col = img.length;
int row = img[0].length;
double entropy = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
entropy += img[i][j] * Math.log(img[i][j]);
}
}
return entropy;
}
public static double getEntropy(double[][] img) {
int col = img[0].length;
int row = img.length;
double entropy = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
entropy += img[i][j] * Math.log(img[i][j] + 1);
}
}
return entropy;
}
public static double getEntropy(BufferedImage actualImage) {
ArrayList<String> values = new ArrayList<String>();
int n = 0;
Map<Integer, Integer> occ = new HashMap<>();
for (int i = 0; i < actualImage.getHeight(); i++) {
for (int j = 0; j < actualImage.getWidth(); j++) {
int pixel = actualImage.getRGB(j, i);
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
//0.2989 * R + 0.5870 * G + 0.1140 * B greyscale conversion
//System.out.println("i="+i+" j="+j+" argb: " + alpha + ", " + red + ", " + green + ", " + blue);
int d = (int) Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue);
if (!values.contains(String.valueOf(d))) {
values.add(String.valueOf(d));
}
if (occ.containsKey(d)) {
occ.put(d, occ.get(d) + 1);
} else {
occ.put(d, 1);
}
++n;
}
}
double e = 0.0;
for (Map.Entry<Integer, Integer> entry : occ.entrySet()) {
int cx = entry.getKey();
double p = (double) entry.getValue() / n;
e += p * Math.log(p);
}
return -e;
}
public static double getEntropyWithHistogram(double[][] d) {
int[] hist = ImageProcess.getHistogram(d);
double sum = FactoryUtils.sum(hist);
double e = 0.0;
for (int h : hist) {
double p = h / sum;
if (p > 0) {
e += p * Math.log(p);
}
}
return -e;
}
/**
* yanlış hesaplıyor güncellenmesi gerekir
*
* @param d
* @return
*/
public static double getHomogeneity(double[][] d) {
//aşağıdaki kod yanlış update edilmesi gerekiyor
int[] hist = ImageProcess.getHistogram(d);
double sum = FactoryUtils.sum(hist);
double e = 0.0;
for (int h : hist) {
double p = h / sum;
if (p > 0) {
e += p * Math.log(p);
}
}
return -e;
}
public static double getEnergy(int[][] img) {
int col = img.length;
int row = img[0].length;
double energy = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
energy += img[i][j] * img[i][j];
}
}
return energy;
}
public static double getKurtosis(int[][] img) {
int[] nums = FactoryUtils.toIntArray1D(img);
int n = nums.length;
double mean = FactoryUtils.getMean(nums);
double deviation = 0.0d;
double variance = 0.0d;
double k = 0.0d;
for (int i = 0; i < n; i++) {
deviation = nums[i] - mean;
variance += Math.pow(deviation, 2);
k += Math.pow(deviation, 4);
}
//variance /= (n - 1);
variance = variance / n;
if (variance != 0.0) {
//k = k / (n * variance * variance) - 3.0;
k = k / (n * variance * variance);
}
return k;
}
public static double getSkewness(int[][] img) {
int[] nums = FactoryUtils.toIntArray1D(img);
int n = nums.length;
double mean = FactoryUtils.getMean(nums);
double deviation = 0.0d;
double variance = 0.0d;
double skew = 0.0d;
for (int i = 0; i < n; i++) {
deviation = nums[i] - mean;
variance += Math.pow(deviation, 2);
skew += Math.pow(deviation, 3);
}
//variance /= (n - 1);
variance /= n;
double standard_deviation = Math.sqrt(variance);
if (variance != 0.0) {
skew /= (n * variance * standard_deviation);
}
return skew;
}
public static BufferedImage clone(BufferedImage img) {
ColorModel cm = img.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = img.copyData(img.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
// public static Image clone(Image img) {
// BufferedImage bf = ImageProcess.toBufferedImage(img);
// BufferedImage ret = new BufferedImage(bf.getWidth(), bf.getHeight(), bf.getType());
// ret.getGraphics().drawImage(img, 0, 0, null);
// return ret;
// }
//
public static int[] getImagePixels(BufferedImage image) {
int[] dummy = null;
int wid, hgt;
// compute size of the array
wid = image.getWidth();
hgt = image.getHeight();
// start getting the pixels
Raster pixelData;
pixelData = image.getData();
System.out.println("wid:" + wid);
System.out.println("hgt:" + hgt);
System.out.println("Channels:" + pixelData.getNumDataElements());
return pixelData.getPixels(0, 0, wid, hgt, dummy);
}
public static int[][] to2DRGB(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[][] result = new int[height][width];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
result[row][col] = image.getRGB(col, row);
}
}
return result;
}
public static int[][] to2D(BufferedImage image) {
// final int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
//image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see e661 Determining If an Image Has Transparent Pixels
//boolean hasAlpha = hasAlpha(image);
boolean hasAlpha = false;
// Create a buffered image with a format that's compatible with the screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
public static BufferedImage imread() {
return readImageFromFile();
}
public static BufferedImage readImageFromFile() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("images"));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
//Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
}
return ret;
}
public static BufferedImage readImageFromFile(File file) {
BufferedImage ret = null;
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
//Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
return ret;
}
public static File readImage() {
JFileChooser chooser = new JFileChooser();
//chooser.setCurrentDirectory(new java.io.File("images"));
chooser.setCurrentDirectory(new java.io.File(FactoryUtils.getWorkingDirectory()));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file = null;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
//Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
}
return file;
}
public static File readImageFileFromFolder() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("images"));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file = null;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
return file;
}
public static File readImageFileFromFolderWithDirectoryPath(String directoryPath) {
if (directoryPath == null || directoryPath.isEmpty()) {
return readImageFileFromFolder();
}
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File(directoryPath));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file = null;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
return file;
}
public static BufferedImage readImageFromFileWithDirectoryPath(String directoryPath) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File(directoryPath));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
//Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
}
return ret;
}
public static BufferedImage imread(String fileName) {
return readImageFromFile(fileName);
}
public static BufferedImage readImageFromFile(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
System.err.println("Fatal Exception: Image File not found at specified path");
System.exit(-1);
return null;
}
BufferedImage ret = null;
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
Logger.getLogger(FactoryUtils.class.getName()).log(Level.SEVERE, null, "Problem reading " + fileName + "\n" + ex);
}
return ret;
}
public static CMatrix getMatrix(BufferedImage img) {
CMatrix cm = CMatrix.getInstance(imageToPixelsInt(img));
return cm;
}
public static boolean writeImage(BufferedImage img) {
return saveImage(img);
}
public static boolean writeImage(BufferedImage img, String fileName) {
return saveImage(img, fileName);
}
public static boolean imwrite(BufferedImage img) {
return saveImage(img);
}
public static boolean imwrite(BufferedImage img, String fileName) {
return saveImage(img, fileName);
}
public static boolean saveImage(BufferedImage img) {
JFileChooser FC = new JFileChooser("C:/");
int retrival = FC.showSaveDialog(null);
if (retrival == FC.APPROVE_OPTION) {
File fileToSave = FC.getSelectedFile();
String extension = FactoryUtils.getFileExtension(fileToSave);
try {
boolean ret = ImageIO.write(img, extension, fileToSave);
return ret;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
System.out.println(ex.getMessage());
return false;
}
return true;
}
return false;
}
public static boolean saveImageAtFolder(BufferedImage img, String folderPath) {
JFileChooser FC = new JFileChooser(folderPath);
int retrival = FC.showSaveDialog(null);
if (retrival == FC.APPROVE_OPTION) {
File fileToSave = FC.getSelectedFile();
String extension = FactoryUtils.getFileExtension(fileToSave);
try {
boolean ret = ImageIO.write(img, extension, fileToSave);
return ret;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
System.out.println(ex.getMessage());
return false;
}
return true;
}
return false;
}
public static boolean saveImage(BufferedImage img, String fileName) {
File file = new File(fileName);
String extension = FactoryUtils.getFileExtension(fileName);
boolean ret = false;
try {
ret = ImageIO.write(img, extension, file);
} catch (IOException ex) {
Logger.getLogger(ImageProcess.class.getName()).log(Level.SEVERE, null, ex);
}
return ret;
}
public static void saveImageSVG(BufferedImage img, String dest_path) {
String path=dest_path.replace("."+FactoryUtils.getFileExtension(dest_path), ".png");
saveImage(img, path);
RasterToVector rtv=new RasterToVector(path);
rtv.convertToSVG(dest_path);
}
public static void saveImageSVG(String source_path, String dest_path) {
RasterToVector rtv=new RasterToVector(source_path);
rtv.convertToSVG(dest_path);
}
public static BufferedImage convertDicomToBufferedImage(String filePath) {
File file = new File(filePath);
Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("DICOM");
BufferedImage img = null;
while (iterator.hasNext()) {
ImageReader imageReader = (ImageReader) iterator.next();
DicomImageReadParam dicomImageReadParam = (DicomImageReadParam) imageReader.getDefaultReadParam();
try {
ImageInputStream iis = ImageIO.createImageInputStream(file);
imageReader.setInput(iis, false);
img = imageReader.read(0, dicomImageReadParam);
iis.close();
if (img == null) {
System.out.println("Could not read image!!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return img;
}
public static boolean ocv_saveImageWithFormat(BufferedImage img, String path) {
Mat imgM = ocv_img2Mat(img);
return Imgcodecs.imwrite(path, imgM);
}
public static Mat ocv_saveImage(BufferedImage img, String path) {
Mat imgM = ocv_img2Mat(img);
Imgcodecs.imwrite(path, imgM);
return imgM;
}
public static BufferedImage ocv_imRead(String path) {
Mat imgM = Imgcodecs.imread(path);
return ocv_mat2Img(imgM);
}
public static void saveGridImage(BufferedImage gridImage, String filePath) {
File output = new File(filePath);
output.delete();
final String formatName = "png";
for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
try {
ImageWriter writer = iw.next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
continue;
}
try {
setDPI(metadata, 300);
} catch (IIOInvalidTreeException ex) {
Logger.getLogger(FactoryUtils.class
.getName()).log(Level.SEVERE, null, ex);
}
final ImageOutputStream stream = ImageIO.createImageOutputStream(output);
try {
writer.setOutput(stream);
writer.write(metadata, new IIOImage(gridImage, null, metadata), writeParam);
} finally {
stream.close();
}
break;
} catch (IOException ex) {
Logger.getLogger(FactoryUtils.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void setDPI(IIOMetadata metadata, int DPI) throws IIOInvalidTreeException {
// for PMG, it's dots per millimeter inc to cm=2.54
// double dotsPerMilli = 1.0 * DPI / 10 / 2.54;
double dotsPerMilli = 1.0 * DPI;
IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
horiz.setAttribute("value", Double.toString(dotsPerMilli));
IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
vert.setAttribute("value", Double.toString(dotsPerMilli));
IIOMetadataNode dim = new IIOMetadataNode("Dimension");
dim.appendChild(horiz);
dim.appendChild(vert);
IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
root.appendChild(dim);
metadata.mergeTree("javax_imageio_1.0", root);
}
public static BufferedImage getBufferedImage(JPanel panel) {
int w = panel.getWidth();
int h = panel.getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
panel.paint(g);
return bi;
}
public static BufferedImage saveImageAsJPEG(String filePath, BufferedImage currBufferedImage, int k) {
//System.out.println("New Image Captured and jpg file saved");
try {
if (currBufferedImage == null) {
return null;
}
File file = new File(filePath + "\\img_" + k + ".jpg");
ImageIO.write(currBufferedImage, "jpg", file);
BufferedImage myImage = ImageIO.read(file);
currBufferedImage = myImage;
} catch (IOException ex) {
ex.printStackTrace();
}
return currBufferedImage;
}
public static BufferedImage getAlphaChannelGray(BufferedImage bf) {
return rgb2gray(getAlphaChannelColor(bf));
}
public static BufferedImage getRedChannelGray(BufferedImage bf) {
return rgb2gray(getRedChannelColor(bf));
}
public static BufferedImage getGreenChannelGray(BufferedImage bf) {
return rgb2gray(getGreenChannelColor(bf));
}
public static BufferedImage getBlueChannelGray(BufferedImage bf) {
return rgb2gray(getBlueChannelColor(bf));
}
public static BufferedImage getAlphaChannelColor(BufferedImage bf) {
int[][][] d = imageToPixelsColorInt(bf);
int[][] ret = new int[d.length][d[0].length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
ret[i][j] = d[i][j][0];
}
}
return pixelsToImageColor(d);
}
public static BufferedImage getRedChannelColor(BufferedImage bf) {
int[][][] d = imageToPixelsColorInt(bf);
int[][][] ret = new int[d.length][d[0].length][4];
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
ret[i][j][0] = d[i][j][0];
ret[i][j][1] = d[i][j][1];
}
}
return pixelsToImageColor(ret);
}
public static BufferedImage getGreenChannelColor(BufferedImage bf) {
int[][][] d = imageToPixelsColorInt(bf);
int[][][] ret = new int[d.length][d[0].length][4];
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
ret[i][j][0] = d[i][j][0];
ret[i][j][2] = d[i][j][2];
}
}
return pixelsToImageColor(ret);
}
public static BufferedImage getBlueChannelColor(BufferedImage bf) {
int[][][] d = imageToPixelsColorInt(bf);
int[][][] ret = new int[d.length][d[0].length][4];
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
ret[i][j][0] = d[i][j][0];
ret[i][j][3] = d[i][j][3];
}
}
return pixelsToImageColor(ret);
}
public static double[][] getRedChannelDouble(double[][][] d) {
double[][] ret = new double[d.length][d[0].length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
ret[i][j] = d[i][j][1];
}
}
return ret;
}
public static double[][] getGreenChannelDouble(double[][][] d) {
double[][] ret = new double[d.length][d[0].length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
ret[i][j] = d[i][j][2];
}
}
return ret;
}
public static double[][] getBlueChannelDouble(double[][][] d) {
double[][] ret = new double[d.length][d[0].length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
ret[i][j] = d[i][j][3];
}
}
return ret;
}
public static BufferedImage filterMedian(BufferedImage imgx) {
return filterMedian(imgx, 3);
}
public static BufferedImage filterGaussian(BufferedImage imgx, int size) {
GaussianFilter gaussianFilter = new GaussianFilter(size);
BufferedImage gaussianFiltered = clone(imgx);
gaussianFilter.filter(imgx, gaussianFiltered);
return gaussianFiltered;
}
public static BufferedImage filterMedian(BufferedImage imgx, int size) {
int w = imgx.getHeight(null);
int h = imgx.getWidth(null);
int[] kernel = new int[size * size];
int dizi[][] = new int[w][h];
int temp[][] = new int[w][h];
dizi = imageToPixelsInt(imgx);
temp = (int[][]) dizi.clone();
for (int i = 1; i < w - 1; i++) {
for (int j = 1; j < h - 1; j++) {
int f = 0;
for (int k = -1; k <= 1; k++) {
for (int t = -1; t <= 1; t++) {
kernel[f] = dizi[i + k][j + t];
f++;
}
}
temp[i][j] = medianKernel(kernel);
}
}
dizi = (int[][]) temp.clone();
BufferedImage ret_img = ImageProcess.pixelsToImageGray(dizi);
return ret_img;
}
public static int medianKernel(int[] kernel) {
int buffer;
for (int i = 0; i < kernel.length; i++) {
for (int j = i; j < kernel.length; j++) {
if (kernel[j] > kernel[i]) {
buffer = kernel[j];
kernel[j] = kernel[i];
kernel[i] = buffer;
}
}
}
int mid = kernel.length / 2;
return kernel[mid];
}
public static BufferedImage filterMean(BufferedImage imgx) {
AverageFilter avgFilter = new AverageFilter();
BufferedImage dest = clone(imgx);
avgFilter.filter(dest, imgx);
return dest;
// return ImageProcess.filterMean(imgx, 3);
}
public static BufferedImage filterMotionBlur(BufferedImage imgx) {
MotionBlurOp op = new MotionBlurOp(5, 45, 13, 3);
// MotionBlurFilter motionFilter=new MotionBlurFilter();
// motionFilter.setAngle(20);
// motionFilter.setDistance(15);
//motionFilter.setRotation(10);
BufferedImage dest = clone(imgx);
op.filter(dest, imgx);
return dest;
}
public static double[][] filterMean(double[][] d) {
double[][] ret = imageToPixelsDouble(filterMean(pixelsToImageGray(d), 3));
return ret;
}
public static BufferedImage filterMean(BufferedImage imgx, int size) {
int w = imgx.getWidth(null);
int h = imgx.getHeight(null);
int[] kernel = new int[size * size];
int dizi[][] = new int[w][h];
int temp[][] = new int[w][h];
dizi = imageToPixelsInt(imgx);
temp = FactoryMatrix.clone(dizi);
int sum = 0;
for (int i = 1; i < w - 1; i++) {
for (int j = 1; j < h - 1; j++) {
int f = 0;
for (int k = -1; k <= 1; k++) {
for (int t = -1; t <= 1; t++) {
kernel[f] = dizi[i + k][j + t];
sum += kernel[f];
f++;
}
}
// if (sum / 9 > 0) {
// System.out.println("org:" + temp[i][j] + " avg:" + (sum / (size * size)) + " r,c:" + j + ":" + i);
// }
temp[i][j] = sum / (size * size);
sum = 0;
}
}
int[][] d = FactoryMatrix.clone(temp);
BufferedImage ret_img = ImageProcess.pixelsToImageGray(d);
return ret_img;
}
// public static double[][] meanFilter(double[][] imgx) {
// int r = imgx.length;
// int c = imgx[0].length;
// int[] kernel = new int[9];
// double temp[][] = new double[r][c];
// temp = FactoryMatrix.clone(imgx);
// int sum = 0;
// for (int row = 1; row < r - 1; row++) {
// for (int column = 1; column < c - 1; column++) {
// int f = 0;
// for (int k = -1; k <= 1; k++) {
// for (int t = -1; t <= 1; t++) {
// kernel[f] = (int) imgx[row + k][column + t];
// sum += kernel[f];
// f++;
// }
// }
// temp[row][column] = (int) (sum / 9.0);
// sum = 0;
// }
// }
// return temp;
// }
public static BufferedImage erode(BufferedImage img, int[][] kernel) {
BufferedImage imgx = clone(img);
int w = imgx.getWidth(null);
int h = imgx.getHeight(null);
int dizi[][] = new int[h][w];
int temp[][] = new int[h][w];
dizi = imageToPixelsInt(imgx);
for (int i = 1; i < h - 1; i++) {
for (int j = 1; j < w - 1; j++) {
if (dizi[i - 1][j - 1] == kernel[0][0] && dizi[i - 1][j] == kernel[0][1] && dizi[i - 1][j + 1] == kernel[0][2]
&& dizi[i][j - 1] == kernel[1][0] && dizi[i][j] == kernel[1][1] && dizi[i][j + 1] == kernel[1][2]
&& dizi[i + 1][j - 1] == kernel[2][0] && dizi[i + 1][j] == kernel[2][1] && dizi[i + 1][j + 1] == kernel[2][2]) {
temp[i][j] = 0;
} else {
temp[i][j] = 255;
}
}
}
dizi = temp;
BufferedImage ret_img = ImageProcess.pixelsToImageGray(dizi);
return ret_img;
}
public static BufferedImage erode(BufferedImage imgx) {
int[][] kernel = {{255, 255, 255}, {255, 255, 255}, {255, 255, 255}};
return dilate(imgx, kernel);
}
public static BufferedImage dilate(BufferedImage img, int[][] kernel) {
int w = img.getWidth(null);
int h = img.getHeight(null);
int dizi[][] = new int[h][w];
int temp[][] = new int[h][w];
BufferedImage imgx = clone(img);
dizi = imageToPixelsInt(imgx);
for (int i = 1; i < h - 1; i++) {
for (int j = 1; j < w - 1; j++) {
if (dizi[i - 1][j - 1] == kernel[0][0] || dizi[i - 1][j] == kernel[0][1] || dizi[i - 1][j + 1] == kernel[0][2]
|| dizi[i][j - 1] == kernel[1][0] || dizi[i][j] == kernel[1][1] || dizi[i][j + 1] == kernel[1][2]
|| dizi[i + 1][j - 1] == kernel[2][0] || dizi[i + 1][j] == kernel[2][1] || dizi[i + 1][j + 1] == kernel[2][2]) {
temp[i][j] = 0;
} else {
temp[i][j] = 255;
}
}
}
dizi = temp;
BufferedImage ret_img = ImageProcess.pixelsToImageGray(dizi);
return ret_img;
}
public static BufferedImage dilate(BufferedImage imgx) {
int[][] kernel = {{255, 255, 255}, {255, 255, 255}, {255, 255, 255}};
return dilate(imgx, kernel);
}
public static BufferedImage kernelFilter(BufferedImage imgx) {
int w = imgx.getWidth(null);
int h = imgx.getHeight(null);
int dizi[][] = new int[w][h];
int kw = 15;
int kh = 15;
int med = kw / 2;
int[][] kernel = new int[kw][kh];
for (int i = 2; i < kw - 2; i++) {
for (int j = 2; j < kh - 2; j++) {
kernel[i][j] = 255;
}
}
dizi = imageToPixelsInt(imgx);
for (int i = med; i < w - med; i++) {
for (int j = med; j < h - med; j++) {
if (dizi[i - med][j - med] == 0 && dizi[i - med][j + med] == 0 && dizi[i + med][j - med] == 0 && dizi[i + med][j + med] == 0
&& dizi[i][j] == 255 && dizi[i - 1][j - 1] == 255 && dizi[i - 1][j + 1] == 255 && dizi[i + 1][j - 1] == 255 && dizi[i + 1][j + 1] == 255) {
for (int k = 0; k < med; k++) {
for (int m = 0; m < med; m++) {
if (dizi[i + k][j + m] == 255) {
dizi[i + k][j + m] = 0;
}
}
}
//writeln("bulundu:"+i+","+j);
}
}
}
//dizi=temp;
BufferedImage ret_img = ImageProcess.pixelsToImageGray(dizi);
return ret_img;
}
/**
* Get binary int treshold using Otsu's method
*/
public static int getOtsuTresholdValue(BufferedImage original) {
double[][] d = ImageProcess.imageToPixelsDouble(original);
return getOtsuTresholdValue(d);
}
/**
* Get binary int treshold using Otsu's method
*/
public static int getOtsuTresholdValue(double[][] d) {
int[] histogram = ImageProcess.getHistogram(d);
int total = d.length * d[0].length;
float sum = 0;
for (int i = 0; i < 256; i++) {
sum += i * histogram[i];
}
float sumB = 0;
int wB = 0;
int wF = 0;
float varMax = 0;
int threshold = 0;
for (int i = 0; i < 256; i++) {
wB += histogram[i];
if (wB == 0) {
continue;
}
wF = total - wB;
if (wF == 0) {
break;
}
sumB += (float) (i * histogram[i]);
float mB = sumB / wB;
float mF = (sum - sumB) / wF;
float varBetween = (float) wB * (float) wF * (mB - mF) * (mB - mF);
if (varBetween > varMax) {
varMax = varBetween;
threshold = i;
}
}
return threshold;
}
/**
* Binarize Color Image with a given threshold value i.e. otsuThreshold
*
* @param original
* @return
*/
public static BufferedImage binarizeColorImage(BufferedImage original, int threshold) {
int red;
int newPixel;
BufferedImage binarized = new BufferedImage(original.getWidth(), original.getHeight(), original.getType());
for (int i = 0; i < original.getWidth(); i++) {
for (int j = 0; j < original.getHeight(); j++) {
// Get pixels
red = new Color(original.getRGB(i, j)).getRed();
int alpha = new Color(original.getRGB(i, j)).getAlpha();
if (red > threshold) {
newPixel = 255;
} else {
newPixel = 0;
}
newPixel = colorToRGB(alpha, newPixel, newPixel, newPixel);
binarized.setRGB(i, j, newPixel);
}
}
return binarized;
}
/**
* Binarize Color Image with a given threshold value i.e. otsuThreshold
*
* @param original
* @return
*/
public static BufferedImage binarizeColorImage(BufferedImage original) {
int threshold = getOtsuTresholdValue(original);
return binarizeColorImage(original, threshold);
}
/**
* Binarize Image with a given threshold value hint: you can determine
* threshold value from otsu approach and then pass as an argument
*
* @param original
* @return
*/
public static BufferedImage binarizeGrayScaleImage(BufferedImage original, int threshold) {
int[][] d = imageToPixelsInt(original);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] > threshold) {
d[i][j] = 255;
} else {
d[i][j] = 0;
}
}
}
BufferedImage binarized = ImageProcess.pixelsToImageGray(d);
return binarized;
}
/**
* Binarize Image with a given threshold value you can determine threshold
* value from otsu approach and then pass as an argument
*
* @param original
* @return
*/
public static BufferedImage binarizeGrayScaleImage(BufferedImage original) {
int threshold = getOtsuTresholdValue(original);
return binarizeGrayScaleImage(original, threshold);
}
/**
* Binarize Image with a given threshold value you can determine threshold
* value from otsu approach
*
* @param d
* @return
*/
public static BufferedImage binarizeGrayScaleImage(double[][] d, int threshold) {
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
if (d[i][j] > threshold) {
d[i][j] = 255;
} else {
d[i][j] = 0;
}
}
}
BufferedImage binarized = pixelsToImageGray(d);
return binarized;
}
// Convert R, G, B, Alpha to standard 8 bit
public static int colorToRGB(int alpha, int red, int green, int blue) {
int newPixel = 0;
newPixel += alpha;
newPixel = newPixel << 8;
newPixel += red;
newPixel = newPixel << 8;
newPixel += green;
newPixel = newPixel << 8;
newPixel += blue;
return newPixel;
}
// /**
// * convert let say gray scale image to RGB or any other types
// *
// * @param img
// * @param newType
// * @return
// */
// public static BufferedImage toNewColorSpace(BufferedImage img, int newType) {
// BufferedImage ret = new BufferedImage(img.getWidth(), img.getHeight(), newType);
// ret.getGraphics().drawImage(img, 0, 0, null);
// return ret;
// }
//
/**
* convert let say gray scale image to RGB or any other types
*
* @param img
* @param newType
* @return
*/
public static BufferedImage toBufferedImage(BufferedImage img, int newType) {
BufferedImage ret = new BufferedImage(img.getWidth(), img.getHeight(), newType);
ret.getGraphics().drawImage(img, 0, 0, null);
return ret;
}
public static double[][] highPassFilter(double[][] m, int t) {
double[][] d = FactoryMatrix.clone(m);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] < t) {
d[i][j] = 0;
}
}
}
return d;
}
public static double[][] lowPassFilter(double[][] m, int t) {
double[][] d = FactoryMatrix.clone(m);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] > t) {
d[i][j] = 0;
}
}
}
return d;
}
public static double[][] swapColor(double[][] m, int c1, int c2) {
double[][] d = FactoryMatrix.clone(m);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] == c1) {
d[i][j] = c2;
}
}
}
return d;
}
public static double[][] imageToPixels2DFromOpenCV(Mat m) {
double[][] ret = new double[m.height()][m.width()];
for (int i = 0; i < m.height(); i++) {
for (int j = 0; j < m.width(); j++) {
ret[i][j] = m.get(i, j)[0];
}
}
return ret;
}
// public static Rectangle[] detectFacesRectangles(String type, BufferedImage img) {
//
// String xml = "";
// if (type.equals("haar")) {
// xml = "etc\\haarcascades\\haarcascade_frontalface_alt.xml";
//// xml = "etc\\haarcascades\\haarcascade_frontalface_alt_tree.xml";
// }
// if (type.equals("lbp")) {
// xml = "etc\\lbpcascades\\lbpcascade_frontalface.xml";
// }
//// System.out.println("xml_file = " + xml);
// CascadeClassifier faceDetector = new CascadeClassifier(xml);
// Mat imageGray = ocv_img2Mat(img);
//
// MatOfRect faceDetections = new MatOfRect();
// faceDetector.detectMultiScale(imageGray, faceDetections);
//// System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
// for (Rect rect : faceDetections.toArray()) {
// Imgproc.rectangle(imageGray, new org.opencv.core.Point(rect.x, rect.y), new org.opencv.core.Point(rect.x + rect.width, rect.y + rect.height),
// new Scalar(0, 255, 255), 2);
//
// }
// return ocv_mat2Img(imageGray);
// }
public static BufferedImage drawRectangle(BufferedImage img, int x, int y, int w, int h, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
//img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawRect(y, x, w, h);
g2d.dispose();
return img;
}
public static BufferedImage drawLine(BufferedImage img, int r1, int c1, int r2, int c2, int thickness, Color color) {
BufferedImage ret = null;
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.setStroke(new BasicStroke(thickness));
g2d.drawLine(c1, r1, c2, r2);
g2d.dispose();
return img;
}
final public static BufferedImage toNewColorSpace(BufferedImage image, int newType) {
BufferedImage ret = null;
try {
ret = new BufferedImage(
image.getWidth(),
image.getHeight(),
newType);
ColorConvertOp xformOp = new ColorConvertOp(null);
xformOp.filter(image, ret);
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
public static BufferedImage fillRectangle(BufferedImage img, int x, int y, int w, int h, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fillRect(y, x, w, h);
g2d.dispose();
return img;
}
public static BufferedImage draw3DRectangle(BufferedImage img, int x, int y, int w, int h, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.draw3DRect(y, x, w, h, true);
g2d.dispose();
return img;
}
public static BufferedImage fill3DRectangle(BufferedImage img, int x, int y, int w, int h, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fill3DRect(y, x, w, h, true);
g2d.dispose();
return img;
}
public static BufferedImage drawRoundRectangle(BufferedImage img, int x, int y, int w, int h, int arcw, int arch, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawRoundRect(y, x, w, h, arcw, arch);
g2d.dispose();
return img;
}
public static BufferedImage fillRoundRectangle(BufferedImage img, int x, int y, int w, int h, int arcw, int arch, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fillRoundRect(y, x, w, h, arcw, arch);
g2d.dispose();
return img;
}
public static BufferedImage drawOval(BufferedImage img, int x, int y, int w, int h, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawOval(y, x, w, h);
g2d.dispose();
return img;
}
public static BufferedImage drawShape(BufferedImage img, Shape p, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.draw(p);
g2d.dispose();
return img;
}
public static BufferedImage fillShape(BufferedImage img, Shape p, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fill(p);
g2d.dispose();
return img;
}
public static BufferedImage drawPolygon(BufferedImage img, Polygon p, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawPolygon(p);
g2d.dispose();
return img;
}
public static BufferedImage fillPolygon(BufferedImage img, Polygon p, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fillPolygon(p);
g2d.dispose();
return img;
}
public static BufferedImage drawArc(BufferedImage img, int x, int y, int w, int h, int startAngle, int arcAngle, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawArc(y, x, w, h, startAngle, arcAngle);
g2d.dispose();
return img;
}
public static BufferedImage drawPolyLine(BufferedImage img, int[] xPoints, int[] yPoints, int nPoints, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawPolyline(yPoints, xPoints, nPoints);
g2d.dispose();
return img;
}
public static BufferedImage fillOval(BufferedImage img, int x, int y, int w, int h, Color color) {
BufferedImage ret = null;
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fillOval(y, x, w, h);
g2d.dispose();
return img;
}
public static BufferedImage detectFaces(String type, BufferedImage img) {
String xml = "";
if (type.equals("haar")) {
xml = "etc\\haarcascades\\haarcascade_frontalface_alt.xml";
}
if (type.equals("lbp")) {
xml = "etc\\lbpcascades\\lbpcascade_frontalface.xml";
}
BufferedImage img2 = ImageProcess.clone(img);
CascadeClassifier faceDetector = new CascadeClassifier(xml);
Mat imageGray = ocv_img2Mat(img2);
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(imageGray, faceDetections);
for (Rect rect : faceDetections.toArray()) {
// Imgproc.rectangle(imageGray, new org.opencv.core.Point(rect.x, rect.y), new org.opencv.core.Point(rect.x + rect.width, rect.y + rect.height),
// new Scalar(0, 255, 255), 2);
drawRectangle(img, rect.y - (int) (rect.height * 0.1), rect.x, rect.width, rect.height + (int) (rect.height * 0.2), 1, Color.yellow);
}
// return ocv_mat2Img(imageGray);
return img;
}
public static BufferedImage detectFaces(String type, BufferedImage img, CRectangle r, boolean showRect) {
String xml = "";
if (type.equals("haar")) {
xml = "etc\\haarcascades\\haarcascade_frontalface_alt.xml";
}
if (type.equals("lbp")) {
xml = "etc\\lbpcascades\\lbpcascade_frontalface.xml";
}
BufferedImage img2 = ImageProcess.clone(img);
CascadeClassifier faceDetector = new CascadeClassifier(xml);
Mat imageGray = ocv_img2Mat(img2);
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(imageGray, faceDetections);
for (Rect rect : faceDetections.toArray()) {
// Imgproc.rectangle(imageGray, new org.opencv.core.Point(rect.x, rect.y), new org.opencv.core.Point(rect.x + rect.width, rect.y + rect.height),
// new Scalar(0, 255, 255), 2);
if (showRect) {
drawRectangle(img, rect.y - (int) (rect.height * 0.1), rect.x, rect.width, rect.height + (int) (rect.height * 0.2), 1, Color.yellow);
}
r.row = rect.y - (int) (rect.height * 0.1);
r.column = rect.x;
r.width = rect.width;
r.height = rect.height + (int) (rect.height * 0.2);
}
// return ocv_mat2Img(imageGray);
return img;
}
public static Rectangle[] getFacesRectangles(String type, BufferedImage img) {
String xml = "";
if (type.equals("haar")) {
xml = "etc\\haarcascades\\haarcascade_frontalface_alt.xml";
// xml = "etc\\haarcascades\\haarcascade_frontalface_alt_tree.xml";
}
if (type.equals("lbp")) {
xml = "etc\\lbpcascades\\lbpcascade_frontalface.xml";
}
BufferedImage img2 = ImageProcess.clone(img);
CascadeClassifier faceDetector = new CascadeClassifier(xml);
Mat imageGray = ocv_img2Mat(img2);
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(imageGray, faceDetections);
Rect[] rects = faceDetections.toArray();
Rectangle[] ret = new Rectangle[faceDetections.toArray().length];
for (int i = 0; i < rects.length; i++) {
Rect r = rects[i];
ret[i] = new Rectangle(r.x, r.y, r.width, r.height);
}
return ret;
}
public static CRectangle[] getFacesRectanglesAsCRectangle(String type, BufferedImage img) {
Rectangle[] rects=getFacesRectangles(type, img);
CRectangle[] ret=new CRectangle[rects.length];
for (int i = 0; i < ret.length; i++) {
ret[i]=new CRectangle(rects[i]);
}
return ret;
}
public static BufferedImage toARGB(BufferedImage image) {
return toNewColorSpace(image, BufferedImage.TYPE_INT_ARGB);
}
public static BufferedImage toBGR(BufferedImage image) {
return toNewColorSpace(image, BufferedImage.TYPE_3BYTE_BGR);
}
public static BufferedImage toGrayLevel(BufferedImage img) {
BufferedImage image = new BufferedImage(img.getWidth(), img.getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
Graphics g = image.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
return image;
// return toNewColorSpace(image, BufferedImage.TYPE_BYTE_GRAY);
// return pixelsToImageGray(imageToPixelsDouble(image));
}
public static BufferedImage toBinary(BufferedImage image) {
return toNewColorSpace(image, BufferedImage.TYPE_BYTE_BINARY);
}
public static BufferedImage flipVertical(BufferedImage image) {
AffineTransform at = new AffineTransform();
at.concatenate(AffineTransform.getScaleInstance(-1, 1));
at.concatenate(AffineTransform.getTranslateInstance(-image.getWidth(), 0));
BufferedImage bf = buildTransformed(image, at);
// BufferedImage bf = new BufferedImage(
// image.getWidth(), image.getHeight(),
// BufferedImage.TYPE_3BYTE_BGR);
// Graphics2D g = image.createGraphics();
// g.drawImage(image , 0,0,-image.getWidth(),image.getHeight(),null);
return bf;
}
public static BufferedImage flipHorizontal(BufferedImage image) {
AffineTransform at = new AffineTransform();
at.concatenate(AffineTransform.getScaleInstance(1, -1));
at.concatenate(AffineTransform.getTranslateInstance(0, -image.getHeight()));
return buildTransformed(image, at);
}
public static BufferedImage buildTransformed(BufferedImage image, AffineTransform at) {
BufferedImage newImage = new BufferedImage(
image.getWidth(), image.getHeight(),
BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = newImage.createGraphics();
g.transform(at);
g.drawImage(image, 0, 0, null);
g.dispose();
return newImage;
}
public static BufferedImage invertImage(BufferedImage image) {
if (image.getType() != BufferedImage.TYPE_INT_ARGB) {
image = toARGB(image);
}
LookupTable lookup = new LookupTable(0, 4) {
@Override
public int[] lookupPixel(int[] src, int[] dest) {
dest[0] = (int) (255 - src[0]);
dest[1] = (int) (255 - src[1]);
dest[2] = (int) (255 - src[2]);
return dest;
}
};
LookupOp op = new LookupOp(lookup, new RenderingHints(null));
return op.filter(image, null);
}
/**
* if location and size are not given overlayed image is positioned at 0,0
* white pixels are ignored through overlaying process
*
* @param bf
* @param overlay
* @return
*/
public static BufferedImage overlayImage(BufferedImage bf, BufferedImage overlay) {
int[][][] bfp = imageToPixelsColorInt(bf);
int[][][] ovp = imageToPixelsColorInt(overlay);
int r = ovp.length;
int c = ovp[0].length;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (ovp[i][j][0] != 255 || ovp[i][j][1] != 255 || ovp[i][j][2] != 255 || ovp[i][j][3] != 255) {
for (int k = 0; k < 4; k++) {
bfp[i][j][k] = ovp[i][j][k];
}
}
}
}
return pixelsToImageColor(bfp);
}
/**
* overlay image onto original image
*
* @param bf
* @param overlay
* @param rect
* @param bkg
* @return
*/
public static BufferedImage overlayImage(BufferedImage bf, BufferedImage overlay, CRectangle rect, int bkg) {
int[][][] bfp = imageToPixelsColorInt(bf);
int[][][] ovp = imageToPixelsColorInt(overlay);
int r1 = bfp.length;
int c1 = bfp[0].length;
int r = ovp.length;
int c = ovp[0].length;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
// if (ovp[i][j][0] != bkg || ovp[i][j][1] != bkg || ovp[i][j][2] != bkg || ovp[i][j][3] != bkg) {
if (ovp[i][j][1] != bkg || ovp[i][j][2] != bkg || ovp[i][j][3] != bkg) {
for (int k = 1; k < 4; k++) {
if (i + rect.row > 0 && j + rect.column > 0 && i + rect.row < r1 && j + rect.column < c1) {
bfp[i + rect.row][j + rect.column][k] = ovp[i][j][k];
}
}
}
}
}
return pixelsToImageColor(bfp);
}
public static BufferedImage overlayImage(BufferedImage bf, BufferedImage overlay, CPoint cp, int bkg) {
int[][][] bfp = imageToPixelsColorInt(bf);
int[][][] ovp = imageToPixelsColorInt(overlay);
int r1 = bfp.length;
int c1 = bfp[0].length;
int r = ovp.length;
int c = ovp[0].length;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (ovp[i][j][1] != bkg || ovp[i][j][2] != bkg || ovp[i][j][3] != bkg) {
for (int k = 1; k < 4; k++) {
if (i + cp.row > 0 && j + cp.column > 0 && i + cp.row < r1 && j + cp.column < c1) {
bfp[i + cp.row][j + cp.column][k] = ovp[i][j][k];
}
}
}
}
}
return pixelsToImageColor(bfp);
}
public static BufferedImage overlayImage(BufferedImage bgImage, BufferedImage fgImage, double alpha) {
int w = bgImage.getWidth();
int h = bgImage.getHeight();
BufferedImage newImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImg.createGraphics();
// Clear the image (optional)
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, w, h);
// Draw the background image
g.setComposite(AlphaComposite.SrcOver);
g.drawImage(bgImage, 0, 0, null);
// Draw the overlay image
g.setComposite(AlphaComposite.SrcOver.derive((float) alpha));
g.drawImage(fgImage, 0, 0, null);
g.dispose();
return newImg;
}
public static BufferedImage overlayImage(BufferedImage bgImage, BufferedImage fgImage, Point p, double alpha) {
int w = bgImage.getWidth();
int h = bgImage.getHeight();
BufferedImage newImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImg.createGraphics();
// Clear the image (optional)
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, w, h);
// Draw the background image
g.setComposite(AlphaComposite.SrcOver);
g.drawImage(bgImage, 0, 0, null);
// Draw the overlay image
g.setComposite(AlphaComposite.SrcOver.derive((float) alpha));
g.drawImage(fgImage, p.x, p.y, null);
g.dispose();
return newImg;
}
public static BufferedImage drawText(BufferedImage bf, String str, int x, int y, Color col) {
BufferedImage newImage = new BufferedImage(
bf.getWidth(), bf.getHeight(),
BufferedImage.TYPE_3BYTE_BGR);
Graphics2D gr = newImage.createGraphics();
gr.drawImage(bf, 0, 0, null);
gr.setColor(col);
gr.drawString(str, x, y);
gr.dispose();
return newImage;
}
public static BufferedImage adaptiveThreshold(double[][] d, int t1, int t2) {
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] >= t1 && d[i][j] <= t2) {
d[i][j] = 255;
} else {
d[i][j] = 0;
}
}
}
BufferedImage binarized = ImageProcess.pixelsToImageGray(d);
return binarized;
}
public static BufferedImage thresholdGray(BufferedImage img, int t1, int t2) {
double[][] d = imageToPixelsDouble(img);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] >= t1 && d[i][j] < t2) {
d[i][j] = 255;
} else {
d[i][j] = 0;
}
}
}
BufferedImage binarized = ImageProcess.pixelsToImageGray(d);
return binarized;
}
public static BufferedImage thresholdHSV(BufferedImage bf, int h1, int h2, int s1, int s2, int v1, int v2) {
BufferedImage ret = null;
int[][] dh = imageToPixelsInt(rgb2gray(getHueChannel(bf)));
int[][] ds = imageToPixelsInt(rgb2gray(getSaturationChannel(bf)));
int[][] dv = imageToPixelsInt(rgb2gray(getValueChannel(bf)));
int nr = dh.length;
int nc = dh[0].length;
int[][] d = new int[nr][nc];
int h, s, v;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
h = dh[i][j];
s = ds[i][j];
v = dv[i][j];
if (h >= h1 && h <= h2 && s >= s1 && s <= s2 && v >= v1 && v <= v2) {
d[i][j] = 255;
}
}
}
ret = pixelsToImageGray(d);
return ret;
}
public static BufferedImage ocv_img2hsv(BufferedImage bf) {
// Mat frame = ImageProcess.ocv_img2Mat(bf);
// Mat hsvImage = new Mat();
// Imgproc.cvtColor(frame, hsvImage, Imgproc.COLOR_BGR2HSV);
// BufferedImage img = ocv_mat2Img(hsvImage);
// return img;
// return ocv_rgb2hsv(bf);
return ocv_2_hsv(bf);
}
public static BufferedImage ocv_rgb2hsv(BufferedImage bf) {
// Mat frame = ImageProcess.ocv_img2Mat(bf);
// Mat hsvImage = new Mat();
// // convert the frame to HSV
// Imgproc.cvtColor(frame, hsvImage, Imgproc.COLOR_BGR2HSV);
// BufferedImage img = ocv_mat2Img(hsvImage);
BufferedImage img = ocv_2_hsv(bf);
return img;
}
public static BufferedImage ocv_hsvThreshold(BufferedImage bf, int h1, int h2, int s1, int s2, int v1, int v2) {
Mat frame = ImageProcess.ocv_img2Mat(bf);
// Mat hsvImage = new Mat();
Mat mask = new Mat();
// convert the frame to HSV
// Imgproc.cvtColor(frame, hsvImage, Imgproc.COLOR_BGR2HSV);
// get thresholding values from the UI
Scalar minValues = new Scalar(h1, s1, v1);
Scalar maxValues = new Scalar(h2, s2, v2);
Core.inRange(frame, minValues, maxValues, mask);
BufferedImage img = ocv_mat2Img(mask);
return img;
}
public static BufferedImage ocv_2_hsv(BufferedImage img) {
Mat blurredImage = new Mat();
Mat hsvImage = new Mat();
Mat mask = new Mat();
Mat morphOutput = new Mat();
Mat frame = ImageProcess.ocv_img2Mat(img);
// remove some noise
Imgproc.blur(frame, blurredImage, new Size(7, 7));
// convert the frame to HSV
Imgproc.cvtColor(blurredImage, hsvImage, Imgproc.COLOR_BGR2HSV);
// get thresholding values from the UI
// remember: H ranges 0-180, S and V range 0-255
Scalar minValues = new Scalar(0, 150, 150);
Scalar maxValues = new Scalar(50, 255, 255);
// show the current selected HSV range
// String valuesToPrint = "Hue range: " + minValues.val[0] + "-" + maxValues.val[0]
// + "\tSaturation range: " + minValues.val[1] + "-" + maxValues.val[1] + "\tValue range: "
// + minValues.val[2] + "-" + maxValues.val[2];
// threshold HSV image to select tennis balls
Core.inRange(hsvImage, minValues, maxValues, mask);
BufferedImage bf = ImageProcess.ocv_mat2Img(hsvImage);
return bf;
}
public static BufferedImage ocv_medianFilter(BufferedImage bf) {
Mat frame = ImageProcess.ocv_img2Mat(bf);
Mat blurredImage = new Mat();
Imgproc.medianBlur(frame, blurredImage, 5);
BufferedImage out = ocv_mat2Img(blurredImage);
return out;
}
public static BufferedImage ocv_negativeImage(BufferedImage bf) {
Mat frame = ImageProcess.ocv_img2Mat(bf);
Mat negativeImage = new Mat();
Core.bitwise_not(frame, negativeImage);
BufferedImage out = ocv_mat2Img(negativeImage);
return out;
}
public static BufferedImage ocv_cloneImage(BufferedImage bf) {
Mat frame = ImageProcess.ocv_img2Mat(bf);
Mat cloneImage = frame.clone();
BufferedImage out = ocv_mat2Img(cloneImage);
return out;
}
public static BufferedImage cropBoundingBox(BufferedImage img) {
BufferedImage bf = clone(img);
int[][] d = imageToPixelsInt(img);
int nr = d.length;
int nc = d[0].length;
int left = nc, right = 0;
int top = nr, bottom = 0;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
if (d[i][j] > 0) {
if (left > j) {
left = j;
}
if (right < j) {
right = j;
}
if (top > i) {
top = i;
}
if (bottom < i) {
bottom = i;
}
}
}
}
bf = cropImage(bf, new CRectangle(top, left, right - left, bottom - top));
return bf;
}
public static CPoint getCenterPoint(BufferedImage img) {
CPoint cp = new CPoint();
cp.row = img.getHeight() / 2;
cp.column = img.getWidth() / 2;
return cp;
}
public static BufferedImage changeQuantizationLevel(BufferedImage image, int n) {
double[][] d = imageToPixelsDouble(image);
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
}
}
return image;
}
public static BufferedImage equalizeHistogram(BufferedImage bi) {
int width = bi.getWidth();
int height = bi.getHeight();
int anzpixel = width * height;
int[] histogram = new int[256];
int[] iarray = new int[1];
int i = 0;
//read pixel intensities into histogram
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int valueBefore = bi.getRaster().getPixel(x, y, iarray)[0];
histogram[valueBefore]++;
}
}
int sum = 0;
// build a Lookup table LUT containing scale factor
float[] lut = new float[anzpixel];
for (i = 0; i < 256; ++i) {
sum += histogram[i];
lut[i] = sum * 255 / anzpixel;
}
// transform image using sum histogram as a Lookup table
for (int x = 1; x < width; x++) {
for (int y = 1; y < height; y++) {
int valueBefore = bi.getRaster().getPixel(x, y, iarray)[0];
int valueAfter = (int) lut[valueBefore];
iarray[0] = valueAfter;
bi.getRaster().setPixel(x, y, iarray);
}
}
return bi;
}
public static double[] getHuMoments(BufferedImage img) {
double[] moments = new double[7];
Mat imagenOriginal;
imagenOriginal = new Mat();
Mat binario;
binario = new Mat();
Mat Canny;
Canny = new Mat();
imagenOriginal = ImageProcess.ocv_img2Mat(img);
Mat gris = new Mat(imagenOriginal.width(), imagenOriginal.height(), imagenOriginal.type());
Imgproc.cvtColor(imagenOriginal, gris, Imgproc.COLOR_RGB2GRAY);
org.opencv.core.Size s = new Size(3, 3);
Imgproc.GaussianBlur(gris, gris, s, 2);
Imgproc.threshold(gris, binario, 100, 255, Imgproc.THRESH_BINARY);
Imgproc.Canny(gris, Canny, 50, 50 * 3);
java.util.List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarcy = new Mat();
Imgproc.findContours(Canny, contours, hierarcy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
Imgproc.drawContours(Canny, contours, -1, new Scalar(Math.random() * 255, Math.random() * 255, Math.random() * 255));
Moments p = new Moments();
java.util.List<Moments> nu = new ArrayList<Moments>(contours.size());
for (int i = 0; i < contours.size(); i++) {
nu.add(i, Imgproc.moments(contours.get(i), false));
p = nu.get(i);
}
double n20 = p.get_nu20(),
n02 = p.get_nu02(),
n30 = p.get_nu30(),
n12 = p.get_nu12(),
n21 = p.get_nu21(),
n03 = p.get_nu03(),
n11 = p.get_nu11();
//First moment
moments[0] = n20 + n02;
//Second moment
moments[1] = Math.pow((n20 - 02), 2) + Math.pow(2 * n11, 2);
//Third moment
moments[2] = Math.pow(n30 - (3 * (n12)), 2)
+ Math.pow((3 * n21 - n03), 2);
//Fourth moment
moments[3] = Math.pow((n30 + n12), 2) + Math.pow((n12 + n03), 2);
//Fifth moment
moments[4] = (n30 - 3 * n12) * (n30 + n12)
* (Math.pow((n30 + n12), 2) - 3 * Math.pow((n21 + n03), 2))
+ (3 * n21 - n03) * (n21 + n03)
* (3 * Math.pow((n30 + n12), 2) - Math.pow((n21 + n03), 2));
//Sixth moment
moments[5] = (n20 - n02)
* (Math.pow((n30 + n12), 2) - Math.pow((n21 + n03), 2))
+ 4 * n11 * (n30 + n12) * (n21 + n03);
//Seventh moment
moments[6] = (3 * n21 - n03) * (n30 + n12)
* (Math.pow((n30 + n12), 2) - 3 * Math.pow((n21 + n03), 2))
+ (n30 - 3 * n12) * (n21 + n03)
* (3 * Math.pow((n30 + n12), 2) - Math.pow((n21 + n03), 2));
// //Eighth moment
// moments[7] = n11 * (Math.pow((n30 + n12), 2) - Math.pow((n03 + n21), 2))
// - (n20 - n02) * (n30 + n12) * (n03 + n21);
return moments;
}
public static int[][] rgb2lab(int[][] img) {
int r = img.length;
int c = img[0].length;
int[][] ret = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
int val = img[i][j];
Color col = new Color(val, true);
int red = col.getRed();
int green = col.getGreen();
int blue = col.getBlue();
ColorSpaceLAB lab = ColorSpaceLAB.fromRGB(red, green, blue, 255);
}
}
return ret;
}
public static BufferedImage convertToBufferedImageTypes(BufferedImage img, int TYPE) {
BufferedImage convertedImg = new BufferedImage(img.getWidth(), img.getHeight(), TYPE);
convertedImg.getGraphics().drawImage(img, 0, 0, null);
return convertedImg;
}
}
|
UTF-8
|
Java
| 149,295 |
java
|
ImageProcess.java
|
Java
|
[
{
"context": "cv.objdetect.CascadeClassifier;\n\n/**\n *\n * @author venap3\n */\npublic final class ImageProcess {\n static{",
"end": 2686,
"score": 0.9996153712272644,
"start": 2680,
"tag": "USERNAME",
"value": "venap3"
},
{
"context": " return mean;\n }\n\n /**\n * 16.04.2014 Musa Ataş Bir imgenin çerisinde küçük bir imgeyi correlatio",
"end": 65608,
"score": 0.9998853802680969,
"start": 65599,
"tag": "NAME",
"value": "Musa Ataş"
}
] | null |
[] |
/**
* TODO: ImageProcess ve diğer core classlardaki tüm işlemler parametre olarak
* double[][] almalı.
*
* ****************************************************************************
* OpenCV komutlarını çağıran harici uygulamalarda
* System.loadLibrary(Core.NATIVE_LIBRARY_NAME); eklenmeli ve 64 bit jar add jar
* ile eklendikten sonra dll dosyası da kök dizinde bulunmalı
* ****************************************************************************
*/
package cezeri.image_processing;
import cezeri.factory.FactoryNormalization;
import cezeri.factory.FactoryStatistic;
import cezeri.factory.FactorySimilarityDistance;
import cezeri.factory.FactoryUtils;
import cezeri.types.TRoi;
import cezeri.types.TGrayPixel;
import cezeri.types.TWord;
import cezeri.machine_learning.extraction.FeatureExtractionLBP;
import cezeri.matrix.CMatrix;
import cezeri.matrix.CPoint;
import cezeri.matrix.CRectangle;
import cezeri.factory.FactoryMatrix;
import cezeri.utils.*;
import com.jhlabs.composite.ColorDodgeComposite;
import com.jhlabs.image.AverageFilter;
import com.jhlabs.image.GaussianFilter;
import com.jhlabs.image.GrayscaleFilter;
import com.jhlabs.image.InvertFilter;
import com.jhlabs.image.MotionBlurFilter;
import com.jhlabs.image.MotionBlurOp;
import com.jhlabs.image.PointFilter;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOInvalidTreeException;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.GrayFilter;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.Moments;
import org.opencv.objdetect.CascadeClassifier;
/**
*
* @author venap3
*/
public final class ImageProcess {
static{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
/**
* Conversion from RGB space to LAB space (CIE)
*
* @param R
* @param G
* @param B
* @return
*/
public static double[] rgbToLab(int R, int G, int B) {
double r, g, b, X, Y, Z, xr, yr, zr;
// D65/2°
double Xr = 95.047;
double Yr = 100.0;
double Zr = 108.883;
// --------- RGB to XYZ ---------//
r = R / 255.0;
g = G / 255.0;
b = B / 255.0;
if (r > 0.04045) {
r = Math.pow((r + 0.055) / 1.055, 2.4);
} else {
r = r / 12.92;
}
if (g > 0.04045) {
g = Math.pow((g + 0.055) / 1.055, 2.4);
} else {
g = g / 12.92;
}
if (b > 0.04045) {
b = Math.pow((b + 0.055) / 1.055, 2.4);
} else {
b = b / 12.92;
}
r *= 100;
g *= 100;
b *= 100;
X = 0.4124 * r + 0.3576 * g + 0.1805 * b;
Y = 0.2126 * r + 0.7152 * g + 0.0722 * b;
Z = 0.0193 * r + 0.1192 * g + 0.9505 * b;
// --------- XYZ to Lab --------- //
xr = X / Xr;
yr = Y / Yr;
zr = Z / Zr;
if (xr > 0.008856) {
xr = (float) Math.pow(xr, 1 / 3.);
} else {
xr = (float) ((7.787 * xr) + 16 / 116.0);
}
if (yr > 0.008856) {
yr = (float) Math.pow(yr, 1 / 3.);
} else {
yr = (float) ((7.787 * yr) + 16 / 116.0);
}
if (zr > 0.008856) {
zr = (float) Math.pow(zr, 1 / 3.);
} else {
zr = (float) ((7.787 * zr) + 16 / 116.0);
}
double[] lab = new double[3];
lab[0] = (116 * yr) - 16;
lab[1] = 500 * (xr - yr);
lab[2] = 200 * (yr - zr);
return lab;
}
/**
* Canny Edge Detector
*
* @param d : inputImage
* @return BufferedImage
*/
public static double[][] edgeDetectionCanny(double[][] d) {
float lowThreshold = 0.3f;
float highTreshold = 1.0f;
float gaussianKernelRadious = 2.5f;
int guassianKernelWidth = 3;
boolean isContrastNormalized = false;
BufferedImage currBufferedImage = ImageProcess.pixelsToImageGray(d);
currBufferedImage = edgeDetectionCanny(currBufferedImage, lowThreshold, highTreshold, gaussianKernelRadious, guassianKernelWidth, isContrastNormalized);
currBufferedImage = toGrayLevel(currBufferedImage);
return imageToPixelsDouble(currBufferedImage);
}
public static BufferedImage edgeDetectionCannyAsImage(double[][] d) {
float lowThreshold = 0.3f;
float highTreshold = 1.0f;
float gaussianKernelRadious = 2.5f;
int guassianKernelWidth = 3;
boolean isContrastNormalized = false;
BufferedImage currBufferedImage = ImageProcess.pixelsToImageGray(d);
currBufferedImage = edgeDetectionCanny(currBufferedImage, lowThreshold, highTreshold, gaussianKernelRadious, guassianKernelWidth, isContrastNormalized);
currBufferedImage = toGrayLevel(currBufferedImage);
return currBufferedImage;
}
public static double[][] edgeDetectionCanny(BufferedImage img) {
float lowThreshold = 0.3f;
float highTreshold = 1.0f;
float gaussianKernelRadious = 2.5f;
int guassianKernelWidth = 3;
boolean isContrastNormalized = false;
BufferedImage currBufferedImage = edgeDetectionCanny(img, lowThreshold, highTreshold, gaussianKernelRadious, guassianKernelWidth, isContrastNormalized);
return imageToPixelsDouble(currBufferedImage);
}
public static Mat ocv_edgeDetectionCanny(Mat imageGray) {
Mat imageCanny = new Mat();
Imgproc.Canny(imageGray, imageCanny, 10, 100, 3, true);
return imageCanny;
}
public static BufferedImage ocv_edgeDetectionCanny(BufferedImage img) {
Mat imageGray = ocv_img2Mat(img);
Mat imageCanny = new Mat();
Imgproc.Canny(imageGray, imageCanny, 10, 100, 3, true);
return ocv_mat2Img(imageCanny);
}
public static Mat ocv_blendImagesMat(Mat img1, Mat img2) {
Mat dst = new Mat();
Core.addWeighted(img1, 0.5, img2, 0.5, 0.0, dst);
return dst;
}
public static Mat ocv_blendImagesMat(BufferedImage img1, BufferedImage img2) {
Mat src1 = ImageProcess.ocv_img2Mat(img1);
Mat src2 = ImageProcess.ocv_img2Mat(img2);
Mat dst = new Mat();
Core.addWeighted(src1, 0.5, src2, 0.5, 0.0, dst);
return dst;
}
public static BufferedImage ocv_blendImagesBuffered(BufferedImage img1, BufferedImage img2) {
Mat src1 = ImageProcess.ocv_img2Mat(img1);
Mat src2 = ImageProcess.ocv_img2Mat(img2);
Mat dst = new Mat();
Core.addWeighted(src1, 0.5, src2, 0.5, 0.0, dst);
BufferedImage bf_3 = ImageProcess.ocv_mat2Img(dst);
return bf_3;
}
public static BufferedImage ocv_edgeDetectionCanny(double[][] d) {
BufferedImage img = pixelsToImageGray(d);
Mat imageGray = ocv_img2Mat(img);
Mat imageCanny = new Mat();
// Imgproc.Canny(imageGray, imageCanny, 10, 100, 3, true);
Imgproc.Canny(imageGray, imageCanny, 10, 150, 3, true);
return ocv_mat2Img(imageCanny);
}
public static double[][] ocv_edgeDetectionCanny2D(BufferedImage img) {
Mat imageGray = ocv_img2Mat(img);
Mat imageCanny = new Mat();
// Imgproc.Canny(imageGray, imageCanny, 50, 200, 3, true);
// Imgproc.Canny(imageGray, imageCanny, 20, 150, 3, true);
// Imgproc.Canny(imageGray, imageCanny, 20, 100, 3, true);
Imgproc.Canny(imageGray, imageCanny, 50, 100, 3, true);
double[][] ret = imageToPixelsDouble(ocv_mat2Img(imageCanny));
return ret;
}
/**
* Musa Edge Detector
*
* @param d: inputImage
* @param thr: threshold double value
* @return
*/
public static double[][] edgeDetectionMusa(double[][] d, int thr) {
// double thr=30;
double[][] a1 = FactoryUtils.shiftOnRow(d, 1);
double[][] a2 = FactoryUtils.shiftOnRow(d, -1);
double[][] a3 = FactoryUtils.shiftOnColumn(d, 1);
double[][] a4 = FactoryUtils.shiftOnColumn(d, -1);
double[][] ret1 = FactoryUtils.subtractWithThreshold(d, a1, thr);
double[][] ret2 = FactoryUtils.subtractWithThreshold(d, a2, thr);
double[][] ret3 = FactoryUtils.subtractWithThreshold(d, a3, thr);
double[][] ret4 = FactoryUtils.subtractWithThreshold(d, a4, thr);
double[][] retx = FactoryUtils.add(ret1, ret2);
double[][] rety = FactoryUtils.add(ret3, ret4);
double[][] ret = FactoryUtils.add(retx, rety);
// double[][] ret=FactoryUtils.add(ret1,ret3);
return ret;
}
/**
* Canny Edge Detector
*
* @param d : inputImage
* @param lowThreshold: default value is 0.3f
* @param highTreshold:default value is 1.0f
* @param gaussianKernelRadious:default value is 2.5f
* @param guassianKernelWidth:default value is 3
* @param isContrastNormalized : default false
* @return BufferedImage
*/
public static int[][] edgeDetectionCanny(
double[][] d,
float lowThreshold,
float highTreshold,
float gaussianKernelRadious,
int guassianKernelWidth,
boolean isContrastNormalized) {
BufferedImage currBufferedImage = ImageProcess.pixelsToImageGray(d);
currBufferedImage = edgeDetectionCanny(currBufferedImage, lowThreshold, highTreshold, gaussianKernelRadious, guassianKernelWidth, isContrastNormalized);
return imageToPixelsInt(currBufferedImage);
}
/**
* Canny Edge Detector
*
* @param img : inputImage
* @param lowThreshold: default value is 0.3f
* @param highTreshold:default value is 1.0f
* @param gaussianKernelRadious:default value is 2.5f
* @param guassianKernelWidth:default value is 3
* @param isContrastNormalized : default false
* @return BufferedImage
*/
public static BufferedImage edgeDetectionCanny(
BufferedImage img,
float lowThreshold,
float highTreshold,
float gaussianKernelRadious,
int guassianKernelWidth,
boolean isContrastNormalized) {
BufferedImage currBufferedImage = img;
CannyEdgeDetector detector = new CannyEdgeDetector();
detector.setLowThreshold(lowThreshold);
detector.setHighThreshold(highTreshold);
detector.setGaussianKernelRadius(gaussianKernelRadious);
detector.setGaussianKernelWidth(guassianKernelWidth);
detector.setContrastNormalized(isContrastNormalized);
detector.setSourceImage(currBufferedImage);
detector.process();
currBufferedImage = detector.getEdgesImage();
return ImageProcess.rgb2gray(currBufferedImage);
}
public static BufferedImage isolateChannel(BufferedImage image, String channel) {
BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
int iAlpha = 0;
int iRed = 0;
int iGreen = 0;
int iBlue = 0;
int newPixel = 0;
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
int rgb = image.getRGB(i, j);
newPixel = 0;
iAlpha = rgb >> 24 & 0xff;
iRed = rgb >> 16 & 0xff;
iGreen = rgb >> 8 & 0xff;
iBlue = rgb & 0xff;
if (channel.equals("red")) {
// Tevafuk için eklenmişti
// if (iRed > 110 && iRed < 220 && iGreen > 20 && iGreen < 110 && iBlue > 20 && iBlue < 110) {
// newPixel = 0 | 170 << 16;
// } else {
// newPixel = 0;
// }
newPixel = newPixel | iRed << 16;
}
if (channel.equals("green")) {
newPixel = newPixel | iGreen << 8;
}
if (channel.equals("blue")) {
newPixel = newPixel | iBlue;
}
result.setRGB(i, j, newPixel);
}
}
return result;
}
public static BufferedImage showRedPixels(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
BufferedImage redImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Color color;
int t = 140;
//int[] pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
//yaz(pixels);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//int pp = img.getRGB(x, y);
// printPixelARGB(pp);
Color cl = new Color(img.getRGB(x, y));
int r = cl.getRed();
int g = cl.getGreen();
int b = cl.getBlue();
// float[] hsv = new float[3];
// hsv = cl.RGBtoHSB(r, g, b, hsv);
// int q = 15;
// if (hsv[0] * 360 > 345 || hsv[0] * 360 < 15) {
// //yaz("red:" + (hsv[0] * 360));
// }else{
// yaz("bulmadi");
// }
//
yaz("rgb:" + r + "," + g + "," + b);
// if (red == green && red == blue) {
// color = new Color(0, 0, 0);
// } else if (red > t && green < t && blue < t) {
// color = new Color(255, 0, 0);
// } else {
// color = new Color(0, 0, 0);
// }
//
// redImage.setRGB(x, y, color.getRGB());
}
}
return redImage;
}
public static void printPixelARGB(int pixel) {
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
System.out.println("argb: " + alpha + ", " + red + ", " + green + ", " + blue);
}
public static BufferedImage changeToRedMonochrome(BufferedImage grayImage) {
int width = grayImage.getWidth();
int height = grayImage.getHeight();
BufferedImage redImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Color grayColor = new Color(grayImage.getRGB(x, y));
int gray = grayColor.getRed();
int red = (gray > 127) ? 255 : gray / 2;
int blue = (gray > 127) ? gray / 2 : 0;
int green = (gray > 127) ? gray / 2 : 0;
Color redColor = new Color(red, blue, green);
redImage.setRGB(x, y, redColor.getRGB());
}
}
return redImage;
}
public static BufferedImage DCT(BufferedImage bimg) {
final int N = 8; // Block size
int nrows, ncols, m, n, x, y, u, v, img[][], in[][];
double dct[][], sum, au, av;
double n1 = Math.sqrt(1.0 / N), n2 = Math.sqrt(2.0 / N);
img = imageToPixelsInt(bimg);
nrows = img.length;
ncols = img[0].length;
if (nrows % N != 0 || ncols % N != 0) {
System.out.println("Nrows and ncols should be 8's power");
return bimg;
// System.exit(0);
}
in = new int[nrows][ncols];
dct = new double[nrows][ncols];
// For each NxN block[m,n]
for (m = 0; m < nrows; m += N) {
for (n = 0; n < ncols; n += N) {
// For each pixel[u,v] in block[m,n]
for (u = m; u < m + N; u++) {
au = (u == m) ? n1 : n2;
for (v = n; v < n + N; v++) {
av = (v == n) ? n1 : n2;
// Sum up all pixels in the block
for (x = m, sum = 0; x < m + N; x++) {
for (y = n; y < n + N; y++) {
in[x][y] = img[x][y] - 128; // Subtract by 128
sum += in[x][y] * Math.cos((2 * (x - m) + 1) * (u - m) * Math.PI / (2 * N))
* Math.cos((2 * (y - n) + 1) * (v - n) * Math.PI / (2 * N));
}
}
dct[u][v] = au * av * sum;
} // for v
} // for u
} // for n
} // for m
return ImageProcess.pixelsToImageGray(FactoryUtils.toIntArray2D(dct));
}
public static BufferedImage cropImage(BufferedImage src, CRectangle rect) {
if (src.getType() == BufferedImage.TYPE_BYTE_GRAY) {
return src.getSubimage(rect.column, rect.row, rect.width, rect.height);
} else {
return toBGR(src.getSubimage(rect.column, rect.row, rect.width, rect.height));
}
// BufferedImage dest = clone(src);
// try {
// src = src.getSubimage(rect.column, rect.row, rect.width, rect.height);
// } catch (Exception ex) {
// Logger.getLogger(ImageProcess.class.getName()).log(Level.SEVERE, null, ex);
// }
// return dest;
}
public static BufferedImage convertImageToPencilSketch(BufferedImage src) {
PointFilter grayScaleFilter = new GrayscaleFilter();
BufferedImage grayScale = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
grayScaleFilter.filter(src, grayScale);
//inverted gray scale
BufferedImage inverted = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
PointFilter invertFilter = new InvertFilter();
invertFilter.filter(grayScale, inverted);
//gaussian blurr
GaussianFilter gaussianFilter = new GaussianFilter(20);
BufferedImage gaussianFiltered = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
gaussianFilter.filter(inverted, gaussianFiltered);
//color dodge
ColorDodgeComposite cdc = new ColorDodgeComposite(1.0f);
CompositeContext cc = cdc.createContext(inverted.getColorModel(), grayScale.getColorModel(), null);
Raster invertedR = gaussianFiltered.getRaster();
Raster grayScaleR = grayScale.getRaster();
BufferedImage composite = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
WritableRaster colorDodgedR = composite.getRaster();
cc.compose(invertedR, grayScaleR, colorDodgedR);
//==================================
return composite;
}
public static boolean lookNeighbourPixels(int[][] img, Point p, int r) {
ArrayList<Point> lst = getWindowEdgePixelPositions(img, p, r);
for (Point pt : lst) {
if (img[pt.x][pt.y] != 127 && img[pt.x][pt.y] != 0) {
p.x = pt.x;
p.y = pt.y;
//yaz("konumlandı: p.x:"+p.x+" p.y:"+p.y);
return true;
}
}
return false;
}
public static ArrayList<Point> getWindowEdgePixelPositions(int[][] img, Point p, int r) {
Point m = new Point();
m.x = p.x - r;
m.y = p.y - r;
Point pt = null;
ArrayList<Point> lst = new ArrayList<Point>();
if (m.x <= 0 || m.y <= 0 || m.x + 2 * r >= img.length || m.y + 2 * r >= img[0].length) {
return lst;
}
for (int i = 0; i < 2 * r + 1; i++) {
for (int j = 0; j < 2 * r + 1; j++) {
pt = new Point(m.x + j, m.y + i);
lst.add(pt);
}
}
lst = FactoryUtils.shuffleList(lst);
return lst;
}
/**
* return Alpha, Red, Green and Blue values of original RGB image
*
* @param image
* @return
*/
public static int[][][] imageToPixelsColorInt(BufferedImage image) {
int numRows = image.getHeight();
int numCols = image.getWidth();
// Now we make our array.
int[][][] pixels = new int[numRows][numCols][4];
// int[] outputChannels=new int[4];
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
// image.getRaster().getPixel(col,row,outputChannels);
// pixels[row][col]=outputChannels;
Color c = new Color(image.getRGB(col, row));
pixels[row][col][0] = c.getAlpha(); // Alpha
pixels[row][col][1] = c.getRed(); // Red
pixels[row][col][2] = c.getGreen(); // Green
pixels[row][col][3] = c.getBlue(); // Blue
}
}
return pixels;
}
/**
* return Alpha, Red, Green and Blue values of original RGB image
*
* @param image
* @return
*/
public static double[][][] imageToPixelsColorDouble(BufferedImage image) {
int numRows = image.getHeight();
int numCols = image.getWidth();
// Now we make our array.
double[][][] pixels = new double[numRows][numCols][4];
// double[] outputChannels=new double[4];
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
// image.getRaster().getPixel(col,row,outputChannels);
// pixels[row][col]=outputChannels;
Color c = new Color(image.getRGB(col, row));
pixels[row][col][0] = c.getAlpha(); // Alpha
pixels[row][col][1] = c.getRed(); // Red
pixels[row][col][2] = c.getGreen(); // Green
pixels[row][col][3] = c.getBlue(); // Blue
}
}
return pixels;
}
/**
* return Alpha, Red, Green and Blue values of original RGB image
*
* @param image
* @return
*/
public static int[][][] imageToPixelsColorIntV2(BufferedImage image) {
// Java's peculiar way of extracting pixels is to give them
// back as a one-dimensional array from which we will construct
// our version.
int numRows = image.getHeight();
int numCols = image.getWidth();
int[] oneDPixels = new int[numRows * numCols];
// This will place the pixels in oneDPixels[]. Each int in
// oneDPixels has 4 bytes containing the 4 pieces we need.
PixelGrabber grabber = new PixelGrabber(image, 0, 0, numCols, numRows,
oneDPixels, 0, numCols);
try {
grabber.grabPixels(0);
} catch (InterruptedException e) {
System.out.println(e);
}
// Now we make our array.
int[][][] pixels = new int[numRows][numCols][4];
for (int row = 0; row < numRows; row++) {
// First extract a row of int's from the right place.
int[] aRow = new int[numCols];
for (int col = 0; col < numCols; col++) {
int element = row * numCols + col;
aRow[col] = oneDPixels[element];
}
// In Java, the most significant byte is the alpha value,
// followed by R, then G, then B. Thus, to extract the alpha
// value, we shift by 24 and make sure we extract only that byte.
for (int col = 0; col < numCols; col++) {
pixels[row][col][0] = (aRow[col] >> 24) & 0xFF; // Alpha
pixels[row][col][1] = (aRow[col] >> 16) & 0xFF; // Red
pixels[row][col][2] = (aRow[col] >> 8) & 0xFF; // Green
pixels[row][col][3] = (aRow[col]) & 0xFF; // Blue
}
}
return pixels;
}
/**
* return Alpha, Red, Green and Blue values of original RGB image
*
* @param image
* @return
*/
public static double[][][] imageToPixelsColorDoubleFaster(BufferedImage image) {
// Java's peculiar way of extracting pixels is to give them
// back as a one-dimensional array from which we will construct
// our version.
int numRows = image.getHeight();
int numCols = image.getWidth();
int[] oneDPixels = new int[numRows * numCols];
// This will place the pixels in oneDPixels[]. Each int in
// oneDPixels has 4 bytes containing the 4 pieces we need.
PixelGrabber grabber = new PixelGrabber(image, 0, 0, numCols, numRows,
oneDPixels, 0, numCols);
try {
grabber.grabPixels(0);
} catch (InterruptedException e) {
System.out.println(e);
}
// Now we make our array.
double[][][] pixels = new double[4][numRows][numCols];
for (int row = 0; row < numRows; row++) {
// First extract a row of int's from the right place.
int[] aRow = new int[numCols];
for (int col = 0; col < numCols; col++) {
int element = row * numCols + col;
aRow[col] = oneDPixels[element];
}
// In Java, the most significant byte is the alpha value,
// followed by R, then G, then B. Thus, to extract the alpha
// value, we shift by 24 and make sure we extract only that byte.
for (int col = 0; col < numCols; col++) {
pixels[0][row][col] = (aRow[col] >> 24) & 0xFF; // Alpha
pixels[1][row][col] = (aRow[col] >> 16) & 0xFF; // Red
pixels[2][row][col] = (aRow[col] >> 8) & 0xFF; // Green
pixels[3][row][col] = (aRow[col]) & 0xFF; // Blue
}
}
return pixels;
}
public static BufferedImage pixelsToImageColor(int[][][] pixels) {
int numRows = pixels.length;
int numCols = pixels[0].length;
int[] oneDPixels = new int[numRows * numCols];
int index = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
oneDPixels[index] = ((pixels[row][col][0] << 24) & 0xFF000000)
| ((pixels[row][col][1] << 16) & 0x00FF0000)
| ((pixels[row][col][2] << 8) & 0x0000FF00)
| ((pixels[row][col][3]) & 0x000000FF);
index++;
}
}
// The MemoryImageSource class is an ImageProducer that can
// build an image out of 1D pixels. Then, rather confusingly,
// the createImage() method, inherited from Component, is used
// to make the actual Image instance. This is simply Java's
// confusing, roundabout way. An alternative is to use the
// Raster models provided in BufferedImage.
MemoryImageSource imSource = new MemoryImageSource(numCols, numRows, oneDPixels, 0, numCols);
Image imG = Toolkit.getDefaultToolkit().createImage(imSource);
BufferedImage I = imageToBufferedImage(imG);
return I;
}
public static BufferedImage pixelsToImageColor(double[][][] pixels) {
int numRows = pixels.length;
int numCols = pixels[0].length;
int[] oneDPixels = new int[numRows * numCols];
int index = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
oneDPixels[index] = (((int) pixels[row][col][0] << 24) & 0xFF000000)
| (((int) pixels[row][col][1] << 16) & 0x00FF0000)
| (((int) pixels[row][col][2] << 8) & 0x0000FF00)
| (((int) pixels[row][col][3]) & 0x000000FF);
index++;
}
}
// The MemoryImageSource class is an ImageProducer that can
// build an image out of 1D pixels. Then, rather confusingly,
// the createImage() method, inherited from Component, is used
// to make the actual Image instance. This is simply Java's
// confusing, roundabout way. An alternative is to use the
// Raster models provided in BufferedImage.
MemoryImageSource imSource = new MemoryImageSource(numCols, numRows, oneDPixels, 0, numCols);
Image imG = Toolkit.getDefaultToolkit().createImage(imSource);
BufferedImage I = imageToBufferedImage(imG);
return I;
}
public static BufferedImage pixelsToImageColor(double[][] pixels) {
int numRows = pixels.length;
int numCols = pixels[0].length;
int[] oneDPixels = new int[numRows * numCols];
int index = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
oneDPixels[index] = (int) pixels[row][col];
index++;
}
}
// The MemoryImageSource class is an ImageProducer that can
// build an image out of 1D pixels. Then, rather confusingly,
// the createImage() method, inherited from Component, is used
// to make the actual Image instance. This is simply Java's
// confusing, roundabout way. An alternative is to use the
// Raster models provided in BufferedImage.
MemoryImageSource imSource = new MemoryImageSource(numCols, numRows, oneDPixels, 0, numCols);
Image imG = Toolkit.getDefaultToolkit().createImage(imSource);
BufferedImage I = imageToBufferedImage(imG);
return I;
}
public static BufferedImage pixelsToImageColorArgbFormat(double[][][] pixels) {
int numRows = pixels[0].length;
int numCols = pixels[0][0].length;
int[] oneDPixels = new int[numRows * numCols];
int index = 0;
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
oneDPixels[index] = (((int) pixels[0][row][col] << 24) & 0xFF000000)
| (((int) pixels[1][row][col] << 16) & 0x00FF0000)
| (((int) pixels[2][row][col] << 8) & 0x0000FF00)
| (((int) pixels[3][row][col]) & 0x000000FF);
index++;
}
}
// The MemoryImageSource class is an ImageProducer that can
// build an image out of 1D pixels. Then, rather confusingly,
// the createImage() method, inherited from Component, is used
// to make the actual Image instance. This is simply Java's
// confusing, roundabout way. An alternative is to use the
// Raster models provided in BufferedImage.
MemoryImageSource imSource = new MemoryImageSource(numCols, numRows, oneDPixels, 0, numCols);
Image imG = Toolkit.getDefaultToolkit().createImage(imSource);
BufferedImage I = imageToBufferedImage(imG);
return I;
}
public static byte[] getBytes(BufferedImage img) {
return ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
}
public static int[][] convertTo2DWithoutUsingGetRGB(BufferedImage image) {
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
public static double[][] convertBufferedImageTo2D(BufferedImage image) {
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
double[][] result = new double[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
public static BufferedImage readImage(String fileName) {
try {
return ImageIO.read(new File(fileName));
} catch (IOException ex) {
Logger.getLogger(ImageProcess.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static double[][] bufferedImageToArray2D(BufferedImage img) {
double[][] ret = null;
if (img.getColorModel().getNumComponents() == 4) {
img = convertToBufferedImageTypes(img, 5);
ret = convertBufferedImageTo2D(img);
// WritableRaster raster = img.getRaster();
// DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
// byte[] d = data.getData();
// double[] r = FactoryUtils.byte2Double(d);
// double[] t = new double[r.length / 4];
// int size = t.length;
// for (int i = 0; i < size; i++) {
// t[i] = (int) ((r[4 * i + 1] + r[4 * i + 2] + r[4 * i + 3]) / 3);
// }
// ret = FactoryMatrix.reshapeBasedOnRows(t, img.getHeight(), img.getWidth());
// return ret;
} else if (img.getColorModel().getNumComponents() == 1 && !img.getColorModel().hasAlpha()) {
// int w=img.getWidth();
// int h=img.getHeight();
// byte[] imageBytes=new byte[w*h];
// img.getRaster().setDataElements(0, 0, w, h, imageBytes);
WritableRaster raster = img.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] d = data.getData();
double[] r = FactoryUtils.byte2Double(d);
if (r.length != img.getWidth() * img.getHeight()) {
System.out.println("farklı");
}
ret = FactoryMatrix.reshapeBasedOnRows(r, img.getHeight(), img.getWidth());
return ret;
} else if (img.getColorModel().getNumComponents() == 3 && !img.getColorModel().hasAlpha()) {
img = convertToBufferedImageTypes(img, 5);
ret = convertBufferedImageTo2D(img);
// WritableRaster raster = img.getRaster();
// DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
// int[] rgb = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
//
// byte[] d = data.getData();
// double[] r = FactoryUtils.byte2Double(d);
// double[] t = new double[r.length / 3];
// int size = t.length;
// for (int i = 0; i < size; i++) {
// t[i] = (int) ((r[3 * i] + r[3 * i + 1] + r[3 * i + 2]) / 3);
// }
// ret = FactoryMatrix.reshapeBasedOnRows(t, img.getHeight(), img.getWidth());
return ret;
}
return ret;
}
public static double[][][] bufferedImageToArray3D(BufferedImage img) {
double[][][] ret = null;
if (img.getColorModel().getNumComponents() == 1 && !img.getColorModel().hasAlpha()) {
throw new ArithmeticException("BufferedImage has not rgba channels");
} else if (img.getColorModel().getNumComponents() == 3 && !img.getColorModel().hasAlpha()) {
WritableRaster raster = img.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] d = data.getData();
double[] q = FactoryUtils.byte2Double(d);
double[] r = new double[q.length / 3];
double[] g = new double[q.length / 3];
double[] b = new double[q.length / 3];
int size = r.length;
for (int i = 0; i < size; i++) {
r[i] = q[3 * i];
g[i] = q[3 * i + 1];
b[i] = q[3 * i + 2];
}
double[][] rr = FactoryMatrix.reshape(r, img.getHeight(), img.getWidth());
double[][] gg = FactoryMatrix.reshape(g, img.getHeight(), img.getWidth());
double[][] bb = FactoryMatrix.reshape(b, img.getHeight(), img.getWidth());
ret = new double[3][][];
ret[0] = rr;
ret[1] = gg;
ret[2] = bb;
return ret;
}
return ret;
}
public static int[][] imageToPixelsInt(BufferedImage img) {
double[][] d = imageToPixelsDouble(img);
int[][] original = FactoryUtils.toIntArray2D(d);
return original;
}
public static double[][] imageToPixelsDouble(BufferedImage img) {
// if (img == null) {
// return null;
// }
// double[][] original = new double[img.getHeight()][img.getWidth()]; // where we'll put the image
// if ((img.getType() == BufferedImage.TYPE_CUSTOM)
// || (img.getType() == BufferedImage.TYPE_INT_RGB)
// || (img.getType() == BufferedImage.TYPE_INT_ARGB)
// || (img.getType() == BufferedImage.TYPE_3BYTE_BGR)
// || (img.getType() == BufferedImage.TYPE_4BYTE_ABGR)) {
// for (int i = 0; i < img.getHeight(); i++) {
// for (int j = 0; j < img.getWidth(); j++) {
// original[i][j] = img.getRGB(j, i);
// }
// }
// } else {
// Raster image_raster = img.getData();
// //get pixel by pixel
// int[] pixel = new int[1];
// int[] buffer = new int[1];
//
// // declaring the size of arrays
// original = new double[img.getHeight()][img.getWidth()];
//
// //get the image in the array
// for (int i = 0; i < img.getHeight(); i++) {
// for (int j = 0; j < img.getWidth(); j++) {
// pixel = image_raster.getPixel(j, i, buffer);
// original[i][j] = pixel[0];
// }
// }
// }
// return original;
return bufferedImageToArray2D(img);
}
public static int[][] imageToPixels255_CIZ(BufferedImage img) {
return imageToPixelsInt(img);
// MediaTracker mt = new MediaTracker(null);
// mt.addImage(img, 0);
// try {
// mt.waitForID(0);
// } catch (Exception e) {
// // TODO: handle exception
// }
//
// int w = img.getWidth();
// int h = img.getHeight();
// //System.out.println("w:"+w+" h:"+h);
// int pixels[] = new int[w * h];
// int fpixels[] = new int[w * h];
// int dpixel[][] = new int[w][h];
// PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
// try {
// pg.grabPixels();
// } catch (Exception e) {
// // TODO: handle exception
// }
// int red = (pixels[0] >> 16 & 0xff);
// int green = pixels[0] >> 8 & 0xff;
// int blue = pixels[0] & 0xff;
//
// if (red == green && red == blue) {
// for (int i = 0; i < pixels.length; i++) {
// fpixels[i] = pixels[i] & 0xff;
// }
// } else {
// for (int i = 0; i < pixels.length; i++) {
// int r = pixels[i] >> 16 & 0xff;
// int g = pixels[i] >> 8 & 0xff;
// int b = pixels[i] & 0xff;
// int y = (int) (0.33000000000000002D * (double) r + 0.56000000000000005D * (double) g + 0.11D * (double) b);
// fpixels[i] = y;
//// fpixels[i] = pixels[i];
// }
// }
// int k = 0;
// for (int i = 0; i < h; i++) {
// for (int j = 0; j < w; j++) {
// dpixel[j][i] = fpixels[k];
// k++;
// }
// }
//
// return dpixel;
}
public static int[] imageToPixelsTo1D(BufferedImage img) {
return FactoryUtils.toIntArray1D(imageToPixelsInt(img));
}
public static int[][] imageToPixelsROI(BufferedImage img, Rectangle roi) {
MediaTracker mt = new MediaTracker(null);
mt.addImage(img, 0);
try {
mt.waitForID(0);
} catch (Exception e) {
// TODO: handle exception
}
int w = img.getWidth();
int h = img.getHeight();
//System.out.println("w:"+w+" h:"+h);
int pixels[] = new int[w * h];
int fpixels[] = new int[w * h];
int dpixel[][] = new int[roi.width][roi.height];
PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
try {
pg.grabPixels();
} catch (Exception e) {
// TODO: handle exception
}
int cnt = 0;
int py = 0;
for (int i = roi.y * w + roi.x; i < (roi.y + roi.height) * w + roi.x; i++) {
if (cnt < roi.width) {
int r = pixels[i] >> 16 & 0xff;
int g = pixels[i] >> 8 & 0xff;
int b = pixels[i] >> 0 & 0xff;
int y = (int) (0.33000000000000002D * (double) r + 0.56000000000000005D * (double) g + 0.11D * (double) b);
dpixel[cnt][py] = y;
cnt++;
} else {
cnt = 0;
i = i + w - roi.width;
py++;
}
}
return dpixel;
}
public static BufferedImage imageToBufferedImage(Image im) {
BufferedImage bi = new BufferedImage(im.getWidth(null), im.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();
return bi;
}
public static BufferedImage pixelsToImageGray(int dizi[][]) {
int[] pixels = FactoryUtils.toIntArray1D(dizi);
int h = dizi.length;
int w = dizi[0].length;
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
WritableRaster raster = image.getRaster();
raster.setPixels(0, 0, w, h, pixels);
return image;
}
public static BufferedImage pixelsToImageGray(double dizi[][]) {
int[] pixels = FactoryUtils.toIntArray1DBasedOnRows(dizi);
int h = dizi.length;
int w = dizi[0].length;
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
WritableRaster raster = image.getRaster();
raster.setPixels(0, 0, w, h, pixels);
return image;
}
public static BufferedImage pixelsToBufferedImage255_CIZ(int dizi[][]) {
int w = dizi.length;
int h = dizi[0].length;
int ai[] = new int[w * h];
int aix[] = new int[w * h];
int k = 0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
ai[k] = dizi[j][i];
aix[k] = (0xff000000 | ai[k] << 16 | ai[k] << 8 | ai[k]);
k++;
}
}
Image imG = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, aix, 0, w));
BufferedImage myImage = imageToBufferedImage(imG);
return myImage;
}
// public static BufferedImage toGrayLevel(BufferedImage img) {
// return rgb2gray(img);
// }
public static BufferedImage rgb2hsv(BufferedImage img) {
int[][][] ret = convertHSV(img);
BufferedImage rimg = pixelsToImageColor(ret);
return rimg;
}
public static BufferedImage hsv2rgb(BufferedImage img) {
int[][][] d = imageToPixelsColorInt(img);
int nr = d.length;
int nc = d[0].length;
int ch = d[0][0].length;
int[][][] ret = new int[nr][nc][ch];
int red, green, blue;
float hue, saturation, brightness;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
hue = d[i][j][1] / 255.0f;
saturation = d[i][j][2] / 255.0f;
brightness = d[i][j][3] / 255.0f;
int rgb = Color.HSBtoRGB(hue, saturation, brightness);
red = (rgb >> 16) & 0xFF;
green = (rgb >> 8) & 0xFF;
blue = rgb & 0xFF;
ret[i][j][0] = 255;//alpha channel
ret[i][j][1] = red;
ret[i][j][2] = green;
ret[i][j][3] = blue;
}
}
BufferedImage rimg = pixelsToImageColor(ret);
return rimg;
}
public static BufferedImage toHSVColorSpace(BufferedImage img) {
return rgb2hsv(img);
}
public static BufferedImage getHueChannel(BufferedImage img) {
int[][][] ret = convertHSV(img);
int[][] d = new int[ret.length][ret[0].length];
for (int i = 0; i < ret.length; i++) {
for (int j = 0; j < ret[0].length; j++) {
d[i][j] = ret[i][j][1];
}
}
BufferedImage bf = ImageProcess.pixelsToImageGray(d);
return bf;
}
public static BufferedImage getSaturationChannel(BufferedImage img) {
int[][][] ret = convertHSV(img);
int[][] d = new int[ret.length][ret[0].length];
for (int i = 0; i < ret.length; i++) {
for (int j = 0; j < ret[0].length; j++) {
d[i][j] = ret[i][j][2];
}
}
BufferedImage bf = ImageProcess.pixelsToImageGray(d);
return bf;
}
public static BufferedImage getValueChannel(BufferedImage img) {
int[][][] ret = convertHSV(img);
int[][] d = new int[ret.length][ret[0].length];
for (int i = 0; i < ret.length; i++) {
for (int j = 0; j < ret[0].length; j++) {
d[i][j] = ret[i][j][3];
}
}
BufferedImage bf = ImageProcess.pixelsToImageGray(d);
return bf;
}
public static int[][][] convertHSV(BufferedImage img) {
int[][][] d = imageToPixelsColorInt(img);
int[][][] ret = new int[d.length][d[0].length][d[0][0].length];
int n = 255;
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
int[] val = FactoryMatrix.clone(d[i][j]);
float[] q = toHSV(val[1], val[2], val[3]);
val[1] = (int) (q[0] * n);
val[2] = (int) (q[1] * n);
val[3] = (int) (q[2] * n);
ret[i][j] = val;
}
}
return ret;
}
public static float[] toHSV(int red, int green, int blue) {
float[] hsv = new float[3];
hsv = Color.RGBtoHSB(red, green, blue, null);
return hsv;
}
public static float[] rgb2hsv(int red, int green, int blue) {
return toHSV(red, green, blue);
}
public static float[] toRGB(int hue, int sat, int val) {
float[] rgb = new float[3];
int n = Color.HSBtoRGB(hue, sat, val);
return rgb;
}
public static BufferedImage rgb2gray(BufferedImage img) {
return toGrayLevel(img);
}
public static BufferedImage ocv_rgb2gray(BufferedImage img) {
Mat rgbImage = ocv_img2Mat(img);
Mat imageGray = new Mat();
if (img.getType()==0 || img.getType()==1) {
Imgproc.cvtColor(rgbImage, imageGray, Imgproc.COLOR_RGB2GRAY);
}else if (img.getType()==4){
Imgproc.cvtColor(rgbImage, imageGray, Imgproc.COLOR_BGR2GRAY);
}
return ocv_mat2Img(imageGray);
}
public static BufferedImage ocv_rgb2RedChannel(BufferedImage img) {
Mat rgbImage = ocv_img2Mat(img);
ArrayList<Mat> bgr=new ArrayList();
Core.split(rgbImage, bgr);
int type = bgr.get(2).type();
System.out.println("type = " + type);
Mat imageRed = new Mat();
if (img.getType()==0 || img.getType()==1) {
Imgproc.cvtColor(bgr.get(2), imageRed, Imgproc.COLOR_GRAY2RGB);
}else if (img.getType()==4){
Imgproc.cvtColor(bgr.get(2), imageRed, Imgproc.COLOR_GRAY2BGR);
}
return ocv_mat2Img(imageRed);
}
public static BufferedImage ocv_rgb2gray(Mat rgbImage) {
Mat imageGray = new Mat();
Imgproc.cvtColor(rgbImage, imageGray, Imgproc.COLOR_BGR2GRAY);
return ocv_mat2Img(imageGray);
}
public static Mat ocv_rgb2grayMat(Mat rgbImage) {
Mat imageGray = new Mat();
Imgproc.cvtColor(rgbImage, imageGray, Imgproc.COLOR_BGR2GRAY);
return imageGray;
}
public static BufferedImage ocv_mat2Img(Mat m) {
int type = BufferedImage.TYPE_BYTE_GRAY;
if (m.channels() > 1) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = m.channels() * m.cols() * m.rows();
byte[] b = new byte[bufferSize];
m.get(0, 0, b); // get all the pixels
BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(b, 0, targetPixels, 0, b.length);
return image;
}
public static Mat ocv_img2Mat(BufferedImage in) {
if (in.getType() == BufferedImage.TYPE_INT_RGB) {
Mat out;
byte[] data;
int r, g, b;
out = new Mat(in.getHeight(), in.getWidth(), CvType.CV_8UC3);
data = new byte[in.getWidth() * in.getHeight() * (int) out.elemSize()];
int[] dataBuff = in.getRGB(0, 0, in.getWidth(), in.getHeight(), null, 0, in.getWidth());
for (int i = 0; i < dataBuff.length; i++) {
data[i * 3] = (byte) ((dataBuff[i] >> 0) & 0xFF);
data[i * 3 + 1] = (byte) ((dataBuff[i] >> 8) & 0xFF);
data[i * 3 + 2] = (byte) ((dataBuff[i] >> 16) & 0xFF);
}
return out;
}
byte[] pixels = ((DataBufferByte) in.getRaster().getDataBuffer()).getData();
Mat mat = null;
if (in.getType() == BufferedImage.TYPE_BYTE_GRAY) {
mat = new Mat(in.getHeight(), in.getWidth(), CvType.CV_8UC1);
} else {
mat = new Mat(in.getHeight(), in.getWidth(), CvType.CV_8UC3);
}
mat.put(0, 0, pixels);
return mat;
}
public static double[][] rgb2gray2D(BufferedImage img) {
// BufferedImage retImg = toNewColorSpace(img, BufferedImage.TYPE_BYTE_GRAY);
BufferedImage retImg = toGrayLevel(img);
double[][] ret = imageToPixelsDouble(retImg);
return ret;
}
private static void yaz(int[] p) {
for (int i = 0; i < p.length; i++) {
System.out.println(p[i]);
}
}
private static void yaz(String s) {
System.out.println(s);
}
public static BufferedImage getHistogramImage(int[] lbp) {
lbp = FactoryNormalization.normalizeMinMax(lbp);
BufferedImage img = new BufferedImage(lbp.length * 10, 300, BufferedImage.TYPE_BYTE_GRAY);
Graphics gr = img.getGraphics();
gr.setColor(Color.white);
int w = img.getWidth();
int h = img.getHeight();
int a = 20;
gr.drawRect(a, a, w - 2 * a, h - 2 * a);
return img;
}
// public static BufferedImage getHistogramImage(BufferedImage imgx) {
// int[] hist=getHistogramData(imgx);
// BufferedImage img = new BufferedImage(hist.length * 10, 300, BufferedImage.TYPE_BYTE_GRAY);
// Graphics gr = img.getGraphics();
// gr.setColor(Color.white);
// int w = img.getWidth();
// int h = img.getHeight();
// int a = 20;
// gr.drawRect(a, a, w - 2 * a, h - 2 * a);
// return img;
// }
public static int[] getHistogram(BufferedImage imgx) {
int[] d = imageToPixelsTo1D(imgx);
int[] ret = new int[256];
for (int i = 0; i < 256; i++) {
for (int j = 0; j < d.length; j++) {
if (d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
// public static CMatrix getHistogram(BufferedImage imgx) {
// CMatrix cm;
// int[] d = imageToPixels255_1D(imgx);
// int[] returnedValue = getHistogram(d);
// cm = CMatrix.getInstance(returnedValue);
// return cm;
// }
/**
* 8 bit gray level histogram
*
* @param d
* @return
*/
public static int[] getHistogram(int[] d) {
int[] ret = new int[256];
for (int i = 0; i < 256; i++) {
for (int j = 0; j < d.length; j++) {
if (d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
/**
* N bins of histogram
*
* @param d
* @return
*/
public static int[] getHistogram(int[] d, int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < d.length; j++) {
if (d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
public static int[] getHistogram(double[][] p) {
double[] d = FactoryUtils.toDoubleArray1D(p);
int[] ret = new int[256];
for (int i = 0; i < 256; i++) {
for (int j = 0; j < d.length; j++) {
if ((int) d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
public static int[] getHistogram(int[][] p) {
int[] d = FactoryUtils.toIntArray1D(p);
int[] ret = new int[256];
for (int i = 0; i < 256; i++) {
for (int j = 0; j < d.length; j++) {
if ((int) d[j] == i) {
ret[i]++;
}
}
}
return ret;
}
public static CMatrix getHistogramRed(CMatrix cm) {
int[] d = cm.getRedChannelColor().toIntArray1D();
int[] ret = ImageProcess.getHistogram(d);
cm = CMatrix.getInstance(ret).transpose();
return cm;
}
public static CMatrix getHistogramGreen(CMatrix cm) {
int[] d = cm.getGreenChannelColor().toIntArray1D();
int[] ret = ImageProcess.getHistogram(d);
cm = CMatrix.getInstance(ret).transpose();
return cm;
}
public static CMatrix getHistogramBlue(CMatrix cm) {
int[] d = cm.getBlueChannelColor().toIntArray1D();
int[] ret = ImageProcess.getHistogram(d);
cm = CMatrix.getInstance(ret).transpose();
return cm;
}
public static CMatrix getHistogramAlpha(CMatrix cm) {
int[] d = cm.getAlphaChannelColor().toIntArray1D();
int[] ret = ImageProcess.getHistogram(d);
cm = CMatrix.getInstance(ret).transpose();
return cm;
}
public static CMatrix getHistogram(CMatrix cm) {
if (cm.getImage().getType() == BufferedImage.TYPE_BYTE_GRAY) {
short[] d = cm.toShortArray1D();
double[] ret = FactoryMatrix.getHistogram(d, 256);
cm.setArray(ret);
cm = cm.transpose();
} else {
int[][][] d = imageToPixelsColorInt(cm.getImage());
double[][] ret = FactoryMatrix.getHistogram(d, 256);
cm.setArray(ret);
}
cm.name += "|" + "Histogram";
return cm;
}
public static BufferedImage revert(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int p = img.getRGB(x, y);
int a = (p >> 24) & 0xff;
int r = (p >> 16) & 0xff;
int g = (p >> 8) & 0xff;
int b = p & 0xff;
r = 255 - r;
g = 255 - g;
b = 255 - b;
p = (a << 24) | (r << 16) | (g << 8) | b;
img.setRGB(x, y, p);
}
}
return img;
// BufferedImage ret = null;
// int[][] d = imageToPixelsInt(img);
// int[][] q = new int[d.length][d[0].length];
// for (int i = 0; i < d.length; i++) {
// for (int j = 0; j < d[0].length; j++) {
// q[i][j] = Math.abs(255 - d[i][j]);
// }
// }
// ret = ImageProcess.pixelsToImageGray(q);
// return ret;
}
/**
* resize the image to desired width and height value by using
* Image.SCALE_SMOOTH format
*
* @param src:BufferedImage
* @param w:width
* @param h:height
* @return
*/
public static BufferedImage resize(BufferedImage src, int w, int h) {
//// Image tmp = img.getScaledInstance(w, h, Image.SCALE_FAST);
// Image tmp = img.getScaledInstance(w, h, Image.SCALE_SMOOTH);
//// Image tmp = img.getScaledInstance(w, h, Image.SCALE_REPLICATE);
// BufferedImage dimg = new BufferedImage(w, h, img.getType());
// Graphics2D g2d = dimg.createGraphics();
// g2d.drawImage(tmp, 0, 0, null);
// g2d.dispose();
// return dimg;
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
Graphics2D g2 = resizedImg.createGraphics();
// g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.drawImage(src, 0, 0, w, h, null);
g2.dispose();
BufferedImage img = new BufferedImage(w, h, src.getType());
g2 = img.createGraphics();
g2.drawImage(resizedImg, 0, 0, w, h, null);
g2.dispose();
return img;
}
public static BufferedImage resizeSmooth(BufferedImage src, int w, int h) {
Image img = src.getScaledInstance(w, h, BufferedImage.SCALE_SMOOTH);
BufferedImage ret = toBufferedImage(img);
return ret;
}
/**
* Resizes an image using a Graphics2D object backed by a BufferedImage.
*
* @param src - source image to scale
* @param w - desired width
* @param h - desired height
* @return - the new resized image
*/
public static BufferedImage resizeAspectRatio(BufferedImage src, int w, int h) {
int finalw = w;
int finalh = h;
double factor = 1.0d;
if (src.getWidth() > src.getHeight()) {
factor = ((double) src.getHeight() / (double) src.getWidth());
finalh = (int) (finalw * factor);
} else {
factor = ((double) src.getWidth() / (double) src.getHeight());
finalw = (int) (finalh * factor);
}
BufferedImage resizedImg = new BufferedImage(finalw, finalh, BufferedImage.TRANSLUCENT);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(src, 0, 0, finalw, finalh, null);
g2.dispose();
BufferedImage img = new BufferedImage(finalw, finalh, BufferedImage.TYPE_3BYTE_BGR);
g2 = img.createGraphics();
g2.drawImage(resizedImg, 0, 0, finalw, finalh, null);
g2.dispose();
// return resizedImg;
return img;
}
public static BufferedImage rotateImage(BufferedImage img, double theta) {
double radians = theta * Math.PI / 180;
AffineTransform transform = new AffineTransform();
transform.rotate(radians, img.getWidth() / 2, img.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
BufferedImage newImage = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
img = op.filter(img, newImage);
return newImage;
}
public static BufferedImage rotateImage(BufferedImage img, CPoint cp, double theta) {
double radians = theta * Math.PI / 180;
AffineTransform transform = new AffineTransform();
transform.rotate(radians, cp.column, cp.row);
AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
BufferedImage newImage = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
img = op.filter(img, newImage);
return newImage;
}
public static ArrayList<TRoi> getSpecialROIPositions(BufferedImage img) {
ArrayList<TRoi> pos = new ArrayList<>();
int[][] m = imageToPixelsInt(img);
m = binarizeImage(m);
m = FactoryUtils.transpose(m);
int hImg = m.length;
//each page of Quran is made up of 15 rows
int hRow = hImg / 15;
for (int i = 0; i < 15; i++) {
addPosForEachRow(m, pos, i, hRow);
}
return pos;
}
private static int[][] binarizeImage(int[][] m) {
int[][] ret = new int[m.length][m[0].length];
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
if (m[i][j] > 0) {
ret[i][j] = 255;
}
}
}
return ret;
}
private static void addPosForEachRow(int[][] m, ArrayList<TRoi> pl, int n, int hRow) {
CPoint p1 = new CPoint(n * hRow, 0);
CPoint p2 = new CPoint(n * hRow + hRow, m[0].length);
int[][] subMatrix = FactoryUtils.getSubMatrix(m, p1, p2);
int[] prjMatrix = FactoryUtils.getProjectedMatrixOnX(subMatrix);
TWord[] points = FactoryUtils.getPoints(prjMatrix);
for (int i = 0; i < points.length; i++) {
Point p = new Point(n * hRow + hRow / 2, points[i].centerPos);
TRoi roi = new TRoi();
roi.cp = p;
roi.width = points[i].width;
pl.add(roi);
//yaz((n + 1) + ".satır da "+(i+1)+". yer"+" pos:"+p.x+","+p.y);
}
}
private static double checkWindowDensity(int[][] m, int x, int y, int dx) {
int w = 30;
int h = 30 - dx;
CPoint p1 = new CPoint(x, y);
CPoint p2 = new CPoint(x + h, y + w);
int[][] subMatrix = FactoryUtils.getSubMatrix(m, p1, p2);
// double mean = Utils.getMeanValue(subMatrix);
double mean = FactoryUtils.getPixelCount(subMatrix);
yaz("roi pos:" + x + "," + y + " mean:" + mean);
return mean;
}
/**
* 16.04.2014 <NAME> Bir imgenin çerisinde küçük bir imgeyi correlation
* coefficient tabanlı arar, en iyi correlation coefficient değerine sahip
* koordinatı geri gönderir.
*/
public static Point getPositionOfSubImageFromParentImage(int[][] parentImg, int[][] subImg, String filterType) {
Point ret = new Point();
ArrayList<TGrayPixel> cr = null;
if (filterType.equals("DirectCorrelationBased")) {
cr = performConvolveOperationForCorrelation(parentImg, subImg);
}
if (filterType.equals("LBP")) {
cr = performConvolveOperationForLBP(parentImg, subImg);
}
for (int i = 0; i < 10; i++) {
FactoryUtils.yaz(cr.get(i).toString());
}
return ret;
}
private static double[] to1D(int[][] parentImg) {
int index = -1;
double[] d = new double[parentImg.length * parentImg[0].length];
for (int i = 0; i < parentImg.length; i++) {
for (int j = 0; j < parentImg[0].length; j++) {
d[++index] = parentImg[i][j] * 1.0;
}
}
return d;
}
private static ArrayList<TGrayPixel> performConvolveOperationForCorrelation(int[][] parentImg, int[][] subImg) {
return getPossiblePixelsAfterConvolution(parentImg, subImg, "PearsonCorrelationCoefficient");
}
private static ArrayList<TGrayPixel> performConvolveOperationForLBP(int[][] parentImg, int[][] subImg) {
return getPossiblePixelsAfterConvolution(parentImg, subImg, "LBP");
}
public static ArrayList<TGrayPixel> getPossiblePixelsAfterConvolution(int[][] parentImg, int[][] subImg, String filterType) {
ArrayList<TGrayPixel> ret = new ArrayList<TGrayPixel>();
int pw = parentImg.length;
int ph = parentImg[0].length;
int sw = subImg.length;
int sh = subImg[0].length;
FactoryUtils.yazln("pw:" + pw + " ph:" + ph + " sw:" + sw + " sh:" + sh);
double[] m2 = to1D(subImg);
double[] m1 = null;
for (int i = sw / 2; i < pw - sw; i++) {
for (int j = sh / 2; j < ph - sh; j++) {
//Utils.yaz("i:"+i+" j:"+j);
int[][] d = FactoryUtils.getSubMatrix(parentImg, new CPoint(i, j), new CPoint(i + sw, j + sh));
m1 = to1D(d);
double cor = 0;
if (filterType.equals("PearsonCorrelationCoefficient")) {
cor = FactoryStatistic.PEARSON(m1, m2);
}
if (filterType.equals("LBP")) {
int[] subImgLBP = FeatureExtractionLBP.getLBP(subImg, true);
int[] parentImgLBP = FeatureExtractionLBP.getLBP(d, true);
//cor = Distance.getCorrelationCoefficientDistance(Utils.to2DArrayDouble(subImgLBP),Utilto2DArrayDoubleay(parentImgLBP));
cor = FactorySimilarityDistance.getEuclideanDistance(FactoryUtils.toDoubleArray1D(subImgLBP), FactoryUtils.toDoubleArray1D(parentImgLBP));
}
// if (cor > 0.85) {
// Utils.yazln("high Correlation:" + cor + " coordinates:" + i + ":" + j);
// Utils.yaz("M1=");
// Utils.yaz(m1);
// Utils.yaz("M2=");
// Utils.yaz(m2);
// }
TGrayPixel gp = new TGrayPixel();
gp.corValue = cor;
gp.x = i;
gp.y = j;
ret.add(gp);
}
}
Collections.sort(ret, new CustomComparatorForGrayPixelCorrelation());
return ret;
}
public static int[][] getAbsoluteMatrixDifferenceWithROI(int[][] m_prev, int[][] m_curr, Rectangle r) {
int[][] ret = new int[r.width][r.height];
int k = 0;
int l = 0;
for (int i = r.x; i < r.x + r.width - 1; i++) {
l = 0;
for (int j = r.y; j < r.y + r.height - 1; j++) {
int a = Math.abs(m_prev[i][j] - m_curr[i][j]);
ret[k][l++] = (a < 20) ? 0 : a;
}
k++;
}
return ret;
}
public static int[][] segmentImageDifference(int[][] m, int size) {
int w = m.length;
int h = m[0].length;
int nx = w / size;
int ny = h / size;
int[][] segM = new int[nx][ny];
int[][] v = new int[size][size];
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
v = cropMatrix(m, new Rectangle(i * size, j * size, size, size));
segM[i][j] = (int) FactoryUtils.getMean(v);
}
}
return segM;
}
public static int[][] cropMatrix(int[][] m, Rectangle r) {
int[][] ret = new int[r.width][r.height];
int k = 0;
int l = 0;
for (int i = r.x; i < r.x + r.width - 1; i++) {
l = 0;
for (int j = r.y; j < r.y + r.height - 1; j++) {
ret[k][l++] = m[i][j];
}
k++;
}
return ret;
}
public static CPoint getCenterOfGravityGray(BufferedImage img) {
int[][] m = imageToPixelsInt(img);
return ImageProcess.getCenterOfGravityGray(m);
}
public static CPoint getCenterOfGravityGray(BufferedImage img, boolean isShowCenter) {
int[][] m = null;
if (img.getType() != BufferedImage.TYPE_BYTE_GRAY) {
BufferedImage temp = rgb2gray(img);
m = imageToPixelsInt(temp);
} else {
m = imageToPixelsInt(img);
}
CPoint cp = ImageProcess.getCenterOfGravityGray(m);
if (isShowCenter) {
img = fillRectangle(img, cp.row - 2, cp.column - 2, 5, 5, Color.black);
}
return cp;
}
public static CPoint getCenterOfGravityColor(BufferedImage img, boolean isShowCenter) {
int[][][] m = null;
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
System.err.println("You should not use gray level image for this particular case");
return new CPoint();
} else {
m = imageToPixelsColorInt(img);
}
BufferedImage red = ImageProcess.getRedChannelGray(img);
BufferedImage green = ImageProcess.getGreenChannelGray(img);
BufferedImage blue = ImageProcess.getRedChannelGray(img);
CPoint cpRed = ImageProcess.getCenterOfGravityGray(red);
CPoint cpGreen = ImageProcess.getCenterOfGravityGray(green);
CPoint cpBlue = ImageProcess.getCenterOfGravityGray(blue);
CPoint cp = new CPoint();
cp.row = (int) ((cpRed.row + cpGreen.row + cpBlue.row) / 3.0);
cp.column = (int) ((cpRed.column + cpGreen.column + cpBlue.column) / 3.0);
if (isShowCenter) {
img = fillRectangle(img, cp.row - 2, cp.column - 2, 5, 5, Color.red);
}
return cp;
}
public static CPoint getCenterOfGravityGray(int[][] m) {
int w = m.length;
int h = m[0].length;
int sumX = 0;
int sumY = 0;
int np = 0;
CPoint cp = new CPoint();
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (m[i][j] > 0) {
sumX += i;
sumY += j;
np++;
}
}
}
double pr = 0;
double pc = 0;
if (np != 0) {
pr = sumX * 1.0 / np;
pc = sumY * 1.0 / np;
cp.row = (int) pr;
cp.column = (int) pc;
}
return cp;
}
public static int[][] getCenterOfGravityCiz(int[][] m) {
int w = m.length;
int h = m[0].length;
int[][] ret = new int[w][h];
int sumX = 0;
int sumY = 0;
int np = 0;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (m[i][j] > 0) {
sumX += i;
sumY += j;
np++;
}
}
}
//avoid division by zero
double px = 0;
double py = 0;
if (np != 0) {
px = sumX * 1.0 / np;
py = sumY * 1.0 / np;
ret[(int) px][(int) py] = 255;
//writeToFile((int) px * zoom, 400 - (int) py * zoom, ++ID);
}
return ret;
}
public static CPoint getCenterOfGravityGray(double[][] m) {
int w = m.length;
int h = m[0].length;
int sumX = 0;
int sumY = 0;
int np = 0;
CPoint cp = new CPoint();
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (m[i][j] > 0) {
sumX += i;
sumY += j;
np++;
}
}
}
double pr = 0;
double pc = 0;
if (np != 0) {
pr = sumX * 1.0 / np;
pc = sumY * 1.0 / np;
cp.row = (int) pr;
cp.column = (int) pc;
}
return cp;
}
public static double getInverseDiffMoment(int[][] img) {
int col = img.length;
int row = img[0].length;
double IDF = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
IDF += img[i][j] / (1 + (i - j) * (i - j));
}
}
return IDF;
}
public static double getInverseDiffMoment(BufferedImage img) {
int[][] d = imageToPixelsInt(img);
return getInverseDiffMoment(d);
}
public static double getInverseDiffMoment(double[][] img) {
int col = img.length;
int row = img[0].length;
double IDF = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
IDF += img[i][j] / (1 + (i - j) * (i - j));
}
}
return IDF;
}
public static double getContrast(BufferedImage img) {
int[][] d = imageToPixelsInt(img);
return getContrast(d);
}
public static double getContrast(int[][] img) {
int col = img.length;
int row = img[0].length;
double contrast = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
contrast += img[i][j] * ((i - j) * (i - j));
}
}
return contrast;
}
public static double getContrast(double[][] img) {
int col = img.length;
int row = img[0].length;
double contrast = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
contrast += img[i][j] * ((i - j) * (i - j));
}
}
return contrast;
}
public static double getEntropy(int[][] img) {
int col = img.length;
int row = img[0].length;
double entropy = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
entropy += img[i][j] * Math.log(img[i][j]);
}
}
return entropy;
}
public static double getEntropy(double[][] img) {
int col = img[0].length;
int row = img.length;
double entropy = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
entropy += img[i][j] * Math.log(img[i][j] + 1);
}
}
return entropy;
}
public static double getEntropy(BufferedImage actualImage) {
ArrayList<String> values = new ArrayList<String>();
int n = 0;
Map<Integer, Integer> occ = new HashMap<>();
for (int i = 0; i < actualImage.getHeight(); i++) {
for (int j = 0; j < actualImage.getWidth(); j++) {
int pixel = actualImage.getRGB(j, i);
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
//0.2989 * R + 0.5870 * G + 0.1140 * B greyscale conversion
//System.out.println("i="+i+" j="+j+" argb: " + alpha + ", " + red + ", " + green + ", " + blue);
int d = (int) Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue);
if (!values.contains(String.valueOf(d))) {
values.add(String.valueOf(d));
}
if (occ.containsKey(d)) {
occ.put(d, occ.get(d) + 1);
} else {
occ.put(d, 1);
}
++n;
}
}
double e = 0.0;
for (Map.Entry<Integer, Integer> entry : occ.entrySet()) {
int cx = entry.getKey();
double p = (double) entry.getValue() / n;
e += p * Math.log(p);
}
return -e;
}
public static double getEntropyWithHistogram(double[][] d) {
int[] hist = ImageProcess.getHistogram(d);
double sum = FactoryUtils.sum(hist);
double e = 0.0;
for (int h : hist) {
double p = h / sum;
if (p > 0) {
e += p * Math.log(p);
}
}
return -e;
}
/**
* yanlış hesaplıyor güncellenmesi gerekir
*
* @param d
* @return
*/
public static double getHomogeneity(double[][] d) {
//aşağıdaki kod yanlış update edilmesi gerekiyor
int[] hist = ImageProcess.getHistogram(d);
double sum = FactoryUtils.sum(hist);
double e = 0.0;
for (int h : hist) {
double p = h / sum;
if (p > 0) {
e += p * Math.log(p);
}
}
return -e;
}
public static double getEnergy(int[][] img) {
int col = img.length;
int row = img[0].length;
double energy = 0.0d;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
energy += img[i][j] * img[i][j];
}
}
return energy;
}
public static double getKurtosis(int[][] img) {
int[] nums = FactoryUtils.toIntArray1D(img);
int n = nums.length;
double mean = FactoryUtils.getMean(nums);
double deviation = 0.0d;
double variance = 0.0d;
double k = 0.0d;
for (int i = 0; i < n; i++) {
deviation = nums[i] - mean;
variance += Math.pow(deviation, 2);
k += Math.pow(deviation, 4);
}
//variance /= (n - 1);
variance = variance / n;
if (variance != 0.0) {
//k = k / (n * variance * variance) - 3.0;
k = k / (n * variance * variance);
}
return k;
}
public static double getSkewness(int[][] img) {
int[] nums = FactoryUtils.toIntArray1D(img);
int n = nums.length;
double mean = FactoryUtils.getMean(nums);
double deviation = 0.0d;
double variance = 0.0d;
double skew = 0.0d;
for (int i = 0; i < n; i++) {
deviation = nums[i] - mean;
variance += Math.pow(deviation, 2);
skew += Math.pow(deviation, 3);
}
//variance /= (n - 1);
variance /= n;
double standard_deviation = Math.sqrt(variance);
if (variance != 0.0) {
skew /= (n * variance * standard_deviation);
}
return skew;
}
public static BufferedImage clone(BufferedImage img) {
ColorModel cm = img.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = img.copyData(img.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
// public static Image clone(Image img) {
// BufferedImage bf = ImageProcess.toBufferedImage(img);
// BufferedImage ret = new BufferedImage(bf.getWidth(), bf.getHeight(), bf.getType());
// ret.getGraphics().drawImage(img, 0, 0, null);
// return ret;
// }
//
public static int[] getImagePixels(BufferedImage image) {
int[] dummy = null;
int wid, hgt;
// compute size of the array
wid = image.getWidth();
hgt = image.getHeight();
// start getting the pixels
Raster pixelData;
pixelData = image.getData();
System.out.println("wid:" + wid);
System.out.println("hgt:" + hgt);
System.out.println("Channels:" + pixelData.getNumDataElements());
return pixelData.getPixels(0, 0, wid, hgt, dummy);
}
public static int[][] to2DRGB(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[][] result = new int[height][width];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
result[row][col] = image.getRGB(col, row);
}
}
return result;
}
public static int[][] to2D(BufferedImage image) {
// final int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
//image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see e661 Determining If an Image Has Transparent Pixels
//boolean hasAlpha = hasAlpha(image);
boolean hasAlpha = false;
// Create a buffered image with a format that's compatible with the screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
public static BufferedImage imread() {
return readImageFromFile();
}
public static BufferedImage readImageFromFile() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("images"));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
//Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
}
return ret;
}
public static BufferedImage readImageFromFile(File file) {
BufferedImage ret = null;
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
//Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
return ret;
}
public static File readImage() {
JFileChooser chooser = new JFileChooser();
//chooser.setCurrentDirectory(new java.io.File("images"));
chooser.setCurrentDirectory(new java.io.File(FactoryUtils.getWorkingDirectory()));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file = null;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
//Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
}
return file;
}
public static File readImageFileFromFolder() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("images"));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file = null;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
return file;
}
public static File readImageFileFromFolderWithDirectoryPath(String directoryPath) {
if (directoryPath == null || directoryPath.isEmpty()) {
return readImageFileFromFolder();
}
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File(directoryPath));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file = null;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
}
return file;
}
public static BufferedImage readImageFromFileWithDirectoryPath(String directoryPath) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File(directoryPath));
chooser.setDialogTitle("select Data Set file");
chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
File file;
BufferedImage ret = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
//Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
}
return ret;
}
public static BufferedImage imread(String fileName) {
return readImageFromFile(fileName);
}
public static BufferedImage readImageFromFile(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
System.err.println("Fatal Exception: Image File not found at specified path");
System.exit(-1);
return null;
}
BufferedImage ret = null;
try {
ret = ImageIO.read(file);
} catch (IOException ex) {
Logger.getLogger(FactoryUtils.class.getName()).log(Level.SEVERE, null, "Problem reading " + fileName + "\n" + ex);
}
return ret;
}
public static CMatrix getMatrix(BufferedImage img) {
CMatrix cm = CMatrix.getInstance(imageToPixelsInt(img));
return cm;
}
public static boolean writeImage(BufferedImage img) {
return saveImage(img);
}
public static boolean writeImage(BufferedImage img, String fileName) {
return saveImage(img, fileName);
}
public static boolean imwrite(BufferedImage img) {
return saveImage(img);
}
public static boolean imwrite(BufferedImage img, String fileName) {
return saveImage(img, fileName);
}
public static boolean saveImage(BufferedImage img) {
JFileChooser FC = new JFileChooser("C:/");
int retrival = FC.showSaveDialog(null);
if (retrival == FC.APPROVE_OPTION) {
File fileToSave = FC.getSelectedFile();
String extension = FactoryUtils.getFileExtension(fileToSave);
try {
boolean ret = ImageIO.write(img, extension, fileToSave);
return ret;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
System.out.println(ex.getMessage());
return false;
}
return true;
}
return false;
}
public static boolean saveImageAtFolder(BufferedImage img, String folderPath) {
JFileChooser FC = new JFileChooser(folderPath);
int retrival = FC.showSaveDialog(null);
if (retrival == FC.APPROVE_OPTION) {
File fileToSave = FC.getSelectedFile();
String extension = FactoryUtils.getFileExtension(fileToSave);
try {
boolean ret = ImageIO.write(img, extension, fileToSave);
return ret;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
System.out.println(ex.getMessage());
return false;
}
return true;
}
return false;
}
public static boolean saveImage(BufferedImage img, String fileName) {
File file = new File(fileName);
String extension = FactoryUtils.getFileExtension(fileName);
boolean ret = false;
try {
ret = ImageIO.write(img, extension, file);
} catch (IOException ex) {
Logger.getLogger(ImageProcess.class.getName()).log(Level.SEVERE, null, ex);
}
return ret;
}
public static void saveImageSVG(BufferedImage img, String dest_path) {
String path=dest_path.replace("."+FactoryUtils.getFileExtension(dest_path), ".png");
saveImage(img, path);
RasterToVector rtv=new RasterToVector(path);
rtv.convertToSVG(dest_path);
}
public static void saveImageSVG(String source_path, String dest_path) {
RasterToVector rtv=new RasterToVector(source_path);
rtv.convertToSVG(dest_path);
}
public static BufferedImage convertDicomToBufferedImage(String filePath) {
File file = new File(filePath);
Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("DICOM");
BufferedImage img = null;
while (iterator.hasNext()) {
ImageReader imageReader = (ImageReader) iterator.next();
DicomImageReadParam dicomImageReadParam = (DicomImageReadParam) imageReader.getDefaultReadParam();
try {
ImageInputStream iis = ImageIO.createImageInputStream(file);
imageReader.setInput(iis, false);
img = imageReader.read(0, dicomImageReadParam);
iis.close();
if (img == null) {
System.out.println("Could not read image!!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return img;
}
public static boolean ocv_saveImageWithFormat(BufferedImage img, String path) {
Mat imgM = ocv_img2Mat(img);
return Imgcodecs.imwrite(path, imgM);
}
public static Mat ocv_saveImage(BufferedImage img, String path) {
Mat imgM = ocv_img2Mat(img);
Imgcodecs.imwrite(path, imgM);
return imgM;
}
public static BufferedImage ocv_imRead(String path) {
Mat imgM = Imgcodecs.imread(path);
return ocv_mat2Img(imgM);
}
public static void saveGridImage(BufferedImage gridImage, String filePath) {
File output = new File(filePath);
output.delete();
final String formatName = "png";
for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
try {
ImageWriter writer = iw.next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
continue;
}
try {
setDPI(metadata, 300);
} catch (IIOInvalidTreeException ex) {
Logger.getLogger(FactoryUtils.class
.getName()).log(Level.SEVERE, null, ex);
}
final ImageOutputStream stream = ImageIO.createImageOutputStream(output);
try {
writer.setOutput(stream);
writer.write(metadata, new IIOImage(gridImage, null, metadata), writeParam);
} finally {
stream.close();
}
break;
} catch (IOException ex) {
Logger.getLogger(FactoryUtils.class
.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void setDPI(IIOMetadata metadata, int DPI) throws IIOInvalidTreeException {
// for PMG, it's dots per millimeter inc to cm=2.54
// double dotsPerMilli = 1.0 * DPI / 10 / 2.54;
double dotsPerMilli = 1.0 * DPI;
IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
horiz.setAttribute("value", Double.toString(dotsPerMilli));
IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
vert.setAttribute("value", Double.toString(dotsPerMilli));
IIOMetadataNode dim = new IIOMetadataNode("Dimension");
dim.appendChild(horiz);
dim.appendChild(vert);
IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
root.appendChild(dim);
metadata.mergeTree("javax_imageio_1.0", root);
}
public static BufferedImage getBufferedImage(JPanel panel) {
int w = panel.getWidth();
int h = panel.getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
panel.paint(g);
return bi;
}
public static BufferedImage saveImageAsJPEG(String filePath, BufferedImage currBufferedImage, int k) {
//System.out.println("New Image Captured and jpg file saved");
try {
if (currBufferedImage == null) {
return null;
}
File file = new File(filePath + "\\img_" + k + ".jpg");
ImageIO.write(currBufferedImage, "jpg", file);
BufferedImage myImage = ImageIO.read(file);
currBufferedImage = myImage;
} catch (IOException ex) {
ex.printStackTrace();
}
return currBufferedImage;
}
public static BufferedImage getAlphaChannelGray(BufferedImage bf) {
return rgb2gray(getAlphaChannelColor(bf));
}
public static BufferedImage getRedChannelGray(BufferedImage bf) {
return rgb2gray(getRedChannelColor(bf));
}
public static BufferedImage getGreenChannelGray(BufferedImage bf) {
return rgb2gray(getGreenChannelColor(bf));
}
public static BufferedImage getBlueChannelGray(BufferedImage bf) {
return rgb2gray(getBlueChannelColor(bf));
}
public static BufferedImage getAlphaChannelColor(BufferedImage bf) {
int[][][] d = imageToPixelsColorInt(bf);
int[][] ret = new int[d.length][d[0].length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
ret[i][j] = d[i][j][0];
}
}
return pixelsToImageColor(d);
}
public static BufferedImage getRedChannelColor(BufferedImage bf) {
int[][][] d = imageToPixelsColorInt(bf);
int[][][] ret = new int[d.length][d[0].length][4];
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
ret[i][j][0] = d[i][j][0];
ret[i][j][1] = d[i][j][1];
}
}
return pixelsToImageColor(ret);
}
public static BufferedImage getGreenChannelColor(BufferedImage bf) {
int[][][] d = imageToPixelsColorInt(bf);
int[][][] ret = new int[d.length][d[0].length][4];
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
ret[i][j][0] = d[i][j][0];
ret[i][j][2] = d[i][j][2];
}
}
return pixelsToImageColor(ret);
}
public static BufferedImage getBlueChannelColor(BufferedImage bf) {
int[][][] d = imageToPixelsColorInt(bf);
int[][][] ret = new int[d.length][d[0].length][4];
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
ret[i][j][0] = d[i][j][0];
ret[i][j][3] = d[i][j][3];
}
}
return pixelsToImageColor(ret);
}
public static double[][] getRedChannelDouble(double[][][] d) {
double[][] ret = new double[d.length][d[0].length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
ret[i][j] = d[i][j][1];
}
}
return ret;
}
public static double[][] getGreenChannelDouble(double[][][] d) {
double[][] ret = new double[d.length][d[0].length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
ret[i][j] = d[i][j][2];
}
}
return ret;
}
public static double[][] getBlueChannelDouble(double[][][] d) {
double[][] ret = new double[d.length][d[0].length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
ret[i][j] = d[i][j][3];
}
}
return ret;
}
public static BufferedImage filterMedian(BufferedImage imgx) {
return filterMedian(imgx, 3);
}
public static BufferedImage filterGaussian(BufferedImage imgx, int size) {
GaussianFilter gaussianFilter = new GaussianFilter(size);
BufferedImage gaussianFiltered = clone(imgx);
gaussianFilter.filter(imgx, gaussianFiltered);
return gaussianFiltered;
}
public static BufferedImage filterMedian(BufferedImage imgx, int size) {
int w = imgx.getHeight(null);
int h = imgx.getWidth(null);
int[] kernel = new int[size * size];
int dizi[][] = new int[w][h];
int temp[][] = new int[w][h];
dizi = imageToPixelsInt(imgx);
temp = (int[][]) dizi.clone();
for (int i = 1; i < w - 1; i++) {
for (int j = 1; j < h - 1; j++) {
int f = 0;
for (int k = -1; k <= 1; k++) {
for (int t = -1; t <= 1; t++) {
kernel[f] = dizi[i + k][j + t];
f++;
}
}
temp[i][j] = medianKernel(kernel);
}
}
dizi = (int[][]) temp.clone();
BufferedImage ret_img = ImageProcess.pixelsToImageGray(dizi);
return ret_img;
}
public static int medianKernel(int[] kernel) {
int buffer;
for (int i = 0; i < kernel.length; i++) {
for (int j = i; j < kernel.length; j++) {
if (kernel[j] > kernel[i]) {
buffer = kernel[j];
kernel[j] = kernel[i];
kernel[i] = buffer;
}
}
}
int mid = kernel.length / 2;
return kernel[mid];
}
public static BufferedImage filterMean(BufferedImage imgx) {
AverageFilter avgFilter = new AverageFilter();
BufferedImage dest = clone(imgx);
avgFilter.filter(dest, imgx);
return dest;
// return ImageProcess.filterMean(imgx, 3);
}
public static BufferedImage filterMotionBlur(BufferedImage imgx) {
MotionBlurOp op = new MotionBlurOp(5, 45, 13, 3);
// MotionBlurFilter motionFilter=new MotionBlurFilter();
// motionFilter.setAngle(20);
// motionFilter.setDistance(15);
//motionFilter.setRotation(10);
BufferedImage dest = clone(imgx);
op.filter(dest, imgx);
return dest;
}
public static double[][] filterMean(double[][] d) {
double[][] ret = imageToPixelsDouble(filterMean(pixelsToImageGray(d), 3));
return ret;
}
public static BufferedImage filterMean(BufferedImage imgx, int size) {
int w = imgx.getWidth(null);
int h = imgx.getHeight(null);
int[] kernel = new int[size * size];
int dizi[][] = new int[w][h];
int temp[][] = new int[w][h];
dizi = imageToPixelsInt(imgx);
temp = FactoryMatrix.clone(dizi);
int sum = 0;
for (int i = 1; i < w - 1; i++) {
for (int j = 1; j < h - 1; j++) {
int f = 0;
for (int k = -1; k <= 1; k++) {
for (int t = -1; t <= 1; t++) {
kernel[f] = dizi[i + k][j + t];
sum += kernel[f];
f++;
}
}
// if (sum / 9 > 0) {
// System.out.println("org:" + temp[i][j] + " avg:" + (sum / (size * size)) + " r,c:" + j + ":" + i);
// }
temp[i][j] = sum / (size * size);
sum = 0;
}
}
int[][] d = FactoryMatrix.clone(temp);
BufferedImage ret_img = ImageProcess.pixelsToImageGray(d);
return ret_img;
}
// public static double[][] meanFilter(double[][] imgx) {
// int r = imgx.length;
// int c = imgx[0].length;
// int[] kernel = new int[9];
// double temp[][] = new double[r][c];
// temp = FactoryMatrix.clone(imgx);
// int sum = 0;
// for (int row = 1; row < r - 1; row++) {
// for (int column = 1; column < c - 1; column++) {
// int f = 0;
// for (int k = -1; k <= 1; k++) {
// for (int t = -1; t <= 1; t++) {
// kernel[f] = (int) imgx[row + k][column + t];
// sum += kernel[f];
// f++;
// }
// }
// temp[row][column] = (int) (sum / 9.0);
// sum = 0;
// }
// }
// return temp;
// }
public static BufferedImage erode(BufferedImage img, int[][] kernel) {
BufferedImage imgx = clone(img);
int w = imgx.getWidth(null);
int h = imgx.getHeight(null);
int dizi[][] = new int[h][w];
int temp[][] = new int[h][w];
dizi = imageToPixelsInt(imgx);
for (int i = 1; i < h - 1; i++) {
for (int j = 1; j < w - 1; j++) {
if (dizi[i - 1][j - 1] == kernel[0][0] && dizi[i - 1][j] == kernel[0][1] && dizi[i - 1][j + 1] == kernel[0][2]
&& dizi[i][j - 1] == kernel[1][0] && dizi[i][j] == kernel[1][1] && dizi[i][j + 1] == kernel[1][2]
&& dizi[i + 1][j - 1] == kernel[2][0] && dizi[i + 1][j] == kernel[2][1] && dizi[i + 1][j + 1] == kernel[2][2]) {
temp[i][j] = 0;
} else {
temp[i][j] = 255;
}
}
}
dizi = temp;
BufferedImage ret_img = ImageProcess.pixelsToImageGray(dizi);
return ret_img;
}
public static BufferedImage erode(BufferedImage imgx) {
int[][] kernel = {{255, 255, 255}, {255, 255, 255}, {255, 255, 255}};
return dilate(imgx, kernel);
}
public static BufferedImage dilate(BufferedImage img, int[][] kernel) {
int w = img.getWidth(null);
int h = img.getHeight(null);
int dizi[][] = new int[h][w];
int temp[][] = new int[h][w];
BufferedImage imgx = clone(img);
dizi = imageToPixelsInt(imgx);
for (int i = 1; i < h - 1; i++) {
for (int j = 1; j < w - 1; j++) {
if (dizi[i - 1][j - 1] == kernel[0][0] || dizi[i - 1][j] == kernel[0][1] || dizi[i - 1][j + 1] == kernel[0][2]
|| dizi[i][j - 1] == kernel[1][0] || dizi[i][j] == kernel[1][1] || dizi[i][j + 1] == kernel[1][2]
|| dizi[i + 1][j - 1] == kernel[2][0] || dizi[i + 1][j] == kernel[2][1] || dizi[i + 1][j + 1] == kernel[2][2]) {
temp[i][j] = 0;
} else {
temp[i][j] = 255;
}
}
}
dizi = temp;
BufferedImage ret_img = ImageProcess.pixelsToImageGray(dizi);
return ret_img;
}
public static BufferedImage dilate(BufferedImage imgx) {
int[][] kernel = {{255, 255, 255}, {255, 255, 255}, {255, 255, 255}};
return dilate(imgx, kernel);
}
public static BufferedImage kernelFilter(BufferedImage imgx) {
int w = imgx.getWidth(null);
int h = imgx.getHeight(null);
int dizi[][] = new int[w][h];
int kw = 15;
int kh = 15;
int med = kw / 2;
int[][] kernel = new int[kw][kh];
for (int i = 2; i < kw - 2; i++) {
for (int j = 2; j < kh - 2; j++) {
kernel[i][j] = 255;
}
}
dizi = imageToPixelsInt(imgx);
for (int i = med; i < w - med; i++) {
for (int j = med; j < h - med; j++) {
if (dizi[i - med][j - med] == 0 && dizi[i - med][j + med] == 0 && dizi[i + med][j - med] == 0 && dizi[i + med][j + med] == 0
&& dizi[i][j] == 255 && dizi[i - 1][j - 1] == 255 && dizi[i - 1][j + 1] == 255 && dizi[i + 1][j - 1] == 255 && dizi[i + 1][j + 1] == 255) {
for (int k = 0; k < med; k++) {
for (int m = 0; m < med; m++) {
if (dizi[i + k][j + m] == 255) {
dizi[i + k][j + m] = 0;
}
}
}
//writeln("bulundu:"+i+","+j);
}
}
}
//dizi=temp;
BufferedImage ret_img = ImageProcess.pixelsToImageGray(dizi);
return ret_img;
}
/**
* Get binary int treshold using Otsu's method
*/
public static int getOtsuTresholdValue(BufferedImage original) {
double[][] d = ImageProcess.imageToPixelsDouble(original);
return getOtsuTresholdValue(d);
}
/**
* Get binary int treshold using Otsu's method
*/
public static int getOtsuTresholdValue(double[][] d) {
int[] histogram = ImageProcess.getHistogram(d);
int total = d.length * d[0].length;
float sum = 0;
for (int i = 0; i < 256; i++) {
sum += i * histogram[i];
}
float sumB = 0;
int wB = 0;
int wF = 0;
float varMax = 0;
int threshold = 0;
for (int i = 0; i < 256; i++) {
wB += histogram[i];
if (wB == 0) {
continue;
}
wF = total - wB;
if (wF == 0) {
break;
}
sumB += (float) (i * histogram[i]);
float mB = sumB / wB;
float mF = (sum - sumB) / wF;
float varBetween = (float) wB * (float) wF * (mB - mF) * (mB - mF);
if (varBetween > varMax) {
varMax = varBetween;
threshold = i;
}
}
return threshold;
}
/**
* Binarize Color Image with a given threshold value i.e. otsuThreshold
*
* @param original
* @return
*/
public static BufferedImage binarizeColorImage(BufferedImage original, int threshold) {
int red;
int newPixel;
BufferedImage binarized = new BufferedImage(original.getWidth(), original.getHeight(), original.getType());
for (int i = 0; i < original.getWidth(); i++) {
for (int j = 0; j < original.getHeight(); j++) {
// Get pixels
red = new Color(original.getRGB(i, j)).getRed();
int alpha = new Color(original.getRGB(i, j)).getAlpha();
if (red > threshold) {
newPixel = 255;
} else {
newPixel = 0;
}
newPixel = colorToRGB(alpha, newPixel, newPixel, newPixel);
binarized.setRGB(i, j, newPixel);
}
}
return binarized;
}
/**
* Binarize Color Image with a given threshold value i.e. otsuThreshold
*
* @param original
* @return
*/
public static BufferedImage binarizeColorImage(BufferedImage original) {
int threshold = getOtsuTresholdValue(original);
return binarizeColorImage(original, threshold);
}
/**
* Binarize Image with a given threshold value hint: you can determine
* threshold value from otsu approach and then pass as an argument
*
* @param original
* @return
*/
public static BufferedImage binarizeGrayScaleImage(BufferedImage original, int threshold) {
int[][] d = imageToPixelsInt(original);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] > threshold) {
d[i][j] = 255;
} else {
d[i][j] = 0;
}
}
}
BufferedImage binarized = ImageProcess.pixelsToImageGray(d);
return binarized;
}
/**
* Binarize Image with a given threshold value you can determine threshold
* value from otsu approach and then pass as an argument
*
* @param original
* @return
*/
public static BufferedImage binarizeGrayScaleImage(BufferedImage original) {
int threshold = getOtsuTresholdValue(original);
return binarizeGrayScaleImage(original, threshold);
}
/**
* Binarize Image with a given threshold value you can determine threshold
* value from otsu approach
*
* @param d
* @return
*/
public static BufferedImage binarizeGrayScaleImage(double[][] d, int threshold) {
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
if (d[i][j] > threshold) {
d[i][j] = 255;
} else {
d[i][j] = 0;
}
}
}
BufferedImage binarized = pixelsToImageGray(d);
return binarized;
}
// Convert R, G, B, Alpha to standard 8 bit
public static int colorToRGB(int alpha, int red, int green, int blue) {
int newPixel = 0;
newPixel += alpha;
newPixel = newPixel << 8;
newPixel += red;
newPixel = newPixel << 8;
newPixel += green;
newPixel = newPixel << 8;
newPixel += blue;
return newPixel;
}
// /**
// * convert let say gray scale image to RGB or any other types
// *
// * @param img
// * @param newType
// * @return
// */
// public static BufferedImage toNewColorSpace(BufferedImage img, int newType) {
// BufferedImage ret = new BufferedImage(img.getWidth(), img.getHeight(), newType);
// ret.getGraphics().drawImage(img, 0, 0, null);
// return ret;
// }
//
/**
* convert let say gray scale image to RGB or any other types
*
* @param img
* @param newType
* @return
*/
public static BufferedImage toBufferedImage(BufferedImage img, int newType) {
BufferedImage ret = new BufferedImage(img.getWidth(), img.getHeight(), newType);
ret.getGraphics().drawImage(img, 0, 0, null);
return ret;
}
public static double[][] highPassFilter(double[][] m, int t) {
double[][] d = FactoryMatrix.clone(m);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] < t) {
d[i][j] = 0;
}
}
}
return d;
}
public static double[][] lowPassFilter(double[][] m, int t) {
double[][] d = FactoryMatrix.clone(m);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] > t) {
d[i][j] = 0;
}
}
}
return d;
}
public static double[][] swapColor(double[][] m, int c1, int c2) {
double[][] d = FactoryMatrix.clone(m);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] == c1) {
d[i][j] = c2;
}
}
}
return d;
}
public static double[][] imageToPixels2DFromOpenCV(Mat m) {
double[][] ret = new double[m.height()][m.width()];
for (int i = 0; i < m.height(); i++) {
for (int j = 0; j < m.width(); j++) {
ret[i][j] = m.get(i, j)[0];
}
}
return ret;
}
// public static Rectangle[] detectFacesRectangles(String type, BufferedImage img) {
//
// String xml = "";
// if (type.equals("haar")) {
// xml = "etc\\haarcascades\\haarcascade_frontalface_alt.xml";
//// xml = "etc\\haarcascades\\haarcascade_frontalface_alt_tree.xml";
// }
// if (type.equals("lbp")) {
// xml = "etc\\lbpcascades\\lbpcascade_frontalface.xml";
// }
//// System.out.println("xml_file = " + xml);
// CascadeClassifier faceDetector = new CascadeClassifier(xml);
// Mat imageGray = ocv_img2Mat(img);
//
// MatOfRect faceDetections = new MatOfRect();
// faceDetector.detectMultiScale(imageGray, faceDetections);
//// System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
// for (Rect rect : faceDetections.toArray()) {
// Imgproc.rectangle(imageGray, new org.opencv.core.Point(rect.x, rect.y), new org.opencv.core.Point(rect.x + rect.width, rect.y + rect.height),
// new Scalar(0, 255, 255), 2);
//
// }
// return ocv_mat2Img(imageGray);
// }
public static BufferedImage drawRectangle(BufferedImage img, int x, int y, int w, int h, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
//img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawRect(y, x, w, h);
g2d.dispose();
return img;
}
public static BufferedImage drawLine(BufferedImage img, int r1, int c1, int r2, int c2, int thickness, Color color) {
BufferedImage ret = null;
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.setStroke(new BasicStroke(thickness));
g2d.drawLine(c1, r1, c2, r2);
g2d.dispose();
return img;
}
final public static BufferedImage toNewColorSpace(BufferedImage image, int newType) {
BufferedImage ret = null;
try {
ret = new BufferedImage(
image.getWidth(),
image.getHeight(),
newType);
ColorConvertOp xformOp = new ColorConvertOp(null);
xformOp.filter(image, ret);
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
public static BufferedImage fillRectangle(BufferedImage img, int x, int y, int w, int h, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fillRect(y, x, w, h);
g2d.dispose();
return img;
}
public static BufferedImage draw3DRectangle(BufferedImage img, int x, int y, int w, int h, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.draw3DRect(y, x, w, h, true);
g2d.dispose();
return img;
}
public static BufferedImage fill3DRectangle(BufferedImage img, int x, int y, int w, int h, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fill3DRect(y, x, w, h, true);
g2d.dispose();
return img;
}
public static BufferedImage drawRoundRectangle(BufferedImage img, int x, int y, int w, int h, int arcw, int arch, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawRoundRect(y, x, w, h, arcw, arch);
g2d.dispose();
return img;
}
public static BufferedImage fillRoundRectangle(BufferedImage img, int x, int y, int w, int h, int arcw, int arch, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fillRoundRect(y, x, w, h, arcw, arch);
g2d.dispose();
return img;
}
public static BufferedImage drawOval(BufferedImage img, int x, int y, int w, int h, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawOval(y, x, w, h);
g2d.dispose();
return img;
}
public static BufferedImage drawShape(BufferedImage img, Shape p, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.draw(p);
g2d.dispose();
return img;
}
public static BufferedImage fillShape(BufferedImage img, Shape p, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fill(p);
g2d.dispose();
return img;
}
public static BufferedImage drawPolygon(BufferedImage img, Polygon p, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawPolygon(p);
g2d.dispose();
return img;
}
public static BufferedImage fillPolygon(BufferedImage img, Polygon p, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fillPolygon(p);
g2d.dispose();
return img;
}
public static BufferedImage drawArc(BufferedImage img, int x, int y, int w, int h, int startAngle, int arcAngle, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawArc(y, x, w, h, startAngle, arcAngle);
g2d.dispose();
return img;
}
public static BufferedImage drawPolyLine(BufferedImage img, int[] xPoints, int[] yPoints, int nPoints, int thickness, Color color) {
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setStroke(new BasicStroke(thickness));
g2d.setColor(color);
g2d.drawPolyline(yPoints, xPoints, nPoints);
g2d.dispose();
return img;
}
public static BufferedImage fillOval(BufferedImage img, int x, int y, int w, int h, Color color) {
BufferedImage ret = null;
if (img.getType() == BufferedImage.TYPE_BYTE_GRAY) {
img = toNewColorSpace(img, BufferedImage.TYPE_3BYTE_BGR);
}
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setColor(color);
g2d.fillOval(y, x, w, h);
g2d.dispose();
return img;
}
public static BufferedImage detectFaces(String type, BufferedImage img) {
String xml = "";
if (type.equals("haar")) {
xml = "etc\\haarcascades\\haarcascade_frontalface_alt.xml";
}
if (type.equals("lbp")) {
xml = "etc\\lbpcascades\\lbpcascade_frontalface.xml";
}
BufferedImage img2 = ImageProcess.clone(img);
CascadeClassifier faceDetector = new CascadeClassifier(xml);
Mat imageGray = ocv_img2Mat(img2);
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(imageGray, faceDetections);
for (Rect rect : faceDetections.toArray()) {
// Imgproc.rectangle(imageGray, new org.opencv.core.Point(rect.x, rect.y), new org.opencv.core.Point(rect.x + rect.width, rect.y + rect.height),
// new Scalar(0, 255, 255), 2);
drawRectangle(img, rect.y - (int) (rect.height * 0.1), rect.x, rect.width, rect.height + (int) (rect.height * 0.2), 1, Color.yellow);
}
// return ocv_mat2Img(imageGray);
return img;
}
public static BufferedImage detectFaces(String type, BufferedImage img, CRectangle r, boolean showRect) {
String xml = "";
if (type.equals("haar")) {
xml = "etc\\haarcascades\\haarcascade_frontalface_alt.xml";
}
if (type.equals("lbp")) {
xml = "etc\\lbpcascades\\lbpcascade_frontalface.xml";
}
BufferedImage img2 = ImageProcess.clone(img);
CascadeClassifier faceDetector = new CascadeClassifier(xml);
Mat imageGray = ocv_img2Mat(img2);
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(imageGray, faceDetections);
for (Rect rect : faceDetections.toArray()) {
// Imgproc.rectangle(imageGray, new org.opencv.core.Point(rect.x, rect.y), new org.opencv.core.Point(rect.x + rect.width, rect.y + rect.height),
// new Scalar(0, 255, 255), 2);
if (showRect) {
drawRectangle(img, rect.y - (int) (rect.height * 0.1), rect.x, rect.width, rect.height + (int) (rect.height * 0.2), 1, Color.yellow);
}
r.row = rect.y - (int) (rect.height * 0.1);
r.column = rect.x;
r.width = rect.width;
r.height = rect.height + (int) (rect.height * 0.2);
}
// return ocv_mat2Img(imageGray);
return img;
}
public static Rectangle[] getFacesRectangles(String type, BufferedImage img) {
String xml = "";
if (type.equals("haar")) {
xml = "etc\\haarcascades\\haarcascade_frontalface_alt.xml";
// xml = "etc\\haarcascades\\haarcascade_frontalface_alt_tree.xml";
}
if (type.equals("lbp")) {
xml = "etc\\lbpcascades\\lbpcascade_frontalface.xml";
}
BufferedImage img2 = ImageProcess.clone(img);
CascadeClassifier faceDetector = new CascadeClassifier(xml);
Mat imageGray = ocv_img2Mat(img2);
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(imageGray, faceDetections);
Rect[] rects = faceDetections.toArray();
Rectangle[] ret = new Rectangle[faceDetections.toArray().length];
for (int i = 0; i < rects.length; i++) {
Rect r = rects[i];
ret[i] = new Rectangle(r.x, r.y, r.width, r.height);
}
return ret;
}
public static CRectangle[] getFacesRectanglesAsCRectangle(String type, BufferedImage img) {
Rectangle[] rects=getFacesRectangles(type, img);
CRectangle[] ret=new CRectangle[rects.length];
for (int i = 0; i < ret.length; i++) {
ret[i]=new CRectangle(rects[i]);
}
return ret;
}
public static BufferedImage toARGB(BufferedImage image) {
return toNewColorSpace(image, BufferedImage.TYPE_INT_ARGB);
}
public static BufferedImage toBGR(BufferedImage image) {
return toNewColorSpace(image, BufferedImage.TYPE_3BYTE_BGR);
}
public static BufferedImage toGrayLevel(BufferedImage img) {
BufferedImage image = new BufferedImage(img.getWidth(), img.getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
Graphics g = image.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
return image;
// return toNewColorSpace(image, BufferedImage.TYPE_BYTE_GRAY);
// return pixelsToImageGray(imageToPixelsDouble(image));
}
public static BufferedImage toBinary(BufferedImage image) {
return toNewColorSpace(image, BufferedImage.TYPE_BYTE_BINARY);
}
public static BufferedImage flipVertical(BufferedImage image) {
AffineTransform at = new AffineTransform();
at.concatenate(AffineTransform.getScaleInstance(-1, 1));
at.concatenate(AffineTransform.getTranslateInstance(-image.getWidth(), 0));
BufferedImage bf = buildTransformed(image, at);
// BufferedImage bf = new BufferedImage(
// image.getWidth(), image.getHeight(),
// BufferedImage.TYPE_3BYTE_BGR);
// Graphics2D g = image.createGraphics();
// g.drawImage(image , 0,0,-image.getWidth(),image.getHeight(),null);
return bf;
}
public static BufferedImage flipHorizontal(BufferedImage image) {
AffineTransform at = new AffineTransform();
at.concatenate(AffineTransform.getScaleInstance(1, -1));
at.concatenate(AffineTransform.getTranslateInstance(0, -image.getHeight()));
return buildTransformed(image, at);
}
public static BufferedImage buildTransformed(BufferedImage image, AffineTransform at) {
BufferedImage newImage = new BufferedImage(
image.getWidth(), image.getHeight(),
BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = newImage.createGraphics();
g.transform(at);
g.drawImage(image, 0, 0, null);
g.dispose();
return newImage;
}
public static BufferedImage invertImage(BufferedImage image) {
if (image.getType() != BufferedImage.TYPE_INT_ARGB) {
image = toARGB(image);
}
LookupTable lookup = new LookupTable(0, 4) {
@Override
public int[] lookupPixel(int[] src, int[] dest) {
dest[0] = (int) (255 - src[0]);
dest[1] = (int) (255 - src[1]);
dest[2] = (int) (255 - src[2]);
return dest;
}
};
LookupOp op = new LookupOp(lookup, new RenderingHints(null));
return op.filter(image, null);
}
/**
* if location and size are not given overlayed image is positioned at 0,0
* white pixels are ignored through overlaying process
*
* @param bf
* @param overlay
* @return
*/
public static BufferedImage overlayImage(BufferedImage bf, BufferedImage overlay) {
int[][][] bfp = imageToPixelsColorInt(bf);
int[][][] ovp = imageToPixelsColorInt(overlay);
int r = ovp.length;
int c = ovp[0].length;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (ovp[i][j][0] != 255 || ovp[i][j][1] != 255 || ovp[i][j][2] != 255 || ovp[i][j][3] != 255) {
for (int k = 0; k < 4; k++) {
bfp[i][j][k] = ovp[i][j][k];
}
}
}
}
return pixelsToImageColor(bfp);
}
/**
* overlay image onto original image
*
* @param bf
* @param overlay
* @param rect
* @param bkg
* @return
*/
public static BufferedImage overlayImage(BufferedImage bf, BufferedImage overlay, CRectangle rect, int bkg) {
int[][][] bfp = imageToPixelsColorInt(bf);
int[][][] ovp = imageToPixelsColorInt(overlay);
int r1 = bfp.length;
int c1 = bfp[0].length;
int r = ovp.length;
int c = ovp[0].length;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
// if (ovp[i][j][0] != bkg || ovp[i][j][1] != bkg || ovp[i][j][2] != bkg || ovp[i][j][3] != bkg) {
if (ovp[i][j][1] != bkg || ovp[i][j][2] != bkg || ovp[i][j][3] != bkg) {
for (int k = 1; k < 4; k++) {
if (i + rect.row > 0 && j + rect.column > 0 && i + rect.row < r1 && j + rect.column < c1) {
bfp[i + rect.row][j + rect.column][k] = ovp[i][j][k];
}
}
}
}
}
return pixelsToImageColor(bfp);
}
public static BufferedImage overlayImage(BufferedImage bf, BufferedImage overlay, CPoint cp, int bkg) {
int[][][] bfp = imageToPixelsColorInt(bf);
int[][][] ovp = imageToPixelsColorInt(overlay);
int r1 = bfp.length;
int c1 = bfp[0].length;
int r = ovp.length;
int c = ovp[0].length;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (ovp[i][j][1] != bkg || ovp[i][j][2] != bkg || ovp[i][j][3] != bkg) {
for (int k = 1; k < 4; k++) {
if (i + cp.row > 0 && j + cp.column > 0 && i + cp.row < r1 && j + cp.column < c1) {
bfp[i + cp.row][j + cp.column][k] = ovp[i][j][k];
}
}
}
}
}
return pixelsToImageColor(bfp);
}
public static BufferedImage overlayImage(BufferedImage bgImage, BufferedImage fgImage, double alpha) {
int w = bgImage.getWidth();
int h = bgImage.getHeight();
BufferedImage newImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImg.createGraphics();
// Clear the image (optional)
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, w, h);
// Draw the background image
g.setComposite(AlphaComposite.SrcOver);
g.drawImage(bgImage, 0, 0, null);
// Draw the overlay image
g.setComposite(AlphaComposite.SrcOver.derive((float) alpha));
g.drawImage(fgImage, 0, 0, null);
g.dispose();
return newImg;
}
public static BufferedImage overlayImage(BufferedImage bgImage, BufferedImage fgImage, Point p, double alpha) {
int w = bgImage.getWidth();
int h = bgImage.getHeight();
BufferedImage newImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImg.createGraphics();
// Clear the image (optional)
g.setComposite(AlphaComposite.Clear);
g.fillRect(0, 0, w, h);
// Draw the background image
g.setComposite(AlphaComposite.SrcOver);
g.drawImage(bgImage, 0, 0, null);
// Draw the overlay image
g.setComposite(AlphaComposite.SrcOver.derive((float) alpha));
g.drawImage(fgImage, p.x, p.y, null);
g.dispose();
return newImg;
}
public static BufferedImage drawText(BufferedImage bf, String str, int x, int y, Color col) {
BufferedImage newImage = new BufferedImage(
bf.getWidth(), bf.getHeight(),
BufferedImage.TYPE_3BYTE_BGR);
Graphics2D gr = newImage.createGraphics();
gr.drawImage(bf, 0, 0, null);
gr.setColor(col);
gr.drawString(str, x, y);
gr.dispose();
return newImage;
}
public static BufferedImage adaptiveThreshold(double[][] d, int t1, int t2) {
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] >= t1 && d[i][j] <= t2) {
d[i][j] = 255;
} else {
d[i][j] = 0;
}
}
}
BufferedImage binarized = ImageProcess.pixelsToImageGray(d);
return binarized;
}
public static BufferedImage thresholdGray(BufferedImage img, int t1, int t2) {
double[][] d = imageToPixelsDouble(img);
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
if (d[i][j] >= t1 && d[i][j] < t2) {
d[i][j] = 255;
} else {
d[i][j] = 0;
}
}
}
BufferedImage binarized = ImageProcess.pixelsToImageGray(d);
return binarized;
}
public static BufferedImage thresholdHSV(BufferedImage bf, int h1, int h2, int s1, int s2, int v1, int v2) {
BufferedImage ret = null;
int[][] dh = imageToPixelsInt(rgb2gray(getHueChannel(bf)));
int[][] ds = imageToPixelsInt(rgb2gray(getSaturationChannel(bf)));
int[][] dv = imageToPixelsInt(rgb2gray(getValueChannel(bf)));
int nr = dh.length;
int nc = dh[0].length;
int[][] d = new int[nr][nc];
int h, s, v;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
h = dh[i][j];
s = ds[i][j];
v = dv[i][j];
if (h >= h1 && h <= h2 && s >= s1 && s <= s2 && v >= v1 && v <= v2) {
d[i][j] = 255;
}
}
}
ret = pixelsToImageGray(d);
return ret;
}
public static BufferedImage ocv_img2hsv(BufferedImage bf) {
// Mat frame = ImageProcess.ocv_img2Mat(bf);
// Mat hsvImage = new Mat();
// Imgproc.cvtColor(frame, hsvImage, Imgproc.COLOR_BGR2HSV);
// BufferedImage img = ocv_mat2Img(hsvImage);
// return img;
// return ocv_rgb2hsv(bf);
return ocv_2_hsv(bf);
}
public static BufferedImage ocv_rgb2hsv(BufferedImage bf) {
// Mat frame = ImageProcess.ocv_img2Mat(bf);
// Mat hsvImage = new Mat();
// // convert the frame to HSV
// Imgproc.cvtColor(frame, hsvImage, Imgproc.COLOR_BGR2HSV);
// BufferedImage img = ocv_mat2Img(hsvImage);
BufferedImage img = ocv_2_hsv(bf);
return img;
}
public static BufferedImage ocv_hsvThreshold(BufferedImage bf, int h1, int h2, int s1, int s2, int v1, int v2) {
Mat frame = ImageProcess.ocv_img2Mat(bf);
// Mat hsvImage = new Mat();
Mat mask = new Mat();
// convert the frame to HSV
// Imgproc.cvtColor(frame, hsvImage, Imgproc.COLOR_BGR2HSV);
// get thresholding values from the UI
Scalar minValues = new Scalar(h1, s1, v1);
Scalar maxValues = new Scalar(h2, s2, v2);
Core.inRange(frame, minValues, maxValues, mask);
BufferedImage img = ocv_mat2Img(mask);
return img;
}
public static BufferedImage ocv_2_hsv(BufferedImage img) {
Mat blurredImage = new Mat();
Mat hsvImage = new Mat();
Mat mask = new Mat();
Mat morphOutput = new Mat();
Mat frame = ImageProcess.ocv_img2Mat(img);
// remove some noise
Imgproc.blur(frame, blurredImage, new Size(7, 7));
// convert the frame to HSV
Imgproc.cvtColor(blurredImage, hsvImage, Imgproc.COLOR_BGR2HSV);
// get thresholding values from the UI
// remember: H ranges 0-180, S and V range 0-255
Scalar minValues = new Scalar(0, 150, 150);
Scalar maxValues = new Scalar(50, 255, 255);
// show the current selected HSV range
// String valuesToPrint = "Hue range: " + minValues.val[0] + "-" + maxValues.val[0]
// + "\tSaturation range: " + minValues.val[1] + "-" + maxValues.val[1] + "\tValue range: "
// + minValues.val[2] + "-" + maxValues.val[2];
// threshold HSV image to select tennis balls
Core.inRange(hsvImage, minValues, maxValues, mask);
BufferedImage bf = ImageProcess.ocv_mat2Img(hsvImage);
return bf;
}
public static BufferedImage ocv_medianFilter(BufferedImage bf) {
Mat frame = ImageProcess.ocv_img2Mat(bf);
Mat blurredImage = new Mat();
Imgproc.medianBlur(frame, blurredImage, 5);
BufferedImage out = ocv_mat2Img(blurredImage);
return out;
}
public static BufferedImage ocv_negativeImage(BufferedImage bf) {
Mat frame = ImageProcess.ocv_img2Mat(bf);
Mat negativeImage = new Mat();
Core.bitwise_not(frame, negativeImage);
BufferedImage out = ocv_mat2Img(negativeImage);
return out;
}
public static BufferedImage ocv_cloneImage(BufferedImage bf) {
Mat frame = ImageProcess.ocv_img2Mat(bf);
Mat cloneImage = frame.clone();
BufferedImage out = ocv_mat2Img(cloneImage);
return out;
}
public static BufferedImage cropBoundingBox(BufferedImage img) {
BufferedImage bf = clone(img);
int[][] d = imageToPixelsInt(img);
int nr = d.length;
int nc = d[0].length;
int left = nc, right = 0;
int top = nr, bottom = 0;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
if (d[i][j] > 0) {
if (left > j) {
left = j;
}
if (right < j) {
right = j;
}
if (top > i) {
top = i;
}
if (bottom < i) {
bottom = i;
}
}
}
}
bf = cropImage(bf, new CRectangle(top, left, right - left, bottom - top));
return bf;
}
public static CPoint getCenterPoint(BufferedImage img) {
CPoint cp = new CPoint();
cp.row = img.getHeight() / 2;
cp.column = img.getWidth() / 2;
return cp;
}
public static BufferedImage changeQuantizationLevel(BufferedImage image, int n) {
double[][] d = imageToPixelsDouble(image);
int nr = d.length;
int nc = d[0].length;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
}
}
return image;
}
public static BufferedImage equalizeHistogram(BufferedImage bi) {
int width = bi.getWidth();
int height = bi.getHeight();
int anzpixel = width * height;
int[] histogram = new int[256];
int[] iarray = new int[1];
int i = 0;
//read pixel intensities into histogram
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int valueBefore = bi.getRaster().getPixel(x, y, iarray)[0];
histogram[valueBefore]++;
}
}
int sum = 0;
// build a Lookup table LUT containing scale factor
float[] lut = new float[anzpixel];
for (i = 0; i < 256; ++i) {
sum += histogram[i];
lut[i] = sum * 255 / anzpixel;
}
// transform image using sum histogram as a Lookup table
for (int x = 1; x < width; x++) {
for (int y = 1; y < height; y++) {
int valueBefore = bi.getRaster().getPixel(x, y, iarray)[0];
int valueAfter = (int) lut[valueBefore];
iarray[0] = valueAfter;
bi.getRaster().setPixel(x, y, iarray);
}
}
return bi;
}
public static double[] getHuMoments(BufferedImage img) {
double[] moments = new double[7];
Mat imagenOriginal;
imagenOriginal = new Mat();
Mat binario;
binario = new Mat();
Mat Canny;
Canny = new Mat();
imagenOriginal = ImageProcess.ocv_img2Mat(img);
Mat gris = new Mat(imagenOriginal.width(), imagenOriginal.height(), imagenOriginal.type());
Imgproc.cvtColor(imagenOriginal, gris, Imgproc.COLOR_RGB2GRAY);
org.opencv.core.Size s = new Size(3, 3);
Imgproc.GaussianBlur(gris, gris, s, 2);
Imgproc.threshold(gris, binario, 100, 255, Imgproc.THRESH_BINARY);
Imgproc.Canny(gris, Canny, 50, 50 * 3);
java.util.List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarcy = new Mat();
Imgproc.findContours(Canny, contours, hierarcy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
Imgproc.drawContours(Canny, contours, -1, new Scalar(Math.random() * 255, Math.random() * 255, Math.random() * 255));
Moments p = new Moments();
java.util.List<Moments> nu = new ArrayList<Moments>(contours.size());
for (int i = 0; i < contours.size(); i++) {
nu.add(i, Imgproc.moments(contours.get(i), false));
p = nu.get(i);
}
double n20 = p.get_nu20(),
n02 = p.get_nu02(),
n30 = p.get_nu30(),
n12 = p.get_nu12(),
n21 = p.get_nu21(),
n03 = p.get_nu03(),
n11 = p.get_nu11();
//First moment
moments[0] = n20 + n02;
//Second moment
moments[1] = Math.pow((n20 - 02), 2) + Math.pow(2 * n11, 2);
//Third moment
moments[2] = Math.pow(n30 - (3 * (n12)), 2)
+ Math.pow((3 * n21 - n03), 2);
//Fourth moment
moments[3] = Math.pow((n30 + n12), 2) + Math.pow((n12 + n03), 2);
//Fifth moment
moments[4] = (n30 - 3 * n12) * (n30 + n12)
* (Math.pow((n30 + n12), 2) - 3 * Math.pow((n21 + n03), 2))
+ (3 * n21 - n03) * (n21 + n03)
* (3 * Math.pow((n30 + n12), 2) - Math.pow((n21 + n03), 2));
//Sixth moment
moments[5] = (n20 - n02)
* (Math.pow((n30 + n12), 2) - Math.pow((n21 + n03), 2))
+ 4 * n11 * (n30 + n12) * (n21 + n03);
//Seventh moment
moments[6] = (3 * n21 - n03) * (n30 + n12)
* (Math.pow((n30 + n12), 2) - 3 * Math.pow((n21 + n03), 2))
+ (n30 - 3 * n12) * (n21 + n03)
* (3 * Math.pow((n30 + n12), 2) - Math.pow((n21 + n03), 2));
// //Eighth moment
// moments[7] = n11 * (Math.pow((n30 + n12), 2) - Math.pow((n03 + n21), 2))
// - (n20 - n02) * (n30 + n12) * (n03 + n21);
return moments;
}
public static int[][] rgb2lab(int[][] img) {
int r = img.length;
int c = img[0].length;
int[][] ret = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
int val = img[i][j];
Color col = new Color(val, true);
int red = col.getRed();
int green = col.getGreen();
int blue = col.getBlue();
ColorSpaceLAB lab = ColorSpaceLAB.fromRGB(red, green, blue, 255);
}
}
return ret;
}
public static BufferedImage convertToBufferedImageTypes(BufferedImage img, int TYPE) {
BufferedImage convertedImg = new BufferedImage(img.getWidth(), img.getHeight(), TYPE);
convertedImg.getGraphics().drawImage(img, 0, 0, null);
return convertedImg;
}
}
| 149,291 | 0.52624 | 0.508137 | 4,056 | 35.799557 | 26.947159 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.883136 | false | false |
3
|
ae62bd85a4f9d3830072ce72ee34052308db53ce
| 26,139,170,976,288 |
0049b616606db8d20a8765fba3f1d845281b9761
|
/orange-talents-05-template-proposta-api/src/main/java/com/orangetalents/proposta/bloqueios/BloquearCartaoResponse.java
|
e2d94d8d3ebec6159f099bbeec7709fdfd5732e3
|
[
"Apache-2.0"
] |
permissive
|
aleszilagyi/orange-talents-05-template-proposta
|
https://github.com/aleszilagyi/orange-talents-05-template-proposta
|
78b465891152b645db940eb0954d0b280a7cbebc
|
8755eea99d1c17919f056f2f8cb7ba586811b152
|
refs/heads/main
| 2023-05-28T01:45:51.361000 | 2021-06-19T00:45:22 | 2021-06-19T00:45:22 | 373,314,588 | 1 | 0 |
Apache-2.0
| true | 2021-06-02T22:05:28 | 2021-06-02T22:05:28 | 2021-06-02T19:09:59 | 2021-05-05T17:04:44 | 5 | 0 | 0 | 0 | null | false | false |
package com.orangetalents.proposta.bloqueios;
import com.orangetalents.proposta.config.encrypt.EncryptEDecrypt;
import java.time.LocalDateTime;
public class BloquearCartaoResponse {
private String idCartao;
private String userId;
private StatusBloqueio statusBloqueio;
private LocalDateTime momentoCriaco;
private LocalDateTime ultimaAtualizacao;
public BloquearCartaoResponse(BloqueioCartao bloqueioCartao, EncryptEDecrypt encryptEDecrypt) {
this.idCartao = encryptEDecrypt.ofuscar(bloqueioCartao.getNumCartao());
this.userId = bloqueioCartao.getUserId();
this.statusBloqueio = bloqueioCartao.getStatusBloqueio();
this.momentoCriaco = bloqueioCartao.getMomentoCriaco();
this.ultimaAtualizacao =bloqueioCartao.getUltimaAtualizacao();
}
public String getIdCartao() {
return idCartao;
}
public String getUserId() {
return userId;
}
public StatusBloqueio getStatusBloqueio() {
return statusBloqueio;
}
public LocalDateTime getMomentoCriaco() {
return momentoCriaco;
}
public LocalDateTime getUltimaAtualizacao() {
return ultimaAtualizacao;
}
}
|
UTF-8
|
Java
| 1,199 |
java
|
BloquearCartaoResponse.java
|
Java
|
[] | null |
[] |
package com.orangetalents.proposta.bloqueios;
import com.orangetalents.proposta.config.encrypt.EncryptEDecrypt;
import java.time.LocalDateTime;
public class BloquearCartaoResponse {
private String idCartao;
private String userId;
private StatusBloqueio statusBloqueio;
private LocalDateTime momentoCriaco;
private LocalDateTime ultimaAtualizacao;
public BloquearCartaoResponse(BloqueioCartao bloqueioCartao, EncryptEDecrypt encryptEDecrypt) {
this.idCartao = encryptEDecrypt.ofuscar(bloqueioCartao.getNumCartao());
this.userId = bloqueioCartao.getUserId();
this.statusBloqueio = bloqueioCartao.getStatusBloqueio();
this.momentoCriaco = bloqueioCartao.getMomentoCriaco();
this.ultimaAtualizacao =bloqueioCartao.getUltimaAtualizacao();
}
public String getIdCartao() {
return idCartao;
}
public String getUserId() {
return userId;
}
public StatusBloqueio getStatusBloqueio() {
return statusBloqueio;
}
public LocalDateTime getMomentoCriaco() {
return momentoCriaco;
}
public LocalDateTime getUltimaAtualizacao() {
return ultimaAtualizacao;
}
}
| 1,199 | 0.730609 | 0.730609 | 42 | 27.547619 | 25.695286 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452381 | false | false |
3
|
92adb5631dfe10196caf08d723a95d11160ea436
| 17,987,323,047,915 |
bbb0fdf7b4dbf1b1e67cd3d23dfa4bd9e23c0990
|
/ex4/oop/ex4/crosswords/MyCrosswordVacantEntry.java
|
65a963c1ca8ab7406eae2c7a7deff0a324bbc555
|
[] |
no_license
|
yossimamo/hujioopex1
|
https://github.com/yossimamo/hujioopex1
|
4b1b1fc99da9e6335429f48ab8b52a0c0b9d8d56
|
3ae1d832f8128ad71358c7ee657968640498e812
|
refs/heads/master
| 2021-01-18T14:23:55.390000 | 2010-06-20T12:03:16 | 2010-06-20T12:03:16 | 32,140,450 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//###############
// FILE : MyCrosswordVacantEntry.java
// WRITER : Uri Greenberg, urig03, 021986039
// WRITER : Yossi Mamo, ymamo29, 038073722
// EXERCISE : oop ex4 2010
// DESCRIPTION: A crossword vacant entry is an empty entry (an entry you can
// put word in).
//###############
package oop.ex4.crosswords;
/**
* A crossword vacant entry is an empty entry (an entry you can
* put word in).
* @author Uri Greenberg and Yossi Mamo.
*
*/
public class MyCrosswordVacantEntry extends CrosswordVacantEntry {
// The position of the vacant entry.
private CrosswordPosition _position;
// The max capacity (length) of the vacant entry.
private int _maxCapacity;
/**
* Constructs a new vacant entry from a position and a max capacity.
* @param pos The position of the vacant entry.
* @param maxCapacity The max capacity of the vacant entry.
*/
public MyCrosswordVacantEntry(CrosswordPosition pos, int maxCapacity) {
_position = pos;
_maxCapacity = maxCapacity;
}
/**
* Returns the position of the vacant entry.
* @return The position of the vacant entry.
*/
public CrosswordPosition getPosition() {
return _position;
}
/**
* Returns the max capacity of the vacant entry.
* @return The max capacity of the vacant entry.
*/
public int getMaxCapacity() {
return _maxCapacity;
}
/**
* Compares this vacant entry to another. first by max capacity, then
* by the position (x,y,is vertical). returns a positive int if this
* vacant entry is "bigger" and a negative int if the other is "bigger".
* @param other another CrosswordVacantEntry.
*/
public int compareTo(CrosswordVacantEntry other) {
if (this._maxCapacity == other.getMaxCapacity()) {
if (this._position.getX() == other.getPosition().getX()) {
if (this._position.getY() == other.getPosition().getY()) {
if (this._position.isVertical() == other.getPosition().isVertical()) {
return 0;
} else {
return (this._position.isVertical() ? 1 : -1);
}
} else {
return (other.getPosition().getY() - this._position.getY());
}
} else {
return (other.getPosition().getX() - this._position.getX());
}
} else {
return (this._maxCapacity - other.getMaxCapacity());
}
}
/**
* For debugging purposes.
*/
public String toString() {
return String.format("<%d> (%d,%d) %s", _maxCapacity, _position.getX(), _position.getY(), _position.isVertical() ? "V" : "H");
}
}
|
UTF-8
|
Java
| 2,538 |
java
|
MyCrosswordVacantEntry.java
|
Java
|
[
{
"context": " FILE : MyCrosswordVacantEntry.java \r\n// WRITER : Uri Greenberg, urig03, 021986039 \r\n// WRITER : Yossi Mamo, yma",
"end": 87,
"score": 0.9998853802680969,
"start": 74,
"tag": "NAME",
"value": "Uri Greenberg"
},
{
"context": "wordVacantEntry.java \r\n// WRITER : Uri Greenberg, urig03, 021986039 \r\n// WRITER : Yossi Mamo, ymamo29, 03",
"end": 95,
"score": 0.9994484186172485,
"start": 89,
"tag": "USERNAME",
"value": "urig03"
},
{
"context": " : Uri Greenberg, urig03, 021986039 \r\n// WRITER : Yossi Mamo, ymamo29, 038073722\r\n// EXERCISE : oop ex4 2010 ",
"end": 132,
"score": 0.9998122453689575,
"start": 122,
"tag": "NAME",
"value": "Yossi Mamo"
},
{
"context": "berg, urig03, 021986039 \r\n// WRITER : Yossi Mamo, ymamo29, 038073722\r\n// EXERCISE : oop ex4 2010 \r\n// DESC",
"end": 141,
"score": 0.999438464641571,
"start": 134,
"tag": "USERNAME",
"value": "ymamo29"
},
{
"context": "y (an entry you can \r\n * put word in).\r\n * @author Uri Greenberg and Yossi Mamo.\r\n *\r\n */\r\npublic class MyCrosswor",
"end": 446,
"score": 0.9998968243598938,
"start": 433,
"tag": "NAME",
"value": "Uri Greenberg"
},
{
"context": "n \r\n * put word in).\r\n * @author Uri Greenberg and Yossi Mamo.\r\n *\r\n */\r\npublic class MyCrosswordVacantEntry ex",
"end": 461,
"score": 0.99989253282547,
"start": 451,
"tag": "NAME",
"value": "Yossi Mamo"
}
] | null |
[] |
//###############
// FILE : MyCrosswordVacantEntry.java
// WRITER : <NAME>, urig03, 021986039
// WRITER : <NAME>, ymamo29, 038073722
// EXERCISE : oop ex4 2010
// DESCRIPTION: A crossword vacant entry is an empty entry (an entry you can
// put word in).
//###############
package oop.ex4.crosswords;
/**
* A crossword vacant entry is an empty entry (an entry you can
* put word in).
* @author <NAME> and <NAME>.
*
*/
public class MyCrosswordVacantEntry extends CrosswordVacantEntry {
// The position of the vacant entry.
private CrosswordPosition _position;
// The max capacity (length) of the vacant entry.
private int _maxCapacity;
/**
* Constructs a new vacant entry from a position and a max capacity.
* @param pos The position of the vacant entry.
* @param maxCapacity The max capacity of the vacant entry.
*/
public MyCrosswordVacantEntry(CrosswordPosition pos, int maxCapacity) {
_position = pos;
_maxCapacity = maxCapacity;
}
/**
* Returns the position of the vacant entry.
* @return The position of the vacant entry.
*/
public CrosswordPosition getPosition() {
return _position;
}
/**
* Returns the max capacity of the vacant entry.
* @return The max capacity of the vacant entry.
*/
public int getMaxCapacity() {
return _maxCapacity;
}
/**
* Compares this vacant entry to another. first by max capacity, then
* by the position (x,y,is vertical). returns a positive int if this
* vacant entry is "bigger" and a negative int if the other is "bigger".
* @param other another CrosswordVacantEntry.
*/
public int compareTo(CrosswordVacantEntry other) {
if (this._maxCapacity == other.getMaxCapacity()) {
if (this._position.getX() == other.getPosition().getX()) {
if (this._position.getY() == other.getPosition().getY()) {
if (this._position.isVertical() == other.getPosition().isVertical()) {
return 0;
} else {
return (this._position.isVertical() ? 1 : -1);
}
} else {
return (other.getPosition().getY() - this._position.getY());
}
} else {
return (other.getPosition().getX() - this._position.getX());
}
} else {
return (this._maxCapacity - other.getMaxCapacity());
}
}
/**
* For debugging purposes.
*/
public String toString() {
return String.format("<%d> (%d,%d) %s", _maxCapacity, _position.getX(), _position.getY(), _position.isVertical() ? "V" : "H");
}
}
| 2,516 | 0.636328 | 0.624114 | 85 | 27.858824 | 27.065565 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.694118 | false | false |
3
|
5a9354bbb01008adb4d2da2c5cabd626f9862770
| 30,562,987,289,546 |
c8d0e3f2d66869c95f60fde236588db1cfe344a7
|
/appcheck_spi/src/main/java/appcheck/defaultcheckers/AbstractRemoteEJBLookupChecker.java
|
eff36f8c6bcc3fff8ccc1e171a6f173c34c898f2
|
[] |
no_license
|
brunocarneiro/appcheck
|
https://github.com/brunocarneiro/appcheck
|
8a7643bf42f392c5521af4c28d07ca7357ab2e06
|
4c0463e3d159cf79aaa289400ec1dd117a69061a
|
refs/heads/master
| 2021-01-13T01:41:31.927000 | 2015-08-27T13:51:32 | 2015-08-27T13:51:32 | 41,489,343 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package appcheck.defaultcheckers;
import java.io.PrintWriter;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import appcheck.ComponentChecker;
/**
* Checa configuracao de JNDIs para EJB's.
* @author bruno.carneiro
*
*/
public abstract class AbstractRemoteEJBLookupChecker implements ComponentChecker {
@Override
public void check(PrintWriter out) throws Exception {
Map <String, Class<?>> jndisClass = getJNDIClassMap();
for(String jndi : jndisClass.keySet()){
out.println(" Vai fazer lookup de: "+jndi+", para a classe "+jndisClass.get(jndi));
try{
lookup(jndi, jndisClass.get(jndi));
out.println(" Ok!");
}catch(Exception e){
out.println(" Erro!");
e.printStackTrace(out);
}
}
}
protected void lookup(String jndi, Class<?> castClass) throws NamingException {
InitialContext context= new InitialContext();
Object object = context.lookup(jndi);
javax.rmi.PortableRemoteObject.narrow(object, castClass);
}
@Override
public String getDescription() {
return "AbstractRemoteEJBLookupChecker - Checa configuracao de JNDIs para EJB's.";
}
public abstract Map <String, Class<?>> getJNDIClassMap();
}
|
UTF-8
|
Java
| 1,216 |
java
|
AbstractRemoteEJBLookupChecker.java
|
Java
|
[
{
"context": "Checa configuracao de JNDIs para EJB's.\n * @author bruno.carneiro\n *\n */\npublic abstract class AbstractRemoteEJBLoo",
"end": 268,
"score": 0.9945445656776428,
"start": 254,
"tag": "NAME",
"value": "bruno.carneiro"
}
] | null |
[] |
package appcheck.defaultcheckers;
import java.io.PrintWriter;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import appcheck.ComponentChecker;
/**
* Checa configuracao de JNDIs para EJB's.
* @author bruno.carneiro
*
*/
public abstract class AbstractRemoteEJBLookupChecker implements ComponentChecker {
@Override
public void check(PrintWriter out) throws Exception {
Map <String, Class<?>> jndisClass = getJNDIClassMap();
for(String jndi : jndisClass.keySet()){
out.println(" Vai fazer lookup de: "+jndi+", para a classe "+jndisClass.get(jndi));
try{
lookup(jndi, jndisClass.get(jndi));
out.println(" Ok!");
}catch(Exception e){
out.println(" Erro!");
e.printStackTrace(out);
}
}
}
protected void lookup(String jndi, Class<?> castClass) throws NamingException {
InitialContext context= new InitialContext();
Object object = context.lookup(jndi);
javax.rmi.PortableRemoteObject.narrow(object, castClass);
}
@Override
public String getDescription() {
return "AbstractRemoteEJBLookupChecker - Checa configuracao de JNDIs para EJB's.";
}
public abstract Map <String, Class<?>> getJNDIClassMap();
}
| 1,216 | 0.725329 | 0.725329 | 49 | 23.816326 | 25.544418 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.714286 | false | false |
3
|
87356fd59553c4c88602e68f025ac2576fed0718
| 30,562,987,290,365 |
12c453642784a3359363e33c007d5a5abdae9e4a
|
/container/org/fdesigner/container/internal/hookregistry/HookRegistry.java
|
c895dd98c3294392faabcfc83a9bad0c9ee54398
|
[] |
no_license
|
WeControlTheFuture/fdesigner
|
https://github.com/WeControlTheFuture/fdesigner
|
51e56b6d1935f176b23ebaf42119be4ef57e3bec
|
84483c2f112c8d67ecdf61e9259c1c5556d398c4
|
refs/heads/master
| 2020-09-24T13:44:01.238000 | 2019-12-13T01:21:40 | 2019-12-13T01:21:40 | 225,771,252 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*******************************************************************************
* Copyright (c) 2005, 2016 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.fdesigner.container.internal.hookregistry;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import org.fdesigner.container.internal.cds.CDSHookConfigurator;
import org.fdesigner.container.internal.framework.EquinoxConfiguration;
import org.fdesigner.container.internal.framework.EquinoxContainer;
import org.fdesigner.container.internal.hooks.DevClassLoadingHook;
import org.fdesigner.container.internal.hooks.EclipseLazyStarter;
import org.fdesigner.container.internal.signedcontent.SignedBundleHook;
import org.fdesigner.container.internal.weaving.WeavingHookConfigurator;
import org.fdesigner.supplement.framework.log.FrameworkLogEntry;
import org.fdesigner.supplement.util.ManifestElement;
/**
* The hook registry is used to store all the hooks which are
* configured by the hook configurators.
* @see HookConfigurator
*/
public final class HookRegistry {
/**
* The hook configurators properties file ("hookconfigurators.properties") <p>
* A framework extension may supply a hook configurators properties file to specify a
* list of hook configurators.
* @see #HOOK_CONFIGURATORS
*/
public static final String HOOK_CONFIGURATORS_FILE = "hookconfigurators.properties"; //$NON-NLS-1$
/**
* The hook configurators property key ("hookconfigurators.properties") used in
* a hook configurators properties file to specify a comma separated list of fully
* qualified hook configurator classes.
*/
public static final String HOOK_CONFIGURATORS = "hook.configurators"; //$NON-NLS-1$
/**
* A system property ("osgi.hook.configurators.include") used to add additional
* hook configurators. This is helpful for configuring optional hook configurators.
*/
public static final String PROP_HOOK_CONFIGURATORS_INCLUDE = "osgi.hook.configurators.include"; //$NON-NLS-1$
/**
* A system property ("osgi.hook.configurators.exclude") used to exclude
* any hook configurators. This is helpful for disabling hook
* configurators that is specified in hook configurator properties files.
*/
public static final String PROP_HOOK_CONFIGURATORS_EXCLUDE = "osgi.hook.configurators.exclude"; //$NON-NLS-1$
/**
* A system property ("osgi.hook.configurators") used to specify the list
* of hook configurators. If this property is set then the list of configurators
* specified will be the only configurators used.
*/
public static final String PROP_HOOK_CONFIGURATORS = "osgi.hook.configurators"; //$NON-NLS-1$
private static final String BUILTIN_HOOKS = "builtin.hooks"; //$NON-NLS-1$
private final EquinoxContainer container;
private volatile boolean initialized = false;
private final List<ClassLoaderHook> classLoaderHooks = new ArrayList<>();
private final List<ClassLoaderHook> classLoaderHooksRO = Collections.unmodifiableList(classLoaderHooks);
private final List<StorageHookFactory<?, ?, ?>> storageHookFactories = new ArrayList<>();
private final List<StorageHookFactory<?, ?, ?>> storageHookFactoriesRO = Collections.unmodifiableList(storageHookFactories);
private final List<BundleFileWrapperFactoryHook> bundleFileWrapperFactoryHooks = new ArrayList<>();
private final List<BundleFileWrapperFactoryHook> bundleFileWrapperFactoryHooksRO = Collections.unmodifiableList(bundleFileWrapperFactoryHooks);
private final List<ActivatorHookFactory> activatorHookFactories = new ArrayList<>();
private final List<ActivatorHookFactory> activatorHookFactoriesRO = Collections.unmodifiableList(activatorHookFactories);
public HookRegistry(EquinoxContainer container) {
this.container = container;
}
/**
* Initializes the hook configurators. The following steps are used to initialize the hook configurators. <p>
* 1. Get a list of hook configurators from all hook configurators properties files on the classpath,
* add this list to the overall list of hook configurators, remove duplicates. <p>
* 2. Get a list of hook configurators from the ("osgi.hook.configurators.include") system property
* and add this list to the overall list of hook configurators, remove duplicates. <p>
* 3. Get a list of hook configurators from the ("osgi.hook.configurators.exclude") system property
* and remove this list from the overall list of hook configurators. <p>
* 4. Load each hook configurator class, create a new instance, then call the {@link HookConfigurator#addHooks(HookRegistry)} method <p>
* 5. Set this HookRegistry object to read only to prevent any other hooks from being added. <p>
*/
public void initialize() {
List<String> configurators = new ArrayList<>(5);
List<FrameworkLogEntry> errors = new ArrayList<>(0); // optimistic that no errors will occur
mergeFileHookConfigurators(configurators, errors);
mergePropertyHookConfigurators(configurators);
synchronized (this) {
addClassLoaderHook(new DevClassLoadingHook(container.getConfiguration()));
addClassLoaderHook(new EclipseLazyStarter(container));
addClassLoaderHook(new WeavingHookConfigurator(container));
configurators.add(SignedBundleHook.class.getName());
configurators.add(CDSHookConfigurator.class.getName());
loadConfigurators(configurators, errors);
// set to read-only
initialized = true;
}
for (FrameworkLogEntry error : errors) {
container.getLogServices().getFrameworkLog().log(error);
}
}
private void mergeFileHookConfigurators(List<String> configuratorList, List<FrameworkLogEntry> errors) {
ClassLoader cl = getClass().getClassLoader();
// get all hook configurators files in your classloader delegation
Enumeration<URL> hookConfigurators;
try {
hookConfigurators = cl != null ? cl.getResources(HookRegistry.HOOK_CONFIGURATORS_FILE) : ClassLoader.getSystemResources(HookRegistry.HOOK_CONFIGURATORS_FILE);
} catch (IOException e) {
errors.add(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, "getResources error on " + HookRegistry.HOOK_CONFIGURATORS_FILE, 0, e, null)); //$NON-NLS-1$
return;
}
int curBuiltin = 0;
while (hookConfigurators.hasMoreElements()) {
URL url = hookConfigurators.nextElement();
InputStream input = null;
try {
// check each file for a hook.configurators property
Properties configuratorProps = new Properties();
input = url.openStream();
configuratorProps.load(input);
String hooksValue = configuratorProps.getProperty(HOOK_CONFIGURATORS);
if (hooksValue == null)
continue;
boolean builtin = Boolean.valueOf(configuratorProps.getProperty(BUILTIN_HOOKS)).booleanValue();
String[] configurators = ManifestElement.getArrayFromList(hooksValue, ","); //$NON-NLS-1$
for (String configurator : configurators) {
if (!configuratorList.contains(configurator)) {
if (builtin) {
configuratorList.add(curBuiltin++, configurator);
} else {
configuratorList.add(configurator);
}
}
}
} catch (IOException e) {
errors.add(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, "error loading: " + url.toExternalForm(), 0, e, null)); //$NON-NLS-1$
// ignore and continue to next URL
} finally {
if (input != null)
try {
input.close();
} catch (IOException e) {
// do nothing
}
}
}
}
private void mergePropertyHookConfigurators(List<String> configuratorList) {
// see if there is a configurators list
String[] configurators = ManifestElement.getArrayFromList(container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS), ","); //$NON-NLS-1$
if (configurators.length > 0) {
configuratorList.clear(); // clear the list, we are only going to use the configurators from the list
for (String configurator : configurators) {
if (!configuratorList.contains(configurator)) {
configuratorList.add(configurator);
}
}
return; // don't do anything else
}
// Make sure the configurators from the include property are in the list
String[] includeConfigurators = ManifestElement.getArrayFromList(container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS_INCLUDE), ","); //$NON-NLS-1$
for (String includeConfigurator : includeConfigurators) {
if (!configuratorList.contains(includeConfigurator)) {
configuratorList.add(includeConfigurator);
}
}
// Make sure the configurators from the exclude property are no in the list
String[] excludeHooks = ManifestElement.getArrayFromList(container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS_EXCLUDE), ","); //$NON-NLS-1$
for (String excludeHook : excludeHooks) {
configuratorList.remove(excludeHook);
}
}
private void loadConfigurators(List<String> configurators, List<FrameworkLogEntry> errors) {
for (String hookName : configurators) {
try {
Class<?> clazz = Class.forName(hookName);
HookConfigurator configurator = (HookConfigurator) clazz.getConstructor().newInstance();
configurator.addHooks(this);
} catch (Throwable t) {
// We expect the follow exeptions may happen; but we need to catch all here
// ClassNotFoundException
// IllegalAccessException
// InstantiationException
// ClassCastException
errors.add(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, "error loading hook: " + hookName, 0, t, null)); //$NON-NLS-1$
}
}
}
/**
* Returns the list of configured class loading hooks.
* @return the list of configured class loading hooks.
*/
public List<ClassLoaderHook> getClassLoaderHooks() {
return classLoaderHooksRO;
}
/**
* Returns the list of configured storage hooks.
* @return the list of configured storage hooks.
*/
public List<StorageHookFactory<?, ?, ?>> getStorageHookFactories() {
return storageHookFactoriesRO;
}
/**
* Returns the configured bundle file wrapper factories
* @return the configured bundle file wrapper factories
*/
public List<BundleFileWrapperFactoryHook> getBundleFileWrapperFactoryHooks() {
return bundleFileWrapperFactoryHooksRO;
}
/**
* Returns the configured activator hook factories
* @return the configured activator hook factories
*/
public List<ActivatorHookFactory> getActivatorHookFactories() {
return activatorHookFactoriesRO;
}
private <H> void add(H hook, List<H> hooks) {
if (initialized)
throw new IllegalStateException("Cannot add hooks dynamically."); //$NON-NLS-1$
hooks.add(hook);
}
/**
* Adds a class loader hook to this hook registry.
* @param classLoaderHook a class loading hook object.
*/
public void addClassLoaderHook(ClassLoaderHook classLoaderHook) {
add(classLoaderHook, classLoaderHooks);
}
/**
* Adds a storage hook to this hook registry.
* @param storageHookFactory a storage hook object.
*/
public void addStorageHookFactory(StorageHookFactory<?, ?, ?> storageHookFactory) {
add(storageHookFactory, storageHookFactories);
}
/**
* Adds a bundle file wrapper factory for this hook registry
* @param factory a bundle file wrapper factory object.
*/
public void addBundleFileWrapperFactoryHook(BundleFileWrapperFactoryHook factory) {
add(factory, bundleFileWrapperFactoryHooks);
}
/**
* Adds an activator hook factory. The activators created by this factory will be started and stopped
* when the system bundle is started and stopped.
* @param activatorHookFactory the activator hook factory.
*/
public void addActivatorHookFactory(ActivatorHookFactory activatorHookFactory) {
add(activatorHookFactory, activatorHookFactories);
}
/**
* Returns the configuration associated with this hook registry.
* @return the configuration associated with this hook registry.
*/
public EquinoxConfiguration getConfiguration() {
return container.getConfiguration();
}
/**
* Returns the equinox container associated with this hook registry.
* @return the equinox container associated with this hook registry.
*/
public EquinoxContainer getContainer() {
return container;
}
}
|
UTF-8
|
Java
| 12,745 |
java
|
HookRegistry.java
|
Java
|
[] | null |
[] |
/*******************************************************************************
* Copyright (c) 2005, 2016 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.fdesigner.container.internal.hookregistry;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import org.fdesigner.container.internal.cds.CDSHookConfigurator;
import org.fdesigner.container.internal.framework.EquinoxConfiguration;
import org.fdesigner.container.internal.framework.EquinoxContainer;
import org.fdesigner.container.internal.hooks.DevClassLoadingHook;
import org.fdesigner.container.internal.hooks.EclipseLazyStarter;
import org.fdesigner.container.internal.signedcontent.SignedBundleHook;
import org.fdesigner.container.internal.weaving.WeavingHookConfigurator;
import org.fdesigner.supplement.framework.log.FrameworkLogEntry;
import org.fdesigner.supplement.util.ManifestElement;
/**
* The hook registry is used to store all the hooks which are
* configured by the hook configurators.
* @see HookConfigurator
*/
public final class HookRegistry {
/**
* The hook configurators properties file ("hookconfigurators.properties") <p>
* A framework extension may supply a hook configurators properties file to specify a
* list of hook configurators.
* @see #HOOK_CONFIGURATORS
*/
public static final String HOOK_CONFIGURATORS_FILE = "hookconfigurators.properties"; //$NON-NLS-1$
/**
* The hook configurators property key ("hookconfigurators.properties") used in
* a hook configurators properties file to specify a comma separated list of fully
* qualified hook configurator classes.
*/
public static final String HOOK_CONFIGURATORS = "hook.configurators"; //$NON-NLS-1$
/**
* A system property ("osgi.hook.configurators.include") used to add additional
* hook configurators. This is helpful for configuring optional hook configurators.
*/
public static final String PROP_HOOK_CONFIGURATORS_INCLUDE = "osgi.hook.configurators.include"; //$NON-NLS-1$
/**
* A system property ("osgi.hook.configurators.exclude") used to exclude
* any hook configurators. This is helpful for disabling hook
* configurators that is specified in hook configurator properties files.
*/
public static final String PROP_HOOK_CONFIGURATORS_EXCLUDE = "osgi.hook.configurators.exclude"; //$NON-NLS-1$
/**
* A system property ("osgi.hook.configurators") used to specify the list
* of hook configurators. If this property is set then the list of configurators
* specified will be the only configurators used.
*/
public static final String PROP_HOOK_CONFIGURATORS = "osgi.hook.configurators"; //$NON-NLS-1$
private static final String BUILTIN_HOOKS = "builtin.hooks"; //$NON-NLS-1$
private final EquinoxContainer container;
private volatile boolean initialized = false;
private final List<ClassLoaderHook> classLoaderHooks = new ArrayList<>();
private final List<ClassLoaderHook> classLoaderHooksRO = Collections.unmodifiableList(classLoaderHooks);
private final List<StorageHookFactory<?, ?, ?>> storageHookFactories = new ArrayList<>();
private final List<StorageHookFactory<?, ?, ?>> storageHookFactoriesRO = Collections.unmodifiableList(storageHookFactories);
private final List<BundleFileWrapperFactoryHook> bundleFileWrapperFactoryHooks = new ArrayList<>();
private final List<BundleFileWrapperFactoryHook> bundleFileWrapperFactoryHooksRO = Collections.unmodifiableList(bundleFileWrapperFactoryHooks);
private final List<ActivatorHookFactory> activatorHookFactories = new ArrayList<>();
private final List<ActivatorHookFactory> activatorHookFactoriesRO = Collections.unmodifiableList(activatorHookFactories);
public HookRegistry(EquinoxContainer container) {
this.container = container;
}
/**
* Initializes the hook configurators. The following steps are used to initialize the hook configurators. <p>
* 1. Get a list of hook configurators from all hook configurators properties files on the classpath,
* add this list to the overall list of hook configurators, remove duplicates. <p>
* 2. Get a list of hook configurators from the ("osgi.hook.configurators.include") system property
* and add this list to the overall list of hook configurators, remove duplicates. <p>
* 3. Get a list of hook configurators from the ("osgi.hook.configurators.exclude") system property
* and remove this list from the overall list of hook configurators. <p>
* 4. Load each hook configurator class, create a new instance, then call the {@link HookConfigurator#addHooks(HookRegistry)} method <p>
* 5. Set this HookRegistry object to read only to prevent any other hooks from being added. <p>
*/
public void initialize() {
List<String> configurators = new ArrayList<>(5);
List<FrameworkLogEntry> errors = new ArrayList<>(0); // optimistic that no errors will occur
mergeFileHookConfigurators(configurators, errors);
mergePropertyHookConfigurators(configurators);
synchronized (this) {
addClassLoaderHook(new DevClassLoadingHook(container.getConfiguration()));
addClassLoaderHook(new EclipseLazyStarter(container));
addClassLoaderHook(new WeavingHookConfigurator(container));
configurators.add(SignedBundleHook.class.getName());
configurators.add(CDSHookConfigurator.class.getName());
loadConfigurators(configurators, errors);
// set to read-only
initialized = true;
}
for (FrameworkLogEntry error : errors) {
container.getLogServices().getFrameworkLog().log(error);
}
}
private void mergeFileHookConfigurators(List<String> configuratorList, List<FrameworkLogEntry> errors) {
ClassLoader cl = getClass().getClassLoader();
// get all hook configurators files in your classloader delegation
Enumeration<URL> hookConfigurators;
try {
hookConfigurators = cl != null ? cl.getResources(HookRegistry.HOOK_CONFIGURATORS_FILE) : ClassLoader.getSystemResources(HookRegistry.HOOK_CONFIGURATORS_FILE);
} catch (IOException e) {
errors.add(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, "getResources error on " + HookRegistry.HOOK_CONFIGURATORS_FILE, 0, e, null)); //$NON-NLS-1$
return;
}
int curBuiltin = 0;
while (hookConfigurators.hasMoreElements()) {
URL url = hookConfigurators.nextElement();
InputStream input = null;
try {
// check each file for a hook.configurators property
Properties configuratorProps = new Properties();
input = url.openStream();
configuratorProps.load(input);
String hooksValue = configuratorProps.getProperty(HOOK_CONFIGURATORS);
if (hooksValue == null)
continue;
boolean builtin = Boolean.valueOf(configuratorProps.getProperty(BUILTIN_HOOKS)).booleanValue();
String[] configurators = ManifestElement.getArrayFromList(hooksValue, ","); //$NON-NLS-1$
for (String configurator : configurators) {
if (!configuratorList.contains(configurator)) {
if (builtin) {
configuratorList.add(curBuiltin++, configurator);
} else {
configuratorList.add(configurator);
}
}
}
} catch (IOException e) {
errors.add(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, "error loading: " + url.toExternalForm(), 0, e, null)); //$NON-NLS-1$
// ignore and continue to next URL
} finally {
if (input != null)
try {
input.close();
} catch (IOException e) {
// do nothing
}
}
}
}
private void mergePropertyHookConfigurators(List<String> configuratorList) {
// see if there is a configurators list
String[] configurators = ManifestElement.getArrayFromList(container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS), ","); //$NON-NLS-1$
if (configurators.length > 0) {
configuratorList.clear(); // clear the list, we are only going to use the configurators from the list
for (String configurator : configurators) {
if (!configuratorList.contains(configurator)) {
configuratorList.add(configurator);
}
}
return; // don't do anything else
}
// Make sure the configurators from the include property are in the list
String[] includeConfigurators = ManifestElement.getArrayFromList(container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS_INCLUDE), ","); //$NON-NLS-1$
for (String includeConfigurator : includeConfigurators) {
if (!configuratorList.contains(includeConfigurator)) {
configuratorList.add(includeConfigurator);
}
}
// Make sure the configurators from the exclude property are no in the list
String[] excludeHooks = ManifestElement.getArrayFromList(container.getConfiguration().getConfiguration(HookRegistry.PROP_HOOK_CONFIGURATORS_EXCLUDE), ","); //$NON-NLS-1$
for (String excludeHook : excludeHooks) {
configuratorList.remove(excludeHook);
}
}
private void loadConfigurators(List<String> configurators, List<FrameworkLogEntry> errors) {
for (String hookName : configurators) {
try {
Class<?> clazz = Class.forName(hookName);
HookConfigurator configurator = (HookConfigurator) clazz.getConstructor().newInstance();
configurator.addHooks(this);
} catch (Throwable t) {
// We expect the follow exeptions may happen; but we need to catch all here
// ClassNotFoundException
// IllegalAccessException
// InstantiationException
// ClassCastException
errors.add(new FrameworkLogEntry(EquinoxContainer.NAME, FrameworkLogEntry.ERROR, 0, "error loading hook: " + hookName, 0, t, null)); //$NON-NLS-1$
}
}
}
/**
* Returns the list of configured class loading hooks.
* @return the list of configured class loading hooks.
*/
public List<ClassLoaderHook> getClassLoaderHooks() {
return classLoaderHooksRO;
}
/**
* Returns the list of configured storage hooks.
* @return the list of configured storage hooks.
*/
public List<StorageHookFactory<?, ?, ?>> getStorageHookFactories() {
return storageHookFactoriesRO;
}
/**
* Returns the configured bundle file wrapper factories
* @return the configured bundle file wrapper factories
*/
public List<BundleFileWrapperFactoryHook> getBundleFileWrapperFactoryHooks() {
return bundleFileWrapperFactoryHooksRO;
}
/**
* Returns the configured activator hook factories
* @return the configured activator hook factories
*/
public List<ActivatorHookFactory> getActivatorHookFactories() {
return activatorHookFactoriesRO;
}
private <H> void add(H hook, List<H> hooks) {
if (initialized)
throw new IllegalStateException("Cannot add hooks dynamically."); //$NON-NLS-1$
hooks.add(hook);
}
/**
* Adds a class loader hook to this hook registry.
* @param classLoaderHook a class loading hook object.
*/
public void addClassLoaderHook(ClassLoaderHook classLoaderHook) {
add(classLoaderHook, classLoaderHooks);
}
/**
* Adds a storage hook to this hook registry.
* @param storageHookFactory a storage hook object.
*/
public void addStorageHookFactory(StorageHookFactory<?, ?, ?> storageHookFactory) {
add(storageHookFactory, storageHookFactories);
}
/**
* Adds a bundle file wrapper factory for this hook registry
* @param factory a bundle file wrapper factory object.
*/
public void addBundleFileWrapperFactoryHook(BundleFileWrapperFactoryHook factory) {
add(factory, bundleFileWrapperFactoryHooks);
}
/**
* Adds an activator hook factory. The activators created by this factory will be started and stopped
* when the system bundle is started and stopped.
* @param activatorHookFactory the activator hook factory.
*/
public void addActivatorHookFactory(ActivatorHookFactory activatorHookFactory) {
add(activatorHookFactory, activatorHookFactories);
}
/**
* Returns the configuration associated with this hook registry.
* @return the configuration associated with this hook registry.
*/
public EquinoxConfiguration getConfiguration() {
return container.getConfiguration();
}
/**
* Returns the equinox container associated with this hook registry.
* @return the equinox container associated with this hook registry.
*/
public EquinoxContainer getContainer() {
return container;
}
}
| 12,745 | 0.746018 | 0.742644 | 301 | 41.342194 | 38.652115 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.112957 | false | false |
3
|
30820e68ba0fd809360fef0895c3548b47d2e012
| 10,445,360,521,317 |
f989c40a4906aaf47de053e5a4760679f02ca397
|
/GUI Swing/ContactEditor/src/my/contacteditor/ContactEditorUI.java
|
679ef20f2b5627eab28c9995c4e3df2f480ea811
|
[] |
no_license
|
DouglasRauschkolb/Programacao-Orientada-a-Objetos-II
|
https://github.com/DouglasRauschkolb/Programacao-Orientada-a-Objetos-II
|
9a5147ab8c52ed1bdbd55e5329c5c01f7441d330
|
3d30c3fa31635e967e4363b17380440d88f31372
|
refs/heads/master
| 2023-01-19T03:33:08.865000 | 2020-12-02T02:50:01 | 2020-12-02T02:50:01 | 243,113,373 | 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 my.contacteditor;
/**
*
* @author douglas
*/
public class ContactEditorUI extends javax.swing.JFrame {
/**
* Creates new form ContactEditorUI
*/
public ContactEditorUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
javax.swing.JTextField first_name = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
last_name = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
title = new javax.swing.JTextField();
nickname = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
display_format = new javax.swing.JComboBox<>();
jPanel2 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
email_address = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
list = new javax.swing.JList<>();
add_button = new javax.swing.JButton();
edit_button = new javax.swing.JButton();
remove_button = new javax.swing.JButton();
as_default_button = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jRadioButton4 = new javax.swing.JRadioButton();
cancel_button = new javax.swing.JButton();
ok_button = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Name", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 1, 12))); // NOI18N
jLabel1.setText("First Name:");
first_name.setToolTipText("");
first_name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
first_nameActionPerformed(evt);
}
});
jLabel2.setText("Last Name:");
last_name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
last_nameActionPerformed(evt);
}
});
jLabel3.setText("Title:");
jLabel4.setText("Nickname:");
title.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
titleActionPerformed(evt);
}
});
nickname.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nicknameActionPerformed(evt);
}
});
jLabel5.setText("Display Format");
display_format.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
display_format.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
display_formatActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel5)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(67, 67, 67)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(title, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
.addComponent(first_name, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(last_name, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
.addComponent(nickname, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)))
.addComponent(display_format, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {last_name, nickname, title});
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(first_name, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(last_name, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(title, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(nickname, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(display_format, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {first_name, title});
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "E-mail", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 1, 12))); // NOI18N
jLabel6.setText("E-mail Address:");
email_address.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
email_addressActionPerformed(evt);
}
});
list.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(list);
add_button.setText("Add");
add_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_buttonActionPerformed(evt);
}
});
edit_button.setText("Edit");
edit_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
edit_buttonActionPerformed(evt);
}
});
remove_button.setText("Remove");
remove_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
remove_buttonActionPerformed(evt);
}
});
as_default_button.setText("As Default");
as_default_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
as_default_buttonActionPerformed(evt);
}
});
jLabel7.setText("Mail Format:");
buttonGroup1.add(jRadioButton1);
jRadioButton1.setText("HTML");
jRadioButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
buttonGroup1.add(jRadioButton3);
jRadioButton3.setText("Plain Text");
buttonGroup1.add(jRadioButton4);
jRadioButton4.setText("Custom");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(email_address, javax.swing.GroupLayout.PREFERRED_SIZE, 476, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(add_button)
.addComponent(edit_button)
.addComponent(remove_button)
.addComponent(as_default_button)))
.addComponent(jLabel7)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jRadioButton1)
.addGap(18, 18, 18)
.addComponent(jRadioButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton4)))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {add_button, as_default_button, edit_button, remove_button});
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(email_address, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(add_button, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(edit_button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(remove_button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(as_default_button)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton1)
.addComponent(jRadioButton3)
.addComponent(jRadioButton4)))
);
jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {add_button, as_default_button, edit_button, remove_button});
cancel_button.setText("Cancel");
cancel_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancel_buttonActionPerformed(evt);
}
});
ok_button.setText("OK");
ok_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ok_buttonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(ok_button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancel_button, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancel_button, ok_button});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancel_button, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ok_button))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void first_nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_first_nameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_first_nameActionPerformed
private void add_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_add_buttonActionPerformed
private void remove_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_remove_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_remove_buttonActionPerformed
private void titleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_titleActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_titleActionPerformed
private void last_nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_last_nameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_last_nameActionPerformed
private void nicknameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nicknameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_nicknameActionPerformed
private void display_formatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_display_formatActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_display_formatActionPerformed
private void email_addressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_email_addressActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_email_addressActionPerformed
private void edit_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edit_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_edit_buttonActionPerformed
private void as_default_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_as_default_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_as_default_buttonActionPerformed
private void ok_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ok_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_ok_buttonActionPerformed
private void cancel_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cancel_buttonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ContactEditorUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton add_button;
private javax.swing.JButton as_default_button;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton cancel_button;
private javax.swing.JComboBox<String> display_format;
private javax.swing.JButton edit_button;
private javax.swing.JTextField email_address;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButton4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField last_name;
private javax.swing.JList<String> list;
private javax.swing.JTextField nickname;
private javax.swing.JButton ok_button;
private javax.swing.JButton remove_button;
private javax.swing.JTextField title;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 23,951 |
java
|
ContactEditorUI.java
|
Java
|
[
{
"context": ".\n */\npackage my.contacteditor;\n\n/**\n *\n * @author douglas\n */\npublic class ContactEditorUI extends javax.sw",
"end": 237,
"score": 0.7143190503120422,
"start": 230,
"tag": "NAME",
"value": "douglas"
}
] | 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 my.contacteditor;
/**
*
* @author douglas
*/
public class ContactEditorUI extends javax.swing.JFrame {
/**
* Creates new form ContactEditorUI
*/
public ContactEditorUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
javax.swing.JTextField first_name = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
last_name = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
title = new javax.swing.JTextField();
nickname = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
display_format = new javax.swing.JComboBox<>();
jPanel2 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
email_address = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
list = new javax.swing.JList<>();
add_button = new javax.swing.JButton();
edit_button = new javax.swing.JButton();
remove_button = new javax.swing.JButton();
as_default_button = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jRadioButton4 = new javax.swing.JRadioButton();
cancel_button = new javax.swing.JButton();
ok_button = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Name", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 1, 12))); // NOI18N
jLabel1.setText("First Name:");
first_name.setToolTipText("");
first_name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
first_nameActionPerformed(evt);
}
});
jLabel2.setText("Last Name:");
last_name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
last_nameActionPerformed(evt);
}
});
jLabel3.setText("Title:");
jLabel4.setText("Nickname:");
title.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
titleActionPerformed(evt);
}
});
nickname.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nicknameActionPerformed(evt);
}
});
jLabel5.setText("Display Format");
display_format.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
display_format.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
display_formatActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel5)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(67, 67, 67)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(title, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
.addComponent(first_name, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(last_name, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
.addComponent(nickname, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)))
.addComponent(display_format, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {last_name, nickname, title});
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(first_name, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(last_name, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(title, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(nickname, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(display_format, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {first_name, title});
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "E-mail", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 1, 12))); // NOI18N
jLabel6.setText("E-mail Address:");
email_address.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
email_addressActionPerformed(evt);
}
});
list.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(list);
add_button.setText("Add");
add_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
add_buttonActionPerformed(evt);
}
});
edit_button.setText("Edit");
edit_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
edit_buttonActionPerformed(evt);
}
});
remove_button.setText("Remove");
remove_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
remove_buttonActionPerformed(evt);
}
});
as_default_button.setText("As Default");
as_default_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
as_default_buttonActionPerformed(evt);
}
});
jLabel7.setText("Mail Format:");
buttonGroup1.add(jRadioButton1);
jRadioButton1.setText("HTML");
jRadioButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
buttonGroup1.add(jRadioButton3);
jRadioButton3.setText("Plain Text");
buttonGroup1.add(jRadioButton4);
jRadioButton4.setText("Custom");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(email_address, javax.swing.GroupLayout.PREFERRED_SIZE, 476, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(add_button)
.addComponent(edit_button)
.addComponent(remove_button)
.addComponent(as_default_button)))
.addComponent(jLabel7)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jRadioButton1)
.addGap(18, 18, 18)
.addComponent(jRadioButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton4)))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {add_button, as_default_button, edit_button, remove_button});
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(email_address, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(add_button, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(edit_button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(remove_button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(as_default_button)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton1)
.addComponent(jRadioButton3)
.addComponent(jRadioButton4)))
);
jPanel2Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {add_button, as_default_button, edit_button, remove_button});
cancel_button.setText("Cancel");
cancel_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancel_buttonActionPerformed(evt);
}
});
ok_button.setText("OK");
ok_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ok_buttonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(ok_button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancel_button, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancel_button, ok_button});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancel_button, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ok_button))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void first_nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_first_nameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_first_nameActionPerformed
private void add_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_add_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_add_buttonActionPerformed
private void remove_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_remove_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_remove_buttonActionPerformed
private void titleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_titleActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_titleActionPerformed
private void last_nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_last_nameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_last_nameActionPerformed
private void nicknameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nicknameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_nicknameActionPerformed
private void display_formatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_display_formatActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_display_formatActionPerformed
private void email_addressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_email_addressActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_email_addressActionPerformed
private void edit_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edit_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_edit_buttonActionPerformed
private void as_default_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_as_default_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_as_default_buttonActionPerformed
private void ok_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ok_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_ok_buttonActionPerformed
private void cancel_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel_buttonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cancel_buttonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ContactEditorUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ContactEditorUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton add_button;
private javax.swing.JButton as_default_button;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton cancel_button;
private javax.swing.JComboBox<String> display_format;
private javax.swing.JButton edit_button;
private javax.swing.JTextField email_address;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButton4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField last_name;
private javax.swing.JList<String> list;
private javax.swing.JTextField nickname;
private javax.swing.JButton ok_button;
private javax.swing.JButton remove_button;
private javax.swing.JTextField title;
// End of variables declaration//GEN-END:variables
}
| 23,951 | 0.663647 | 0.654336 | 435 | 54.059769 | 41.814766 | 239 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.668966 | false | false |
3
|
3a7ff8f3d1555aaf51f241ebd806f1208a9dfa88
| 4,063,039,119,294 |
a88ac3221e4d831d0b802a7d5f1841e21d4d369f
|
/hap-gateway/src/main/java/io/choerodon/hap/ApiRequestExecutionAdvisor.java
|
b7e2b50e68f27f3e1533f21cf3993f9abb22c7ad
|
[] |
no_license
|
GeneralAaron/choerodon-hap-framework
|
https://github.com/GeneralAaron/choerodon-hap-framework
|
079568cede8d8b7de1f805dfb5557fbdc931a35f
|
318ec884c49a3a53e01f46015e4381c5fc19b028
|
refs/heads/master
| 2020-07-01T02:04:05.958000 | 2019-07-31T01:37:33 | 2019-07-31T01:37:33 | 201,015,055 | 1 | 0 | null | true | 2019-08-07T09:11:58 | 2019-08-07T09:11:58 | 2019-07-31T01:38:22 | 2019-07-31T01:38:19 | 17,152 | 0 | 0 | 0 | null | false | false |
package io.choerodon.hap;
import io.choerodon.hap.api.gateway.controllers.ApiInvokeContoller;
import io.choerodon.hap.api.logs.service.impl.ApiRequestExecutionAdvice;
import org.aopalliance.aop.Advice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @author jiameng.cao
* @since 2019/2/28
*/
@Component
public class ApiRequestExecutionAdvisor extends AbstractPointcutAdvisor {
private static final long serialVersionUID = 1L;
@Autowired
private ApiRequestExecutionAdvice apiRequestExecutionAdvice;
private final StaticMethodMatcherPointcut pointcut = new StaticMethodMatcherPointcut() {
@Override
public boolean matches(Method method, Class<?> aClass) {
if (ApiInvokeContoller.class.isAssignableFrom(aClass)) {
if ("sentRequest".equals(method.getName())) {
return true;
}
}
return false;
}
};
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
@Override
public Advice getAdvice() {
return this.apiRequestExecutionAdvice;
}
}
|
UTF-8
|
Java
| 1,400 |
java
|
ApiRequestExecutionAdvisor.java
|
Java
|
[
{
"context": "\n\nimport java.lang.reflect.Method;\n\n/**\n * @author jiameng.cao\n * @since 2019/2/28\n */\n@Component\npublic class A",
"end": 549,
"score": 0.9979888796806335,
"start": 538,
"tag": "NAME",
"value": "jiameng.cao"
}
] | null |
[] |
package io.choerodon.hap;
import io.choerodon.hap.api.gateway.controllers.ApiInvokeContoller;
import io.choerodon.hap.api.logs.service.impl.ApiRequestExecutionAdvice;
import org.aopalliance.aop.Advice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @author jiameng.cao
* @since 2019/2/28
*/
@Component
public class ApiRequestExecutionAdvisor extends AbstractPointcutAdvisor {
private static final long serialVersionUID = 1L;
@Autowired
private ApiRequestExecutionAdvice apiRequestExecutionAdvice;
private final StaticMethodMatcherPointcut pointcut = new StaticMethodMatcherPointcut() {
@Override
public boolean matches(Method method, Class<?> aClass) {
if (ApiInvokeContoller.class.isAssignableFrom(aClass)) {
if ("sentRequest".equals(method.getName())) {
return true;
}
}
return false;
}
};
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
@Override
public Advice getAdvice() {
return this.apiRequestExecutionAdvice;
}
}
| 1,400 | 0.716429 | 0.710714 | 48 | 28.166666 | 26.156845 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false |
3
|
9ce86b207fb781bae31850b7b9c20ec6d45aa893
| 38,379,827,769,244 |
fb47b69ffede7130b6014ffdefcb1e2c19310380
|
/server/src/main/java/es/caib/seycon/ng/sync/web/admin/DatabaseStatusServlet.java
|
9033425f8a7bedd7df47c18ef3b482a1c6c1afcf
|
[] |
no_license
|
lulzzz/syncserver
|
https://github.com/lulzzz/syncserver
|
c9a47a0c1209f3e72656db960cc3b583b544cdbc
|
7b29f068614a44b6106a11f045e47a2e4ef11e14
|
refs/heads/master
| 2020-09-08T18:03:47.195000 | 2018-06-11T13:05:49 | 2018-06-11T13:05:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package es.caib.seycon.ng.sync.web.admin;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.log.Log;
import org.mortbay.log.Logger;
import es.caib.seycon.ng.sync.engine.db.ConnectionPool;
public class DatabaseStatusServlet extends HttpServlet {
Logger log = Log.getLogger("Tasques Pendents Servlet");
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
try {
try {
PrintWriter printWriter = response.getWriter();
printWriter.println("<p>[<a href=\"main\">main</a>] -- Database Connection status.</p>");
ConnectionPool pool = ConnectionPool.getPool();
printWriter.println(pool!=null && pool.getStatus()!=null?pool.getStatus().replaceAll("\n", "<br>"):"");
printWriter.flush();
response.flushBuffer();
} catch (Throwable t) {
PrintWriter printWriter = response.getWriter();
printWriter.println("<p>DatabaseStatusServlet: Error generando página: </p>"
+ (t.getCause()!=null?t.getCause().getMessage():t.toString()));
}
} catch (Exception e) {
log.warn("Error invoking " + request.getRequestURI(), e);
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
doPost(req, response);
}
}
|
UTF-8
|
Java
| 1,546 |
java
|
DatabaseStatusServlet.java
|
Java
|
[] | null |
[] |
package es.caib.seycon.ng.sync.web.admin;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.log.Log;
import org.mortbay.log.Logger;
import es.caib.seycon.ng.sync.engine.db.ConnectionPool;
public class DatabaseStatusServlet extends HttpServlet {
Logger log = Log.getLogger("Tasques Pendents Servlet");
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
try {
try {
PrintWriter printWriter = response.getWriter();
printWriter.println("<p>[<a href=\"main\">main</a>] -- Database Connection status.</p>");
ConnectionPool pool = ConnectionPool.getPool();
printWriter.println(pool!=null && pool.getStatus()!=null?pool.getStatus().replaceAll("\n", "<br>"):"");
printWriter.flush();
response.flushBuffer();
} catch (Throwable t) {
PrintWriter printWriter = response.getWriter();
printWriter.println("<p>DatabaseStatusServlet: Error generando página: </p>"
+ (t.getCause()!=null?t.getCause().getMessage():t.toString()));
}
} catch (Exception e) {
log.warn("Error invoking " + request.getRequestURI(), e);
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
doPost(req, response);
}
}
| 1,546 | 0.732686 | 0.732039 | 46 | 32.586956 | 28.286251 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.173913 | false | false |
3
|
cde77831a0e4cadd87b0e03586a7bf025255e765
| 31,662,498,924,153 |
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
|
/com.tencent.mm/classes.jar/com/tencent/mm/plugin/mv/model/a/i.java
|
920453ffa70b26e0bcc4d9f0ddbd58e53e78ca94
|
[] |
no_license
|
tsuzcx/qq_apk
|
https://github.com/tsuzcx/qq_apk
|
0d5e792c3c7351ab781957bac465c55c505caf61
|
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
|
refs/heads/main
| 2022-07-02T10:32:11.651000 | 2022-02-01T12:41:38 | 2022-02-01T12:41:38 | 453,860,108 | 36 | 9 | null | false | 2022-01-31T09:46:26 | 2022-01-31T02:43:22 | 2022-01-31T06:56:43 | 2022-01-31T09:46:26 | 167,304 | 0 | 1 | 1 |
Java
| false | false |
package com.tencent.mm.plugin.mv.model.a;
import android.content.Context;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.am.c;
import com.tencent.mm.am.c.a;
import com.tencent.mm.am.c.b;
import com.tencent.mm.am.c.c;
import com.tencent.mm.am.h;
import com.tencent.mm.am.p;
import com.tencent.mm.bx.b;
import com.tencent.mm.model.cn;
import com.tencent.mm.network.g;
import com.tencent.mm.network.m;
import com.tencent.mm.plugin.mv.ui.uic.j;
import com.tencent.mm.protocal.protobuf.atz;
import com.tencent.mm.protocal.protobuf.boo;
import com.tencent.mm.protocal.protobuf.dsq;
import com.tencent.mm.protocal.protobuf.dsr;
import com.tencent.mm.sdk.platformtools.Log;
import com.tencent.mm.ui.component.k;
import com.tencent.mm.ui.component.k.b;
import kotlin.Metadata;
import org.json.JSONObject;
@Metadata(d1={""}, d2={"Lcom/tencent/mm/plugin/mv/model/netscene/NetSceneMusicMvGetFeedRecommendList;", "Lcom/tencent/mm/plugin/mv/model/netscene/BaseMvNetScene;", "context", "Landroid/content/Context;", "lastBuffer", "Lcom/tencent/mm/protobuf/ByteString;", "(Landroid/content/Context;Lcom/tencent/mm/protobuf/ByteString;)V", "callback", "Lcom/tencent/mm/modelbase/IOnSceneEnd;", "commReqResp", "Lcom/tencent/mm/modelbase/CommReqResp;", "request", "Lcom/tencent/mm/protocal/protobuf/MusicLiveGetRelatedListReq;", "response", "Lcom/tencent/mm/protocal/protobuf/MusicLiveGetRelatedListResp;", "doScene", "", "dispatcher", "Lcom/tencent/mm/network/IDispatcher;", "getResponse", "getType", "onGYNetEnd", "", "netId", "errType", "errCode", "errMsg", "", "rr", "Lcom/tencent/mm/network/IReqResp;", "cookie", "", "Companion", "plugin-mv_release"}, k=1, mv={1, 5, 1}, xi=48)
public final class i
extends a
{
public static final a LYZ;
public dsr LXH;
private dsq LZa;
private h callback;
private final c oDw;
static
{
AppMethodBeat.i(286277);
LYZ = new a((byte)0);
AppMethodBeat.o(286277);
}
public i(Context paramContext, b paramb)
{
AppMethodBeat.i(286269);
Object localObject1 = new c.a();
((c.a)localObject1).funcId = 6860;
((c.a)localObject1).uri = "/cgi-bin/micromsg-bin/musiclivegetrelatedlist";
((c.a)localObject1).otE = ((com.tencent.mm.bx.a)new dsq());
((c.a)localObject1).otF = ((com.tencent.mm.bx.a)new dsr());
localObject1 = ((c.a)localObject1).bEF();
kotlin.g.b.s.s(localObject1, "commReqRespBuilder.buildInstance()");
this.oDw = ((c)localObject1);
localObject1 = c.b.b(this.oDw.otB);
if (localObject1 == null)
{
paramContext = new NullPointerException("null cannot be cast to non-null type com.tencent.mm.protocal.protobuf.MusicLiveGetRelatedListReq");
AppMethodBeat.o(286269);
throw paramContext;
}
this.LZa = ((dsq)localObject1);
localObject1 = this.LZa;
if (localObject1 != null) {
((dsq)localObject1).scene = 101;
}
localObject1 = k.aeZF;
paramContext = (j)k.nq(paramContext).q(j.class);
Object localObject2 = new JSONObject();
((JSONObject)localObject2).put("bgmid", paramContext.LWI.mLQ);
((JSONObject)localObject2).put("songname", paramContext.LWI.songName);
((JSONObject)localObject2).put("singername", paramContext.LWI.rDl);
((JSONObject)localObject2).put("songdesc", "");
localObject1 = new JSONObject();
((JSONObject)localObject1).put("type", 1);
((JSONObject)localObject1).put("bgmquery", localObject2);
localObject2 = com.tencent.mm.plugin.mv.ui.a.Maz;
((JSONObject)localObject1).put("songinfobufferbase64", com.tencent.mm.plugin.mv.ui.a.a(paramContext.LWI));
localObject2 = this.LZa;
if (localObject2 != null) {
((dsq)localObject2).source = ((JSONObject)localObject1).toString();
}
Log.i("MicroMsg.Mv.NetSceneMusicMvGetMVRecommendList", kotlin.g.b.s.X("create NetSceneMusicMvGetFeedRecommendList songId:", paramContext.LWI.mLQ));
paramContext = this.LZa;
if (paramContext != null) {
paramContext.YIY = new atz();
}
paramContext = this.LZa;
if (paramContext == null)
{
paramContext = null;
if (paramContext != null) {
paramContext.scene = 93;
}
paramContext = this.LZa;
if (paramContext != null) {
break label388;
}
}
label388:
for (paramContext = null;; paramContext = paramContext.YIY)
{
if (paramContext != null) {
paramContext.Bjl = cn.bDv();
}
paramContext = this.LZa;
if (paramContext != null) {
paramContext.ZEQ = paramb;
}
AppMethodBeat.o(286269);
return;
paramContext = paramContext.YIY;
break;
}
}
public final int doScene(g paramg, h paramh)
{
AppMethodBeat.i(286289);
kotlin.g.b.s.u(paramg, "dispatcher");
kotlin.g.b.s.u(paramh, "callback");
this.callback = paramh;
int i = dispatch(paramg, (com.tencent.mm.network.s)this.oDw, (m)this);
AppMethodBeat.o(286289);
return i;
}
public final int getType()
{
return 6860;
}
public final void onGYNetEnd(int paramInt1, int paramInt2, int paramInt3, String paramString, com.tencent.mm.network.s params, byte[] paramArrayOfByte)
{
AppMethodBeat.i(286300);
super.onGYNetEnd(paramInt1, paramInt2, paramInt3, paramString, params, paramArrayOfByte);
Log.i("MicroMsg.Mv.NetSceneMusicMvGetMVRecommendList", "netId %d | errType %d | errCode %d | errMsg %s", new Object[] { Integer.valueOf(paramInt1), Integer.valueOf(paramInt2), Integer.valueOf(paramInt3), paramString });
if ((paramInt2 != 0) || (paramInt3 != 0))
{
params = this.callback;
if (params != null) {
params.onSceneEnd(paramInt2, paramInt3, paramString, (p)this);
}
AppMethodBeat.o(286300);
return;
}
params = c.c.b(this.oDw.otC);
if (params == null)
{
paramString = new NullPointerException("null cannot be cast to non-null type com.tencent.mm.protocal.protobuf.MusicLiveGetRelatedListResp");
AppMethodBeat.o(286300);
throw paramString;
}
this.LXH = ((dsr)params);
params = this.callback;
if (params != null) {
params.onSceneEnd(paramInt2, paramInt3, paramString, (p)this);
}
AppMethodBeat.o(286300);
}
@Metadata(d1={""}, d2={"Lcom/tencent/mm/plugin/mv/model/netscene/NetSceneMusicMvGetFeedRecommendList$Companion;", "", "()V", "TAG", "", "plugin-mv_release"}, k=1, mv={1, 5, 1}, xi=48)
public static final class a {}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes2.jar
* Qualified Name: com.tencent.mm.plugin.mv.model.a.i
* JD-Core Version: 0.7.0.1
*/
|
UTF-8
|
Java
| 6,785 |
java
|
i.java
|
Java
|
[] | null |
[] |
package com.tencent.mm.plugin.mv.model.a;
import android.content.Context;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.am.c;
import com.tencent.mm.am.c.a;
import com.tencent.mm.am.c.b;
import com.tencent.mm.am.c.c;
import com.tencent.mm.am.h;
import com.tencent.mm.am.p;
import com.tencent.mm.bx.b;
import com.tencent.mm.model.cn;
import com.tencent.mm.network.g;
import com.tencent.mm.network.m;
import com.tencent.mm.plugin.mv.ui.uic.j;
import com.tencent.mm.protocal.protobuf.atz;
import com.tencent.mm.protocal.protobuf.boo;
import com.tencent.mm.protocal.protobuf.dsq;
import com.tencent.mm.protocal.protobuf.dsr;
import com.tencent.mm.sdk.platformtools.Log;
import com.tencent.mm.ui.component.k;
import com.tencent.mm.ui.component.k.b;
import kotlin.Metadata;
import org.json.JSONObject;
@Metadata(d1={""}, d2={"Lcom/tencent/mm/plugin/mv/model/netscene/NetSceneMusicMvGetFeedRecommendList;", "Lcom/tencent/mm/plugin/mv/model/netscene/BaseMvNetScene;", "context", "Landroid/content/Context;", "lastBuffer", "Lcom/tencent/mm/protobuf/ByteString;", "(Landroid/content/Context;Lcom/tencent/mm/protobuf/ByteString;)V", "callback", "Lcom/tencent/mm/modelbase/IOnSceneEnd;", "commReqResp", "Lcom/tencent/mm/modelbase/CommReqResp;", "request", "Lcom/tencent/mm/protocal/protobuf/MusicLiveGetRelatedListReq;", "response", "Lcom/tencent/mm/protocal/protobuf/MusicLiveGetRelatedListResp;", "doScene", "", "dispatcher", "Lcom/tencent/mm/network/IDispatcher;", "getResponse", "getType", "onGYNetEnd", "", "netId", "errType", "errCode", "errMsg", "", "rr", "Lcom/tencent/mm/network/IReqResp;", "cookie", "", "Companion", "plugin-mv_release"}, k=1, mv={1, 5, 1}, xi=48)
public final class i
extends a
{
public static final a LYZ;
public dsr LXH;
private dsq LZa;
private h callback;
private final c oDw;
static
{
AppMethodBeat.i(286277);
LYZ = new a((byte)0);
AppMethodBeat.o(286277);
}
public i(Context paramContext, b paramb)
{
AppMethodBeat.i(286269);
Object localObject1 = new c.a();
((c.a)localObject1).funcId = 6860;
((c.a)localObject1).uri = "/cgi-bin/micromsg-bin/musiclivegetrelatedlist";
((c.a)localObject1).otE = ((com.tencent.mm.bx.a)new dsq());
((c.a)localObject1).otF = ((com.tencent.mm.bx.a)new dsr());
localObject1 = ((c.a)localObject1).bEF();
kotlin.g.b.s.s(localObject1, "commReqRespBuilder.buildInstance()");
this.oDw = ((c)localObject1);
localObject1 = c.b.b(this.oDw.otB);
if (localObject1 == null)
{
paramContext = new NullPointerException("null cannot be cast to non-null type com.tencent.mm.protocal.protobuf.MusicLiveGetRelatedListReq");
AppMethodBeat.o(286269);
throw paramContext;
}
this.LZa = ((dsq)localObject1);
localObject1 = this.LZa;
if (localObject1 != null) {
((dsq)localObject1).scene = 101;
}
localObject1 = k.aeZF;
paramContext = (j)k.nq(paramContext).q(j.class);
Object localObject2 = new JSONObject();
((JSONObject)localObject2).put("bgmid", paramContext.LWI.mLQ);
((JSONObject)localObject2).put("songname", paramContext.LWI.songName);
((JSONObject)localObject2).put("singername", paramContext.LWI.rDl);
((JSONObject)localObject2).put("songdesc", "");
localObject1 = new JSONObject();
((JSONObject)localObject1).put("type", 1);
((JSONObject)localObject1).put("bgmquery", localObject2);
localObject2 = com.tencent.mm.plugin.mv.ui.a.Maz;
((JSONObject)localObject1).put("songinfobufferbase64", com.tencent.mm.plugin.mv.ui.a.a(paramContext.LWI));
localObject2 = this.LZa;
if (localObject2 != null) {
((dsq)localObject2).source = ((JSONObject)localObject1).toString();
}
Log.i("MicroMsg.Mv.NetSceneMusicMvGetMVRecommendList", kotlin.g.b.s.X("create NetSceneMusicMvGetFeedRecommendList songId:", paramContext.LWI.mLQ));
paramContext = this.LZa;
if (paramContext != null) {
paramContext.YIY = new atz();
}
paramContext = this.LZa;
if (paramContext == null)
{
paramContext = null;
if (paramContext != null) {
paramContext.scene = 93;
}
paramContext = this.LZa;
if (paramContext != null) {
break label388;
}
}
label388:
for (paramContext = null;; paramContext = paramContext.YIY)
{
if (paramContext != null) {
paramContext.Bjl = cn.bDv();
}
paramContext = this.LZa;
if (paramContext != null) {
paramContext.ZEQ = paramb;
}
AppMethodBeat.o(286269);
return;
paramContext = paramContext.YIY;
break;
}
}
public final int doScene(g paramg, h paramh)
{
AppMethodBeat.i(286289);
kotlin.g.b.s.u(paramg, "dispatcher");
kotlin.g.b.s.u(paramh, "callback");
this.callback = paramh;
int i = dispatch(paramg, (com.tencent.mm.network.s)this.oDw, (m)this);
AppMethodBeat.o(286289);
return i;
}
public final int getType()
{
return 6860;
}
public final void onGYNetEnd(int paramInt1, int paramInt2, int paramInt3, String paramString, com.tencent.mm.network.s params, byte[] paramArrayOfByte)
{
AppMethodBeat.i(286300);
super.onGYNetEnd(paramInt1, paramInt2, paramInt3, paramString, params, paramArrayOfByte);
Log.i("MicroMsg.Mv.NetSceneMusicMvGetMVRecommendList", "netId %d | errType %d | errCode %d | errMsg %s", new Object[] { Integer.valueOf(paramInt1), Integer.valueOf(paramInt2), Integer.valueOf(paramInt3), paramString });
if ((paramInt2 != 0) || (paramInt3 != 0))
{
params = this.callback;
if (params != null) {
params.onSceneEnd(paramInt2, paramInt3, paramString, (p)this);
}
AppMethodBeat.o(286300);
return;
}
params = c.c.b(this.oDw.otC);
if (params == null)
{
paramString = new NullPointerException("null cannot be cast to non-null type com.tencent.mm.protocal.protobuf.MusicLiveGetRelatedListResp");
AppMethodBeat.o(286300);
throw paramString;
}
this.LXH = ((dsr)params);
params = this.callback;
if (params != null) {
params.onSceneEnd(paramInt2, paramInt3, paramString, (p)this);
}
AppMethodBeat.o(286300);
}
@Metadata(d1={""}, d2={"Lcom/tencent/mm/plugin/mv/model/netscene/NetSceneMusicMvGetFeedRecommendList$Companion;", "", "()V", "TAG", "", "plugin-mv_release"}, k=1, mv={1, 5, 1}, xi=48)
public static final class a {}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes2.jar
* Qualified Name: com.tencent.mm.plugin.mv.model.a.i
* JD-Core Version: 0.7.0.1
*/
| 6,785 | 0.659248 | 0.635962 | 173 | 37.254333 | 71.444504 | 866 | false | false | 0 | 0 | 0 | 0 | 76 | 0.022402 | 1.190751 | false | false |
3
|
507b9a01f9d0cb7414c9a5ec85cf1a4982b7fa4a
| 20,882,131,008,681 |
1cbaec1d1ba307688a9ebc8f9bcd5d896da35edc
|
/HomePage.java
|
a2d4377a4d4c9986f5b3cb47f48cdfaedbece958
|
[] |
no_license
|
SreehariRamMohan/Rent-It
|
https://github.com/SreehariRamMohan/Rent-It
|
ef560ae577e876b065b4db7fc327ef8e7f8ac98d
|
52c7b58185c1b84bab636ecfa4852809a1acca3d
|
refs/heads/master
| 2021-06-13T12:08:46.632000 | 2017-03-16T04:12:22 | 2017-03-16T04:12:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.android.bookrent;
import android.content.ContentUris;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class HomePage extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Button calendarButton = (Button) findViewById(R.id.button8);
calendarButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
long startMillis = System.currentTimeMillis();
Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
builder.appendPath("time");
ContentUris.appendId(builder, startMillis);
Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
startActivity(intent);
}
});
}
}
|
UTF-8
|
Java
| 1,151 |
java
|
HomePage.java
|
Java
|
[] | null |
[] |
package com.example.android.bookrent;
import android.content.ContentUris;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class HomePage extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Button calendarButton = (Button) findViewById(R.id.button8);
calendarButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
long startMillis = System.currentTimeMillis();
Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
builder.appendPath("time");
ContentUris.appendId(builder, startMillis);
Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
startActivity(intent);
}
});
}
}
| 1,151 | 0.674196 | 0.672459 | 43 | 25.767443 | 25.802322 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.465116 | false | false |
3
|
f1cee1df2c61ed6bafed07e56fd803562a99096b
| 20,066,087,225,650 |
c9c6e68aab2186a0ff7ec0c3409225666a3f4de8
|
/employee/EmployeeDto.java
|
b1e5ab9510aa719693fb0ed2223ff4b6630236b4
|
[] |
no_license
|
ltchounang/technoWeb2TchounangDLorisYanisSellalii
|
https://github.com/ltchounang/technoWeb2TchounangDLorisYanisSellalii
|
7c611cfea47af5327641108c6701b38f9d4d9d5b
|
167702de94825df976499fd8469d9f2ba0c641d5
|
refs/heads/master
| 2021-01-03T00:15:14.793000 | 2020-02-11T22:04:15 | 2020-02-11T22:04:15 | 239,830,836 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fr.univparis8.iut.dut.employee;
import fr.univparis8.iut.dut.salary.SalaryDto;
import java.util.List;
public class EmployeeDto {
private Long id;
private String firstName;
private String lastName;
private Address address;
private Long salaryAmount;
private List<SalaryDto> salaries;
public EmployeeDto() {
}
public EmployeeDto(Long id, String firstName, String lastName, Address address, Long salaryAmount, List<SalaryDto> salaryDtos) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.salaries = salaryDtos;
this.salaryAmount = salaryAmount;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<SalaryDto> getSalaries() {
return salaries;
}
public void setSalaries(List<SalaryDto> salaries) {
this.salaries = salaries;
}
public Long getSalaryAmount() {
return salaryAmount;
}
public void setSalaryAmount(Long salaryAmount) {
this.salaryAmount = salaryAmount;
}
public static final class EmployeeDtoBuilder {
private Long id;
private String firstName;
private String lastName;
private Address address;
private Long salaryAmount;
private List<SalaryDto> salaries;
private EmployeeDtoBuilder() {
}
public static EmployeeDtoBuilder create() {
return new EmployeeDtoBuilder();
}
public EmployeeDtoBuilder withId(Long id) {
this.id = id;
return this;
}
public EmployeeDtoBuilder withFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public EmployeeDtoBuilder withLastName(String lastName) {
this.lastName = lastName;
return this;
}
public EmployeeDtoBuilder withAddress(Address address) {
this.address = address;
return this;
}
public EmployeeDtoBuilder withSalaryDtos(List<SalaryDto> salaryDtos) {
this.salaries = salaryDtos;
return this;
}
public EmployeeDtoBuilder withSalaryAmount(Long salaryAmount) {
this.salaryAmount = salaryAmount;
return this;
}
public EmployeeDto build() {
return new EmployeeDto(id, firstName, lastName, address, salaryAmount, salaries);
}
}
}
|
UTF-8
|
Java
| 3,030 |
java
|
EmployeeDto.java
|
Java
|
[
{
"context": "yeeDto {\n\n private Long id;\n\n private String firstName;\n\n private String lastName;\n\n private Addre",
"end": 191,
"score": 0.745297372341156,
"start": 182,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\n private String firstName;\n\n private String lastName;\n\n private Address address;\n\n private Long ",
"end": 221,
"score": 0.7503178119659424,
"start": 213,
"tag": "NAME",
"value": "lastName"
},
{
"context": "() {\n }\n\n public EmployeeDto(Long id, String firstName, String lastName, Address address, Long salaryAmo",
"end": 407,
"score": 0.7197779417037964,
"start": 398,
"tag": "NAME",
"value": "firstName"
},
{
"context": "blic EmployeeDto(Long id, String firstName, String lastName, Address address, Long salaryAmount, List<SalaryD",
"end": 424,
"score": 0.8485094308853149,
"start": 416,
"tag": "NAME",
"value": "lastName"
},
{
"context": ") {\n this.id = id;\n this.firstName = firstName;\n this.lastName = lastName;\n this.a",
"end": 548,
"score": 0.9620615243911743,
"start": 539,
"tag": "NAME",
"value": "firstName"
},
{
"context": "his.firstName = firstName;\n this.lastName = lastName;\n this.address = address;\n this.sal",
"end": 582,
"score": 0.9403271079063416,
"start": 574,
"tag": "NAME",
"value": "lastName"
},
{
"context": "\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String first",
"end": 874,
"score": 0.5968790054321289,
"start": 865,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastNa",
"end": 1032,
"score": 0.5048678517341614,
"start": 1024,
"tag": "NAME",
"value": "lastName"
},
{
"context": "ame(String lastName) {\n this.lastName = lastName;\n return this;\n }\n\n publ",
"end": 2397,
"score": 0.7888666391372681,
"start": 2389,
"tag": "NAME",
"value": "lastName"
},
{
"context": "o build() {\n return new EmployeeDto(id, firstName, lastName, address, salaryAmount, salaries);\n ",
"end": 2966,
"score": 0.9996064305305481,
"start": 2957,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\n return new EmployeeDto(id, firstName, lastName, address, salaryAmount, salaries);\n }\n ",
"end": 2976,
"score": 0.9995916485786438,
"start": 2968,
"tag": "NAME",
"value": "lastName"
}
] | null |
[] |
package fr.univparis8.iut.dut.employee;
import fr.univparis8.iut.dut.salary.SalaryDto;
import java.util.List;
public class EmployeeDto {
private Long id;
private String firstName;
private String lastName;
private Address address;
private Long salaryAmount;
private List<SalaryDto> salaries;
public EmployeeDto() {
}
public EmployeeDto(Long id, String firstName, String lastName, Address address, Long salaryAmount, List<SalaryDto> salaryDtos) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.salaries = salaryDtos;
this.salaryAmount = salaryAmount;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<SalaryDto> getSalaries() {
return salaries;
}
public void setSalaries(List<SalaryDto> salaries) {
this.salaries = salaries;
}
public Long getSalaryAmount() {
return salaryAmount;
}
public void setSalaryAmount(Long salaryAmount) {
this.salaryAmount = salaryAmount;
}
public static final class EmployeeDtoBuilder {
private Long id;
private String firstName;
private String lastName;
private Address address;
private Long salaryAmount;
private List<SalaryDto> salaries;
private EmployeeDtoBuilder() {
}
public static EmployeeDtoBuilder create() {
return new EmployeeDtoBuilder();
}
public EmployeeDtoBuilder withId(Long id) {
this.id = id;
return this;
}
public EmployeeDtoBuilder withFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public EmployeeDtoBuilder withLastName(String lastName) {
this.lastName = lastName;
return this;
}
public EmployeeDtoBuilder withAddress(Address address) {
this.address = address;
return this;
}
public EmployeeDtoBuilder withSalaryDtos(List<SalaryDto> salaryDtos) {
this.salaries = salaryDtos;
return this;
}
public EmployeeDtoBuilder withSalaryAmount(Long salaryAmount) {
this.salaryAmount = salaryAmount;
return this;
}
public EmployeeDto build() {
return new EmployeeDto(id, firstName, lastName, address, salaryAmount, salaries);
}
}
}
| 3,030 | 0.611881 | 0.611221 | 130 | 22.307692 | 22.241627 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438462 | false | false |
3
|
79355f8ef62738a0d8b5717df87fa3bd8e6ca43d
| 12,025,908,450,274 |
ce4b89285d6a178bbd44ddeedc0bd5519f4142c1
|
/Server/src/com/tntniceman/server/Main.java
|
59bca533fb0a052e4542e3d41b4ff58ce2f841d9
|
[] |
no_license
|
TNTniceman/Networking_Engine_2
|
https://github.com/TNTniceman/Networking_Engine_2
|
011ddfc3d72428e3d6846f59502ae2652ebd8d13
|
01a912cc6669151675275016bf077946f5537b95
|
refs/heads/master
| 2015-07-25T23:47:50 | 2015-03-31T16:31:15 | 2015-03-31T16:31:15 | 32,087,627 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tntniceman.server;
import javax.swing.*;
/**
* Created by spens_000 on 3/31/2015.
*/
public class Main {
private static JFrame frame;
private static Game game;
private static void init() {
}
public static void main(String[] args) {
frame = new JFrame("Server");
frame.setLayout(null);
frame.setSize(640, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
|
UTF-8
|
Java
| 479 |
java
|
Main.java
|
Java
|
[
{
"context": ".server;\n\nimport javax.swing.*;\n\n/**\n * Created by spens_000 on 3/31/2015.\n */\npublic class Main {\n\n privat",
"end": 82,
"score": 0.9994451999664307,
"start": 73,
"tag": "USERNAME",
"value": "spens_000"
}
] | null |
[] |
package com.tntniceman.server;
import javax.swing.*;
/**
* Created by spens_000 on 3/31/2015.
*/
public class Main {
private static JFrame frame;
private static Game game;
private static void init() {
}
public static void main(String[] args) {
frame = new JFrame("Server");
frame.setLayout(null);
frame.setSize(640, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
| 479 | 0.626305 | 0.592902 | 26 | 17.423077 | 17.663898 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false |
3
|
05464fcad542e8056202ef55d13495e29cf8c12d
| 18,674,517,869,532 |
b0157008f095dfb5047ee6060ac104da4d554309
|
/spring-rabbitmq-skeletons/src/main/java/fanout/consumer/FanoutExchangeConsumer2.java
|
a9e6b9c30e3a3e80503010ad3c1b4e6b42b0b54c
|
[] |
no_license
|
bbakla/rabbitmq
|
https://github.com/bbakla/rabbitmq
|
8a895a0f3eba9c9d49904c951d45d3baf0523a64
|
83eb14c77cc6e1e6edb541e718cb8bba0b641d07
|
refs/heads/master
| 2021-01-20T06:52:12.125000 | 2017-06-22T12:33:45 | 2017-06-22T12:33:45 | 89,151,678 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fanout.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
public class FanoutExchangeConsumer2 {
@RabbitListener(queues=FanoutConsumerConfiguration.FANOUT_QUEUE_NAME2)
public void handleMessage(String text) {
System.out.println("Received in FanoutExchangeConsumer2: " + text);
}
}
|
UTF-8
|
Java
| 335 |
java
|
FanoutExchangeConsumer2.java
|
Java
|
[] | null |
[] |
package fanout.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
public class FanoutExchangeConsumer2 {
@RabbitListener(queues=FanoutConsumerConfiguration.FANOUT_QUEUE_NAME2)
public void handleMessage(String text) {
System.out.println("Received in FanoutExchangeConsumer2: " + text);
}
}
| 335 | 0.78209 | 0.773134 | 12 | 25.916666 | 28.391485 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false |
3
|
4576c6c7bac820be76b8144e7a49591c3e20bf83
| 11,639,361,434,399 |
81f60980105c4b278dc1bf2b90b860b6c1c4c7c1
|
/chatsdk/src/main/java/chat/ono/chatsdk/callback/SuccessCallback.java
|
b50de753088309b1b380735cf7418e1f678ad350
|
[] |
no_license
|
lhs168/ONOChatAndroidSDK
|
https://github.com/lhs168/ONOChatAndroidSDK
|
9fd1895925953357a45f1b0b5e27ea3f4a277e8a
|
592420a2eb27a159f370930732a859a93e36e385
|
refs/heads/master
| 2020-03-18T17:33:27.678000 | 2018-06-25T12:27:51 | 2018-06-25T12:27:51 | 135,035,356 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package chat.ono.chatsdk.callback;
/**
* Created by kevin on 2018/5/27.
*/
public interface SuccessCallback<T> {
void onSuccess(T result);
}
|
UTF-8
|
Java
| 149 |
java
|
SuccessCallback.java
|
Java
|
[
{
"context": "kage chat.ono.chatsdk.callback;\n\n/**\n * Created by kevin on 2018/5/27.\n */\n\npublic interface SuccessCallba",
"end": 59,
"score": 0.9989310503005981,
"start": 54,
"tag": "USERNAME",
"value": "kevin"
}
] | null |
[] |
package chat.ono.chatsdk.callback;
/**
* Created by kevin on 2018/5/27.
*/
public interface SuccessCallback<T> {
void onSuccess(T result);
}
| 149 | 0.691275 | 0.644295 | 9 | 15.555555 | 15.972971 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false |
3
|
987b5718ad0b9371f4f93837a4f6eab4d18a4732
| 944,892,874,218 |
df22744c4977b3f4b1a20dcf41a58d14ca44bc2a
|
/appmojo-sdk/src/main/java/com/appmojo/sdk/AMTokenHelper.java
|
eb0e0dfa89492dbcbd29c86703e368a5b04bdfe5
|
[
"Apache-2.0"
] |
permissive
|
AppsynthAsia/appmojo-android-sdk
|
https://github.com/AppsynthAsia/appmojo-android-sdk
|
73a92ba18fc387c86e165eac3b66934297a5ff0a
|
5215349b84fb4394ca2b53a1f7f32df94f9a80f6
|
refs/heads/master
| 2021-01-15T09:09:48.404000 | 2015-08-07T10:31:10 | 2015-08-07T10:31:10 | 37,514,485 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.appmojo.sdk;
import android.content.Context;
import com.appmojo.sdk.utils.AMFileUtils;
import com.appmojo.sdk.utils.AMSharePrefs;
/**
* Created by nutron on 7/21/15 AD.
*/
class AMTokenHelper {
private static final String TOKEN_FILE_NAME = "auth_token";
private static final String PREF_KEY_TOKEN = "pref_key_token";
private AMTokenHelper(){
}
static void writeToken(Context context, AMToken token) {
if(token != null && token.getToken() != null) {
AMSharePrefs.setPreference(context, PREF_KEY_TOKEN, token.getToken());
AMFileUtils.serializeObjectInCacheDir(context, TOKEN_FILE_NAME, token);
}
}
public static String getToken(Context context) {
return AMSharePrefs.getPreferenceString(context, PREF_KEY_TOKEN, null);
}
public static AMToken readToken(Context context) {
return (AMToken)AMFileUtils.readSerializeObjectFormCacheDir(context, TOKEN_FILE_NAME);
}
}
|
UTF-8
|
Java
| 978 |
java
|
AMTokenHelper.java
|
Java
|
[
{
"context": "appmojo.sdk.utils.AMSharePrefs;\n\n/**\n * Created by nutron on 7/21/15 AD.\n */\nclass AMTokenHelper {\n priv",
"end": 169,
"score": 0.9994456768035889,
"start": 163,
"tag": "USERNAME",
"value": "nutron"
}
] | null |
[] |
package com.appmojo.sdk;
import android.content.Context;
import com.appmojo.sdk.utils.AMFileUtils;
import com.appmojo.sdk.utils.AMSharePrefs;
/**
* Created by nutron on 7/21/15 AD.
*/
class AMTokenHelper {
private static final String TOKEN_FILE_NAME = "auth_token";
private static final String PREF_KEY_TOKEN = "pref_key_token";
private AMTokenHelper(){
}
static void writeToken(Context context, AMToken token) {
if(token != null && token.getToken() != null) {
AMSharePrefs.setPreference(context, PREF_KEY_TOKEN, token.getToken());
AMFileUtils.serializeObjectInCacheDir(context, TOKEN_FILE_NAME, token);
}
}
public static String getToken(Context context) {
return AMSharePrefs.getPreferenceString(context, PREF_KEY_TOKEN, null);
}
public static AMToken readToken(Context context) {
return (AMToken)AMFileUtils.readSerializeObjectFormCacheDir(context, TOKEN_FILE_NAME);
}
}
| 978 | 0.698364 | 0.693252 | 32 | 29.5625 | 30.065489 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false |
3
|
82291fe2867c694b0181f2055117d2d25f695d54
| 22,265,110,525,806 |
6c0ed5bd14412605f06513f620792bf293504202
|
/poverenik/src/main/java/rs/pijz/server/poverenik/controller/ZalbaCutanjeController.java
|
8feb9d2872110330ac88ebf800634eff93d0eb86
|
[] |
no_license
|
gagi3/XML-2020
|
https://github.com/gagi3/XML-2020
|
af05b1f3df1f73ef3c83398c869d968c490ff960
|
1d3b8b5f91f2e4b2a74deed24143a78b90e06625
|
refs/heads/dev
| 2023-03-01T21:50:16.732000 | 2021-02-06T22:07:35 | 2021-02-06T22:07:35 | 319,427,300 | 0 | 1 | null | false | 2021-02-06T16:34:17 | 2020-12-07T19:48:09 | 2021-02-06T13:52:28 | 2021-02-06T16:34:17 | 35,959 | 0 | 1 | 0 |
Java
| false | false |
package rs.pijz.server.poverenik.controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import rs.pijz.server.poverenik.dto.ResponseMessage;
import rs.pijz.server.poverenik.dto.sparql.ZalbaCutanjeSPARQL;
import rs.pijz.server.poverenik.fuseki.MetadataExtractor;
import rs.pijz.server.poverenik.model.zalba_cutanje.ZalbaCutanje;
import rs.pijz.server.poverenik.service.DomParserService;
import rs.pijz.server.poverenik.service.ZalbaCutanjeService;
@CrossOrigin
@RestController
@RequestMapping("/zalba-cutanje")
public class ZalbaCutanjeController {
@Autowired
private ZalbaCutanjeService zalbaCutanjeService;
@Autowired
private DomParserService domParserService;
@Autowired
private MetadataExtractor metadataExtractor;
private final String dataset = "conn.zalba-cutanje-dataset";
// @GetMapping(value = "", produces = MediaType.APPLICATION_XML_VALUE)
// private ResponseEntity<List<ZalbaCutanje>> findAll() {
// try {
// List<ZalbaCutanje> zalbe = zalbaCutanjeService.findAll();
// return ResponseEntity.ok().body(zalbe);
// } catch (Exception e) {
// e.printStackTrace();
// return ResponseEntity.badRequest().body(null);
// }
// }
@GetMapping(value = "", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<List<ZalbaCutanje>> findAllByParams(@RequestParam (required = false) String broj,
@RequestParam (required = false) String gradjaninID,
@RequestParam (required = false) Date datum,
@RequestParam (required = false) Date datumZahteva,
@RequestParam (required = false) String poverenikID,
@RequestParam (required = false) String sluzbenikID) {
try {
List<ZalbaCutanje> list;
if (broj != null && !broj.equals("")) {
list = zalbaCutanjeService.findAllByBroj(broj);
} else if (gradjaninID != null && !gradjaninID.equals("")) {
list = zalbaCutanjeService.findAllByGradjanin(gradjaninID);
} else if (datum != null) {
list = zalbaCutanjeService.findAllByDatum(datum);
} else if (datumZahteva != null) {
list = zalbaCutanjeService.findAllByDatumZahteva(datumZahteva);
} else if (poverenikID != null && !poverenikID.equals("")) {
list = zalbaCutanjeService.findAllByPoverenik(poverenikID);
} else if (sluzbenikID != null && !sluzbenikID.equals("")) {
list = zalbaCutanjeService.findAllBySluzbenik(sluzbenikID);
} else {
list = zalbaCutanjeService.findAll();
}
return ResponseEntity.ok().body(list);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@GetMapping(value = "/search", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<ZalbaCutanje> getOne(@RequestParam String id) {
try {
ZalbaCutanje zalba = zalbaCutanjeService.getOne(id);
return ResponseEntity.ok().body(zalba);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@PostMapping(value = "/create", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<ZalbaCutanje> create(@RequestBody ZalbaCutanje zalba) {
try {
ZalbaCutanje zalbaCutanje = zalbaCutanjeService.create(zalba);
return ResponseEntity.ok().body(zalbaCutanje);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@PostMapping(value = "/edit", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<ZalbaCutanje> edit(@RequestBody ZalbaCutanje zalbaCutanje) {
try {
ZalbaCutanje zalbaCutanje1 = zalbaCutanjeService.edit(zalbaCutanje);
return ResponseEntity.ok().body(zalbaCutanje1);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@DeleteMapping(value = "/delete", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<Boolean> delete(@RequestParam String id) {
try {
Boolean deleted = zalbaCutanjeService.delete(id);
return ResponseEntity.ok().body(deleted);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@GetMapping(value = "/generate")
private ResponseEntity<ResponseMessage> generateDocuments(@RequestParam String id) {
try {
zalbaCutanjeService.generateDocuments(id);
return ResponseEntity.ok().body(new ResponseMessage("Uspesno kreiranje."));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(new ResponseMessage("Neuspesno kreiranje."));
}
}
@PostMapping(value = "/extract-metadata")
public ResponseEntity<String> extractMetadata(@RequestParam("file") MultipartFile file) throws Exception {
metadataExtractor.extract(domParserService.readMultipartXMLFile(file), dataset);
return new ResponseEntity<>("Metadata extraction finished.", HttpStatus.OK);
}
@PostMapping("/search-metadata")
public ResponseEntity<Collection<String>> searchMetadata(@RequestBody ZalbaCutanjeSPARQL zalbaCutanjeSPARQL) throws IOException {
ArrayList<String> result = zalbaCutanjeService.searchMetadata(zalbaCutanjeSPARQL, dataset);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@PostMapping(value = "/convert-to-html")
public ResponseEntity<String> convertToHTML(@RequestParam("file") MultipartFile file) throws Exception {
String result = zalbaCutanjeService.convertToHTML(domParserService.readMultipartXMLFile(file));
return new ResponseEntity<>(result, HttpStatus.OK);
}
@PostMapping(value = "/convert-to-pdf")
public ResponseEntity<byte[]> convertToPDF(@RequestParam("file") MultipartFile file) throws Exception {
ByteArrayOutputStream result = zalbaCutanjeService.convertToPDF(domParserService.readMultipartXMLFile(file));
return new ResponseEntity<>(result.toByteArray(), HttpStatus.OK);
}
}
|
UTF-8
|
Java
| 7,578 |
java
|
ZalbaCutanjeController.java
|
Java
|
[] | null |
[] |
package rs.pijz.server.poverenik.controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import rs.pijz.server.poverenik.dto.ResponseMessage;
import rs.pijz.server.poverenik.dto.sparql.ZalbaCutanjeSPARQL;
import rs.pijz.server.poverenik.fuseki.MetadataExtractor;
import rs.pijz.server.poverenik.model.zalba_cutanje.ZalbaCutanje;
import rs.pijz.server.poverenik.service.DomParserService;
import rs.pijz.server.poverenik.service.ZalbaCutanjeService;
@CrossOrigin
@RestController
@RequestMapping("/zalba-cutanje")
public class ZalbaCutanjeController {
@Autowired
private ZalbaCutanjeService zalbaCutanjeService;
@Autowired
private DomParserService domParserService;
@Autowired
private MetadataExtractor metadataExtractor;
private final String dataset = "conn.zalba-cutanje-dataset";
// @GetMapping(value = "", produces = MediaType.APPLICATION_XML_VALUE)
// private ResponseEntity<List<ZalbaCutanje>> findAll() {
// try {
// List<ZalbaCutanje> zalbe = zalbaCutanjeService.findAll();
// return ResponseEntity.ok().body(zalbe);
// } catch (Exception e) {
// e.printStackTrace();
// return ResponseEntity.badRequest().body(null);
// }
// }
@GetMapping(value = "", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<List<ZalbaCutanje>> findAllByParams(@RequestParam (required = false) String broj,
@RequestParam (required = false) String gradjaninID,
@RequestParam (required = false) Date datum,
@RequestParam (required = false) Date datumZahteva,
@RequestParam (required = false) String poverenikID,
@RequestParam (required = false) String sluzbenikID) {
try {
List<ZalbaCutanje> list;
if (broj != null && !broj.equals("")) {
list = zalbaCutanjeService.findAllByBroj(broj);
} else if (gradjaninID != null && !gradjaninID.equals("")) {
list = zalbaCutanjeService.findAllByGradjanin(gradjaninID);
} else if (datum != null) {
list = zalbaCutanjeService.findAllByDatum(datum);
} else if (datumZahteva != null) {
list = zalbaCutanjeService.findAllByDatumZahteva(datumZahteva);
} else if (poverenikID != null && !poverenikID.equals("")) {
list = zalbaCutanjeService.findAllByPoverenik(poverenikID);
} else if (sluzbenikID != null && !sluzbenikID.equals("")) {
list = zalbaCutanjeService.findAllBySluzbenik(sluzbenikID);
} else {
list = zalbaCutanjeService.findAll();
}
return ResponseEntity.ok().body(list);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@GetMapping(value = "/search", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<ZalbaCutanje> getOne(@RequestParam String id) {
try {
ZalbaCutanje zalba = zalbaCutanjeService.getOne(id);
return ResponseEntity.ok().body(zalba);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@PostMapping(value = "/create", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<ZalbaCutanje> create(@RequestBody ZalbaCutanje zalba) {
try {
ZalbaCutanje zalbaCutanje = zalbaCutanjeService.create(zalba);
return ResponseEntity.ok().body(zalbaCutanje);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@PostMapping(value = "/edit", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<ZalbaCutanje> edit(@RequestBody ZalbaCutanje zalbaCutanje) {
try {
ZalbaCutanje zalbaCutanje1 = zalbaCutanjeService.edit(zalbaCutanje);
return ResponseEntity.ok().body(zalbaCutanje1);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@DeleteMapping(value = "/delete", produces = MediaType.APPLICATION_XML_VALUE)
private ResponseEntity<Boolean> delete(@RequestParam String id) {
try {
Boolean deleted = zalbaCutanjeService.delete(id);
return ResponseEntity.ok().body(deleted);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(null);
}
}
@GetMapping(value = "/generate")
private ResponseEntity<ResponseMessage> generateDocuments(@RequestParam String id) {
try {
zalbaCutanjeService.generateDocuments(id);
return ResponseEntity.ok().body(new ResponseMessage("Uspesno kreiranje."));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(new ResponseMessage("Neuspesno kreiranje."));
}
}
@PostMapping(value = "/extract-metadata")
public ResponseEntity<String> extractMetadata(@RequestParam("file") MultipartFile file) throws Exception {
metadataExtractor.extract(domParserService.readMultipartXMLFile(file), dataset);
return new ResponseEntity<>("Metadata extraction finished.", HttpStatus.OK);
}
@PostMapping("/search-metadata")
public ResponseEntity<Collection<String>> searchMetadata(@RequestBody ZalbaCutanjeSPARQL zalbaCutanjeSPARQL) throws IOException {
ArrayList<String> result = zalbaCutanjeService.searchMetadata(zalbaCutanjeSPARQL, dataset);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@PostMapping(value = "/convert-to-html")
public ResponseEntity<String> convertToHTML(@RequestParam("file") MultipartFile file) throws Exception {
String result = zalbaCutanjeService.convertToHTML(domParserService.readMultipartXMLFile(file));
return new ResponseEntity<>(result, HttpStatus.OK);
}
@PostMapping(value = "/convert-to-pdf")
public ResponseEntity<byte[]> convertToPDF(@RequestParam("file") MultipartFile file) throws Exception {
ByteArrayOutputStream result = zalbaCutanjeService.convertToPDF(domParserService.readMultipartXMLFile(file));
return new ResponseEntity<>(result.toByteArray(), HttpStatus.OK);
}
}
| 7,578 | 0.665347 | 0.665083 | 164 | 45.207317 | 32.654972 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548781 | false | false |
3
|
bd53ec669d6ac6ce4fdcb448c15bbbe6513399a7
| 22,265,110,526,914 |
a277550342c60b932a36727eeeae21e9678eb8e0
|
/src/main/java/mods/cartlivery/common/network/LiveryGuiPatternMessage.java
|
ae7de16f4036fdcc04c43fc90ffa63530533b1c2
|
[
"MIT"
] |
permissive
|
kuenzign/CartLivery
|
https://github.com/kuenzign/CartLivery
|
20272678d5fde121d2e1d4254da63554f52676f9
|
b898241b2c968762b21b596b74d2926130374aa6
|
refs/heads/master
| 2021-01-22T16:18:16.245000 | 2015-07-23T06:04:51 | 2015-07-23T06:04:51 | 24,208,549 | 9 | 4 | null | true | 2015-07-05T02:23:48 | 2014-09-18T23:24:18 | 2015-04-13T20:00:40 | 2015-07-05T02:23:48 | 877 | 3 | 2 | 1 |
Java
| null | null |
package mods.cartlivery.common.network;
import mods.cartlivery.common.utils.NetworkUtil;
import io.netty.buffer.ByteBuf;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
public class LiveryGuiPatternMessage implements IMessage {
String pattern;
public LiveryGuiPatternMessage() { }
public LiveryGuiPatternMessage(String pattern) {
this.pattern = pattern;
}
public void fromBytes(ByteBuf buf) {
pattern = NetworkUtil.readString(buf);
}
public void toBytes(ByteBuf buf) {
NetworkUtil.writeString(pattern, buf);
}
}
|
UTF-8
|
Java
| 545 |
java
|
LiveryGuiPatternMessage.java
|
Java
|
[] | null |
[] |
package mods.cartlivery.common.network;
import mods.cartlivery.common.utils.NetworkUtil;
import io.netty.buffer.ByteBuf;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
public class LiveryGuiPatternMessage implements IMessage {
String pattern;
public LiveryGuiPatternMessage() { }
public LiveryGuiPatternMessage(String pattern) {
this.pattern = pattern;
}
public void fromBytes(ByteBuf buf) {
pattern = NetworkUtil.readString(buf);
}
public void toBytes(ByteBuf buf) {
NetworkUtil.writeString(pattern, buf);
}
}
| 545 | 0.774312 | 0.774312 | 25 | 20.799999 | 20.803846 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.04 | false | false |
3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.