file_id
stringlengths 5
9
| repo
stringlengths 8
57
| token_length
int64 59
7.96k
| path
stringlengths 8
105
| content
stringlengths 147
30.2k
| original_comment
stringlengths 14
5.13k
| prompt
stringlengths 82
30.2k
| Included
stringclasses 2
values |
---|---|---|---|---|---|---|---|
944_3 | bernii/IrisRecognition | 2,736 | src/MyGabor.java | import volume.GaussianDerivative;
import volume.Kernel1D;
import bijnum.BIJmatrix;
public class MyGabor {
public static Feature[] filter(float image[], float mask[], int width, float scales[])
{
int nrOrders = 3;
Feature ls[][][] = new Feature[scales.length][nrOrders][];
float thetas[][] = new float[nrOrders][];
int length = 0;
for(int j = 0; j < scales.length; j++)
{
for(int order = 0; order < nrOrders; order++)
{
thetas[order] = thetaSet(order);
ls[j][order] = L(image, mask, width, order, scales[j], thetas[order]);
length += ls[j][order].length;
}
}
Feature Ln[] = new Feature[length];
int index = 0;
for(int j = 0; j < scales.length; j++)
{
for(int order = 0; order < nrOrders; order++)
{
for(int i = 0; i < ls[j][order].length; i++)
Ln[index++] = ls[j][order][i];
}
}
ls = (Feature[][][])null;
return Ln;
}
public static float[] thetaSet(int order)
{
float theta[] = new float[order + 1];
theta[0] = 0.0F;
if(order == 1)
theta[1] = 90F;
else
if(order == 2)
{
theta[1] = 60F;
theta[2] = 120F;
} else
if(order != 0)
throw new IllegalArgumentException("order > 2");
return theta;
}
protected static String name(int order, double scale, double theta, String extraText)
{
if(order == 0)
return extraText + "L" + order + " scale=" + scale + "p";
else
return extraText + "L" + order + "(" + theta + " dgrs) scale=" + scale + "p";
}
public static Feature[] L(float image[], float mask[], int width, int n, double scale, float theta[])
{
Feature f[] = new Feature[theta.length];
float L[][] = new float[theta.length][];
if(n == 0)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
L[0] = convolvex(image, mask, width, image.length / width, k0);
L[0] = convolvey(L[0], width, image.length / width, k0);
f[0] = new Feature(name(n, scale, 0.0D, ""), L[0]);
} else
if(n == 1)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
volume.Kernel1D k1 = new GaussianDerivative(scale, 1);
float Lx[] = convolvex(image, mask, width, image.length / width, k1);
Lx = convolvey(Lx, width, image.length / width, k0);
float Ly[] = convolvex(image, mask, width, image.length / width, k0);
Ly = convolvey(Ly, width, image.length / width, k1);
for(int i = 0; i < theta.length; i++)
{
double cth = Math.cos((double)(theta[i] / 180F) * 3.1415926535897931D);
double sth = Math.sin((double)(theta[i] / 180F) * 3.1415926535897931D);
float px[] = new float[Lx.length];
BIJmatrix.mulElements(px, Lx, cth);
float py[] = new float[Lx.length];
BIJmatrix.mulElements(py, Ly, sth);
L[i] = BIJmatrix.addElements(px, py);
f[i] = new Feature(name(n, scale, theta[i], ""), L[i]);
}
} else
if(n == 2)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
volume.Kernel1D k1 = new GaussianDerivative(scale, 1);
volume.Kernel1D k2 = new GaussianDerivative(scale, 2);
float Lxx[] = convolvex(image, mask, width, image.length / width, k2);
Lxx = convolvey(Lxx, width, image.length / width, k0);
float Lxy[] = convolvex(image, mask, width, image.length / width, k1);
Lxy = convolvey(Lxy, width, image.length / width, k1);
float Lyy[] = convolvex(image, mask, width, image.length / width, k0);
Lyy = convolvey(Lyy, width, image.length / width, k2);
for(int i = 0; i < theta.length; i++)
{
double cth = Math.cos((double)(theta[i] / 180F) * 3.1415926535897931D);
double sth = Math.sin((double)(theta[i] / 180F) * 3.1415926535897931D);
double c2th = cth * cth;
double csth = cth * sth;
double s2th = sth * sth;
float pxx2[] = new float[Lxx.length];
BIJmatrix.mulElements(pxx2, Lxx, c2th);
float pxy2[] = new float[Lxy.length];
BIJmatrix.mulElements(pxy2, Lxy, 2D * csth);
float pyy2[] = new float[Lyy.length];
BIJmatrix.mulElements(pyy2, Lyy, s2th);
L[i] = BIJmatrix.addElements(pxx2, pxy2);
BIJmatrix.addElements(L[i], L[i], pyy2);
f[i] = new Feature(name(n, scale, theta[i], ""), L[i]);
}
}
return f;
}
/**
* Convolution of plane with 1D separated kernel along the x-axis.
* The image plane is organized as one 1D vector of width*height.
* Return the result as a float array. plane is not touched.
* @param plane the image.
* @param width the width in pixels of the image.
* @param height the height of the image in pixels.
* @param kernel a Kernel1D kernel object.
* @see Kernel1D
* @return a float[] with the resulting convolution.
*/
public static float [] convolvex(float [] plane, float [] mask, int width, int height, Kernel1D kernel)
{
float [] result = new float[plane.length];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float d = 0;
// Around x, convolve over -kernel.halfwidth .. x .. +kernel.halfwidth.
for (int k = -kernel.halfwidth; k <= kernel.halfwidth; k++)
{
// Mirror edges if needed.
int xi = x+k;
int yi = y;
if (xi < 0) xi = -xi;
else if (xi >= width) xi = 2 * width - xi - 1;
if (yi < 0) yi = -yi;
else if (yi >= height) yi = 2 * height - yi - 1;
if(mask[yi*width+xi]!=0) //sprawdzamy czy maska nie jest zerowa
d += plane[yi*width+xi] * kernel.k[k + kernel.halfwidth];
}
result[y*width+x] = d;
}
return result;
}
/**
* Convolution of plane with 1D separated kernel along the y-axis.
* The image plane is organized as one 1D vector of width*height.
* Return the result as a float array. plane is not touched.
* @param plane the image.
* @param width the width in pixels of the image.
* @param height the height of the image in pixels.
* @param kernel a Kernel1D kernel object.
* @see Kernel1D
* @return a float[] with the resulting convolution.
*/
public static float [] convolvey(float [] plane, int width, int height, Kernel1D kernel)
{
float [] result = new float[plane.length];
// Convolve in y direction.
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float d = 0;
// Around y, convolve over -kernel.halfwidth .. y .. +kernel.halfwidth.
for (int k = -kernel.halfwidth; k <= kernel.halfwidth; k++)
{
// Mirror edges if needed.
int xi = x;
int yi = y+k;
if (xi < 0) xi = -xi;
else if (xi >= width) xi = 2 * width - xi - 1;
if (yi < 0) yi = -yi;
else if (yi >= height) yi = 2 * height - yi - 1;
d += plane[yi*width+xi] * kernel.k[k + kernel.halfwidth];
}
result[y*width+x] = d;
}
return result;
}
}
| //sprawdzamy czy maska nie jest zerowa
| import volume.GaussianDerivative;
import volume.Kernel1D;
import bijnum.BIJmatrix;
public class MyGabor {
public static Feature[] filter(float image[], float mask[], int width, float scales[])
{
int nrOrders = 3;
Feature ls[][][] = new Feature[scales.length][nrOrders][];
float thetas[][] = new float[nrOrders][];
int length = 0;
for(int j = 0; j < scales.length; j++)
{
for(int order = 0; order < nrOrders; order++)
{
thetas[order] = thetaSet(order);
ls[j][order] = L(image, mask, width, order, scales[j], thetas[order]);
length += ls[j][order].length;
}
}
Feature Ln[] = new Feature[length];
int index = 0;
for(int j = 0; j < scales.length; j++)
{
for(int order = 0; order < nrOrders; order++)
{
for(int i = 0; i < ls[j][order].length; i++)
Ln[index++] = ls[j][order][i];
}
}
ls = (Feature[][][])null;
return Ln;
}
public static float[] thetaSet(int order)
{
float theta[] = new float[order + 1];
theta[0] = 0.0F;
if(order == 1)
theta[1] = 90F;
else
if(order == 2)
{
theta[1] = 60F;
theta[2] = 120F;
} else
if(order != 0)
throw new IllegalArgumentException("order > 2");
return theta;
}
protected static String name(int order, double scale, double theta, String extraText)
{
if(order == 0)
return extraText + "L" + order + " scale=" + scale + "p";
else
return extraText + "L" + order + "(" + theta + " dgrs) scale=" + scale + "p";
}
public static Feature[] L(float image[], float mask[], int width, int n, double scale, float theta[])
{
Feature f[] = new Feature[theta.length];
float L[][] = new float[theta.length][];
if(n == 0)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
L[0] = convolvex(image, mask, width, image.length / width, k0);
L[0] = convolvey(L[0], width, image.length / width, k0);
f[0] = new Feature(name(n, scale, 0.0D, ""), L[0]);
} else
if(n == 1)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
volume.Kernel1D k1 = new GaussianDerivative(scale, 1);
float Lx[] = convolvex(image, mask, width, image.length / width, k1);
Lx = convolvey(Lx, width, image.length / width, k0);
float Ly[] = convolvex(image, mask, width, image.length / width, k0);
Ly = convolvey(Ly, width, image.length / width, k1);
for(int i = 0; i < theta.length; i++)
{
double cth = Math.cos((double)(theta[i] / 180F) * 3.1415926535897931D);
double sth = Math.sin((double)(theta[i] / 180F) * 3.1415926535897931D);
float px[] = new float[Lx.length];
BIJmatrix.mulElements(px, Lx, cth);
float py[] = new float[Lx.length];
BIJmatrix.mulElements(py, Ly, sth);
L[i] = BIJmatrix.addElements(px, py);
f[i] = new Feature(name(n, scale, theta[i], ""), L[i]);
}
} else
if(n == 2)
{
volume.Kernel1D k0 = new GaussianDerivative(scale, 0);
volume.Kernel1D k1 = new GaussianDerivative(scale, 1);
volume.Kernel1D k2 = new GaussianDerivative(scale, 2);
float Lxx[] = convolvex(image, mask, width, image.length / width, k2);
Lxx = convolvey(Lxx, width, image.length / width, k0);
float Lxy[] = convolvex(image, mask, width, image.length / width, k1);
Lxy = convolvey(Lxy, width, image.length / width, k1);
float Lyy[] = convolvex(image, mask, width, image.length / width, k0);
Lyy = convolvey(Lyy, width, image.length / width, k2);
for(int i = 0; i < theta.length; i++)
{
double cth = Math.cos((double)(theta[i] / 180F) * 3.1415926535897931D);
double sth = Math.sin((double)(theta[i] / 180F) * 3.1415926535897931D);
double c2th = cth * cth;
double csth = cth * sth;
double s2th = sth * sth;
float pxx2[] = new float[Lxx.length];
BIJmatrix.mulElements(pxx2, Lxx, c2th);
float pxy2[] = new float[Lxy.length];
BIJmatrix.mulElements(pxy2, Lxy, 2D * csth);
float pyy2[] = new float[Lyy.length];
BIJmatrix.mulElements(pyy2, Lyy, s2th);
L[i] = BIJmatrix.addElements(pxx2, pxy2);
BIJmatrix.addElements(L[i], L[i], pyy2);
f[i] = new Feature(name(n, scale, theta[i], ""), L[i]);
}
}
return f;
}
/**
* Convolution of plane with 1D separated kernel along the x-axis.
* The image plane is organized as one 1D vector of width*height.
* Return the result as a float array. plane is not touched.
* @param plane the image.
* @param width the width in pixels of the image.
* @param height the height of the image in pixels.
* @param kernel a Kernel1D kernel object.
* @see Kernel1D
* @return a float[] with the resulting convolution.
*/
public static float [] convolvex(float [] plane, float [] mask, int width, int height, Kernel1D kernel)
{
float [] result = new float[plane.length];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float d = 0;
// Around x, convolve over -kernel.halfwidth .. x .. +kernel.halfwidth.
for (int k = -kernel.halfwidth; k <= kernel.halfwidth; k++)
{
// Mirror edges if needed.
int xi = x+k;
int yi = y;
if (xi < 0) xi = -xi;
else if (xi >= width) xi = 2 * width - xi - 1;
if (yi < 0) yi = -yi;
else if (yi >= height) yi = 2 * height - yi - 1;
if(mask[yi*width+xi]!=0) //sprawdzamy czy <SUF>
d += plane[yi*width+xi] * kernel.k[k + kernel.halfwidth];
}
result[y*width+x] = d;
}
return result;
}
/**
* Convolution of plane with 1D separated kernel along the y-axis.
* The image plane is organized as one 1D vector of width*height.
* Return the result as a float array. plane is not touched.
* @param plane the image.
* @param width the width in pixels of the image.
* @param height the height of the image in pixels.
* @param kernel a Kernel1D kernel object.
* @see Kernel1D
* @return a float[] with the resulting convolution.
*/
public static float [] convolvey(float [] plane, int width, int height, Kernel1D kernel)
{
float [] result = new float[plane.length];
// Convolve in y direction.
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
float d = 0;
// Around y, convolve over -kernel.halfwidth .. y .. +kernel.halfwidth.
for (int k = -kernel.halfwidth; k <= kernel.halfwidth; k++)
{
// Mirror edges if needed.
int xi = x;
int yi = y+k;
if (xi < 0) xi = -xi;
else if (xi >= width) xi = 2 * width - xi - 1;
if (yi < 0) yi = -yi;
else if (yi >= height) yi = 2 * height - yi - 1;
d += plane[yi*width+xi] * kernel.k[k + kernel.halfwidth];
}
result[y*width+x] = d;
}
return result;
}
}
| t |
2786_1 | bestemic/PRIR_2023-2024 | 184 | zad3/src/Binder.java | import javax.naming.NamingException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
/**
* Interfejs rejestracji usługi RMI.
*/
public interface Binder {
/**
* Rejestruje w rmiregistry pod podaną nazwą serwer usługi. Usługa rmiregistry
* będzie uruchomiona pod adresem localhost:1099. <b>Metoda nie może
* samodzielnie uruchamiać rmiregistry!</b>
*
* @param serviceName oczekiwana nazwa usługi w rmiregistry
*/
public void bind(String serviceName);
}
| /**
* Rejestruje w rmiregistry pod podaną nazwą serwer usługi. Usługa rmiregistry
* będzie uruchomiona pod adresem localhost:1099. <b>Metoda nie może
* samodzielnie uruchamiać rmiregistry!</b>
*
* @param serviceName oczekiwana nazwa usługi w rmiregistry
*/ | import javax.naming.NamingException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
/**
* Interfejs rejestracji usługi RMI.
*/
public interface Binder {
/**
* Rejestruje w rmiregistry <SUF>*/
public void bind(String serviceName);
}
| f |
6845_2 | beto4444/GRAPHen | 5,577 | src/GNListener.java | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import DataStructures.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
public class GNListener extends GRAPHenBaseListener {
private final HashMap<String, Node> nodes = new HashMap<>();
private final HashMap<String, Edge> edges = new HashMap<>();
private final HashMap<String, Graph> graphs = new HashMap<>();
private final ArrayList<String> errorsList = new ArrayList<String>();
private Node currentNode;
private Edge currentEdge;
private Graph currentGraph;
private Digraph currentDigraph;
public List<Edge> getEdges(){
return new ArrayList<Edge>(edges.values());
}
public List<Node> getNodes(){
return new ArrayList<Node>(nodes.values());
}
public List<Graph> getGraphs(){
return new ArrayList<Graph>(graphs.values());
}
public String errorsToString(){
StringBuilder sb = new StringBuilder();
if(!errorsList.isEmpty()) {
for (String error : errorsList) {
sb.append(error);
sb.append('\n');
}
}
else{
sb.append("Everything ok!");
}
return sb.toString();
}
public void describeData(){
System.out.println("Węzły: ");
if(!nodes.keySet().isEmpty()) {
for (String i : nodes.keySet()) {
System.out.print(i);
System.out.print(", ");
}
}
else{System.out.println("Brak");}
System.out.println("Krawędzie: ");
if(!edges.keySet().isEmpty()) {
for (String i : edges.keySet()) {
System.out.print(i);
System.out.print(", ");
}
}
else{System.out.println("Brak");}
}
@Override
public void enterNode_definition(GRAPHenParser.Node_definitionContext ctx) {
String id = ctx.IDENTIFIER().getText();
Node node = new Node();
currentNode = node;
nodes.put(id, node);
}
@Override
public void enterNode_inline(GRAPHenParser.Node_inlineContext ctx) {
String id = ctx.IDENTIFIER().getText();
Node node = new Node();
currentNode = node;
nodes.put(id, node);
}
@Override
public void enterNode_properties(GRAPHenParser.Node_propertiesContext ctx) {
Node node = currentNode;
TerminalNode numColorNode = ctx.TEXT();
if (numColorNode != null) {
String contents = ctx.TEXT().getText();
node.setNodeContents(contents);
}
TerminalNode contColor = ctx.COLOR(0);
if (contColor != null) {
String Color = contColor.getText();
node.setContColor(Color);
}
TerminalNode contSizeCtx = ctx.POS_NUMBER(0);
if (contSizeCtx != null) {
int Size = Integer.parseInt(contSizeCtx.getText());
node.setContSize(Size);
}
TerminalNode fillColor = ctx.COLOR(1);
if (fillColor != null) {
String Color = fillColor.getText();
node.setFillColor(Color);
}
TerminalNode borderColor = ctx.COLOR(2);
if (borderColor != null) {
String Color = borderColor.getText();
node.setBorderColor(Color);
}
TerminalNode nodeShapeCtx = ctx.NODE_SHAPE();
if (nodeShapeCtx != null) {
NodeShape nodeShape = NodeShape.valueOf(nodeShapeCtx.getText());
node.setNodeShape(nodeShape);
}
TerminalNode nodeSizeCtx = ctx.POS_NUMBER(1);
if (nodeSizeCtx != null) {
int nodeSize = Integer.parseInt(nodeSizeCtx.getText());
node.setNodeSize(nodeSize);
}
// Get the optional 'borderWidth' property
TerminalNode borderWidthCtx = ctx.POS_NUMBER(2);
if (borderWidthCtx != null) {
int borderWidth = Integer.parseInt(borderWidthCtx.getText());
node.setBorderWidth(borderWidth);
}
// Get the optional 'borderLineShape' property
TerminalNode borderLineShapeCtx = ctx.LINE_TYPE();
if (borderLineShapeCtx != null) {
LineType borderLineShape = LineType.valueOf(borderLineShapeCtx.getText());
node.setBorderLineShape(borderLineShape);
}
}
@Override
public void enterEdge_definition(GRAPHenParser.Edge_definitionContext ctx) {
String id = ctx.IDENTIFIER().getText();
Edge edge = new Edge();
currentEdge = edge;
edges.put(id, edge);
}
@Override
public void enterEdge_inline(GRAPHenParser.Edge_inlineContext ctx) {
String id = ctx.IDENTIFIER().getText();
Edge edge = new Edge();
currentEdge = edge;
edges.put(id, edge);
}
@Override
public void enterEdge_properties(GRAPHenParser.Edge_propertiesContext ctx) {
Edge edge = currentEdge;
TerminalNode numberNode = ctx.NUMBER();
if (numberNode != null) {
int number = Integer.parseInt(numberNode.getText());
edge.setNumColor(number);
}
TerminalNode posNumberNode = ctx.POS_NUMBER(0);
if (posNumberNode != null) {
int posNumber = Integer.parseInt(posNumberNode.getText());
edge.setLineWidth(posNumber);
}
TerminalNode colorNode = ctx.COLOR();
if (colorNode != null) {
String color = colorNode.getText();
edge.setColor(color);
}
TerminalNode lineTypeNode = ctx.LINE_TYPE();
if (lineTypeNode != null) {
LineType lineType = LineType.valueOf(lineTypeNode.getText());
edge.setLineType(lineType);
}
}
@Override
public void enterGraph_definition(GRAPHenParser.Graph_definitionContext ctx) {
String graphName = ctx.IDENTIFIER().getText();
Graph graph;
graph = new Graph();
graphs.put(graphName, graph);
currentGraph = graph;
if (ctx.edge_list() != null) {
enterEdge_list(ctx.edge_list());
if (ctx.graph_function() != null){
enterGraph_function(ctx.graph_function());
}
} else if (ctx.graph_add() != null) {
enterGraph_add(ctx.graph_add());
} else if (ctx.graph_substract() != null) {
enterGraph_substract(ctx.graph_substract());
} else if (ctx.graph_union() != null){
enterGraph_union(ctx.graph_union());
}
}
@Override
public void enterEdge_list(GRAPHenParser.Edge_listContext ctx) {
List<GRAPHenParser.Edge_relationContext> edgeRelationContexts = ctx.edge_relation();
for (GRAPHenParser.Edge_relationContext edgeRelationContext : edgeRelationContexts) {
enterEdge_relation(edgeRelationContext);
}
}
@Override
public void enterEdge_relation(GRAPHenParser.Edge_relationContext ctx) {
List<ParseTree> children = ctx.children;
Node parent = null;
Edge edge = null;
List<Node> child = new ArrayList<>();
ParseTree firstNodeOrIdentifier = children.get(0);
if (firstNodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = firstNodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
int Line = ctx.getStart().getLine();
String error = "LISTENER ERROR: Line " + Line + ": 1Node " + identifier + " not defined";
if(!errorsList.contains(error)) {
errorsList.add(error);
}
}else {
parent = nodes.get(identifier);
}
} else if (firstNodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) firstNodeOrIdentifier);
parent = currentNode; //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
ParseTree edgeOrIdentifier = children.get(3);
if (edgeOrIdentifier instanceof TerminalNode) {
String identifier = edgeOrIdentifier.getText();
if (!edges.containsKey(identifier)){
int Line = ctx.getStart().getLine();
String error = "LISTENER ERROR: Line " + Line + ": Edge " + identifier + " not defined";
if(!errorsList.contains(error)) {
errorsList.add(error);
}
}
else {
edge = edges.get(identifier);
}
} else if (edgeOrIdentifier instanceof GRAPHenParser.Edge_inlineContext) {
enterEdge_inline((GRAPHenParser.Edge_inlineContext) edgeOrIdentifier);
edge = currentEdge;
}
ParseTree secondNodeOrIdentifier = children.get(4);
if (secondNodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = secondNodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
int Line = ctx.getStart().getLine();
String error = "LISTENER ERROR: Line " + Line + ": Node " + identifier + " not defined";
if(!errorsList.contains(error)&&!identifier.equals(")")) {
errorsList.add(error);
}
}else {
child.add(nodes.get(identifier));
}
} else if (secondNodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) secondNodeOrIdentifier);
child.add(currentNode); //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
for (int i = 5; i < children.size(); i += 2) {
ParseTree nodeOrIdentifier = children.get(i);
if (nodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = nodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
int Line = ctx.getStart().getLine();
String error = "LISTENER ERROR: Line " + Line + ": Node " + identifier + " not defined";
if(!errorsList.contains(error)) {
errorsList.add(error);
}
}else {
child.add(nodes.get(identifier));
}
} else if (nodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) nodeOrIdentifier);
child.add(currentNode); //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
}
if (parent == null || edge == null || child.size() == 0){
return; //nie powinno się zdarzyć @TODO wyjątek
}
edge.setRelations(parent, child); //@TODO zamienić child na children dlaczego nazwałam to child
currentGraph.addRelation(parent, edge, child);
}
@Override
public void enterGraph_add(GRAPHenParser.Graph_addContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Add(second)); //@TODO: czy tu potrzebne copy?
}
@Override
public void enterGraph_substract(GRAPHenParser.Graph_substractContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Substract(second)); //@TODO: czy tu potrzebne copy?
}
@Override
public void enterGraph_union(GRAPHenParser.Graph_unionContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Union(second)); //@TODO: czy tu potrzebne copy?
}
@Override
public void enterGraph_function(GRAPHenParser.Graph_functionContext ctx) {
if (ctx.colorEdgesFunc() != null){
enterColorEdgesFunc(ctx.colorEdgesFunc());
}
else if (ctx.colorNodesFunc() != null){
enterColorNodesFunc(ctx.colorNodesFunc());
}
else {
String foo = ctx.getText();
if (foo.equals("clearEdges()")) {
currentGraph.clearEdges();
}
}
}
@Override
public void enterColorEdgesFunc(GRAPHenParser.ColorEdgesFuncContext ctx) {
currentGraph.colorEdges();
}
@Override
public void enterColorNodesFunc(GRAPHenParser.ColorNodesFuncContext ctx) {
currentGraph.colorNodes();
}
@Override
public void enterDigraph_definition(GRAPHenParser.Digraph_definitionContext ctx) {
String graphName = ctx.IDENTIFIER().getText();
Graph graph;
graph = new Graph(true);
graphs.put(graphName, graph);
currentGraph = graph;
if (ctx.dedge_list() != null) {
enterDedge_list(ctx.dedge_list());
if (ctx.graph_function() != null){
enterGraph_function(ctx.graph_function());
}
} else if (ctx.digraph_add() != null) {
enterDigraph_add(ctx.digraph_add());
} else if (ctx.digraph_substract() != null) {
enterDigraph_substract(ctx.digraph_substract());
} else if (ctx.digraph_union() != null) {
enterDigraph_union(ctx.digraph_union());
}
}
@Override
public void enterDedge_list(GRAPHenParser.Dedge_listContext ctx) {
List<GRAPHenParser.Dedge_relationContext> dedgeRelationContexts = ctx.dedge_relation();
for (GRAPHenParser.Dedge_relationContext dedgeRelationContext : dedgeRelationContexts) {
enterDedge_relation(dedgeRelationContext);
}
}
@Override
public void enterDedge_relation(GRAPHenParser.Dedge_relationContext ctx) {
List<ParseTree> children = ctx.children;
Node parent = null;
Edge edge = null;
List<Node> child = new ArrayList<>();
ParseTree firstNodeOrIdentifier = children.get(0);
if (firstNodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = firstNodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
//@TODO: throw node does not exist error
}else {
parent = nodes.get(identifier);
}
} else if (firstNodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) firstNodeOrIdentifier);
parent = currentNode; //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
ParseTree edgeOrIdentifier = children.get(3);
if (edgeOrIdentifier instanceof TerminalNode) {
String identifier = edgeOrIdentifier.getText();
if (!edges.containsKey(identifier)){
//@TODO: throw edge does not exist error
}
else {
edge = edges.get(identifier);
}
} else if (edgeOrIdentifier instanceof GRAPHenParser.Edge_inlineContext) {
enterEdge_inline((GRAPHenParser.Edge_inlineContext) edgeOrIdentifier);
edge = currentEdge;
}
ParseTree secondNodeOrIdentifier = children.get(4);
if (secondNodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = secondNodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
//@TODO: throw node does not exist error
}else {
child.add(nodes.get(identifier));
}
} else if (secondNodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) secondNodeOrIdentifier);
child.add(currentNode); //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
for (int i = 5; i < children.size(); i += 2) {
ParseTree nodeOrIdentifier = children.get(i);
if (nodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = nodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
//@TODO: throw node does not exist error
}else {
child.add(nodes.get(identifier));
}
} else if (nodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) nodeOrIdentifier);
child.add(currentNode); //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
}
if (parent == null || edge == null || child.size() == 0){
return; //nie powinno się zdarzyć
}
currentGraph.addRelation(parent, edge, child);
}
@Override
public void enterDigraph_add(GRAPHenParser.Digraph_addContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Add(second));
}
@Override
public void enterDigraph_substract(GRAPHenParser.Digraph_substractContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Substract(second));
}
@Override
public void enterDigraph_union(GRAPHenParser.Digraph_unionContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Union(second));
}
@Override
public void enterGraph_function_statement(GRAPHenParser.Graph_function_statementContext ctx) {
String id = ctx.IDENTIFIER().getText();
if (!graphs.containsKey(id)){
//@TODO: error
}
else {
currentGraph = graphs.get(id);
enterGraph_function(ctx.graph_function());
}
}
//@TODO: export to file function
}
| //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import DataStructures.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
public class GNListener extends GRAPHenBaseListener {
private final HashMap<String, Node> nodes = new HashMap<>();
private final HashMap<String, Edge> edges = new HashMap<>();
private final HashMap<String, Graph> graphs = new HashMap<>();
private final ArrayList<String> errorsList = new ArrayList<String>();
private Node currentNode;
private Edge currentEdge;
private Graph currentGraph;
private Digraph currentDigraph;
public List<Edge> getEdges(){
return new ArrayList<Edge>(edges.values());
}
public List<Node> getNodes(){
return new ArrayList<Node>(nodes.values());
}
public List<Graph> getGraphs(){
return new ArrayList<Graph>(graphs.values());
}
public String errorsToString(){
StringBuilder sb = new StringBuilder();
if(!errorsList.isEmpty()) {
for (String error : errorsList) {
sb.append(error);
sb.append('\n');
}
}
else{
sb.append("Everything ok!");
}
return sb.toString();
}
public void describeData(){
System.out.println("Węzły: ");
if(!nodes.keySet().isEmpty()) {
for (String i : nodes.keySet()) {
System.out.print(i);
System.out.print(", ");
}
}
else{System.out.println("Brak");}
System.out.println("Krawędzie: ");
if(!edges.keySet().isEmpty()) {
for (String i : edges.keySet()) {
System.out.print(i);
System.out.print(", ");
}
}
else{System.out.println("Brak");}
}
@Override
public void enterNode_definition(GRAPHenParser.Node_definitionContext ctx) {
String id = ctx.IDENTIFIER().getText();
Node node = new Node();
currentNode = node;
nodes.put(id, node);
}
@Override
public void enterNode_inline(GRAPHenParser.Node_inlineContext ctx) {
String id = ctx.IDENTIFIER().getText();
Node node = new Node();
currentNode = node;
nodes.put(id, node);
}
@Override
public void enterNode_properties(GRAPHenParser.Node_propertiesContext ctx) {
Node node = currentNode;
TerminalNode numColorNode = ctx.TEXT();
if (numColorNode != null) {
String contents = ctx.TEXT().getText();
node.setNodeContents(contents);
}
TerminalNode contColor = ctx.COLOR(0);
if (contColor != null) {
String Color = contColor.getText();
node.setContColor(Color);
}
TerminalNode contSizeCtx = ctx.POS_NUMBER(0);
if (contSizeCtx != null) {
int Size = Integer.parseInt(contSizeCtx.getText());
node.setContSize(Size);
}
TerminalNode fillColor = ctx.COLOR(1);
if (fillColor != null) {
String Color = fillColor.getText();
node.setFillColor(Color);
}
TerminalNode borderColor = ctx.COLOR(2);
if (borderColor != null) {
String Color = borderColor.getText();
node.setBorderColor(Color);
}
TerminalNode nodeShapeCtx = ctx.NODE_SHAPE();
if (nodeShapeCtx != null) {
NodeShape nodeShape = NodeShape.valueOf(nodeShapeCtx.getText());
node.setNodeShape(nodeShape);
}
TerminalNode nodeSizeCtx = ctx.POS_NUMBER(1);
if (nodeSizeCtx != null) {
int nodeSize = Integer.parseInt(nodeSizeCtx.getText());
node.setNodeSize(nodeSize);
}
// Get the optional 'borderWidth' property
TerminalNode borderWidthCtx = ctx.POS_NUMBER(2);
if (borderWidthCtx != null) {
int borderWidth = Integer.parseInt(borderWidthCtx.getText());
node.setBorderWidth(borderWidth);
}
// Get the optional 'borderLineShape' property
TerminalNode borderLineShapeCtx = ctx.LINE_TYPE();
if (borderLineShapeCtx != null) {
LineType borderLineShape = LineType.valueOf(borderLineShapeCtx.getText());
node.setBorderLineShape(borderLineShape);
}
}
@Override
public void enterEdge_definition(GRAPHenParser.Edge_definitionContext ctx) {
String id = ctx.IDENTIFIER().getText();
Edge edge = new Edge();
currentEdge = edge;
edges.put(id, edge);
}
@Override
public void enterEdge_inline(GRAPHenParser.Edge_inlineContext ctx) {
String id = ctx.IDENTIFIER().getText();
Edge edge = new Edge();
currentEdge = edge;
edges.put(id, edge);
}
@Override
public void enterEdge_properties(GRAPHenParser.Edge_propertiesContext ctx) {
Edge edge = currentEdge;
TerminalNode numberNode = ctx.NUMBER();
if (numberNode != null) {
int number = Integer.parseInt(numberNode.getText());
edge.setNumColor(number);
}
TerminalNode posNumberNode = ctx.POS_NUMBER(0);
if (posNumberNode != null) {
int posNumber = Integer.parseInt(posNumberNode.getText());
edge.setLineWidth(posNumber);
}
TerminalNode colorNode = ctx.COLOR();
if (colorNode != null) {
String color = colorNode.getText();
edge.setColor(color);
}
TerminalNode lineTypeNode = ctx.LINE_TYPE();
if (lineTypeNode != null) {
LineType lineType = LineType.valueOf(lineTypeNode.getText());
edge.setLineType(lineType);
}
}
@Override
public void enterGraph_definition(GRAPHenParser.Graph_definitionContext ctx) {
String graphName = ctx.IDENTIFIER().getText();
Graph graph;
graph = new Graph();
graphs.put(graphName, graph);
currentGraph = graph;
if (ctx.edge_list() != null) {
enterEdge_list(ctx.edge_list());
if (ctx.graph_function() != null){
enterGraph_function(ctx.graph_function());
}
} else if (ctx.graph_add() != null) {
enterGraph_add(ctx.graph_add());
} else if (ctx.graph_substract() != null) {
enterGraph_substract(ctx.graph_substract());
} else if (ctx.graph_union() != null){
enterGraph_union(ctx.graph_union());
}
}
@Override
public void enterEdge_list(GRAPHenParser.Edge_listContext ctx) {
List<GRAPHenParser.Edge_relationContext> edgeRelationContexts = ctx.edge_relation();
for (GRAPHenParser.Edge_relationContext edgeRelationContext : edgeRelationContexts) {
enterEdge_relation(edgeRelationContext);
}
}
@Override
public void enterEdge_relation(GRAPHenParser.Edge_relationContext ctx) {
List<ParseTree> children = ctx.children;
Node parent = null;
Edge edge = null;
List<Node> child = new ArrayList<>();
ParseTree firstNodeOrIdentifier = children.get(0);
if (firstNodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = firstNodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
int Line = ctx.getStart().getLine();
String error = "LISTENER ERROR: Line " + Line + ": 1Node " + identifier + " not defined";
if(!errorsList.contains(error)) {
errorsList.add(error);
}
}else {
parent = nodes.get(identifier);
}
} else if (firstNodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) firstNodeOrIdentifier);
parent = currentNode; //@TODO: zabezpieczyć <SUF>
}
ParseTree edgeOrIdentifier = children.get(3);
if (edgeOrIdentifier instanceof TerminalNode) {
String identifier = edgeOrIdentifier.getText();
if (!edges.containsKey(identifier)){
int Line = ctx.getStart().getLine();
String error = "LISTENER ERROR: Line " + Line + ": Edge " + identifier + " not defined";
if(!errorsList.contains(error)) {
errorsList.add(error);
}
}
else {
edge = edges.get(identifier);
}
} else if (edgeOrIdentifier instanceof GRAPHenParser.Edge_inlineContext) {
enterEdge_inline((GRAPHenParser.Edge_inlineContext) edgeOrIdentifier);
edge = currentEdge;
}
ParseTree secondNodeOrIdentifier = children.get(4);
if (secondNodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = secondNodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
int Line = ctx.getStart().getLine();
String error = "LISTENER ERROR: Line " + Line + ": Node " + identifier + " not defined";
if(!errorsList.contains(error)&&!identifier.equals(")")) {
errorsList.add(error);
}
}else {
child.add(nodes.get(identifier));
}
} else if (secondNodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) secondNodeOrIdentifier);
child.add(currentNode); //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
for (int i = 5; i < children.size(); i += 2) {
ParseTree nodeOrIdentifier = children.get(i);
if (nodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = nodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
int Line = ctx.getStart().getLine();
String error = "LISTENER ERROR: Line " + Line + ": Node " + identifier + " not defined";
if(!errorsList.contains(error)) {
errorsList.add(error);
}
}else {
child.add(nodes.get(identifier));
}
} else if (nodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) nodeOrIdentifier);
child.add(currentNode); //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
}
if (parent == null || edge == null || child.size() == 0){
return; //nie powinno się zdarzyć @TODO wyjątek
}
edge.setRelations(parent, child); //@TODO zamienić child na children dlaczego nazwałam to child
currentGraph.addRelation(parent, edge, child);
}
@Override
public void enterGraph_add(GRAPHenParser.Graph_addContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Add(second)); //@TODO: czy tu potrzebne copy?
}
@Override
public void enterGraph_substract(GRAPHenParser.Graph_substractContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Substract(second)); //@TODO: czy tu potrzebne copy?
}
@Override
public void enterGraph_union(GRAPHenParser.Graph_unionContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Union(second)); //@TODO: czy tu potrzebne copy?
}
@Override
public void enterGraph_function(GRAPHenParser.Graph_functionContext ctx) {
if (ctx.colorEdgesFunc() != null){
enterColorEdgesFunc(ctx.colorEdgesFunc());
}
else if (ctx.colorNodesFunc() != null){
enterColorNodesFunc(ctx.colorNodesFunc());
}
else {
String foo = ctx.getText();
if (foo.equals("clearEdges()")) {
currentGraph.clearEdges();
}
}
}
@Override
public void enterColorEdgesFunc(GRAPHenParser.ColorEdgesFuncContext ctx) {
currentGraph.colorEdges();
}
@Override
public void enterColorNodesFunc(GRAPHenParser.ColorNodesFuncContext ctx) {
currentGraph.colorNodes();
}
@Override
public void enterDigraph_definition(GRAPHenParser.Digraph_definitionContext ctx) {
String graphName = ctx.IDENTIFIER().getText();
Graph graph;
graph = new Graph(true);
graphs.put(graphName, graph);
currentGraph = graph;
if (ctx.dedge_list() != null) {
enterDedge_list(ctx.dedge_list());
if (ctx.graph_function() != null){
enterGraph_function(ctx.graph_function());
}
} else if (ctx.digraph_add() != null) {
enterDigraph_add(ctx.digraph_add());
} else if (ctx.digraph_substract() != null) {
enterDigraph_substract(ctx.digraph_substract());
} else if (ctx.digraph_union() != null) {
enterDigraph_union(ctx.digraph_union());
}
}
@Override
public void enterDedge_list(GRAPHenParser.Dedge_listContext ctx) {
List<GRAPHenParser.Dedge_relationContext> dedgeRelationContexts = ctx.dedge_relation();
for (GRAPHenParser.Dedge_relationContext dedgeRelationContext : dedgeRelationContexts) {
enterDedge_relation(dedgeRelationContext);
}
}
@Override
public void enterDedge_relation(GRAPHenParser.Dedge_relationContext ctx) {
List<ParseTree> children = ctx.children;
Node parent = null;
Edge edge = null;
List<Node> child = new ArrayList<>();
ParseTree firstNodeOrIdentifier = children.get(0);
if (firstNodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = firstNodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
//@TODO: throw node does not exist error
}else {
parent = nodes.get(identifier);
}
} else if (firstNodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) firstNodeOrIdentifier);
parent = currentNode; //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
ParseTree edgeOrIdentifier = children.get(3);
if (edgeOrIdentifier instanceof TerminalNode) {
String identifier = edgeOrIdentifier.getText();
if (!edges.containsKey(identifier)){
//@TODO: throw edge does not exist error
}
else {
edge = edges.get(identifier);
}
} else if (edgeOrIdentifier instanceof GRAPHenParser.Edge_inlineContext) {
enterEdge_inline((GRAPHenParser.Edge_inlineContext) edgeOrIdentifier);
edge = currentEdge;
}
ParseTree secondNodeOrIdentifier = children.get(4);
if (secondNodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = secondNodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
//@TODO: throw node does not exist error
}else {
child.add(nodes.get(identifier));
}
} else if (secondNodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) secondNodeOrIdentifier);
child.add(currentNode); //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
for (int i = 5; i < children.size(); i += 2) {
ParseTree nodeOrIdentifier = children.get(i);
if (nodeOrIdentifier instanceof TerminalNode) {
// Handle identifier
String identifier = nodeOrIdentifier.getText();
if (!nodes.containsKey(identifier)){
//@TODO: throw node does not exist error
}else {
child.add(nodes.get(identifier));
}
} else if (nodeOrIdentifier instanceof GRAPHenParser.Node_inlineContext) {
// Handle node_inline
enterNode_inline((GRAPHenParser.Node_inlineContext) nodeOrIdentifier);
child.add(currentNode); //@TODO: zabezpieczyć (np. zmieniać currentNode na null po zakończeniu używnaia i sprawdzać czy wszystko działa
}
}
if (parent == null || edge == null || child.size() == 0){
return; //nie powinno się zdarzyć
}
currentGraph.addRelation(parent, edge, child);
}
@Override
public void enterDigraph_add(GRAPHenParser.Digraph_addContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Add(second));
}
@Override
public void enterDigraph_substract(GRAPHenParser.Digraph_substractContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Substract(second));
}
@Override
public void enterDigraph_union(GRAPHenParser.Digraph_unionContext ctx) {
String firstId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(firstId)){
//@TODO: graph does not exist
}
Graph first = graphs.get(firstId);
String secondId = ctx.IDENTIFIER(0).getText();
if (!graphs.containsKey(secondId)){
//@TODO: graph does not exist
}
Graph second = graphs.get(secondId);
currentGraph.copy(first.Union(second));
}
@Override
public void enterGraph_function_statement(GRAPHenParser.Graph_function_statementContext ctx) {
String id = ctx.IDENTIFIER().getText();
if (!graphs.containsKey(id)){
//@TODO: error
}
else {
currentGraph = graphs.get(id);
enterGraph_function(ctx.graph_function());
}
}
//@TODO: export to file function
}
| f |
6759_1 | blostic/BO | 597 | BO/src/bo/project/logic/Generator.java | package bo.project.logic;
import java.util.ArrayList;
import java.util.Random;
@SuppressWarnings("serial")
public class Generator extends Junction{
private boolean generateFlag;
public Generator(ArrayList<Road> entryRoads, ArrayList<Road> awayRoads, int x, int y){
super(entryRoads,awayRoads, x, y);
generateFlag=false;
}
/*
* losuje czy powinienem dodawac nowe pojazdy
*
* dziwny warunek w ifie: timeInterval - czas przejazdu jednego samochodu
* trafficIntensity/3600 - ilosc samochodow na sekunde wiec powinno to nam dac
* ilosc samochodow w czasie przejazdu 1 samochodu, max 1 :)
*/
public boolean checkStatus(int currentTime, int timeInterval){
Random random = new Random();
for(Road road: escapeRoads){
if(random.nextDouble()<=(road.getTrafficIntensity()*timeInterval)/(3600.0)){
generateFlag=true;
}
else{
generateFlag=false;
}
}
return generateFlag;
}
/*
* Usuwam z modelu wszystkie samochody, ktoe dojechaly na jego koniec
* Dodaje nowe samochody, jesli jest taka potrzeba
*/
public void moveVehicles(int timeInterval) {
for(Road road: entryRoads){
road.getFirstWaitingVehicle(); //pobieramy pierwszy czekajacy na wyjazd i go od razu gubimy :)
road.moveVehiclesOnRoad(timeInterval); //przesuwam pozostale
}
if(generateFlag){
for(Road road: escapeRoads){
if(!road.isFull() && road.checkLastCarStatus(timeInterval)){
road.addVehicle(new Vehicle());
}
}
}
}
}
| /*
* Usuwam z modelu wszystkie samochody, ktoe dojechaly na jego koniec
* Dodaje nowe samochody, jesli jest taka potrzeba
*/ | package bo.project.logic;
import java.util.ArrayList;
import java.util.Random;
@SuppressWarnings("serial")
public class Generator extends Junction{
private boolean generateFlag;
public Generator(ArrayList<Road> entryRoads, ArrayList<Road> awayRoads, int x, int y){
super(entryRoads,awayRoads, x, y);
generateFlag=false;
}
/*
* losuje czy powinienem dodawac nowe pojazdy
*
* dziwny warunek w ifie: timeInterval - czas przejazdu jednego samochodu
* trafficIntensity/3600 - ilosc samochodow na sekunde wiec powinno to nam dac
* ilosc samochodow w czasie przejazdu 1 samochodu, max 1 :)
*/
public boolean checkStatus(int currentTime, int timeInterval){
Random random = new Random();
for(Road road: escapeRoads){
if(random.nextDouble()<=(road.getTrafficIntensity()*timeInterval)/(3600.0)){
generateFlag=true;
}
else{
generateFlag=false;
}
}
return generateFlag;
}
/*
* Usuwam z modelu <SUF>*/
public void moveVehicles(int timeInterval) {
for(Road road: entryRoads){
road.getFirstWaitingVehicle(); //pobieramy pierwszy czekajacy na wyjazd i go od razu gubimy :)
road.moveVehiclesOnRoad(timeInterval); //przesuwam pozostale
}
if(generateFlag){
for(Road road: escapeRoads){
if(!road.isFull() && road.checkLastCarStatus(timeInterval)){
road.addVehicle(new Vehicle());
}
}
}
}
}
| f |
5202_0 | bruno-kus/Itewriter_2-0 | 1,288 | src/main/java/com/example/itewriter/area/boxview/BoxPaneSequentialController.java | package com.example.itewriter.area.boxview;
import com.example.itewriter.area.tightArea.Registry;
import com.example.itewriter.area.tightArea.TagSelector;
import com.example.itewriter.area.tightArea.VariationSelector;
/**
* moje pytanie brzmi:
* czy jest sens instancjonować BoxPane view bez kontrolera?
* czy może powinienem mieć jeszcze jeden poziom abstrakcji
* czym może być wiele kontrolerów lub wiele boxPane'ów??
*/
public class BoxPaneSequentialController {
/*
registry -> tagSelector -> variationSelector
tagSelector, variationSelector -> boxPaneController
pytanie brzmi czy box pane ma prawo działać, jeżeli selectory nie są połączone
wydaje mi się że powinien być całkowicie z enkapsulowany!
BOX CONTROLLER tyczy się tylko boxa
może nie mieć sensu w ogóle kontroler pojedynczej wariacji dla innych widoków jak choćby sama strefa!
*/
public final BoxPaneView boxPaneView;
private final VariationSelector variationSelector;
private final TagSelector tagSelector;
/*
tutaj powinien być zarówno API do next tag, jak i do next variation
*/
/*
teraz mogę w jakiś zmyślny sposób opakować zarówno niskie api sterowania wariacją,
jak i samym tagiem
pytanie co jest potrzebne do jakiej zmiany, na których mi zależy oraz która klasa powinna tym się zajmować
*/
public BoxPaneSequentialController(BoxPaneView boxPaneView, Registry registry) {
// czy ta klasa powinna mieć properties'a, który byłby zbindowany
int bop = 8;
bop++;
System.out.println(bop);
this.boxPaneView = boxPaneView;
this.variationSelector = new VariationSelector(tagSelector = new TagSelector(registry));
this.variationSelector.getSelectedVariationObservable().addListener((variationProperty, oldVariation, newVariation) -> {
boxPaneView.displayedPassages.setValue(registry.viewOf(newVariation));
// to powinno być przeniesione do implementacji viewOf
for (var textFieldPassage : boxPaneView.getSimpleInternalModelProperty()) {
var variationPassage = newVariation.getPassage(textFieldPassage.getPosition());
textFieldPassage.textProperty().unbind();
textFieldPassage.textProperty().setValue(variationPassage.textProperty().getValue());
textFieldPassage.textProperty().bind(variationPassage.textProperty());
textFieldPassage.textProperty().addListener((textProperty, oldText, newText) -> { // taki sam handler powinien być, kiedy dodawane są nowe elementy do wariacji
registry.offsetAllTags(textFieldPassage.getPosition(), newText.length() - textFieldPassage.textProperty().getValue().length());
newVariation.getPassage(textFieldPassage.getPosition()).textProperty().setValue(newText); // modyfikuje korespondującego indeksem taga
});
}
// oprócz tego trzeba samą w sobie zawartość boxPane związać -> i można przy dodawaniu elementów wywoływac powyższe!
});
}
@Buttonize
public boolean nextTag() {
var currentIndex = tagSelector.currentIndex.getValue();
if (currentIndex < tagSelector.tags.size() - 1) {
tagSelector.setIndex(currentIndex + 1);
return true;
} else
return false;
}
@Buttonize
public boolean previousTag() {
var currentIndex = tagSelector.currentIndex.getValue();
if (currentIndex > 0) {
tagSelector.setIndex(currentIndex - 1);
return true;
} else
return false;
}
@Buttonize
public boolean nextVariation() {
final var optionalTag = tagSelector.getSelectedTag();
if (optionalTag.isPresent()) {
final var tag = optionalTag.get();
final var currentIndex = variationSelector.getIndex(tag);
if (currentIndex < tag.getVariationsProperty().size() - 1) {
variationSelector.setIndex(tag, currentIndex + 1);
return true;
}
}
return false;
}
@Buttonize
public boolean previousVariation() {
final var optionalTag = tagSelector.getSelectedTag();
if (optionalTag.isPresent()) {
final var tag = optionalTag.get();
final var currentIndex = variationSelector.getIndex(tag);
if (currentIndex > 0) {
variationSelector.setIndex(tag, currentIndex + 1);
return true;
}
}
return false;
}
}
| /**
* moje pytanie brzmi:
* czy jest sens instancjonować BoxPane view bez kontrolera?
* czy może powinienem mieć jeszcze jeden poziom abstrakcji
* czym może być wiele kontrolerów lub wiele boxPane'ów??
*/ | package com.example.itewriter.area.boxview;
import com.example.itewriter.area.tightArea.Registry;
import com.example.itewriter.area.tightArea.TagSelector;
import com.example.itewriter.area.tightArea.VariationSelector;
/**
* moje pytanie brzmi: <SUF>*/
public class BoxPaneSequentialController {
/*
registry -> tagSelector -> variationSelector
tagSelector, variationSelector -> boxPaneController
pytanie brzmi czy box pane ma prawo działać, jeżeli selectory nie są połączone
wydaje mi się że powinien być całkowicie z enkapsulowany!
BOX CONTROLLER tyczy się tylko boxa
może nie mieć sensu w ogóle kontroler pojedynczej wariacji dla innych widoków jak choćby sama strefa!
*/
public final BoxPaneView boxPaneView;
private final VariationSelector variationSelector;
private final TagSelector tagSelector;
/*
tutaj powinien być zarówno API do next tag, jak i do next variation
*/
/*
teraz mogę w jakiś zmyślny sposób opakować zarówno niskie api sterowania wariacją,
jak i samym tagiem
pytanie co jest potrzebne do jakiej zmiany, na których mi zależy oraz która klasa powinna tym się zajmować
*/
public BoxPaneSequentialController(BoxPaneView boxPaneView, Registry registry) {
// czy ta klasa powinna mieć properties'a, który byłby zbindowany
int bop = 8;
bop++;
System.out.println(bop);
this.boxPaneView = boxPaneView;
this.variationSelector = new VariationSelector(tagSelector = new TagSelector(registry));
this.variationSelector.getSelectedVariationObservable().addListener((variationProperty, oldVariation, newVariation) -> {
boxPaneView.displayedPassages.setValue(registry.viewOf(newVariation));
// to powinno być przeniesione do implementacji viewOf
for (var textFieldPassage : boxPaneView.getSimpleInternalModelProperty()) {
var variationPassage = newVariation.getPassage(textFieldPassage.getPosition());
textFieldPassage.textProperty().unbind();
textFieldPassage.textProperty().setValue(variationPassage.textProperty().getValue());
textFieldPassage.textProperty().bind(variationPassage.textProperty());
textFieldPassage.textProperty().addListener((textProperty, oldText, newText) -> { // taki sam handler powinien być, kiedy dodawane są nowe elementy do wariacji
registry.offsetAllTags(textFieldPassage.getPosition(), newText.length() - textFieldPassage.textProperty().getValue().length());
newVariation.getPassage(textFieldPassage.getPosition()).textProperty().setValue(newText); // modyfikuje korespondującego indeksem taga
});
}
// oprócz tego trzeba samą w sobie zawartość boxPane związać -> i można przy dodawaniu elementów wywoływac powyższe!
});
}
@Buttonize
public boolean nextTag() {
var currentIndex = tagSelector.currentIndex.getValue();
if (currentIndex < tagSelector.tags.size() - 1) {
tagSelector.setIndex(currentIndex + 1);
return true;
} else
return false;
}
@Buttonize
public boolean previousTag() {
var currentIndex = tagSelector.currentIndex.getValue();
if (currentIndex > 0) {
tagSelector.setIndex(currentIndex - 1);
return true;
} else
return false;
}
@Buttonize
public boolean nextVariation() {
final var optionalTag = tagSelector.getSelectedTag();
if (optionalTag.isPresent()) {
final var tag = optionalTag.get();
final var currentIndex = variationSelector.getIndex(tag);
if (currentIndex < tag.getVariationsProperty().size() - 1) {
variationSelector.setIndex(tag, currentIndex + 1);
return true;
}
}
return false;
}
@Buttonize
public boolean previousVariation() {
final var optionalTag = tagSelector.getSelectedTag();
if (optionalTag.isPresent()) {
final var tag = optionalTag.get();
final var currentIndex = variationSelector.getIndex(tag);
if (currentIndex > 0) {
variationSelector.setIndex(tag, currentIndex + 1);
return true;
}
}
return false;
}
}
| f |
6067_4 | brzaskun/NetBeansProjects | 2,395 | npkpir_23/src/java/dao/FakturywystokresoweDAO.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entity.Faktura;
import entity.Fakturywystokresowe;
import error.E;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
/**
*
* @author Osito
*/
@Stateless
@Transactional
public class FakturywystokresoweDAO extends DAO implements Serializable {
private static final long serialVersionUID = 1L;
@PersistenceContext(unitName = "npkpir_22PU")
private EntityManager em;
@PreDestroy
private void preDestroy() {
em.clear();
em.close();
em.getEntityManagerFactory().close();
em = null;
error.E.s("koniec jpa");
}
protected EntityManager getEntityManager() {
return em;
}
public FakturywystokresoweDAO() {
super(Fakturywystokresowe.class);
super.em = this.em;
}
public Fakturywystokresowe findFakturaOkresowaById(Integer id){
try {
return (Fakturywystokresowe) getEntityManager().createNamedQuery("Fakturywystokresowe.findById").setParameter("id", id).getSingleResult();
} catch (Exception e) { E.e(e);
return null;
}
}
// public List<Fakturywystokresowe> findPodatnik(String podatnik){
// List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
// try {
// zwrot = fakturywystokresoweFacade.findPodatnikFaktury(podatnik);
// } catch (Exception e) { E.e(e); }
// return zwrot;
// }
// public List<Fakturywystokresowe> findPodatnik(String podatnik, String rok){
// List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
// try {
// zwrot = fakturywystokresoweFacade.findPodatnikRokFaktury(podatnik, rok);
// } catch (Exception e) { E.e(e); }
// return zwrot;
// }
public List<Fakturywystokresowe> findPodatnikBiezace(String podatnik, String rok){
List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
try {
zwrot = getEntityManager().createNamedQuery("Fakturywystokresowe.findByPodatnikRokBiezace").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList();
} catch (Exception e) {
E.e(e); }
return zwrot;
}
public List<Fakturywystokresowe> findPodatnik(String podatnik){
List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
try {
zwrot = getEntityManager().createNamedQuery("Fakturywystokresowe.findByPodatnik").setParameter("podatnik", podatnik).getResultList();
} catch (Exception e) {
E.e(e); }
return zwrot;
}
public List<Fakturywystokresowe> findByKlientRok(String niptaxman, String nip, String rok){
List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
try {
zwrot = getEntityManager().createNamedQuery("Fakturywystokresowe.findByKlientRok").setParameter("wystawcanip", niptaxman).setParameter("nip", nip).setParameter("rok", rok).getResultList();
} catch (Exception e) {
E.e(e);
}
return zwrot;
}
public List<Fakturywystokresowe> findPodatnikBiezaceBezzawieszonych(String podatnik, String rok){
List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
try {
zwrot = getEntityManager().createNamedQuery("Fakturywystokresowe.findByPodatnikRokBiezaceBezzawieszonych").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList();
} catch (Exception e) {
E.e(e); }
return zwrot;
}
public Fakturywystokresowe findOkresowa(String rok, String klientnip, String nazwapelna, double brutto) {
try {
return (Fakturywystokresowe) getEntityManager().createNamedQuery("Fakturywystokresowe.findByOkresowa").setParameter("rok", rok).setParameter("podatnik", nazwapelna).setParameter("nipodbiorcy", klientnip).setParameter("brutto", brutto).getSingleResult();
} catch (Exception e) {
E.e(e);
return null;
}
}
public List<Fakturywystokresowe> findOkresoweOstatnie(String podatnik, String mc, String rok) {
try {
switch (mc) {
case "01":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM1").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "02":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM2").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "03":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM3").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "04":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM4").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "05":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM5").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "06":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM6").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "07":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM7").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "08":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM8").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "09":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM9").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "10":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM10").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "11":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM11").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "12":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM12").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
}
return null;
} catch (Exception e) {
E.e(e);
return null;
}
}
public List<Fakturywystokresowe> findFakturaOkresowaByFaktura(Faktura p) {
try {
return getEntityManager().createNamedQuery("Fakturywystokresowe.findByFaktura").setParameter("faktura", p).getResultList();
} catch (Exception e) {
E.e(e);
return null;
}
}
}
| // zwrot = fakturywystokresoweFacade.findPodatnikFaktury(podatnik); | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import entity.Faktura;
import entity.Fakturywystokresowe;
import error.E;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
/**
*
* @author Osito
*/
@Stateless
@Transactional
public class FakturywystokresoweDAO extends DAO implements Serializable {
private static final long serialVersionUID = 1L;
@PersistenceContext(unitName = "npkpir_22PU")
private EntityManager em;
@PreDestroy
private void preDestroy() {
em.clear();
em.close();
em.getEntityManagerFactory().close();
em = null;
error.E.s("koniec jpa");
}
protected EntityManager getEntityManager() {
return em;
}
public FakturywystokresoweDAO() {
super(Fakturywystokresowe.class);
super.em = this.em;
}
public Fakturywystokresowe findFakturaOkresowaById(Integer id){
try {
return (Fakturywystokresowe) getEntityManager().createNamedQuery("Fakturywystokresowe.findById").setParameter("id", id).getSingleResult();
} catch (Exception e) { E.e(e);
return null;
}
}
// public List<Fakturywystokresowe> findPodatnik(String podatnik){
// List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
// try {
// zwrot = <SUF>
// } catch (Exception e) { E.e(e); }
// return zwrot;
// }
// public List<Fakturywystokresowe> findPodatnik(String podatnik, String rok){
// List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
// try {
// zwrot = fakturywystokresoweFacade.findPodatnikRokFaktury(podatnik, rok);
// } catch (Exception e) { E.e(e); }
// return zwrot;
// }
public List<Fakturywystokresowe> findPodatnikBiezace(String podatnik, String rok){
List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
try {
zwrot = getEntityManager().createNamedQuery("Fakturywystokresowe.findByPodatnikRokBiezace").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList();
} catch (Exception e) {
E.e(e); }
return zwrot;
}
public List<Fakturywystokresowe> findPodatnik(String podatnik){
List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
try {
zwrot = getEntityManager().createNamedQuery("Fakturywystokresowe.findByPodatnik").setParameter("podatnik", podatnik).getResultList();
} catch (Exception e) {
E.e(e); }
return zwrot;
}
public List<Fakturywystokresowe> findByKlientRok(String niptaxman, String nip, String rok){
List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
try {
zwrot = getEntityManager().createNamedQuery("Fakturywystokresowe.findByKlientRok").setParameter("wystawcanip", niptaxman).setParameter("nip", nip).setParameter("rok", rok).getResultList();
} catch (Exception e) {
E.e(e);
}
return zwrot;
}
public List<Fakturywystokresowe> findPodatnikBiezaceBezzawieszonych(String podatnik, String rok){
List<Fakturywystokresowe> zwrot = Collections.synchronizedList(new ArrayList<>());
try {
zwrot = getEntityManager().createNamedQuery("Fakturywystokresowe.findByPodatnikRokBiezaceBezzawieszonych").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList();
} catch (Exception e) {
E.e(e); }
return zwrot;
}
public Fakturywystokresowe findOkresowa(String rok, String klientnip, String nazwapelna, double brutto) {
try {
return (Fakturywystokresowe) getEntityManager().createNamedQuery("Fakturywystokresowe.findByOkresowa").setParameter("rok", rok).setParameter("podatnik", nazwapelna).setParameter("nipodbiorcy", klientnip).setParameter("brutto", brutto).getSingleResult();
} catch (Exception e) {
E.e(e);
return null;
}
}
public List<Fakturywystokresowe> findOkresoweOstatnie(String podatnik, String mc, String rok) {
try {
switch (mc) {
case "01":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM1").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "02":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM2").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "03":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM3").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "04":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM4").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "05":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM5").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "06":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM6").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "07":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM7").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "08":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM8").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "09":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM9").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "10":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM10").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "11":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM11").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
case "12":
return Collections.synchronizedList( getEntityManager().createNamedQuery("Fakturywystokresowe.findByM12").setParameter("podatnik", podatnik).setParameter("rok", rok).getResultList());
}
return null;
} catch (Exception e) {
E.e(e);
return null;
}
}
public List<Fakturywystokresowe> findFakturaOkresowaByFaktura(Faktura p) {
try {
return getEntityManager().createNamedQuery("Fakturywystokresowe.findByFaktura").setParameter("faktura", p).getResultList();
} catch (Exception e) {
E.e(e);
return null;
}
}
}
| f |
6401_25 | cafebabepl/cafebabe-kebab20 | 1,368 | src/main/java/pl/cafebabe/kebab/service/MenuService.java | package pl.cafebabe.kebab.service;
import static pl.cafebabe.kebab.Constants.*;
import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.commons.configuration.Configuration;
import org.jongo.Jongo;
import com.mongodb.MongoClient;
import pl.cafebabe.kebab.config.ConfigUtils;
import pl.cafebabe.kebab.model.Menu;
import pl.cafebabe.kebab.mongodb.MongoUtils;
import pl.cafebabe.kebab.schedule.MenuGenerateScheduler;
@Path("/")
@Produces({ "application/json;charset=utf-8"})
public class MenuService {
Configuration configuration = ConfigUtils.getConfiguration();
//TODO usunąć po przeniesieniu do obiektu biznesowego
@EJB
MenuGenerateScheduler scheduler;
// public Menu menu1() throws Exception {
// // A. parsowanie za każdym razem
// //TODO Inject
//// CamelPizzaKebapParser parser = new CamelPizzaKebapParser();
//// return parser.getMenu();
//
// //TODO pousuwać te nazwy do kongiracji albo metody jakiejś
//
// // TODO to jest bardzo brzydkie, nauczyć mongoquery, przerobić na DTO/Biznes
// // B. pobranie z bazy
// try (MongoClient client = MongoUtils.getMongoClient()) {
// MongoCollection<Document> col = client.getDatabase("kebab20").getCollection("menu");
// Document doc = col.find().sort(Sorts.descending("_id")).limit(1).first();
// String tresc = doc.get("tresc", String.class);
// Gson gson = new Gson();
// Menu menu = gson.fromJson(tresc, Menu.class);
// return menu;
// }
// }
@GET
@Path("parse")
public String parse() throws Exception {
scheduler.execute();
return "Done";
}
@GET
@Path("menu")
public Menu menu2() throws Exception {
// TODO trzeba to wszystko przenieść do jakiegoś obiektu biznesowego
try (MongoClient client = MongoUtils.getMongoClient()) {
@SuppressWarnings("deprecation")
// TODO uporządkować konfigurację
Jongo jongo = new Jongo(client.getDB(configuration.getString(MONGODB_DATABASE)));
org.jongo.MongoCollection menus2 = jongo.getCollection(configuration.getString(MONGODB_COLLECTION));
Menu menu = menus2.findOne().orderBy("{aktualnosc: -1}").as(Menu.class);
//TODO jak Jackson datę parsuje bo w jax-rs dostaję liczbę!
return menu;
}
}
//TODO i to uporządkować z bazy
// @GET
// @Path("menu/{grupa}")
// public Collection<Pozycja> pozycje(@PathParam("grupa") String grupa) throws Exception {
// CamelPizzaKebapParser parser = new CamelPizzaKebapParser();
// for (Grupa i : parser.getMenu().getGrupy()) {
// if (i.getNazwa().equalsIgnoreCase(grupa)) {
// return i.getPozycje();
// }
// }
// return Collections.emptyList();
// }
// @GET
// @Path("test")
// public Menu test() throws Exception {
//
// Jongo jongo = new Jongo(MongoUtils.getMongoClient().getDB("kebab20"));
// org.jongo.MongoCollection menus = jongo.getCollection("menu");
//// menus.findOne().
//
// // TODO to jest bardzo brzydkie, nauczyć mongoquery, przerobić na DTO/Biznes
// // B. pobranie z bazy
// try (MongoClient client = MongoUtils.getMongoClient()) {
// MongoCollection<Document> col = client.getDatabase("kebab20").getCollection("menu");
// Document doc = col.find().sort(Sorts.descending("_id")).limit(1).first();
// String tresc = doc.get("tresc", String.class);
// Gson gson = new Gson();
// Menu menu = gson.fromJson(tresc, Menu.class);
// return menu;
// }
// }
}
| // // B. pobranie z bazy
| package pl.cafebabe.kebab.service;
import static pl.cafebabe.kebab.Constants.*;
import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.commons.configuration.Configuration;
import org.jongo.Jongo;
import com.mongodb.MongoClient;
import pl.cafebabe.kebab.config.ConfigUtils;
import pl.cafebabe.kebab.model.Menu;
import pl.cafebabe.kebab.mongodb.MongoUtils;
import pl.cafebabe.kebab.schedule.MenuGenerateScheduler;
@Path("/")
@Produces({ "application/json;charset=utf-8"})
public class MenuService {
Configuration configuration = ConfigUtils.getConfiguration();
//TODO usunąć po przeniesieniu do obiektu biznesowego
@EJB
MenuGenerateScheduler scheduler;
// public Menu menu1() throws Exception {
// // A. parsowanie za każdym razem
// //TODO Inject
//// CamelPizzaKebapParser parser = new CamelPizzaKebapParser();
//// return parser.getMenu();
//
// //TODO pousuwać te nazwy do kongiracji albo metody jakiejś
//
// // TODO to jest bardzo brzydkie, nauczyć mongoquery, przerobić na DTO/Biznes
// // B. pobranie z bazy
// try (MongoClient client = MongoUtils.getMongoClient()) {
// MongoCollection<Document> col = client.getDatabase("kebab20").getCollection("menu");
// Document doc = col.find().sort(Sorts.descending("_id")).limit(1).first();
// String tresc = doc.get("tresc", String.class);
// Gson gson = new Gson();
// Menu menu = gson.fromJson(tresc, Menu.class);
// return menu;
// }
// }
@GET
@Path("parse")
public String parse() throws Exception {
scheduler.execute();
return "Done";
}
@GET
@Path("menu")
public Menu menu2() throws Exception {
// TODO trzeba to wszystko przenieść do jakiegoś obiektu biznesowego
try (MongoClient client = MongoUtils.getMongoClient()) {
@SuppressWarnings("deprecation")
// TODO uporządkować konfigurację
Jongo jongo = new Jongo(client.getDB(configuration.getString(MONGODB_DATABASE)));
org.jongo.MongoCollection menus2 = jongo.getCollection(configuration.getString(MONGODB_COLLECTION));
Menu menu = menus2.findOne().orderBy("{aktualnosc: -1}").as(Menu.class);
//TODO jak Jackson datę parsuje bo w jax-rs dostaję liczbę!
return menu;
}
}
//TODO i to uporządkować z bazy
// @GET
// @Path("menu/{grupa}")
// public Collection<Pozycja> pozycje(@PathParam("grupa") String grupa) throws Exception {
// CamelPizzaKebapParser parser = new CamelPizzaKebapParser();
// for (Grupa i : parser.getMenu().getGrupy()) {
// if (i.getNazwa().equalsIgnoreCase(grupa)) {
// return i.getPozycje();
// }
// }
// return Collections.emptyList();
// }
// @GET
// @Path("test")
// public Menu test() throws Exception {
//
// Jongo jongo = new Jongo(MongoUtils.getMongoClient().getDB("kebab20"));
// org.jongo.MongoCollection menus = jongo.getCollection("menu");
//// menus.findOne().
//
// // TODO to jest bardzo brzydkie, nauczyć mongoquery, przerobić na DTO/Biznes
// // B. pobranie <SUF>
// try (MongoClient client = MongoUtils.getMongoClient()) {
// MongoCollection<Document> col = client.getDatabase("kebab20").getCollection("menu");
// Document doc = col.find().sort(Sorts.descending("_id")).limit(1).first();
// String tresc = doc.get("tresc", String.class);
// Gson gson = new Gson();
// Menu menu = gson.fromJson(tresc, Menu.class);
// return menu;
// }
// }
}
| f |
8159_1 | cerbin1/DicePoker | 194 | src/Dices.java | class Dices {
private int[] playersDices = new int[5];
private String playersName;
private int randomNumber() {
return (int) (Math.floor(Math.random() * 5) + 1);
}
void randomDices() {
for (int i = 0; i < 5; i++) {
playersDices[i] = randomNumber();
}
}
int[] getDices() {
return playersDices;
}
void setPlayersName(String playersName) { // TODO ta metoda nie powinna być tu
this.playersName = playersName;
}
String getPlayersName() { // TODO to też nie
return playersName;
}
}
| // TODO to też nie | class Dices {
private int[] playersDices = new int[5];
private String playersName;
private int randomNumber() {
return (int) (Math.floor(Math.random() * 5) + 1);
}
void randomDices() {
for (int i = 0; i < 5; i++) {
playersDices[i] = randomNumber();
}
}
int[] getDices() {
return playersDices;
}
void setPlayersName(String playersName) { // TODO ta metoda nie powinna być tu
this.playersName = playersName;
}
String getPlayersName() { // TODO to <SUF>
return playersName;
}
}
| f |
9887_0 | cerbin1/TicTacToe | 469 | src/bartek/Console.java | package bartek;
class Console {
void displayHelloMessage() {
System.out.println("Welcome in the TicTacToe game");
}
void displayInstructions() {
System.out.println("Enter the number of index where you want to put sign.");
}
void displayCharBoard(Board b) {
System.out.println("[" + b.getCharBoard()[0] + "]" + "[" + b.getCharBoard()[1] + "]" + "[" + b.getCharBoard()[2] + "]");
System.out.println("[" + b.getCharBoard()[3] + "]" + "[" + b.getCharBoard()[4] + "]" + "[" + b.getCharBoard()[5] + "]");
System.out.println("[" + b.getCharBoard()[6] + "]" + "[" + b.getCharBoard()[7] + "]" + "[" + b.getCharBoard()[8] + "]");
}
void askForCircleMove() { // TODO metody ask powinny zrobić scanner.nextLine() i zwracać tekst
System.out.println("Circle move");
}
void askForCrossMove() {
System.out.println("Cross move");
}
void thisFieldIsNotEmpty() {
System.out.println("This field is not empty. Try to choose another.");
}
void drawn() {
System.out.println("Drawn! Nobody wins.");
}
void wrongMove() {
System.out.println("You entered wrong move. Try do it again.");
}
void circleWins() {
System.out.println("Circle wins!");
}
void crossWins() {
System.out.println("Cross wins!");
}
}
| // TODO metody ask powinny zrobić scanner.nextLine() i zwracać tekst | package bartek;
class Console {
void displayHelloMessage() {
System.out.println("Welcome in the TicTacToe game");
}
void displayInstructions() {
System.out.println("Enter the number of index where you want to put sign.");
}
void displayCharBoard(Board b) {
System.out.println("[" + b.getCharBoard()[0] + "]" + "[" + b.getCharBoard()[1] + "]" + "[" + b.getCharBoard()[2] + "]");
System.out.println("[" + b.getCharBoard()[3] + "]" + "[" + b.getCharBoard()[4] + "]" + "[" + b.getCharBoard()[5] + "]");
System.out.println("[" + b.getCharBoard()[6] + "]" + "[" + b.getCharBoard()[7] + "]" + "[" + b.getCharBoard()[8] + "]");
}
void askForCircleMove() { // TODO metody <SUF>
System.out.println("Circle move");
}
void askForCrossMove() {
System.out.println("Cross move");
}
void thisFieldIsNotEmpty() {
System.out.println("This field is not empty. Try to choose another.");
}
void drawn() {
System.out.println("Drawn! Nobody wins.");
}
void wrongMove() {
System.out.println("You entered wrong move. Try do it again.");
}
void circleWins() {
System.out.println("Circle wins!");
}
void crossWins() {
System.out.println("Cross wins!");
}
}
| f |
7171_1 | code-troopers/languagetool | 1,143 | languagetool-language-modules/pl/src/main/java/org/languagetool/rules/pl/PolishWordRepeatRule.java | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.pl;
import java.util.Collections;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.regex.Pattern;
import org.languagetool.rules.AdvancedWordRepeatRule;
/**
* @author Marcin Miłkowski
*/
public class PolishWordRepeatRule extends AdvancedWordRepeatRule {
/**
* Excluded dictionary words.
*/
private static final Set<String> EXC_WORDS;
static {
final Set<String> tempSet = new HashSet<>();
tempSet.add("nie");
tempSet.add("tuż");
tempSet.add("aż");
tempSet.add("to");
tempSet.add("siebie");
tempSet.add("być");
tempSet.add("ani");
tempSet.add("ni");
tempSet.add("albo");
tempSet.add("lub");
tempSet.add("czy");
tempSet.add("bądź");
tempSet.add("jako");
tempSet.add("zł");
tempSet.add("np");
tempSet.add("coraz");
tempSet.add("bardzo");
tempSet.add("bardziej");
tempSet.add("proc");
tempSet.add("ten");
tempSet.add("jak");
tempSet.add("mln");
tempSet.add("tys");
tempSet.add("swój");
tempSet.add("mój");
tempSet.add("twój");
tempSet.add("nasz");
tempSet.add("wasz");
tempSet.add("i");
tempSet.add("zbyt");
tempSet.add("się");
EXC_WORDS = Collections.unmodifiableSet(tempSet);
}
/**
* Excluded part of speech classes.
*/
private static final Pattern EXC_POS = Pattern.compile("prep:.*|ppron.*");
/**
* Excluded non-words (special symbols, Roman numerals etc.)
*/
private static final Pattern EXC_NONWORDS = Pattern
.compile(""|>|<|&|[0-9].*|"
+ "M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$");
public PolishWordRepeatRule(final ResourceBundle messages) {
super(messages);
}
@Override
public final String getDescription() {
return "Powtórzenia wyrazów w zdaniu (monotonia stylistyczna)";
}
@Override
protected Pattern getExcludedNonWordsPattern() {
return EXC_NONWORDS;
}
@Override
protected Pattern getExcludedPos() {
return EXC_POS;
}
@Override
protected Set<String> getExcludedWordsPattern() {
return EXC_WORDS;
}
@Override
public final String getId() {
return "PL_WORD_REPEAT";
}
@Override
public final String getMessage() {
return "Powtórzony wyraz w zdaniu";
}
@Override
public final String getShortMessage() {
return "Powtórzenie wyrazu";
}
}
| /**
* @author Marcin Miłkowski
*/ | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.pl;
import java.util.Collections;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.regex.Pattern;
import org.languagetool.rules.AdvancedWordRepeatRule;
/**
* @author Marcin Miłkowski <SUF>*/
public class PolishWordRepeatRule extends AdvancedWordRepeatRule {
/**
* Excluded dictionary words.
*/
private static final Set<String> EXC_WORDS;
static {
final Set<String> tempSet = new HashSet<>();
tempSet.add("nie");
tempSet.add("tuż");
tempSet.add("aż");
tempSet.add("to");
tempSet.add("siebie");
tempSet.add("być");
tempSet.add("ani");
tempSet.add("ni");
tempSet.add("albo");
tempSet.add("lub");
tempSet.add("czy");
tempSet.add("bądź");
tempSet.add("jako");
tempSet.add("zł");
tempSet.add("np");
tempSet.add("coraz");
tempSet.add("bardzo");
tempSet.add("bardziej");
tempSet.add("proc");
tempSet.add("ten");
tempSet.add("jak");
tempSet.add("mln");
tempSet.add("tys");
tempSet.add("swój");
tempSet.add("mój");
tempSet.add("twój");
tempSet.add("nasz");
tempSet.add("wasz");
tempSet.add("i");
tempSet.add("zbyt");
tempSet.add("się");
EXC_WORDS = Collections.unmodifiableSet(tempSet);
}
/**
* Excluded part of speech classes.
*/
private static final Pattern EXC_POS = Pattern.compile("prep:.*|ppron.*");
/**
* Excluded non-words (special symbols, Roman numerals etc.)
*/
private static final Pattern EXC_NONWORDS = Pattern
.compile(""|>|<|&|[0-9].*|"
+ "M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$");
public PolishWordRepeatRule(final ResourceBundle messages) {
super(messages);
}
@Override
public final String getDescription() {
return "Powtórzenia wyrazów w zdaniu (monotonia stylistyczna)";
}
@Override
protected Pattern getExcludedNonWordsPattern() {
return EXC_NONWORDS;
}
@Override
protected Pattern getExcludedPos() {
return EXC_POS;
}
@Override
protected Set<String> getExcludedWordsPattern() {
return EXC_WORDS;
}
@Override
public final String getId() {
return "PL_WORD_REPEAT";
}
@Override
public final String getMessage() {
return "Powtórzony wyraz w zdaniu";
}
@Override
public final String getShortMessage() {
return "Powtórzenie wyrazu";
}
}
| f |
9523_7 | damiad/studies | 348 | first_year/object-oriented_programming/project_2/BajtTradeMaven/src/main/java/com/company/Main.java | package com.company;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
//Projekt jest niedokończony... Co się wiąże z bardzo skomplikowaną treścią, która była zmieniana codziennie.
//Mam natomiast nadzieję, że Obiektowość Projektu jest bardzo wysoka, większość klas, ich atrybutów i
//metod jest zaimplementowanych. Braki są np w realizacji transakcji giełdowych spowodowane nierozumieniem,
//jak je obsługiwać przy teoretycznie dążących do nieskończoności poziomach przedmiotów,
//co za tym idzie niskończonych ofertach spekulantów.
//W obecnej fazie jakość ofert została częściowo pominięta, w celu lepszego zwizualizowania projektu.
//Niektóre klasy są całkowicie zakomentowane, ich ostateczna forma (użycie lub usunięcie)
// by wyszła przy skończonym projekcie.
//Z góry dziękuję za wyrozumiałość.
}
}
| // by wyszła przy skończonym projekcie. | package com.company;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
//Projekt jest niedokończony... Co się wiąże z bardzo skomplikowaną treścią, która była zmieniana codziennie.
//Mam natomiast nadzieję, że Obiektowość Projektu jest bardzo wysoka, większość klas, ich atrybutów i
//metod jest zaimplementowanych. Braki są np w realizacji transakcji giełdowych spowodowane nierozumieniem,
//jak je obsługiwać przy teoretycznie dążących do nieskończoności poziomach przedmiotów,
//co za tym idzie niskończonych ofertach spekulantów.
//W obecnej fazie jakość ofert została częściowo pominięta, w celu lepszego zwizualizowania projektu.
//Niektóre klasy są całkowicie zakomentowane, ich ostateczna forma (użycie lub usunięcie)
// by wyszła <SUF>
//Z góry dziękuję za wyrozumiałość.
}
}
| f |
1694_0 | dawidovsky/IIUWr | 1,118 | PO/Lista5/Zadanie1.java | // Dawid Paluszak
// Pracownia PO, czwartek, s. 108
// L5, z1, Por�wnywalna kolekcja
// Zadanie1
// Zadanie1.java
// 2018-03-29
import java.util.Collections;
import java.util.Scanner;
// Main
public class Zadanie1
{
public static void main(String[] args)
{
Zadanie1 start = new Zadanie1();
start.start();
}
public void start()
{
Lista<Integer> lista = new Lista<Integer>();
Scanner s = new Scanner(System.in);
int wybor=5, stan=1, liczba = 0;
while(stan != 0)
{
System.out.print("\nWybierz, co chcesz zrobic:\n");
System.out.print("1.Dodaj liczbe do listy\n");
System.out.print("2.Wyjmij element z listy\n");
System.out.print("3.Wypisz liste\n");
System.out.print("4.Wyjscie\n\n");
wybor = s.nextInt();
switch(wybor)
{
case 1: System.out.print("Podaj liczbe\n");
liczba = s.nextInt();
lista.Dodaj(liczba);
break;
case 2:
try
{
liczba = lista.Pobierz();
}
catch(NullPointerException err)
{
System.out.print("Lista Pusta\n");
break;
}
System.out.print("Wyjeto element " + liczba + "\n");
break;
case 3: lista.Wypisz();
break;
case 4: stan = 0;
break;
default:
System.out.println("Bledne dane");
break;
}
}
}
// Lista zrobiona przeze mnie z dodan� bibliotek� Comparable do
// por�wna�
public class Lista<T extends Comparable>
{
private Lista<T> pierwszy;
private Lista<T> next;
private T wartosc;
// Dodawanie elementu do listy w odpowiednie miejsce
public void Dodaj(T a)
{
if(pierwszy == null)
{
pierwszy = new Lista<T>();
pierwszy.wartosc = a;
pierwszy.next = null;
}
else
{
if(pierwszy.wartosc.compareTo(a) > 0)
{
Lista<T> nowy = new Lista<T>();
nowy.wartosc = pierwszy.wartosc;
pierwszy.wartosc = a;
nowy.next = pierwszy.next;
pierwszy.next = nowy;
}
else
{
Lista<T> wsk = pierwszy;
while(wsk.next != null)
{
if(wsk.next.wartosc.compareTo(a) > 0)
break;
wsk = wsk.next;
}
Lista<T> nowy = new Lista<T>();
nowy.wartosc = a;
nowy.next = wsk.next;
wsk.next = nowy;
}
}
}
// Pobieranie peirwszego elementu i usuwanie go
public T Pobierz()
{
T war = pierwszy.wartosc;
if(pierwszy.next != null)
{
pierwszy = pierwszy.next;
}
else
pierwszy = null;
return war;
}
// Wypisaywanie zawarto�ci listy
public void Wypisz()
{
if(pierwszy == null)
{
System.out.print("Lista jest pusta!");
return;
}
Lista<T> temp = pierwszy;
System.out.print("Lista zawiera:\n");
while (temp != null)
{
System.out.print(temp.wartosc + "\n");
temp = temp.next;
}
}
}
}
| // Pracownia PO, czwartek, s. 108 | // Dawid Paluszak
// Pracownia PO, <SUF>
// L5, z1, Por�wnywalna kolekcja
// Zadanie1
// Zadanie1.java
// 2018-03-29
import java.util.Collections;
import java.util.Scanner;
// Main
public class Zadanie1
{
public static void main(String[] args)
{
Zadanie1 start = new Zadanie1();
start.start();
}
public void start()
{
Lista<Integer> lista = new Lista<Integer>();
Scanner s = new Scanner(System.in);
int wybor=5, stan=1, liczba = 0;
while(stan != 0)
{
System.out.print("\nWybierz, co chcesz zrobic:\n");
System.out.print("1.Dodaj liczbe do listy\n");
System.out.print("2.Wyjmij element z listy\n");
System.out.print("3.Wypisz liste\n");
System.out.print("4.Wyjscie\n\n");
wybor = s.nextInt();
switch(wybor)
{
case 1: System.out.print("Podaj liczbe\n");
liczba = s.nextInt();
lista.Dodaj(liczba);
break;
case 2:
try
{
liczba = lista.Pobierz();
}
catch(NullPointerException err)
{
System.out.print("Lista Pusta\n");
break;
}
System.out.print("Wyjeto element " + liczba + "\n");
break;
case 3: lista.Wypisz();
break;
case 4: stan = 0;
break;
default:
System.out.println("Bledne dane");
break;
}
}
}
// Lista zrobiona przeze mnie z dodan� bibliotek� Comparable do
// por�wna�
public class Lista<T extends Comparable>
{
private Lista<T> pierwszy;
private Lista<T> next;
private T wartosc;
// Dodawanie elementu do listy w odpowiednie miejsce
public void Dodaj(T a)
{
if(pierwszy == null)
{
pierwszy = new Lista<T>();
pierwszy.wartosc = a;
pierwszy.next = null;
}
else
{
if(pierwszy.wartosc.compareTo(a) > 0)
{
Lista<T> nowy = new Lista<T>();
nowy.wartosc = pierwszy.wartosc;
pierwszy.wartosc = a;
nowy.next = pierwszy.next;
pierwszy.next = nowy;
}
else
{
Lista<T> wsk = pierwszy;
while(wsk.next != null)
{
if(wsk.next.wartosc.compareTo(a) > 0)
break;
wsk = wsk.next;
}
Lista<T> nowy = new Lista<T>();
nowy.wartosc = a;
nowy.next = wsk.next;
wsk.next = nowy;
}
}
}
// Pobieranie peirwszego elementu i usuwanie go
public T Pobierz()
{
T war = pierwszy.wartosc;
if(pierwszy.next != null)
{
pierwszy = pierwszy.next;
}
else
pierwszy = null;
return war;
}
// Wypisaywanie zawarto�ci listy
public void Wypisz()
{
if(pierwszy == null)
{
System.out.print("Lista jest pusta!");
return;
}
Lista<T> temp = pierwszy;
System.out.print("Lista zawiera:\n");
while (temp != null)
{
System.out.print(temp.wartosc + "\n");
temp = temp.next;
}
}
}
}
| f |
5208_14 | dedyk/JapaneseDictionaryWeb | 5,478 | src/main/java/pl/idedyk/japanese/dictionary/web/queue/QueueService.java | package pl.idedyk.japanese.dictionary.web.queue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import jakarta.annotation.PostConstruct;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import pl.idedyk.japanese.dictionary.web.mysql.MySQLConnector;
import pl.idedyk.japanese.dictionary.web.mysql.model.QueueItem;
import pl.idedyk.japanese.dictionary.web.mysql.model.QueueItemStatus;
@Service
public class QueueService {
private static final Logger logger = LogManager.getLogger(QueueService.class);
@Autowired
private MySQLConnector mySQLConnector;
@Value("${local.dir.job.queue}")
private String localDirJobQueueDir;
private File localDirJobQueueDirFile;
private File localDirJobQueryArchiveDirFile;
//
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@PostConstruct
public void init() {
logger.info("Inicjalizowanie QueueService");
localDirJobQueueDirFile = new File(localDirJobQueueDir);
if (localDirJobQueueDirFile.exists() == false) {
logger.info("Tworzę katalog " + localDirJobQueueDir + " do ewentualnej lokalnej kolejki");
localDirJobQueueDirFile.mkdirs();
}
if (localDirJobQueueDirFile.exists() == false || localDirJobQueueDirFile.canWrite() == false) {
logger.error("Nie mogę zainicjalizować katalogu " + localDirJobQueueDir + " do ewentualnej lokalnej kolejki");
throw new RuntimeException();
}
//
localDirJobQueryArchiveDirFile = new File(localDirJobQueueDirFile, "archive");
if (localDirJobQueryArchiveDirFile.exists() == false) {
logger.info("Tworzę katalog " + localDirJobQueryArchiveDirFile.getPath() + " do archiwum lokalnej kolejki");
localDirJobQueryArchiveDirFile.mkdirs();
}
if (localDirJobQueryArchiveDirFile.exists() == false || localDirJobQueryArchiveDirFile.canWrite() == false) {
logger.error("Nie mogę zainicjalizować katalogu " + localDirJobQueryArchiveDirFile.getPath() + " do archiwum lokalnej kolejki");
throw new RuntimeException();
}
}
public void sendToQueue(String queueName, byte[] object) throws SQLException {
// stworzenie nowego elementu do kolejki
QueueItem queueItem = new QueueItem();
queueItem.setName(queueName);
queueItem.setStatus(QueueItemStatus.WAITING);
queueItem.setHostName(getHostName());
queueItem.setSendTimestamp(new Timestamp(new Date().getTime()));
queueItem.setDeliveryCount(0);
queueItem.setNextAttempt(queueItem.getSendTimestamp());
queueItem.setObject(object);
// zapisanie do lokalnego katalogu z kolejka
saveToLocalDir(queueItem);
/*
try {
// wstawienie do kolejki
mySQLConnector.insertQueueItem(queueItem);
} catch (SQLException e) {
throw e;
}
*/
}
private String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
private void saveToLocalDir(QueueItem queueItem) {
// logger.info("Zapisanie do lokalnego katalogu kolejki");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = sdf.format(queueItem.getSendTimestamp());
String randomFileName = UUID.randomUUID().toString();
File queueItemFileBody = new File(localDirJobQueueDirFile, queueItem.getName() + "_" + dateString + "_" + randomFileName);
File queueItemBodyReady = new File(localDirJobQueueDirFile, queueItem.getName() + "_" + dateString + "_" + randomFileName + ".ready");
ByteArrayOutputStream bos = null;
ObjectOutput objectOutput = null;
FileOutputStream fos = null;
try {
// serializacja obiektu
bos = new ByteArrayOutputStream();
objectOutput = new ObjectOutputStream(bos);
objectOutput.writeObject(queueItem);
objectOutput.close();
bos.close();
byte[] queueItemByteArray = bos.toByteArray();
fos = new FileOutputStream(queueItemFileBody);
fos.write(queueItemByteArray);
queueItemBodyReady.createNewFile();
} catch (IOException e) {
logger.error("Błąd zapisu do lokalnego katalogu kolejki", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
// noop
}
}
}
}
public List<QueueItem> getNextItemQueueItem(String queueName) throws SQLException {
List<QueueItem> result = mySQLConnector.getNextQueueItem(queueName, getHostName());
if (result != null) {
for (QueueItem queueItem : result) {
// zachowanie zgodnosci
if (queueItem.getHostName() == null) {
queueItem.setHostName(getHostName());
}
}
}
return result;
}
public void setQueueItemDone(QueueItem queueItem) throws SQLException {
queueItem.setStatus(QueueItemStatus.DONE);
// uaktualnie wpisu
mySQLConnector.updateQueueItem(queueItem);
}
public void setQueueItemError(QueueItem queueItem) throws SQLException {
queueItem.setStatus(QueueItemStatus.ERROR);
// uaktualnie wpisu
mySQLConnector.updateQueueItem(queueItem);
}
public void delayQueueItem(QueueItem queueItem) throws SQLException {
int deliveryCount = queueItem.getDeliveryCount() + 1;
Timestamp nextAttempt = queueItem.getNextAttempt();
Calendar calendar = Calendar.getInstance();
calendar.setTime(nextAttempt);
calendar.add(Calendar.SECOND, 10 * deliveryCount * 2);
nextAttempt = new Timestamp(calendar.getTime().getTime());
queueItem.setDeliveryCount(deliveryCount);
queueItem.setNextAttempt(nextAttempt);
// uaktualnie wpisu
mySQLConnector.updateQueueItem(queueItem);
}
public void processLocalDirQueueItems() {
// proba znalezienia plikow z lokalnego katalogu kolejki
File[] queueItemsFileReadyList = localDirJobQueueDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isFile() == false) {
return false;
}
String fileName = pathname.getName();
if (fileName.endsWith(".ready") == true) {
return true;
}
return false;
}
});
Arrays.sort(queueItemsFileReadyList, new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
if (f1.lastModified() < f2.lastModified()) {
return -1;
} else if (f1.lastModified() > f2.lastModified()) {
return 1;
} else {
return 0;
}
}
});
if (queueItemsFileReadyList != null && queueItemsFileReadyList.length > 0) {
// logger.info("Znaleziono pliki z lokalnej kolejki");
for (File currentReadyQueueItemFile : queueItemsFileReadyList) {
File queueItemFile = new File(currentReadyQueueItemFile.getParent(), currentReadyQueueItemFile.getName().substring(0, currentReadyQueueItemFile.getName().length() - ".ready".length()));
// logger.info("Przetwarzam plik " + queueItemFile.getName());
ObjectInputStream ois = null;
QueueItem queueItem = null;
try {
ois = new ObjectInputStream(new FileInputStream(queueItemFile));
queueItem = (QueueItem)ois.readObject();
} catch (Exception e) {
logger.error("Błąd podczas odczytywania pliku z lokalnej kolejki: " + queueItemFile.getName(), e);
continue;
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
// noop
}
}
}
// zachowanie zgodnosci
if (queueItem.getHostName() == null) {
queueItem.setHostName(getHostName());
}
try {
// proba wstawienia do bazy danych
mySQLConnector.insertQueueItem(queueItem);
} catch (SQLException e) {
logger.error("Błąd wstawienia do bazy danych z lokalnej kolejki: " + e.getMessage());
continue;
}
// udalo sie, kasujemy plik ready
currentReadyQueueItemFile.delete();
// przenosimy plik do archiwum
// sprawdzenie i ewentualne utworzenie katalogu z data
File localDirJobQueryArchiveDirWithDateFile = new File(localDirJobQueryArchiveDirFile, dateFormat.format(queueItem.getSendTimestamp()));
if (localDirJobQueryArchiveDirWithDateFile.exists() == false && localDirJobQueryArchiveDirWithDateFile.isDirectory() == false) { // tworzymy katalog
localDirJobQueryArchiveDirWithDateFile.mkdir();
}
// przenosimy plik do wspolnego archiwum
FileSystem archiveFileSystem = null;
try {
// utworzenie nazwy pliku z archiwum
Calendar querySendTimestampCalendar = Calendar.getInstance();
querySendTimestampCalendar.setTime(queueItem.getSendTimestamp());
int sendTimestampHourOfDay = querySendTimestampCalendar.get(Calendar.HOUR_OF_DAY);
String archivePartFileName = dateFormat.format(querySendTimestampCalendar.getTime()) + "_" + (sendTimestampHourOfDay < 10 ? "0" + sendTimestampHourOfDay : sendTimestampHourOfDay)
+ "_" + (querySendTimestampCalendar.get(Calendar.MINUTE) / 10) + "0";
//
File archiveFile = new File(localDirJobQueryArchiveDirWithDateFile, archivePartFileName + ".zip");
URI archiveFileUri = URI.create("jar:file:" + archiveFile.getAbsolutePath());
// utworzenie archiwum
Map<String, String> archiveEnv = new HashMap<>();
archiveEnv.put("create", String.valueOf(archiveFile.exists() == false));
archiveFileSystem = FileSystems.newFileSystem(archiveFileUri, archiveEnv);
// przenoszenie pliku do archiwum
Path queueItemFilePathInArchiveFile = archiveFileSystem.getPath(queueItemFile.getName());
Files.copy(queueItemFile.toPath(), queueItemFilePathInArchiveFile, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
logger.error("Błąd podczas przenoszenia pliku do archiwum: " + e.getMessage());
} finally {
if (archiveFileSystem != null) {
try {
archiveFileSystem.close();
} catch (IOException e) {
logger.error("Błąd podczas przenoszenia pliku do archiwum: " + e.getMessage());
}
}
}
// kasujemy plik
queueItemFile.delete();
}
}
}
/*
private void copyAndGzipFile(File source, File destination) throws IOException {
byte[] buffer = new byte[1024];
FileInputStream sourceInputStream = null;
GZIPOutputStream destinationOutputStream = null;
try {
sourceInputStream = new FileInputStream(source);
destinationOutputStream = new GZIPOutputStream(new FileOutputStream(destination));
int len;
while ((len = sourceInputStream.read(buffer)) > 0) {
destinationOutputStream.write(buffer, 0, len);
}
} finally {
if (sourceInputStream != null) {
sourceInputStream.close();
}
if (destinationOutputStream != null) {
destinationOutputStream.finish();
destinationOutputStream.close();
}
}
}
*/
public void deleteLocalDirArchiveOldQueueItems(final int olderThanDays) {
// pobieramy liste plikow do skasowania
File[] oldQueueItemsDirListFiles = localDirJobQueryArchiveDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isFile() == true) {
return false;
}
if (pathname.isDirectory() == false) {
return false;
}
Date pathnameDate = null;
try {
pathnameDate = dateFormat.parse(pathname.getName());
} catch (ParseException e) { // zly format nazwy katalogu
return false;
}
// nazwa katalogu jest w odpowiednim formacie, wiec sprawdzamy liczbe dni
Calendar calendarNowMinusDays = Calendar.getInstance();
calendarNowMinusDays.add(Calendar.DAY_OF_YEAR, -olderThanDays);
if (calendarNowMinusDays.getTime().getTime() > pathnameDate.getTime()) { // kasujemy
return true;
} else {
return false;
}
}
});
// kasujemy pliki
for (File directoryToDelete : oldQueueItemsDirListFiles) {
logger.info("Kasuje katalog archiwum: " + directoryToDelete.getName());
// najpierw kasujemy pliki z tego katalogu
File[] directoryToDeleteListFiles = directoryToDelete.listFiles();
for (File fileToDelete : directoryToDeleteListFiles) {
fileToDelete.delete();
}
// a pozniej sam katalog (powinien byc) pusty
directoryToDelete.delete();
}
}
//
/*
public static void main(String[] args) {
org.apache.log4j.BasicConfigurator.configure();
QueueService queueService = new QueueService();
queueService.localDirJobQueueDir = "/opt/apache-tomcat-8.0.8/local-job-queue";
queueService.init();
queueService.deleteLocalDirArchiveOldQueueItems(10);
}
*/
}
| // przenoszenie pliku do archiwum | package pl.idedyk.japanese.dictionary.web.queue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import jakarta.annotation.PostConstruct;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import pl.idedyk.japanese.dictionary.web.mysql.MySQLConnector;
import pl.idedyk.japanese.dictionary.web.mysql.model.QueueItem;
import pl.idedyk.japanese.dictionary.web.mysql.model.QueueItemStatus;
@Service
public class QueueService {
private static final Logger logger = LogManager.getLogger(QueueService.class);
@Autowired
private MySQLConnector mySQLConnector;
@Value("${local.dir.job.queue}")
private String localDirJobQueueDir;
private File localDirJobQueueDirFile;
private File localDirJobQueryArchiveDirFile;
//
private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@PostConstruct
public void init() {
logger.info("Inicjalizowanie QueueService");
localDirJobQueueDirFile = new File(localDirJobQueueDir);
if (localDirJobQueueDirFile.exists() == false) {
logger.info("Tworzę katalog " + localDirJobQueueDir + " do ewentualnej lokalnej kolejki");
localDirJobQueueDirFile.mkdirs();
}
if (localDirJobQueueDirFile.exists() == false || localDirJobQueueDirFile.canWrite() == false) {
logger.error("Nie mogę zainicjalizować katalogu " + localDirJobQueueDir + " do ewentualnej lokalnej kolejki");
throw new RuntimeException();
}
//
localDirJobQueryArchiveDirFile = new File(localDirJobQueueDirFile, "archive");
if (localDirJobQueryArchiveDirFile.exists() == false) {
logger.info("Tworzę katalog " + localDirJobQueryArchiveDirFile.getPath() + " do archiwum lokalnej kolejki");
localDirJobQueryArchiveDirFile.mkdirs();
}
if (localDirJobQueryArchiveDirFile.exists() == false || localDirJobQueryArchiveDirFile.canWrite() == false) {
logger.error("Nie mogę zainicjalizować katalogu " + localDirJobQueryArchiveDirFile.getPath() + " do archiwum lokalnej kolejki");
throw new RuntimeException();
}
}
public void sendToQueue(String queueName, byte[] object) throws SQLException {
// stworzenie nowego elementu do kolejki
QueueItem queueItem = new QueueItem();
queueItem.setName(queueName);
queueItem.setStatus(QueueItemStatus.WAITING);
queueItem.setHostName(getHostName());
queueItem.setSendTimestamp(new Timestamp(new Date().getTime()));
queueItem.setDeliveryCount(0);
queueItem.setNextAttempt(queueItem.getSendTimestamp());
queueItem.setObject(object);
// zapisanie do lokalnego katalogu z kolejka
saveToLocalDir(queueItem);
/*
try {
// wstawienie do kolejki
mySQLConnector.insertQueueItem(queueItem);
} catch (SQLException e) {
throw e;
}
*/
}
private String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
private void saveToLocalDir(QueueItem queueItem) {
// logger.info("Zapisanie do lokalnego katalogu kolejki");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = sdf.format(queueItem.getSendTimestamp());
String randomFileName = UUID.randomUUID().toString();
File queueItemFileBody = new File(localDirJobQueueDirFile, queueItem.getName() + "_" + dateString + "_" + randomFileName);
File queueItemBodyReady = new File(localDirJobQueueDirFile, queueItem.getName() + "_" + dateString + "_" + randomFileName + ".ready");
ByteArrayOutputStream bos = null;
ObjectOutput objectOutput = null;
FileOutputStream fos = null;
try {
// serializacja obiektu
bos = new ByteArrayOutputStream();
objectOutput = new ObjectOutputStream(bos);
objectOutput.writeObject(queueItem);
objectOutput.close();
bos.close();
byte[] queueItemByteArray = bos.toByteArray();
fos = new FileOutputStream(queueItemFileBody);
fos.write(queueItemByteArray);
queueItemBodyReady.createNewFile();
} catch (IOException e) {
logger.error("Błąd zapisu do lokalnego katalogu kolejki", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
// noop
}
}
}
}
public List<QueueItem> getNextItemQueueItem(String queueName) throws SQLException {
List<QueueItem> result = mySQLConnector.getNextQueueItem(queueName, getHostName());
if (result != null) {
for (QueueItem queueItem : result) {
// zachowanie zgodnosci
if (queueItem.getHostName() == null) {
queueItem.setHostName(getHostName());
}
}
}
return result;
}
public void setQueueItemDone(QueueItem queueItem) throws SQLException {
queueItem.setStatus(QueueItemStatus.DONE);
// uaktualnie wpisu
mySQLConnector.updateQueueItem(queueItem);
}
public void setQueueItemError(QueueItem queueItem) throws SQLException {
queueItem.setStatus(QueueItemStatus.ERROR);
// uaktualnie wpisu
mySQLConnector.updateQueueItem(queueItem);
}
public void delayQueueItem(QueueItem queueItem) throws SQLException {
int deliveryCount = queueItem.getDeliveryCount() + 1;
Timestamp nextAttempt = queueItem.getNextAttempt();
Calendar calendar = Calendar.getInstance();
calendar.setTime(nextAttempt);
calendar.add(Calendar.SECOND, 10 * deliveryCount * 2);
nextAttempt = new Timestamp(calendar.getTime().getTime());
queueItem.setDeliveryCount(deliveryCount);
queueItem.setNextAttempt(nextAttempt);
// uaktualnie wpisu
mySQLConnector.updateQueueItem(queueItem);
}
public void processLocalDirQueueItems() {
// proba znalezienia plikow z lokalnego katalogu kolejki
File[] queueItemsFileReadyList = localDirJobQueueDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isFile() == false) {
return false;
}
String fileName = pathname.getName();
if (fileName.endsWith(".ready") == true) {
return true;
}
return false;
}
});
Arrays.sort(queueItemsFileReadyList, new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
if (f1.lastModified() < f2.lastModified()) {
return -1;
} else if (f1.lastModified() > f2.lastModified()) {
return 1;
} else {
return 0;
}
}
});
if (queueItemsFileReadyList != null && queueItemsFileReadyList.length > 0) {
// logger.info("Znaleziono pliki z lokalnej kolejki");
for (File currentReadyQueueItemFile : queueItemsFileReadyList) {
File queueItemFile = new File(currentReadyQueueItemFile.getParent(), currentReadyQueueItemFile.getName().substring(0, currentReadyQueueItemFile.getName().length() - ".ready".length()));
// logger.info("Przetwarzam plik " + queueItemFile.getName());
ObjectInputStream ois = null;
QueueItem queueItem = null;
try {
ois = new ObjectInputStream(new FileInputStream(queueItemFile));
queueItem = (QueueItem)ois.readObject();
} catch (Exception e) {
logger.error("Błąd podczas odczytywania pliku z lokalnej kolejki: " + queueItemFile.getName(), e);
continue;
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
// noop
}
}
}
// zachowanie zgodnosci
if (queueItem.getHostName() == null) {
queueItem.setHostName(getHostName());
}
try {
// proba wstawienia do bazy danych
mySQLConnector.insertQueueItem(queueItem);
} catch (SQLException e) {
logger.error("Błąd wstawienia do bazy danych z lokalnej kolejki: " + e.getMessage());
continue;
}
// udalo sie, kasujemy plik ready
currentReadyQueueItemFile.delete();
// przenosimy plik do archiwum
// sprawdzenie i ewentualne utworzenie katalogu z data
File localDirJobQueryArchiveDirWithDateFile = new File(localDirJobQueryArchiveDirFile, dateFormat.format(queueItem.getSendTimestamp()));
if (localDirJobQueryArchiveDirWithDateFile.exists() == false && localDirJobQueryArchiveDirWithDateFile.isDirectory() == false) { // tworzymy katalog
localDirJobQueryArchiveDirWithDateFile.mkdir();
}
// przenosimy plik do wspolnego archiwum
FileSystem archiveFileSystem = null;
try {
// utworzenie nazwy pliku z archiwum
Calendar querySendTimestampCalendar = Calendar.getInstance();
querySendTimestampCalendar.setTime(queueItem.getSendTimestamp());
int sendTimestampHourOfDay = querySendTimestampCalendar.get(Calendar.HOUR_OF_DAY);
String archivePartFileName = dateFormat.format(querySendTimestampCalendar.getTime()) + "_" + (sendTimestampHourOfDay < 10 ? "0" + sendTimestampHourOfDay : sendTimestampHourOfDay)
+ "_" + (querySendTimestampCalendar.get(Calendar.MINUTE) / 10) + "0";
//
File archiveFile = new File(localDirJobQueryArchiveDirWithDateFile, archivePartFileName + ".zip");
URI archiveFileUri = URI.create("jar:file:" + archiveFile.getAbsolutePath());
// utworzenie archiwum
Map<String, String> archiveEnv = new HashMap<>();
archiveEnv.put("create", String.valueOf(archiveFile.exists() == false));
archiveFileSystem = FileSystems.newFileSystem(archiveFileUri, archiveEnv);
// przenoszenie pliku <SUF>
Path queueItemFilePathInArchiveFile = archiveFileSystem.getPath(queueItemFile.getName());
Files.copy(queueItemFile.toPath(), queueItemFilePathInArchiveFile, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
logger.error("Błąd podczas przenoszenia pliku do archiwum: " + e.getMessage());
} finally {
if (archiveFileSystem != null) {
try {
archiveFileSystem.close();
} catch (IOException e) {
logger.error("Błąd podczas przenoszenia pliku do archiwum: " + e.getMessage());
}
}
}
// kasujemy plik
queueItemFile.delete();
}
}
}
/*
private void copyAndGzipFile(File source, File destination) throws IOException {
byte[] buffer = new byte[1024];
FileInputStream sourceInputStream = null;
GZIPOutputStream destinationOutputStream = null;
try {
sourceInputStream = new FileInputStream(source);
destinationOutputStream = new GZIPOutputStream(new FileOutputStream(destination));
int len;
while ((len = sourceInputStream.read(buffer)) > 0) {
destinationOutputStream.write(buffer, 0, len);
}
} finally {
if (sourceInputStream != null) {
sourceInputStream.close();
}
if (destinationOutputStream != null) {
destinationOutputStream.finish();
destinationOutputStream.close();
}
}
}
*/
public void deleteLocalDirArchiveOldQueueItems(final int olderThanDays) {
// pobieramy liste plikow do skasowania
File[] oldQueueItemsDirListFiles = localDirJobQueryArchiveDirFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isFile() == true) {
return false;
}
if (pathname.isDirectory() == false) {
return false;
}
Date pathnameDate = null;
try {
pathnameDate = dateFormat.parse(pathname.getName());
} catch (ParseException e) { // zly format nazwy katalogu
return false;
}
// nazwa katalogu jest w odpowiednim formacie, wiec sprawdzamy liczbe dni
Calendar calendarNowMinusDays = Calendar.getInstance();
calendarNowMinusDays.add(Calendar.DAY_OF_YEAR, -olderThanDays);
if (calendarNowMinusDays.getTime().getTime() > pathnameDate.getTime()) { // kasujemy
return true;
} else {
return false;
}
}
});
// kasujemy pliki
for (File directoryToDelete : oldQueueItemsDirListFiles) {
logger.info("Kasuje katalog archiwum: " + directoryToDelete.getName());
// najpierw kasujemy pliki z tego katalogu
File[] directoryToDeleteListFiles = directoryToDelete.listFiles();
for (File fileToDelete : directoryToDeleteListFiles) {
fileToDelete.delete();
}
// a pozniej sam katalog (powinien byc) pusty
directoryToDelete.delete();
}
}
//
/*
public static void main(String[] args) {
org.apache.log4j.BasicConfigurator.configure();
QueueService queueService = new QueueService();
queueService.localDirJobQueueDir = "/opt/apache-tomcat-8.0.8/local-job-queue";
queueService.init();
queueService.deleteLocalDirArchiveOldQueueItems(10);
}
*/
}
| t |
5196_1 | demsey15/SZI | 4,474 | src/main/java/bohonos/demski/gorska/limiszewska/mieldzioc/logicalLayer/geneticAlgorithm/PathFinder.java | package bohonos.demski.gorska.limiszewska.mieldzioc.logicalLayer.geneticAlgorithm;
import bohonos.demski.gorska.limiszewska.mieldzioc.logicalLayer.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by Dominik on 2015-06-05.
*/
public class PathFinder implements IWalker{
private FindProperOrder properOrderFinder = new FindProperOrder();
private Monitor monitor = Monitor.getInstance();
private Control control = Control.getInstance();
public void goThroughTables(List<Integer> tablesToGoThrow){
List<Integer> tablesToGo = new ArrayList<Integer>();
for(Integer i : tablesToGoThrow){
if(!tablesToGo.contains(i)) tablesToGo.add(i);
}
System.out.println("Wywołano algorytm dominika z listą stołów: " + Arrays.toString(tablesToGo.toArray()));
List<Integer> properOrderTabels = properOrderFinder.findProperOrder(tablesToGo);
Coordinates currentPosition = new Coordinates(0, 0); //zaczynamy od współrzędnych (0, 0)
for(int i = 0; i < properOrderTabels.size() + 1; i++){ //+1 bo jeszcze powrot do (0,0)
Coordinates cornerToGo;
if(i < properOrderTabels.size()) {
Coordinates tableToGo = control.getCoordinatesForTableNumber(properOrderTabels.get(i));
cornerToGo = getTheClosestCorner(tableToGo, currentPosition);
}
else{
cornerToGo = new Coordinates(0, 0);
}
List<Coordinates> path = new ArrayList<Coordinates>();
while(!(currentPosition.getRow() == cornerToGo.getRow() && //jesli nie jestesmy jeszcze na miejscu
currentPosition.getColumn() == cornerToGo.getColumn())) {
boolean wasStep = false;
if (currentPosition.getRow() != cornerToGo.getRow()) { //jesli jestesmy na zlej wysokosci
Coordinates toGo;
if (currentPosition.getRow() > cornerToGo.getRow()) { //jesli powinnismy isc w gore
toGo = new Coordinates(currentPosition.getRow() - 1, currentPosition.getColumn()); //spróbuj iść w górę
} else { //jesli powinnismy isc w dol
toGo = new Coordinates(currentPosition.getRow() + 1, currentPosition.getColumn()); //spróbuj iść w dół
}
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasStep = true;
}
}
if(!wasStep && currentPosition.getColumn() != cornerToGo.getColumn()){ //nie bylo ruchu i jestesmy na zlej pozycji w poziomie
Coordinates toGo;
if (currentPosition.getColumn() > cornerToGo.getColumn()) { //nalezy isc w lewo
toGo = new Coordinates(currentPosition.getRow(), currentPosition.getColumn() - 1); //spróbuj iść w lewo
} else {
toGo = new Coordinates(currentPosition.getRow(), currentPosition.getColumn() + 1); //spróbuj iść w prawo
}
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasStep = true;
}
}
if(!wasStep) { //standardowy ruch sie nie udal - wykonaj ruch awaryjny - po skosie
boolean wasHelpingMove = false;
if (currentPosition.getColumn() > cornerToGo.getColumn()) { //należy poruszać się w lewo
if(currentPosition.getRow() > cornerToGo.getRow()){ //należy poruszać się górę
Coordinates toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w dół i w lewo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
else{ //należy poruszac sie w gore i w lewo
toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w górę i w prawo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else if(currentPosition.getRow() < cornerToGo.getRow()){ //należy poruszać się w dół i w lewo
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w górę i w lewo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
else{
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w dół i w prawo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else{ //tylko w lewo
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w górę i w lewo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
} else {
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w dol i w lewo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
}
else if(currentPosition.getColumn() < cornerToGo.getColumn()){ //należy poruszać się w prawo
if(currentPosition.getRow() > cornerToGo.getRow()){ //należy poruszać się górę
Coordinates toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w dół i w prawo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
else{
toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w górę i w lewo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else if(currentPosition.getRow() < cornerToGo.getRow()){ //należy poruszać się w dół i w prawo
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w górę i w prawo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
else{
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w dół i w lewo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else{ //tylko w prawo
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w górę i w prawo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
} else {
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w dol i w prawo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
}
else{ //nalezy poruszac sie tylko w gore / dol
if(currentPosition.getRow() > cornerToGo.getRow()){ //nalezy isc tylko w gore
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w górę i w prawo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
} else {
toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w gore i w lewo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else{ //nalezy isc tylko w dol
Coordinates toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w dol i w prawo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
} else {
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w dol i w lewo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
}
if(!wasHelpingMove){
System.out.println("Nie mogę znaleźć ścieżki!");
break;
}
}
/* //Wypisywanie z opoznieniem sciezki ktora znajduje
System.out.print(currentPosition + ", ");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
}
if(i < properOrderTabels.size())
System.out.println("Idę do stolika nr: " + properOrderTabels.get(i));
else System.out.println("Wracam do (0, 0)");
System.out.println("Sciezka: " + Arrays.toString(path.toArray()));
monitor.callListenersOnMove(path);
try {
Thread.sleep(3000);
try {
if(i < properOrderTabels.size())
OrdersService.getInstance().removeMealForTableFromTray(properOrderTabels.get(i)); //zdejmij dostarczone potrawy z listy potraw na tacy kelnera
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Coordinates getTheClosestCorner(Coordinates tableCoordinates, Coordinates currentPosition){
Coordinates leftUp = new Coordinates(tableCoordinates.getRow() - 1, tableCoordinates.getColumn() - 1);
Coordinates leftDown = new Coordinates(tableCoordinates.getRow() + 1, tableCoordinates.getColumn() - 1);
Coordinates rightUp = new Coordinates(tableCoordinates.getRow() + 1, tableCoordinates.getColumn() + 1);
Coordinates rightDown = new Coordinates(tableCoordinates.getRow() - 1, tableCoordinates.getColumn() + 1);
List<Coordinates> correctCoordinates = new ArrayList<Coordinates>(4);
if(Map.checkIfCoordinatesAreInMap(leftUp)) correctCoordinates.add(leftUp);
if(Map.checkIfCoordinatesAreInMap(leftDown)) correctCoordinates.add(leftDown);
if(Map.checkIfCoordinatesAreInMap(rightUp)) correctCoordinates.add(rightUp);
if(Map.checkIfCoordinatesAreInMap(rightDown)) correctCoordinates.add(rightDown);
if(correctCoordinates.size() > 0){
Coordinates theBest = correctCoordinates.get(0);
int bestDistance;
for(int i = 1; i < correctCoordinates.size(); i++){
bestDistance = getDistanceBetweenCoordinates(theBest, currentPosition);
Coordinates coord = correctCoordinates.get(i);
int distance = getDistanceBetweenCoordinates(coord, currentPosition);
if(distance < bestDistance) theBest = coord;
}
return theBest;
}
else return null;
}
private int getDistanceBetweenCoordinates(Coordinates coordinates1, Coordinates coordinates2){
return Math.abs(coordinates1.getColumn() - coordinates2.getColumn()) + Math.abs(coordinates1.getRow()
- coordinates2.getRow());
}
public static void main(String[] args) {
Control control = Control.getInstance();
try {
control.prepareMap();
PathFinder f = new PathFinder();
f.goThroughTables(Arrays.asList(new Integer[]{1, 2, 3}));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| //zaczynamy od współrzędnych (0, 0) | package bohonos.demski.gorska.limiszewska.mieldzioc.logicalLayer.geneticAlgorithm;
import bohonos.demski.gorska.limiszewska.mieldzioc.logicalLayer.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by Dominik on 2015-06-05.
*/
public class PathFinder implements IWalker{
private FindProperOrder properOrderFinder = new FindProperOrder();
private Monitor monitor = Monitor.getInstance();
private Control control = Control.getInstance();
public void goThroughTables(List<Integer> tablesToGoThrow){
List<Integer> tablesToGo = new ArrayList<Integer>();
for(Integer i : tablesToGoThrow){
if(!tablesToGo.contains(i)) tablesToGo.add(i);
}
System.out.println("Wywołano algorytm dominika z listą stołów: " + Arrays.toString(tablesToGo.toArray()));
List<Integer> properOrderTabels = properOrderFinder.findProperOrder(tablesToGo);
Coordinates currentPosition = new Coordinates(0, 0); //zaczynamy od <SUF>
for(int i = 0; i < properOrderTabels.size() + 1; i++){ //+1 bo jeszcze powrot do (0,0)
Coordinates cornerToGo;
if(i < properOrderTabels.size()) {
Coordinates tableToGo = control.getCoordinatesForTableNumber(properOrderTabels.get(i));
cornerToGo = getTheClosestCorner(tableToGo, currentPosition);
}
else{
cornerToGo = new Coordinates(0, 0);
}
List<Coordinates> path = new ArrayList<Coordinates>();
while(!(currentPosition.getRow() == cornerToGo.getRow() && //jesli nie jestesmy jeszcze na miejscu
currentPosition.getColumn() == cornerToGo.getColumn())) {
boolean wasStep = false;
if (currentPosition.getRow() != cornerToGo.getRow()) { //jesli jestesmy na zlej wysokosci
Coordinates toGo;
if (currentPosition.getRow() > cornerToGo.getRow()) { //jesli powinnismy isc w gore
toGo = new Coordinates(currentPosition.getRow() - 1, currentPosition.getColumn()); //spróbuj iść w górę
} else { //jesli powinnismy isc w dol
toGo = new Coordinates(currentPosition.getRow() + 1, currentPosition.getColumn()); //spróbuj iść w dół
}
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasStep = true;
}
}
if(!wasStep && currentPosition.getColumn() != cornerToGo.getColumn()){ //nie bylo ruchu i jestesmy na zlej pozycji w poziomie
Coordinates toGo;
if (currentPosition.getColumn() > cornerToGo.getColumn()) { //nalezy isc w lewo
toGo = new Coordinates(currentPosition.getRow(), currentPosition.getColumn() - 1); //spróbuj iść w lewo
} else {
toGo = new Coordinates(currentPosition.getRow(), currentPosition.getColumn() + 1); //spróbuj iść w prawo
}
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasStep = true;
}
}
if(!wasStep) { //standardowy ruch sie nie udal - wykonaj ruch awaryjny - po skosie
boolean wasHelpingMove = false;
if (currentPosition.getColumn() > cornerToGo.getColumn()) { //należy poruszać się w lewo
if(currentPosition.getRow() > cornerToGo.getRow()){ //należy poruszać się górę
Coordinates toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w dół i w lewo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
else{ //należy poruszac sie w gore i w lewo
toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w górę i w prawo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else if(currentPosition.getRow() < cornerToGo.getRow()){ //należy poruszać się w dół i w lewo
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w górę i w lewo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
else{
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w dół i w prawo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else{ //tylko w lewo
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w górę i w lewo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
} else {
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w dol i w lewo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
}
else if(currentPosition.getColumn() < cornerToGo.getColumn()){ //należy poruszać się w prawo
if(currentPosition.getRow() > cornerToGo.getRow()){ //należy poruszać się górę
Coordinates toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w dół i w prawo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
else{
toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w górę i w lewo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else if(currentPosition.getRow() < cornerToGo.getRow()){ //należy poruszać się w dół i w prawo
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w górę i w prawo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
else{
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w dół i w lewo
if(Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD){
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else{ //tylko w prawo
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w górę i w prawo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
} else {
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w dol i w prawo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
}
else{ //nalezy poruszac sie tylko w gore / dol
if(currentPosition.getRow() > cornerToGo.getRow()){ //nalezy isc tylko w gore
Coordinates toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w górę i w prawo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
} else {
toGo = new Coordinates(currentPosition.getRow() - 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w gore i w lewo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
else{ //nalezy isc tylko w dol
Coordinates toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() + 1); //spróbuj iść po skosie w dol i w prawo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
} else {
toGo = new Coordinates(currentPosition.getRow() + 1,
currentPosition.getColumn() - 1); //spróbuj iść po skosie w dol i w lewo
if (Map.checkIfCoordinatesAreInMap(toGo) && control.getObjectId(toGo) == Map.FREE_FIELD) {
path.add(toGo);
currentPosition = toGo;
wasHelpingMove = true;
}
}
}
}
if(!wasHelpingMove){
System.out.println("Nie mogę znaleźć ścieżki!");
break;
}
}
/* //Wypisywanie z opoznieniem sciezki ktora znajduje
System.out.print(currentPosition + ", ");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
}
if(i < properOrderTabels.size())
System.out.println("Idę do stolika nr: " + properOrderTabels.get(i));
else System.out.println("Wracam do (0, 0)");
System.out.println("Sciezka: " + Arrays.toString(path.toArray()));
monitor.callListenersOnMove(path);
try {
Thread.sleep(3000);
try {
if(i < properOrderTabels.size())
OrdersService.getInstance().removeMealForTableFromTray(properOrderTabels.get(i)); //zdejmij dostarczone potrawy z listy potraw na tacy kelnera
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Coordinates getTheClosestCorner(Coordinates tableCoordinates, Coordinates currentPosition){
Coordinates leftUp = new Coordinates(tableCoordinates.getRow() - 1, tableCoordinates.getColumn() - 1);
Coordinates leftDown = new Coordinates(tableCoordinates.getRow() + 1, tableCoordinates.getColumn() - 1);
Coordinates rightUp = new Coordinates(tableCoordinates.getRow() + 1, tableCoordinates.getColumn() + 1);
Coordinates rightDown = new Coordinates(tableCoordinates.getRow() - 1, tableCoordinates.getColumn() + 1);
List<Coordinates> correctCoordinates = new ArrayList<Coordinates>(4);
if(Map.checkIfCoordinatesAreInMap(leftUp)) correctCoordinates.add(leftUp);
if(Map.checkIfCoordinatesAreInMap(leftDown)) correctCoordinates.add(leftDown);
if(Map.checkIfCoordinatesAreInMap(rightUp)) correctCoordinates.add(rightUp);
if(Map.checkIfCoordinatesAreInMap(rightDown)) correctCoordinates.add(rightDown);
if(correctCoordinates.size() > 0){
Coordinates theBest = correctCoordinates.get(0);
int bestDistance;
for(int i = 1; i < correctCoordinates.size(); i++){
bestDistance = getDistanceBetweenCoordinates(theBest, currentPosition);
Coordinates coord = correctCoordinates.get(i);
int distance = getDistanceBetweenCoordinates(coord, currentPosition);
if(distance < bestDistance) theBest = coord;
}
return theBest;
}
else return null;
}
private int getDistanceBetweenCoordinates(Coordinates coordinates1, Coordinates coordinates2){
return Math.abs(coordinates1.getColumn() - coordinates2.getColumn()) + Math.abs(coordinates1.getRow()
- coordinates2.getRow());
}
public static void main(String[] args) {
Control control = Control.getInstance();
try {
control.prepareMap();
PathFinder f = new PathFinder();
f.goThroughTables(Arrays.asList(new Integer[]{1, 2, 3}));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| t |
10308_12 | dixu11/sda129-zaawansowane-programowanie | 796 | src/main/java/advanced/inheritance/AnimalsDemo.java | package advanced.inheritance;
import advanced.inheritance.animal.Animal;
import advanced.inheritance.animal.Cat;
import advanced.inheritance.animal.Dog;
import advanced.inheritance.animal.WildBoar;
import java.util.ArrayList;
import java.util.List;
public class AnimalsDemo {
public static void main(String[] args) {
Dog dog = new Dog("Rex", 1, false);
//dog = new Cat(); // działałoby gdyby referencja dog była typu Animal lub Object
Dog dog2 = new Dog();
dog.bark();
dog.sit();
dog.eat();
Cat cat = new Cat("Kicia Mała", 4, 6);
Cat cat2 = new Cat();
cat.meowing();
cat.climbDoor();
cat.eat();
AnimalKeeper animalKeeper = new AnimalKeeper();
// animalKeeper.feedDog(dog);
// animalKeeper.feedCat(cat);
animalKeeper.feedAnimal(dog);
animalKeeper.feedAnimal(cat);
System.out.println("------------");
//polimorfizm
Animal animal = new Dog();
animal.makeSound(); // szczeka!
animal = new Cat();
animal.makeSound(); // Miałka!
System.out.println("------------");
List<Animal> animals = new ArrayList<>();
//Animal someAnimal = new Animal(); // abstract nas broni przed problemami typu - niewidzialne zwierzeta, figury, samochody
// animalKeeper.feedAnimal(someAnimal);
animals.add(cat);
animals.add(cat2);
animals.add(dog);
animals.add(dog2);
animals.add(new WildBoar("Chrumek", 4));
// animals.add(someAnimal);
for (Animal anAnimal : animals) {
anAnimal.makeSound();
}
}
}
//dziedzienie, cel: ograniczenie powtórek + polimorfizm
//co dziedziczymy? pola, metody, typ
//klasa abstrakcyjna:
//-nie można stworzyć instancji
//-może mieć abstrakcyjne metody
//abstrakcyjna metoda
//nie ma ciała
//trzeba ją nadpisywać
//konkret abstrakcja
//klasa abstr klasa interfejs
//polimorfizm - zdolność języka obiektowego aby wstawiać obiekty różnych typów do wspólnej referencji
// a zachowania referencji dostosują się do aktualnego typu obiektu
//polimorfizm otwiera drogę do wzorców projektowych oraz umożliwia realizowanie zasady O/C solid
// dzięki której tempo dodawania nowych funkcjonalności może być stałe bez względu jak wielka jest aplikacje
| //polimorfizm otwiera drogę do wzorców projektowych oraz umożliwia realizowanie zasady O/C solid | package advanced.inheritance;
import advanced.inheritance.animal.Animal;
import advanced.inheritance.animal.Cat;
import advanced.inheritance.animal.Dog;
import advanced.inheritance.animal.WildBoar;
import java.util.ArrayList;
import java.util.List;
public class AnimalsDemo {
public static void main(String[] args) {
Dog dog = new Dog("Rex", 1, false);
//dog = new Cat(); // działałoby gdyby referencja dog była typu Animal lub Object
Dog dog2 = new Dog();
dog.bark();
dog.sit();
dog.eat();
Cat cat = new Cat("Kicia Mała", 4, 6);
Cat cat2 = new Cat();
cat.meowing();
cat.climbDoor();
cat.eat();
AnimalKeeper animalKeeper = new AnimalKeeper();
// animalKeeper.feedDog(dog);
// animalKeeper.feedCat(cat);
animalKeeper.feedAnimal(dog);
animalKeeper.feedAnimal(cat);
System.out.println("------------");
//polimorfizm
Animal animal = new Dog();
animal.makeSound(); // szczeka!
animal = new Cat();
animal.makeSound(); // Miałka!
System.out.println("------------");
List<Animal> animals = new ArrayList<>();
//Animal someAnimal = new Animal(); // abstract nas broni przed problemami typu - niewidzialne zwierzeta, figury, samochody
// animalKeeper.feedAnimal(someAnimal);
animals.add(cat);
animals.add(cat2);
animals.add(dog);
animals.add(dog2);
animals.add(new WildBoar("Chrumek", 4));
// animals.add(someAnimal);
for (Animal anAnimal : animals) {
anAnimal.makeSound();
}
}
}
//dziedzienie, cel: ograniczenie powtórek + polimorfizm
//co dziedziczymy? pola, metody, typ
//klasa abstrakcyjna:
//-nie można stworzyć instancji
//-może mieć abstrakcyjne metody
//abstrakcyjna metoda
//nie ma ciała
//trzeba ją nadpisywać
//konkret abstrakcja
//klasa abstr klasa interfejs
//polimorfizm - zdolność języka obiektowego aby wstawiać obiekty różnych typów do wspólnej referencji
// a zachowania referencji dostosują się do aktualnego typu obiektu
//polimorfizm otwiera <SUF>
// dzięki której tempo dodawania nowych funkcjonalności może być stałe bez względu jak wielka jest aplikacje
| t |
3782_0 | dominikinik/uwrcourses | 198 | java_course/zadanie3/obliczenia/Wyrazenie.java | package obliczenia;
public abstract class Wyrazenie implements Obliczalny {
public abstract double oblicz();
public static double suma (Wyrazenie... wyrs){
double sum = 0;
for(Wyrazenie wyr : wyrs){
sum += wyr.oblicz();
}
return sum;
}
public static double iloczyn (Wyrazenie... wyrs){ //nie wiem czemu w przykladzie jest int dla mnie to dziwne troche wiec dalem double ale nie oceniam :)
double mul = 1;
for(Wyrazenie wyr : wyrs){
mul *= wyr.oblicz();
}
return mul;
}
}
| //nie wiem czemu w przykladzie jest int dla mnie to dziwne troche wiec dalem double ale nie oceniam :)
| package obliczenia;
public abstract class Wyrazenie implements Obliczalny {
public abstract double oblicz();
public static double suma (Wyrazenie... wyrs){
double sum = 0;
for(Wyrazenie wyr : wyrs){
sum += wyr.oblicz();
}
return sum;
}
public static double iloczyn (Wyrazenie... wyrs){ //nie wiem <SUF>
double mul = 1;
for(Wyrazenie wyr : wyrs){
mul *= wyr.oblicz();
}
return mul;
}
}
| f |
6556_1 | drezew/gui-2 | 589 | Main.java | import javax.swing.SwingUtilities;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Biblioteka bib = new Biblioteka();
bib.dodajCzytelnika(new Czytelnik("Jan", "Kowalski", bib.kolejny_numer_czytelnika()));
bib.dodajCzytelnika(new Czytelnik("Dariusz", "Malinowski", bib.kolejny_numer_czytelnika()));
bib.dodajCzytelnika(new Czytelnik("Wojciech", "Kaminski", bib.kolejny_numer_czytelnika()));
bib.dodajKsiazke(new Ksiazka("D. Thomas", "Programming Ruby 1.9", "978-1-934356-08-1", 5));
bib.dodajKsiazke(new Ksiazka("J. Loeliger", "Version Control with Git", "978-0-596-52012-0", 2));
bib.dodajKsiazke(new Ksiazka("J.E.F. Friedl", "Matering Regular Expressions", "978-0-596-52812-6", 1));
bib.setVisible(true);
}
});
}
}
/* 1 Rozbuduj przykładowy system o następujące elementy:
1.1 Dodawanie książek.
1.2 Usuwanie czytelników.
1.3 Usuwanie książek.
1.4 Zwrot książki.
1.5 Wyświetlanie informacji o koncie czytelnika (o wypożyczonych przez niego książkach).
1.6 Wyświetlanie informacji o książce (komu wypożyczono poszczególne egzemplarze).
2 Dodaj mechanizm serializacji, tak aby możliwe było odtworzenie stanu systemu po jego ponownym uruchomieniu.
*/
| /* 1 Rozbuduj przykładowy system o następujące elementy:
1.1 Dodawanie książek.
1.2 Usuwanie czytelników.
1.3 Usuwanie książek.
1.4 Zwrot książki.
1.5 Wyświetlanie informacji o koncie czytelnika (o wypożyczonych przez niego książkach).
1.6 Wyświetlanie informacji o książce (komu wypożyczono poszczególne egzemplarze).
2 Dodaj mechanizm serializacji, tak aby możliwe było odtworzenie stanu systemu po jego ponownym uruchomieniu.
*/ | import javax.swing.SwingUtilities;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Biblioteka bib = new Biblioteka();
bib.dodajCzytelnika(new Czytelnik("Jan", "Kowalski", bib.kolejny_numer_czytelnika()));
bib.dodajCzytelnika(new Czytelnik("Dariusz", "Malinowski", bib.kolejny_numer_czytelnika()));
bib.dodajCzytelnika(new Czytelnik("Wojciech", "Kaminski", bib.kolejny_numer_czytelnika()));
bib.dodajKsiazke(new Ksiazka("D. Thomas", "Programming Ruby 1.9", "978-1-934356-08-1", 5));
bib.dodajKsiazke(new Ksiazka("J. Loeliger", "Version Control with Git", "978-0-596-52012-0", 2));
bib.dodajKsiazke(new Ksiazka("J.E.F. Friedl", "Matering Regular Expressions", "978-0-596-52812-6", 1));
bib.setVisible(true);
}
});
}
}
/* 1 Rozbuduj przykładowy <SUF>*/
| f |
2033_16 | dromara/hutool | 7,426 | hutool-core/src/main/java/cn/hutool/core/lang/hash/CityHash.java | package cn.hutool.core.lang.hash;
import cn.hutool.core.util.ByteUtil;
import java.util.Arrays;
/**
* Google发布的Hash计算算法:CityHash64 与 CityHash128。<br>
* 它们分别根据字串计算 64 和 128 位的散列值。这些算法不适用于加密,但适合用在散列表等处。
*
* <p>
* 代码来自:https://github.com/rolandhe/string-tools<br>
* 原始算法:https://github.com/google/cityhash
*
* @author hexiufeng
* @since 5.2.5
*/
public class CityHash {
// Some primes between 2^63 and 2^64 for various uses.
private static final long k0 = 0xc3a5c85c97cb3127L;
private static final long k1 = 0xb492b66fbe98f273L;
private static final long k2 = 0x9ae16a3b2f90404fL;
private static final long kMul = 0x9ddfea08eb382d69L;
// Magic numbers for 32-bit hashing. Copied from Murmur3.
private static final int c1 = 0xcc9e2d51;
private static final int c2 = 0x1b873593;
/**
* 计算32位City Hash值
*
* @param data 数据
* @return hash值
*/
public static int hash32(byte[] data) {
int len = data.length;
if (len <= 24) {
return len <= 12 ?
(len <= 4 ? hash32Len0to4(data) : hash32Len5to12(data)) :
hash32Len13to24(data);
}
// len > 24
int h = len, g = c1 * len, f = g;
int a0 = rotate32(fetch32(data, len - 4) * c1, 17) * c2;
int a1 = rotate32(fetch32(data, len - 8) * c1, 17) * c2;
int a2 = rotate32(fetch32(data, len - 16) * c1, 17) * c2;
int a3 = rotate32(fetch32(data, len - 12) * c1, 17) * c2;
int a4 = rotate32(fetch32(data, len - 20) * c1, 17) * c2;
h ^= a0;
h = rotate32(h, 19);
h = h * 5 + 0xe6546b64;
h ^= a2;
h = rotate32(h, 19);
h = h * 5 + 0xe6546b64;
g ^= a1;
g = rotate32(g, 19);
g = g * 5 + 0xe6546b64;
g ^= a3;
g = rotate32(g, 19);
g = g * 5 + 0xe6546b64;
f += a4;
f = rotate32(f, 19);
f = f * 5 + 0xe6546b64;
int iters = (len - 1) / 20;
int pos = 0;
do {
a0 = rotate32(fetch32(data, pos) * c1, 17) * c2;
a1 = fetch32(data, pos + 4);
a2 = rotate32(fetch32(data, pos + 8) * c1, 17) * c2;
a3 = rotate32(fetch32(data, pos + 12) * c1, 17) * c2;
a4 = fetch32(data, pos + 16);
h ^= a0;
h = rotate32(h, 18);
h = h * 5 + 0xe6546b64;
f += a1;
f = rotate32(f, 19);
f = f * c1;
g += a2;
g = rotate32(g, 18);
g = g * 5 + 0xe6546b64;
h ^= a3 + a1;
h = rotate32(h, 19);
h = h * 5 + 0xe6546b64;
g ^= a4;
g = Integer.reverseBytes(g) * 5;
h += a4 * 5;
h = Integer.reverseBytes(h);
f += a0;
int swapValue = f;
f = g;
g = h;
h = swapValue;
pos += 20;
} while (--iters != 0);
g = rotate32(g, 11) * c1;
g = rotate32(g, 17) * c1;
f = rotate32(f, 11) * c1;
f = rotate32(f, 17) * c1;
h = rotate32(h + g, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * c1;
h = rotate32(h + f, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * c1;
return h;
}
/**
* 计算64位City Hash值
*
* @param data 数据
* @return hash值
*/
public static long hash64(byte[] data) {
int len = data.length;
if (len <= 32) {
if (len <= 16) {
return hashLen0to16(data);
} else {
return hashLen17to32(data);
}
} else if (len <= 64) {
return hashLen33to64(data);
}
// For strings over 64 bytes we hash the end first, and then as we
// loop we keep 56 bytes of state: v, w, x, y, and z.
long x = fetch64(data, len - 40);
long y = fetch64(data, len - 16) + fetch64(data, len - 56);
long z = hashLen16(fetch64(data, len - 48) + len, fetch64(data, len - 24));
Number128 v = weakHashLen32WithSeeds(data, len - 64, len, z);
Number128 w = weakHashLen32WithSeeds(data, len - 32, y + k1, x);
x = x * k1 + fetch64(data, 0);
// Decrease len to the nearest multiple of 64, and operate on 64-byte chunks.
len = (len - 1) & ~63;
int pos = 0;
do {
x = rotate64(x + y + v.getLowValue() + fetch64(data, pos + 8), 37) * k1;
y = rotate64(y + v.getHighValue() + fetch64(data, pos + 48), 42) * k1;
x ^= w.getHighValue();
y += v.getLowValue() + fetch64(data, pos + 40);
z = rotate64(z + w.getLowValue(), 33) * k1;
v = weakHashLen32WithSeeds(data, pos, v.getHighValue() * k1, x + w.getLowValue());
w = weakHashLen32WithSeeds(data, pos + 32, z + w.getHighValue(), y + fetch64(data, pos + 16));
// swap z,x value
long swapValue = x;
x = z;
z = swapValue;
pos += 64;
len -= 64;
} while (len != 0);
return hashLen16(hashLen16(v.getLowValue(), w.getLowValue()) + shiftMix(y) * k1 + z,
hashLen16(v.getHighValue(), w.getHighValue()) + x);
}
/**
* 计算64位City Hash值
*
* @param data 数据
* @param seed0 种子1
* @param seed1 种子2
* @return hash值
*/
public static long hash64(byte[] data, long seed0, long seed1) {
return hashLen16(hash64(data) - seed0, seed1);
}
/**
* 计算64位City Hash值,种子1使用默认的{@link #k2}
*
* @param data 数据
* @param seed 种子2
* @return hash值
*/
public static long hash64(byte[] data, long seed) {
return hash64(data, k2, seed);
}
/**
* 计算128位City Hash值
*
* @param data 数据
* @return hash值
*/
public static Number128 hash128(byte[] data) {
int len = data.length;
return len >= 16 ?
hash128(data, 16,
new Number128(fetch64(data, 0), fetch64(data, 8) + k0)) :
hash128(data, 0, new Number128(k0, k1));
}
/**
* 计算128位City Hash值
*
* @param data 数据
* @param seed 种子
* @return hash值
*/
public static Number128 hash128(byte[] data, Number128 seed) {
return hash128(data, 0, seed);
}
//------------------------------------------------------------------------------------------------------- Private method start
private static Number128 hash128(final byte[] byteArray, int start, final Number128 seed) {
int len = byteArray.length - start;
if (len < 128) {
return cityMurmur(Arrays.copyOfRange(byteArray, start, byteArray.length), seed);
}
// We expect len >= 128 to be the common case. Keep 56 bytes of state:
// v, w, x, y, and z.
Number128 v = new Number128(0L, 0L);
Number128 w = new Number128(0L, 0L);
long x = seed.getLowValue();
long y = seed.getHighValue();
long z = len * k1;
v.setLowValue(rotate64(y ^ k1, 49) * k1 + fetch64(byteArray, start));
v.setHighValue(rotate64(v.getLowValue(), 42) * k1 + fetch64(byteArray, start + 8));
w.setLowValue(rotate64(y + z, 35) * k1 + x);
w.setHighValue(rotate64(x + fetch64(byteArray, start + 88), 53) * k1);
// This is the same inner loop as CityHash64(), manually unrolled.
int pos = start;
do {
x = rotate64(x + y + v.getLowValue() + fetch64(byteArray, pos + 8), 37) * k1;
y = rotate64(y + v.getHighValue() + fetch64(byteArray, pos + 48), 42) * k1;
x ^= w.getHighValue();
y += v.getLowValue() + fetch64(byteArray, pos + 40);
z = rotate64(z + w.getLowValue(), 33) * k1;
v = weakHashLen32WithSeeds(byteArray, pos, v.getHighValue() * k1, x + w.getLowValue());
w = weakHashLen32WithSeeds(byteArray, pos + 32, z + w.getHighValue(), y + fetch64(byteArray, pos + 16));
long swapValue = x;
x = z;
z = swapValue;
pos += 64;
x = rotate64(x + y + v.getLowValue() + fetch64(byteArray, pos + 8), 37) * k1;
y = rotate64(y + v.getHighValue() + fetch64(byteArray, pos + 48), 42) * k1;
x ^= w.getHighValue();
y += v.getLowValue() + fetch64(byteArray, pos + 40);
z = rotate64(z + w.getLowValue(), 33) * k1;
v = weakHashLen32WithSeeds(byteArray, pos, v.getHighValue() * k1, x + w.getLowValue());
w = weakHashLen32WithSeeds(byteArray, pos + 32, z + w.getHighValue(), y + fetch64(byteArray, pos + 16));
swapValue = x;
x = z;
z = swapValue;
pos += 64;
len -= 128;
} while (len >= 128);
x += rotate64(v.getLowValue() + z, 49) * k0;
y = y * k0 + rotate64(w.getHighValue(), 37);
z = z * k0 + rotate64(w.getLowValue(), 27);
w.setLowValue(w.getLowValue() * 9);
v.setLowValue(v.getLowValue() * k0);
// If 0 < len < 128, hash up to 4 chunks of 32 bytes each from the end of s.
for (int tail_done = 0; tail_done < len; ) {
tail_done += 32;
y = rotate64(x + y, 42) * k0 + v.getHighValue();
w.setLowValue(w.getLowValue() + fetch64(byteArray, pos + len - tail_done + 16));
x = x * k0 + w.getLowValue();
z += w.getHighValue() + fetch64(byteArray, pos + len - tail_done);
w.setHighValue(w.getHighValue() + v.getLowValue());
v = weakHashLen32WithSeeds(byteArray, pos + len - tail_done, v.getLowValue() + z, v.getHighValue());
v.setLowValue(v.getLowValue() * k0);
}
// At this point our 56 bytes of state should contain more than
// enough information for a strong 128-bit hash. We use two
// different 56-byte-to-8-byte hashes to get a 16-byte final result.
x = hashLen16(x, v.getLowValue());
y = hashLen16(y + z, w.getLowValue());
return new Number128(hashLen16(x + v.getHighValue(), w.getHighValue()) + y,
hashLen16(x + w.getHighValue(), y + v.getHighValue()));
}
private static int hash32Len0to4(final byte[] byteArray) {
int b = 0;
int c = 9;
int len = byteArray.length;
for (int v : byteArray) {
b = b * c1 + v;
c ^= b;
}
return fmix(mur(b, mur(len, c)));
}
private static int hash32Len5to12(final byte[] byteArray) {
int len = byteArray.length;
int a = len, b = len * 5, c = 9, d = b;
a += fetch32(byteArray, 0);
b += fetch32(byteArray, len - 4);
c += fetch32(byteArray, ((len >>> 1) & 4));
return fmix(mur(c, mur(b, mur(a, d))));
}
private static int hash32Len13to24(byte[] byteArray) {
int len = byteArray.length;
int a = fetch32(byteArray, (len >>> 1) - 4);
int b = fetch32(byteArray, 4);
int c = fetch32(byteArray, len - 8);
int d = fetch32(byteArray, (len >>> 1));
int e = fetch32(byteArray, 0);
int f = fetch32(byteArray, len - 4);
@SuppressWarnings("UnnecessaryLocalVariable")
int h = len;
return fmix(mur(f, mur(e, mur(d, mur(c, mur(b, mur(a, h)))))));
}
private static long hashLen0to16(byte[] byteArray) {
int len = byteArray.length;
if (len >= 8) {
long mul = k2 + len * 2L;
long a = fetch64(byteArray, 0) + k2;
long b = fetch64(byteArray, len - 8);
long c = rotate64(b, 37) * mul + a;
long d = (rotate64(a, 25) + b) * mul;
return hashLen16(c, d, mul);
}
if (len >= 4) {
long mul = k2 + len * 2;
long a = fetch32(byteArray, 0) & 0xffffffffL;
return hashLen16(len + (a << 3), fetch32(byteArray, len - 4) & 0xffffffffL, mul);
}
if (len > 0) {
int a = byteArray[0] & 0xff;
int b = byteArray[len >>> 1] & 0xff;
int c = byteArray[len - 1] & 0xff;
int y = a + (b << 8);
int z = len + (c << 2);
return shiftMix(y * k2 ^ z * k0) * k2;
}
return k2;
}
// This probably works well for 16-byte strings as well, but it may be overkill in that case.
private static long hashLen17to32(byte[] byteArray) {
int len = byteArray.length;
long mul = k2 + len * 2L;
long a = fetch64(byteArray, 0) * k1;
long b = fetch64(byteArray, 8);
long c = fetch64(byteArray, len - 8) * mul;
long d = fetch64(byteArray, len - 16) * k2;
return hashLen16(rotate64(a + b, 43) + rotate64(c, 30) + d,
a + rotate64(b + k2, 18) + c, mul);
}
private static long hashLen33to64(byte[] byteArray) {
int len = byteArray.length;
long mul = k2 + len * 2L;
long a = fetch64(byteArray, 0) * k2;
long b = fetch64(byteArray, 8);
long c = fetch64(byteArray, len - 24);
long d = fetch64(byteArray, len - 32);
long e = fetch64(byteArray, 16) * k2;
long f = fetch64(byteArray, 24) * 9;
long g = fetch64(byteArray, len - 8);
long h = fetch64(byteArray, len - 16) * mul;
long u = rotate64(a + g, 43) + (rotate64(b, 30) + c) * 9;
long v = ((a + g) ^ d) + f + 1;
long w = Long.reverseBytes((u + v) * mul) + h;
long x = rotate64(e + f, 42) + c;
long y = (Long.reverseBytes((v + w) * mul) + g) * mul;
long z = e + f + c;
a = Long.reverseBytes((x + z) * mul + y) + b;
b = shiftMix((z + a) * mul + d + h) * mul;
return b + x;
}
private static long fetch64(byte[] byteArray, int start) {
return ByteUtil.bytesToLong(byteArray, start, ByteUtil.CPU_ENDIAN);
}
private static int fetch32(byte[] byteArray, final int start) {
return ByteUtil.bytesToInt(byteArray, start, ByteUtil.CPU_ENDIAN);
}
private static long rotate64(long val, int shift) {
// Avoid shifting by 64: doing so yields an undefined result.
return shift == 0 ? val : ((val >>> shift) | (val << (64 - shift)));
}
private static int rotate32(int val, int shift) {
// Avoid shifting by 32: doing so yields an undefined result.
return shift == 0 ? val : ((val >>> shift) | (val << (32 - shift)));
}
private static long hashLen16(long u, long v, long mul) {
// Murmur-inspired hashing.
long a = (u ^ v) * mul;
a ^= (a >>> 47);
long b = (v ^ a) * mul;
b ^= (b >>> 47);
b *= mul;
return b;
}
private static long hashLen16(long u, long v) {
return hash128to64(new Number128(u, v));
}
private static long hash128to64(final Number128 number128) {
// Murmur-inspired hashing.
long a = (number128.getLowValue() ^ number128.getHighValue()) * kMul;
a ^= (a >>> 47);
long b = (number128.getHighValue() ^ a) * kMul;
b ^= (b >>> 47);
b *= kMul;
return b;
}
private static long shiftMix(long val) {
return val ^ (val >>> 47);
}
private static int fmix(int h) {
h ^= h >>> 16;
h *= 0x85ebca6b;
h ^= h >>> 13;
h *= 0xc2b2ae35;
h ^= h >>> 16;
return h;
}
private static int mur(int a, int h) {
// Helper from Murmur3 for combining two 32-bit values.
a *= c1;
a = rotate32(a, 17);
a *= c2;
h ^= a;
h = rotate32(h, 19);
return h * 5 + 0xe6546b64;
}
private static Number128 weakHashLen32WithSeeds(
long w, long x, long y, long z, long a, long b) {
a += w;
b = rotate64(b + a + z, 21);
long c = a;
a += x;
a += y;
b += rotate64(a, 44);
return new Number128(a + z, b + c);
}
// Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty.
private static Number128 weakHashLen32WithSeeds(
byte[] byteArray, int start, long a, long b) {
return weakHashLen32WithSeeds(fetch64(byteArray, start),
fetch64(byteArray, start + 8),
fetch64(byteArray, start + 16),
fetch64(byteArray, start + 24),
a,
b);
}
private static Number128 cityMurmur(final byte[] byteArray, Number128 seed) {
int len = byteArray.length;
long a = seed.getLowValue();
long b = seed.getHighValue();
long c;
long d;
int l = len - 16;
if (l <= 0) { // len <= 16
a = shiftMix(a * k1) * k1;
c = b * k1 + hashLen0to16(byteArray);
d = shiftMix(a + (len >= 8 ? fetch64(byteArray, 0) : c));
} else { // len > 16
c = hashLen16(fetch64(byteArray, len - 8) + k1, a);
d = hashLen16(b + len, c + fetch64(byteArray, len - 16));
a += d;
int pos = 0;
do {
a ^= shiftMix(fetch64(byteArray, pos) * k1) * k1;
a *= k1;
b ^= a;
c ^= shiftMix(fetch64(byteArray, pos + 8) * k1) * k1;
c *= k1;
d ^= c;
pos += 16;
l -= 16;
} while (l > 0);
}
a = hashLen16(a, c);
b = hashLen16(d, b);
return new Number128(a ^ b, hashLen16(b, a));
}
//------------------------------------------------------------------------------------------------------- Private method end
}
| // v, w, x, y, and z. | package cn.hutool.core.lang.hash;
import cn.hutool.core.util.ByteUtil;
import java.util.Arrays;
/**
* Google发布的Hash计算算法:CityHash64 与 CityHash128。<br>
* 它们分别根据字串计算 64 和 128 位的散列值。这些算法不适用于加密,但适合用在散列表等处。
*
* <p>
* 代码来自:https://github.com/rolandhe/string-tools<br>
* 原始算法:https://github.com/google/cityhash
*
* @author hexiufeng
* @since 5.2.5
*/
public class CityHash {
// Some primes between 2^63 and 2^64 for various uses.
private static final long k0 = 0xc3a5c85c97cb3127L;
private static final long k1 = 0xb492b66fbe98f273L;
private static final long k2 = 0x9ae16a3b2f90404fL;
private static final long kMul = 0x9ddfea08eb382d69L;
// Magic numbers for 32-bit hashing. Copied from Murmur3.
private static final int c1 = 0xcc9e2d51;
private static final int c2 = 0x1b873593;
/**
* 计算32位City Hash值
*
* @param data 数据
* @return hash值
*/
public static int hash32(byte[] data) {
int len = data.length;
if (len <= 24) {
return len <= 12 ?
(len <= 4 ? hash32Len0to4(data) : hash32Len5to12(data)) :
hash32Len13to24(data);
}
// len > 24
int h = len, g = c1 * len, f = g;
int a0 = rotate32(fetch32(data, len - 4) * c1, 17) * c2;
int a1 = rotate32(fetch32(data, len - 8) * c1, 17) * c2;
int a2 = rotate32(fetch32(data, len - 16) * c1, 17) * c2;
int a3 = rotate32(fetch32(data, len - 12) * c1, 17) * c2;
int a4 = rotate32(fetch32(data, len - 20) * c1, 17) * c2;
h ^= a0;
h = rotate32(h, 19);
h = h * 5 + 0xe6546b64;
h ^= a2;
h = rotate32(h, 19);
h = h * 5 + 0xe6546b64;
g ^= a1;
g = rotate32(g, 19);
g = g * 5 + 0xe6546b64;
g ^= a3;
g = rotate32(g, 19);
g = g * 5 + 0xe6546b64;
f += a4;
f = rotate32(f, 19);
f = f * 5 + 0xe6546b64;
int iters = (len - 1) / 20;
int pos = 0;
do {
a0 = rotate32(fetch32(data, pos) * c1, 17) * c2;
a1 = fetch32(data, pos + 4);
a2 = rotate32(fetch32(data, pos + 8) * c1, 17) * c2;
a3 = rotate32(fetch32(data, pos + 12) * c1, 17) * c2;
a4 = fetch32(data, pos + 16);
h ^= a0;
h = rotate32(h, 18);
h = h * 5 + 0xe6546b64;
f += a1;
f = rotate32(f, 19);
f = f * c1;
g += a2;
g = rotate32(g, 18);
g = g * 5 + 0xe6546b64;
h ^= a3 + a1;
h = rotate32(h, 19);
h = h * 5 + 0xe6546b64;
g ^= a4;
g = Integer.reverseBytes(g) * 5;
h += a4 * 5;
h = Integer.reverseBytes(h);
f += a0;
int swapValue = f;
f = g;
g = h;
h = swapValue;
pos += 20;
} while (--iters != 0);
g = rotate32(g, 11) * c1;
g = rotate32(g, 17) * c1;
f = rotate32(f, 11) * c1;
f = rotate32(f, 17) * c1;
h = rotate32(h + g, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * c1;
h = rotate32(h + f, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * c1;
return h;
}
/**
* 计算64位City Hash值
*
* @param data 数据
* @return hash值
*/
public static long hash64(byte[] data) {
int len = data.length;
if (len <= 32) {
if (len <= 16) {
return hashLen0to16(data);
} else {
return hashLen17to32(data);
}
} else if (len <= 64) {
return hashLen33to64(data);
}
// For strings over 64 bytes we hash the end first, and then as we
// loop we keep 56 bytes of state: v, w, x, y, and z.
long x = fetch64(data, len - 40);
long y = fetch64(data, len - 16) + fetch64(data, len - 56);
long z = hashLen16(fetch64(data, len - 48) + len, fetch64(data, len - 24));
Number128 v = weakHashLen32WithSeeds(data, len - 64, len, z);
Number128 w = weakHashLen32WithSeeds(data, len - 32, y + k1, x);
x = x * k1 + fetch64(data, 0);
// Decrease len to the nearest multiple of 64, and operate on 64-byte chunks.
len = (len - 1) & ~63;
int pos = 0;
do {
x = rotate64(x + y + v.getLowValue() + fetch64(data, pos + 8), 37) * k1;
y = rotate64(y + v.getHighValue() + fetch64(data, pos + 48), 42) * k1;
x ^= w.getHighValue();
y += v.getLowValue() + fetch64(data, pos + 40);
z = rotate64(z + w.getLowValue(), 33) * k1;
v = weakHashLen32WithSeeds(data, pos, v.getHighValue() * k1, x + w.getLowValue());
w = weakHashLen32WithSeeds(data, pos + 32, z + w.getHighValue(), y + fetch64(data, pos + 16));
// swap z,x value
long swapValue = x;
x = z;
z = swapValue;
pos += 64;
len -= 64;
} while (len != 0);
return hashLen16(hashLen16(v.getLowValue(), w.getLowValue()) + shiftMix(y) * k1 + z,
hashLen16(v.getHighValue(), w.getHighValue()) + x);
}
/**
* 计算64位City Hash值
*
* @param data 数据
* @param seed0 种子1
* @param seed1 种子2
* @return hash值
*/
public static long hash64(byte[] data, long seed0, long seed1) {
return hashLen16(hash64(data) - seed0, seed1);
}
/**
* 计算64位City Hash值,种子1使用默认的{@link #k2}
*
* @param data 数据
* @param seed 种子2
* @return hash值
*/
public static long hash64(byte[] data, long seed) {
return hash64(data, k2, seed);
}
/**
* 计算128位City Hash值
*
* @param data 数据
* @return hash值
*/
public static Number128 hash128(byte[] data) {
int len = data.length;
return len >= 16 ?
hash128(data, 16,
new Number128(fetch64(data, 0), fetch64(data, 8) + k0)) :
hash128(data, 0, new Number128(k0, k1));
}
/**
* 计算128位City Hash值
*
* @param data 数据
* @param seed 种子
* @return hash值
*/
public static Number128 hash128(byte[] data, Number128 seed) {
return hash128(data, 0, seed);
}
//------------------------------------------------------------------------------------------------------- Private method start
private static Number128 hash128(final byte[] byteArray, int start, final Number128 seed) {
int len = byteArray.length - start;
if (len < 128) {
return cityMurmur(Arrays.copyOfRange(byteArray, start, byteArray.length), seed);
}
// We expect len >= 128 to be the common case. Keep 56 bytes of state:
// v, w, <SUF>
Number128 v = new Number128(0L, 0L);
Number128 w = new Number128(0L, 0L);
long x = seed.getLowValue();
long y = seed.getHighValue();
long z = len * k1;
v.setLowValue(rotate64(y ^ k1, 49) * k1 + fetch64(byteArray, start));
v.setHighValue(rotate64(v.getLowValue(), 42) * k1 + fetch64(byteArray, start + 8));
w.setLowValue(rotate64(y + z, 35) * k1 + x);
w.setHighValue(rotate64(x + fetch64(byteArray, start + 88), 53) * k1);
// This is the same inner loop as CityHash64(), manually unrolled.
int pos = start;
do {
x = rotate64(x + y + v.getLowValue() + fetch64(byteArray, pos + 8), 37) * k1;
y = rotate64(y + v.getHighValue() + fetch64(byteArray, pos + 48), 42) * k1;
x ^= w.getHighValue();
y += v.getLowValue() + fetch64(byteArray, pos + 40);
z = rotate64(z + w.getLowValue(), 33) * k1;
v = weakHashLen32WithSeeds(byteArray, pos, v.getHighValue() * k1, x + w.getLowValue());
w = weakHashLen32WithSeeds(byteArray, pos + 32, z + w.getHighValue(), y + fetch64(byteArray, pos + 16));
long swapValue = x;
x = z;
z = swapValue;
pos += 64;
x = rotate64(x + y + v.getLowValue() + fetch64(byteArray, pos + 8), 37) * k1;
y = rotate64(y + v.getHighValue() + fetch64(byteArray, pos + 48), 42) * k1;
x ^= w.getHighValue();
y += v.getLowValue() + fetch64(byteArray, pos + 40);
z = rotate64(z + w.getLowValue(), 33) * k1;
v = weakHashLen32WithSeeds(byteArray, pos, v.getHighValue() * k1, x + w.getLowValue());
w = weakHashLen32WithSeeds(byteArray, pos + 32, z + w.getHighValue(), y + fetch64(byteArray, pos + 16));
swapValue = x;
x = z;
z = swapValue;
pos += 64;
len -= 128;
} while (len >= 128);
x += rotate64(v.getLowValue() + z, 49) * k0;
y = y * k0 + rotate64(w.getHighValue(), 37);
z = z * k0 + rotate64(w.getLowValue(), 27);
w.setLowValue(w.getLowValue() * 9);
v.setLowValue(v.getLowValue() * k0);
// If 0 < len < 128, hash up to 4 chunks of 32 bytes each from the end of s.
for (int tail_done = 0; tail_done < len; ) {
tail_done += 32;
y = rotate64(x + y, 42) * k0 + v.getHighValue();
w.setLowValue(w.getLowValue() + fetch64(byteArray, pos + len - tail_done + 16));
x = x * k0 + w.getLowValue();
z += w.getHighValue() + fetch64(byteArray, pos + len - tail_done);
w.setHighValue(w.getHighValue() + v.getLowValue());
v = weakHashLen32WithSeeds(byteArray, pos + len - tail_done, v.getLowValue() + z, v.getHighValue());
v.setLowValue(v.getLowValue() * k0);
}
// At this point our 56 bytes of state should contain more than
// enough information for a strong 128-bit hash. We use two
// different 56-byte-to-8-byte hashes to get a 16-byte final result.
x = hashLen16(x, v.getLowValue());
y = hashLen16(y + z, w.getLowValue());
return new Number128(hashLen16(x + v.getHighValue(), w.getHighValue()) + y,
hashLen16(x + w.getHighValue(), y + v.getHighValue()));
}
private static int hash32Len0to4(final byte[] byteArray) {
int b = 0;
int c = 9;
int len = byteArray.length;
for (int v : byteArray) {
b = b * c1 + v;
c ^= b;
}
return fmix(mur(b, mur(len, c)));
}
private static int hash32Len5to12(final byte[] byteArray) {
int len = byteArray.length;
int a = len, b = len * 5, c = 9, d = b;
a += fetch32(byteArray, 0);
b += fetch32(byteArray, len - 4);
c += fetch32(byteArray, ((len >>> 1) & 4));
return fmix(mur(c, mur(b, mur(a, d))));
}
private static int hash32Len13to24(byte[] byteArray) {
int len = byteArray.length;
int a = fetch32(byteArray, (len >>> 1) - 4);
int b = fetch32(byteArray, 4);
int c = fetch32(byteArray, len - 8);
int d = fetch32(byteArray, (len >>> 1));
int e = fetch32(byteArray, 0);
int f = fetch32(byteArray, len - 4);
@SuppressWarnings("UnnecessaryLocalVariable")
int h = len;
return fmix(mur(f, mur(e, mur(d, mur(c, mur(b, mur(a, h)))))));
}
private static long hashLen0to16(byte[] byteArray) {
int len = byteArray.length;
if (len >= 8) {
long mul = k2 + len * 2L;
long a = fetch64(byteArray, 0) + k2;
long b = fetch64(byteArray, len - 8);
long c = rotate64(b, 37) * mul + a;
long d = (rotate64(a, 25) + b) * mul;
return hashLen16(c, d, mul);
}
if (len >= 4) {
long mul = k2 + len * 2;
long a = fetch32(byteArray, 0) & 0xffffffffL;
return hashLen16(len + (a << 3), fetch32(byteArray, len - 4) & 0xffffffffL, mul);
}
if (len > 0) {
int a = byteArray[0] & 0xff;
int b = byteArray[len >>> 1] & 0xff;
int c = byteArray[len - 1] & 0xff;
int y = a + (b << 8);
int z = len + (c << 2);
return shiftMix(y * k2 ^ z * k0) * k2;
}
return k2;
}
// This probably works well for 16-byte strings as well, but it may be overkill in that case.
private static long hashLen17to32(byte[] byteArray) {
int len = byteArray.length;
long mul = k2 + len * 2L;
long a = fetch64(byteArray, 0) * k1;
long b = fetch64(byteArray, 8);
long c = fetch64(byteArray, len - 8) * mul;
long d = fetch64(byteArray, len - 16) * k2;
return hashLen16(rotate64(a + b, 43) + rotate64(c, 30) + d,
a + rotate64(b + k2, 18) + c, mul);
}
private static long hashLen33to64(byte[] byteArray) {
int len = byteArray.length;
long mul = k2 + len * 2L;
long a = fetch64(byteArray, 0) * k2;
long b = fetch64(byteArray, 8);
long c = fetch64(byteArray, len - 24);
long d = fetch64(byteArray, len - 32);
long e = fetch64(byteArray, 16) * k2;
long f = fetch64(byteArray, 24) * 9;
long g = fetch64(byteArray, len - 8);
long h = fetch64(byteArray, len - 16) * mul;
long u = rotate64(a + g, 43) + (rotate64(b, 30) + c) * 9;
long v = ((a + g) ^ d) + f + 1;
long w = Long.reverseBytes((u + v) * mul) + h;
long x = rotate64(e + f, 42) + c;
long y = (Long.reverseBytes((v + w) * mul) + g) * mul;
long z = e + f + c;
a = Long.reverseBytes((x + z) * mul + y) + b;
b = shiftMix((z + a) * mul + d + h) * mul;
return b + x;
}
private static long fetch64(byte[] byteArray, int start) {
return ByteUtil.bytesToLong(byteArray, start, ByteUtil.CPU_ENDIAN);
}
private static int fetch32(byte[] byteArray, final int start) {
return ByteUtil.bytesToInt(byteArray, start, ByteUtil.CPU_ENDIAN);
}
private static long rotate64(long val, int shift) {
// Avoid shifting by 64: doing so yields an undefined result.
return shift == 0 ? val : ((val >>> shift) | (val << (64 - shift)));
}
private static int rotate32(int val, int shift) {
// Avoid shifting by 32: doing so yields an undefined result.
return shift == 0 ? val : ((val >>> shift) | (val << (32 - shift)));
}
private static long hashLen16(long u, long v, long mul) {
// Murmur-inspired hashing.
long a = (u ^ v) * mul;
a ^= (a >>> 47);
long b = (v ^ a) * mul;
b ^= (b >>> 47);
b *= mul;
return b;
}
private static long hashLen16(long u, long v) {
return hash128to64(new Number128(u, v));
}
private static long hash128to64(final Number128 number128) {
// Murmur-inspired hashing.
long a = (number128.getLowValue() ^ number128.getHighValue()) * kMul;
a ^= (a >>> 47);
long b = (number128.getHighValue() ^ a) * kMul;
b ^= (b >>> 47);
b *= kMul;
return b;
}
private static long shiftMix(long val) {
return val ^ (val >>> 47);
}
private static int fmix(int h) {
h ^= h >>> 16;
h *= 0x85ebca6b;
h ^= h >>> 13;
h *= 0xc2b2ae35;
h ^= h >>> 16;
return h;
}
private static int mur(int a, int h) {
// Helper from Murmur3 for combining two 32-bit values.
a *= c1;
a = rotate32(a, 17);
a *= c2;
h ^= a;
h = rotate32(h, 19);
return h * 5 + 0xe6546b64;
}
private static Number128 weakHashLen32WithSeeds(
long w, long x, long y, long z, long a, long b) {
a += w;
b = rotate64(b + a + z, 21);
long c = a;
a += x;
a += y;
b += rotate64(a, 44);
return new Number128(a + z, b + c);
}
// Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty.
private static Number128 weakHashLen32WithSeeds(
byte[] byteArray, int start, long a, long b) {
return weakHashLen32WithSeeds(fetch64(byteArray, start),
fetch64(byteArray, start + 8),
fetch64(byteArray, start + 16),
fetch64(byteArray, start + 24),
a,
b);
}
private static Number128 cityMurmur(final byte[] byteArray, Number128 seed) {
int len = byteArray.length;
long a = seed.getLowValue();
long b = seed.getHighValue();
long c;
long d;
int l = len - 16;
if (l <= 0) { // len <= 16
a = shiftMix(a * k1) * k1;
c = b * k1 + hashLen0to16(byteArray);
d = shiftMix(a + (len >= 8 ? fetch64(byteArray, 0) : c));
} else { // len > 16
c = hashLen16(fetch64(byteArray, len - 8) + k1, a);
d = hashLen16(b + len, c + fetch64(byteArray, len - 16));
a += d;
int pos = 0;
do {
a ^= shiftMix(fetch64(byteArray, pos) * k1) * k1;
a *= k1;
b ^= a;
c ^= shiftMix(fetch64(byteArray, pos + 8) * k1) * k1;
c *= k1;
d ^= c;
pos += 16;
l -= 16;
} while (l > 0);
}
a = hashLen16(a, c);
b = hashLen16(d, b);
return new Number128(a ^ b, hashLen16(b, a));
}
//------------------------------------------------------------------------------------------------------- Private method end
}
| f |
9639_34 | eclab/edisyn | 7,935 | edisyn/gui/LabelledDial.java | /***
Copyright 2017 by Sean Luke
Licensed under the Apache License version 2.0
*/
package edisyn.gui;
import edisyn.*;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.accessibility.*;
/**
A labelled dial which the user can modify with the mouse.
The dial updates the model and changes in response to it.
For an unlabelled dial, see Dial.
You can add a second label (or in fact, though it's not obvious,
additional labels!)
@author Sean Luke
*/
public class LabelledDial extends NumericalComponent
{
ArrayList<String> labels = new ArrayList();
Dial dial;
JLabel label;
Box labelBox;
Component glue;
boolean updatesDynamically = true;
boolean updatingDynamically = false;
public void repaintDial() { dial.repaint(); }
public void setEnabled(boolean val)
{
dial.setEnabled(val);
label.setEnabled(val);
}
public Insets getInsets() { return Style.LABELLED_DIAL_INSETS(); }
public void update(String key, Model model)
{
if (dial.isVisible()) dial.repaint();
}
public LabelledDial setLabel(String text)
{
if (labels.size() == 0)
{
labels.add(text);
}
else
{
labels.set(0, text);
}
dial.updateAccessibleName();
label.setText(text);
label.revalidate();
if (label.isVisible()) label.repaint();
return this;
}
public JLabel getJLabel()
{
return label;
}
public Color getTextColor() { return dial.field.getForeground(); }
public void setTextColor(Color color) { dial.field.setForeground(color); if (dial.isVisible()) dial.repaint(); }
public boolean getUpdatesDyamically() { return updatesDynamically; }
public void setUpdatesDynamically(boolean val) { updatesDynamically = val; }
public boolean isUpdatingDynamically() { return updatingDynamically; }
public String map(int val) { return "" + (val - dial.subtractForDisplay); }
public boolean isSymmetric() { return dial.getCanonicalSymmetric(); }
public double getStartAngle() { return dial.getCanonicalStartAngle(); }
/** Adds a second (or third or fourth or more!) label to the dial, to allow
for multiline labels. */
public JLabel addAdditionalLabel(String _label)
{
if (labels.size() == 0)
{
labels.add("");
}
labels.add(_label);
dial.updateAccessibleName();
JLabel label2 = new JLabel(_label);
label2.setFont(Style.SMALL_FONT());
label2.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
label2.setForeground(Style.TEXT_COLOR());
Box box = new Box(BoxLayout.X_AXIS);
box.add(Box.createGlue());
box.add(label2);
box.add(Box.createGlue());
labelBox.remove(glue);
labelBox.add(box);
labelBox.add(glue = Box.createGlue());
revalidate();
if (isVisible()) repaint();
return label2;
}
public void setLabelFont(Font font)
{
dial.field.setFont(font);
dial.revalidate();
if (dial.isVisible()) dial.repaint();
}
public Font getLabelFont()
{
return dial.field.getFont();
}
/** Makes a labelled dial for the given key parameter on the given synth, and with the given color and
minimum and maximum. Prior to display, subtractForDisplay is
SUBTRACTED from the parameter value. You can use this to convert 0...127 in the model
to -64...63 on-screen, for example. */
public LabelledDial(String _label, Synth synth, String key, Color staticColor, int min, int max, int subtractForDisplay)
{
this(_label, synth, key, staticColor, min, max);
dial.subtractForDisplay = subtractForDisplay;
update(key, synth.getModel());
if (isVisible()) repaint();
}
/** Makes a labelled dial for the given key parameter on the given synth, and with the given color and
minimum and maximum. */
public LabelledDial(String _label, Synth synth, String key, Color staticColor, int min, int max)
{
this(_label, synth, key, staticColor);
if (min > max)
System.err.println("Warning (LabelledDial): min (" + min + ") is > max (" + max + ") for " + key);
setMin(min);
setMax(max);
synth.getModel().setMetricMin(key, min);
synth.getModel().setMetricMax(key, max);
setState(getState());
}
/** Makes a labelled dial for the given key parameter on the given synth, and with the given color. No minimum or maximum is set. */
LabelledDial(String _label, Synth synth, String key, Color staticColor)
{
super(synth, key);
setBackground(Style.BACKGROUND_COLOR());
dial = new Dial(staticColor);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Style.BACKGROUND_COLOR());
panel.add(dial, BorderLayout.CENTER);
label = new JLabel(_label);
if (_label != null)
{
labels.add(_label);
label.setFont(Style.SMALL_FONT());
label.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
label.setForeground(Style.TEXT_COLOR());
labelBox = new Box(BoxLayout.Y_AXIS);
Box box = new Box(BoxLayout.X_AXIS);
box.add(Box.createGlue());
box.add(label);
box.add(Box.createGlue());
labelBox.add(box);
labelBox.add(glue = Box.createGlue());
panel.add(labelBox, BorderLayout.SOUTH);
}
dial.updateAccessibleName();
setLayout(new BorderLayout());
add(panel, BorderLayout.NORTH);
}
public int reviseToAltValue(int val) { return val; }
public int getDefaultValue()
{
if (isSymmetric())
{
return (int)Math.ceil((getMin() + getMax()) / 2.0); // we do ceiling so we push to 64 on 0...127
}
else return getMin();
}
/** A useful utility function which returns the element in the sorted
(low to high) array A which is closest to VALUE. You could use this
to search arrays for alt values for rounding for example. */
public static int findClosestValue(int value, int[] a)
{
if (value < a[0]) { return a[0]; }
if (value > a[a.length-1]) { return a[a.length-1]; }
int lo = 0;
int hi = a.length - 1;
while (lo <= hi)
{
// this could obviously overflow if hi and lo are really big
int mid = (hi + lo) / 2;
if (value < a[mid])
hi = mid - 1;
else if (value > a[mid])
lo = mid + 1;
else
return a[mid];
}
return (a[lo] - value) < (value - a[hi]) ? a[lo] : a[hi];
}
// a hook for ASMHydrasynth
public int updateProposedState(int proposedState)
{
return proposedState;
}
class Dial extends JPanel
{
// What's going on? Is the user changing the dial?
public static final int STATUS_STATIC = 0;
public static final int STATUS_DIAL_DYNAMIC = 1;
int status = STATUS_STATIC;
Color staticColor;
// The largest vertical range that a dial ought to go.
public static final int MAX_EXTENT = 256;
// The typical vertical range that the dial goes. 128 is reasonable
public static final int MIN_EXTENT = 128;
// The state when the mouse was pressed
int startState;
// The mouse position when the mouse was pressed
int startX;
int startY;
// Is the mouse pressed? This is part of a mechanism for dealing with
// a stupidity in Java: if you PRESS in a widget, it'll be told. But if
// you then drag elsewhere and RELEASE, the widget is never told.
boolean mouseDown;
// how much should be subtracted from the value in the model before
// it is displayed onscreen?
int subtractForDisplay = 0;
// Field in the center of the dial
JLabel field = new JLabel("88888", SwingConstants.CENTER);
public Dimension getPreferredSize() { return new Dimension(Style.LABELLED_DIAL_WIDTH(), Style.LABELLED_DIAL_WIDTH()); }
public Dimension getMinimumSize() { return new Dimension(Style.LABELLED_DIAL_WIDTH(), Style.LABELLED_DIAL_WIDTH()); }
boolean enabled = true;
public void setEnabled(boolean val)
{
enabled = val;
field.setEnabled(val);
if (isVisible()) repaint();
}
void mouseReleased(MouseEvent e)
{
if (!enabled) return;
if (mouseDown)
{
status = STATUS_STATIC;
if (isVisible()) repaint();
mouseDown = false;
if (releaseListener != null)
Toolkit.getDefaultToolkit().removeAWTEventListener(releaseListener);
}
}
public int getProposedState(MouseEvent e)
{
int y = -(e.getY() - startY);
int min = getMin();
int max = getMax();
int range = (max - min + 1 );
double multiplicand = 1;
double extent = range;
if (extent < MIN_EXTENT) extent = MIN_EXTENT;
if (extent > MAX_EXTENT) extent = MAX_EXTENT;
multiplicand = extent / (double) range;
int proposedState = startState + (int)(y / multiplicand);
if (((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) &&
(((e.getModifiers() & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) ||
((e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK)))
{
proposedState = startState + (int)(y / multiplicand / 64);
}
else if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK)
{
proposedState = startState + (int)(y / multiplicand / 16);
}
else if (((e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK))
{
proposedState = startState + (int)(y / multiplicand / 4);
}
else if (((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) ||
((e.getModifiers() & InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK))
{
proposedState = reviseToAltValue(proposedState);
}
if (proposedState < min)
proposedState = min;
else if (proposedState > max)
proposedState = max;
return updateProposedState(proposedState);
}
public Dial(Color staticColor)
{
setFocusable(true);
setRequestFocusEnabled(false);
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
int state = getState();
int max = getMax();
int min = getMin();
int modifiers = e.getModifiersEx();
boolean shift = (modifiers & KeyEvent.SHIFT_DOWN_MASK) == KeyEvent.SHIFT_DOWN_MASK;
// boolean ctrl = (modifiers & KeyEvent.CTRL_DOWN_MASK) == KeyEvent.CTRL_DOWN_MASK;
// Can't use alt, MacOS uses it already for moving around
// boolean alt = (modifiers & KeyEvent.ALT_DOWN_MASK) == KeyEvent.ALT_DOWN_MASK;
int multiplier = 1;
if (shift) multiplier *= 16;
// if (ctrl) multiplier *= 256;
// if (alt) multiplier *= 256;
if (e.getKeyCode() == KeyEvent.VK_UP)
{
state += multiplier;
if (state > max) state = max;
setState(state);
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
state -= multiplier;
if (state < min) state = min;
setState(state);
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
state += multiplier * 256;
if (state > max) state = max;
setState(state);
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
state -= multiplier * 256;
if (state < min) state = min;
setState(state);
}
else if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
setState(getDefaultValue());
}
else if (e.getKeyCode() == KeyEvent.VK_HOME)
{
setState(getMin());
}
else if (e.getKeyCode() == KeyEvent.VK_END)
{
setState(getMax());
}
}
});
this.staticColor = staticColor;
field.setFont(Style.DIAL_FONT());
field.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
field.setForeground(Style.TEXT_COLOR());
addMouseWheelListener(new MouseWheelListener()
{
public void mouseWheelMoved(MouseWheelEvent e)
{
if (!enabled) return;
int val = getState() - e.getWheelRotation();
if (val > getMax()) val = getMax();
if (val < getMin()) val = getMin();
setState(val);
}
});
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
if (!enabled) return;
mouseDown = true;
startX = e.getX();
startY = e.getY();
startState = getState();
status = STATUS_DIAL_DYNAMIC;
if (isVisible()) repaint();
if (releaseListener != null)
Toolkit.getDefaultToolkit().removeAWTEventListener(releaseListener);
// This gunk fixes a BAD MISFEATURE in Java: mouseReleased isn't sent to the
// same component that received mouseClicked. What the ... ? Asinine.
// So we create a global event listener which checks for mouseReleased and
// calls our own private function. EVERYONE is going to do this.
Toolkit.getDefaultToolkit().addAWTEventListener( releaseListener = new AWTEventListener()
{
public void eventDispatched(AWTEvent e)
{
if (e instanceof MouseEvent && e.getID() == MouseEvent.MOUSE_RELEASED)
{
mouseReleased((MouseEvent)e);
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
}
MouseEvent lastRelease;
public void mouseReleased(MouseEvent e)
{
if (!enabled) return;
if (e == lastRelease) // we just had this event because we're in the AWT Event Listener. So we ignore it
return;
if (!updatesDynamically)
{
int proposedState = getProposedState(e);
// at present we're just going to use y. It's confusing to use either y or x.
if (startState != proposedState)
{
setState(proposedState);
}
}
status = STATUS_STATIC;
if (isVisible()) repaint();
if (releaseListener != null)
Toolkit.getDefaultToolkit().removeAWTEventListener(releaseListener);
lastRelease = e;
}
public void mouseClicked(MouseEvent e)
{
if (synth.isShowingMutation())
{
synth.mutationMap.setFree(key, !synth.mutationMap.isFree(key));
if (LabelledDial.this.isVisible()) LabelledDial.this.repaint();
}
else if (e.getClickCount() == 2)
{
setState(getDefaultValue());
}
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
if (!enabled) return;
int proposedState = getProposedState(e);
// at present we're just going to use y. It's confusing to use either y or x.
if (getState() != proposedState)
{
if (!updatesDynamically)
synth.setSendMIDI(false);
updatingDynamically = true;
setState(proposedState);
updatingDynamically = false;
if (!updatesDynamically)
synth.setSendMIDI(true);
}
}
});
setLayout(new BorderLayout());
add(field, BorderLayout.CENTER);
if (isVisible()) repaint();
}
AWTEventListener releaseListener = null;
/** Returns the actual square within which the Dial's circle
is drawn. */
public Rectangle getDrawSquare()
{
Insets insets = getInsets();
Dimension size = getSize();
int width = size.width - insets.left - insets.right;
int height = size.height - insets.top - insets.bottom;
// How big do we draw our circle?
if (width > height)
{
// base it on height
int h = height;
int w = h;
int y = insets.top;
int x = insets.left + (width - w) / 2;
return new Rectangle(x, y, w, h);
}
else
{
// base it on width
int w = width;
int h = w;
int x = insets.left;
int y = insets.top + (height - h) / 2;
return new Rectangle(x, y, w, h);
}
}
public boolean getCanonicalSymmetric()
{
return subtractForDisplay == 64 || subtractForDisplay == 50 ||
getMax() == (0 - getMin()) ||
(getMax() == 127 && getMin() == -128) || (getMax() == 63 && getMin() == -64);
}
public double getCanonicalStartAngle()
{
if (isSymmetric())
{
return 90 + (270 / 2);
}
else
{
return 270;
}
}
public void paintComponent(Graphics g)
{
// revise label if needed
String val = (Style.showRaw ? ("" + getState()) : map(getState()));
if (!(val.equals(dial.field.getText())))
dial.field.setText(val);
super.paintComponent(g);
int min = getMin();
int max = getMax();
Graphics2D graphics = (Graphics2D) g;
RenderingHints oldHints = graphics.getRenderingHints();
Style.prepareGraphics(graphics);
Rectangle rect = getBounds();
rect.x = 0;
rect.y = 0;
graphics.setPaint(Style.BACKGROUND_COLOR());
graphics.fill(rect);
rect = getDrawSquare();
graphics.setPaint(Style.DIAL_UNSET_COLOR());
graphics.setStroke(Style.DIAL_THIN_STROKE());
Arc2D.Double arc = new Arc2D.Double();
double startAngle = getStartAngle();
double interval = -270;
arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), startAngle, interval, Arc2D.OPEN);
graphics.draw(arc);
if (!enabled)
{
graphics.setRenderingHints(oldHints);
return;
}
graphics.setStroke(Style.DIAL_THICK_STROKE());
arc = new Arc2D.Double();
int state = getState();
interval = -((state - min) / (double)(max - min) * 265) - 5;
if (status == STATUS_DIAL_DYNAMIC)
{
graphics.setPaint(Style.DIAL_DYNAMIC_COLOR());
if (state == min)
{
interval = 0;
// This is NO LONGER TRUE:
// interval = -5;
// If we're basically at zero, we still want to show a little bit while the user is scrolling so
// he gets some feedback.
//arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), 270, -5, Arc2D.OPEN);
}
else
{
//arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), 270, -((state - min) / (double)(max - min) * 265) - 5, Arc2D.OPEN);
}
}
else
{
graphics.setPaint(staticColor);
if (state == min)
{
interval = 0;
// do nothing. Here we'll literally draw a zero
}
else
{
//arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), 270, -((state - min) / (double)(max - min) * 265) - 5, Arc2D.OPEN);
}
}
arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), startAngle, interval, Arc2D.OPEN);
graphics.draw(arc);
graphics.setRenderingHints(oldHints);
}
//// ACCESSIBILITY FOR THE BLIND
//// LabelledDial is a custom widget and must provide its own accessibility features.
//// Fortunately Java has good accessibility capabilities. Unfortunately they're a little
//// broken in that they rely on the assumption that you're using standard Swing widgets.
// We need a function which updates the name of our widget. It appears that accessible
// tools for the blind will announce the widget as "NAME ROLE" (as in "Envelope Attack Slider").
// Unfortunately we do not have an easy way to encorporate the enclosing Category into the name
// at this point. We'll add that later below.
void updateAccessibleName()
{
String str = "";
for(String l : labels)
str += (l + " ");
dial.getAccessibleContext().setAccessibleName(str);
}
// This is the top-level accessible context for the Dial. It gives accessibility information.
class AccessibleDial extends AccessibleJComponent implements AccessibleValue, AccessibleComponent
{
// Here we try to tack the Category onto the END of the accessible name so
// the user can skip it if he knows what it is.
public String getAccessibleName()
{
String name = super.getAccessibleName();
// Find enclosing Category
Component obj = LabelledDial.this;
while(obj != null)
{
if (obj instanceof Category)
{
return name + " " + ((Category)obj).getName() + ", " + map(getState());
}
else obj = obj.getParent();
}
return name + ", " + map(getState());
}
// Provide myself as the AccessibleValue (I implement that interface) so I don't
// need to have a separate object
public AccessibleValue getAccessibleValue()
{
return this;
}
// We must define a ROLE that our widget fulfills. We can't be a JPanel because
// that causes the system to freak. Notionally you're supposed to be
// be able to can provide custom roles, but in reality, if you do so, Java accessibility
// will simply break for your widget. So here we're borrowing the role from the closest
// widget to our own: a JSlider.
public AccessibleRole getAccessibleRole()
{
return ROLE; //ccessibleRole.SLIDER; // AccessibleRole.SLIDER;
}
// Add whether the user is frobbing me to my current state
public AccessibleStateSet getAccessibleStateSet()
{
AccessibleStateSet states = super.getAccessibleStateSet();
/*
if (dial.mouseDown)
{
states.add(AccessibleState.BUSY);
}
*/
return states;
}
// My current numerical value
public Number getCurrentAccessibleValue()
{
return Integer.valueOf(getState());
};
// You can't set my value
public boolean setCurrentAccessibleValue(Number n)
{
return false;
};
// My minimum numerical value
public Number getMinimumAccessibleValue()
{
return Integer.valueOf(getMin());
};
// My maximum numerical value
public Number getMaximumAccessibleValue()
{
return Integer.valueOf(getMax());
};
}
AccessibleContext accessibleContext = null;
// Generate and provide the context information when asked
public AccessibleContext getAccessibleContext()
{
if (accessibleContext == null)
{
accessibleContext = new AccessibleDial();
}
return accessibleContext;
}
protected void stateSet(int oldVal, int newVal)
{
AccessibleContext context = getAccessibleContext();
if (context != null)
{
context.firePropertyChange(AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, Integer.valueOf(oldVal), Integer.valueOf(newVal));
context.firePropertyChange(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, "yo", "mama");
}
}
/// END ACCESSSIBILITY FOR THE BLIND
}
public static class DialRole extends AccessibleRole
{
public DialRole(String key)
{
super(key);
}
}
public static final DialRole ROLE = new DialRole("dial");
}
| // How big do we draw our circle? | /***
Copyright 2017 by Sean Luke
Licensed under the Apache License version 2.0
*/
package edisyn.gui;
import edisyn.*;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.accessibility.*;
/**
A labelled dial which the user can modify with the mouse.
The dial updates the model and changes in response to it.
For an unlabelled dial, see Dial.
You can add a second label (or in fact, though it's not obvious,
additional labels!)
@author Sean Luke
*/
public class LabelledDial extends NumericalComponent
{
ArrayList<String> labels = new ArrayList();
Dial dial;
JLabel label;
Box labelBox;
Component glue;
boolean updatesDynamically = true;
boolean updatingDynamically = false;
public void repaintDial() { dial.repaint(); }
public void setEnabled(boolean val)
{
dial.setEnabled(val);
label.setEnabled(val);
}
public Insets getInsets() { return Style.LABELLED_DIAL_INSETS(); }
public void update(String key, Model model)
{
if (dial.isVisible()) dial.repaint();
}
public LabelledDial setLabel(String text)
{
if (labels.size() == 0)
{
labels.add(text);
}
else
{
labels.set(0, text);
}
dial.updateAccessibleName();
label.setText(text);
label.revalidate();
if (label.isVisible()) label.repaint();
return this;
}
public JLabel getJLabel()
{
return label;
}
public Color getTextColor() { return dial.field.getForeground(); }
public void setTextColor(Color color) { dial.field.setForeground(color); if (dial.isVisible()) dial.repaint(); }
public boolean getUpdatesDyamically() { return updatesDynamically; }
public void setUpdatesDynamically(boolean val) { updatesDynamically = val; }
public boolean isUpdatingDynamically() { return updatingDynamically; }
public String map(int val) { return "" + (val - dial.subtractForDisplay); }
public boolean isSymmetric() { return dial.getCanonicalSymmetric(); }
public double getStartAngle() { return dial.getCanonicalStartAngle(); }
/** Adds a second (or third or fourth or more!) label to the dial, to allow
for multiline labels. */
public JLabel addAdditionalLabel(String _label)
{
if (labels.size() == 0)
{
labels.add("");
}
labels.add(_label);
dial.updateAccessibleName();
JLabel label2 = new JLabel(_label);
label2.setFont(Style.SMALL_FONT());
label2.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
label2.setForeground(Style.TEXT_COLOR());
Box box = new Box(BoxLayout.X_AXIS);
box.add(Box.createGlue());
box.add(label2);
box.add(Box.createGlue());
labelBox.remove(glue);
labelBox.add(box);
labelBox.add(glue = Box.createGlue());
revalidate();
if (isVisible()) repaint();
return label2;
}
public void setLabelFont(Font font)
{
dial.field.setFont(font);
dial.revalidate();
if (dial.isVisible()) dial.repaint();
}
public Font getLabelFont()
{
return dial.field.getFont();
}
/** Makes a labelled dial for the given key parameter on the given synth, and with the given color and
minimum and maximum. Prior to display, subtractForDisplay is
SUBTRACTED from the parameter value. You can use this to convert 0...127 in the model
to -64...63 on-screen, for example. */
public LabelledDial(String _label, Synth synth, String key, Color staticColor, int min, int max, int subtractForDisplay)
{
this(_label, synth, key, staticColor, min, max);
dial.subtractForDisplay = subtractForDisplay;
update(key, synth.getModel());
if (isVisible()) repaint();
}
/** Makes a labelled dial for the given key parameter on the given synth, and with the given color and
minimum and maximum. */
public LabelledDial(String _label, Synth synth, String key, Color staticColor, int min, int max)
{
this(_label, synth, key, staticColor);
if (min > max)
System.err.println("Warning (LabelledDial): min (" + min + ") is > max (" + max + ") for " + key);
setMin(min);
setMax(max);
synth.getModel().setMetricMin(key, min);
synth.getModel().setMetricMax(key, max);
setState(getState());
}
/** Makes a labelled dial for the given key parameter on the given synth, and with the given color. No minimum or maximum is set. */
LabelledDial(String _label, Synth synth, String key, Color staticColor)
{
super(synth, key);
setBackground(Style.BACKGROUND_COLOR());
dial = new Dial(staticColor);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Style.BACKGROUND_COLOR());
panel.add(dial, BorderLayout.CENTER);
label = new JLabel(_label);
if (_label != null)
{
labels.add(_label);
label.setFont(Style.SMALL_FONT());
label.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
label.setForeground(Style.TEXT_COLOR());
labelBox = new Box(BoxLayout.Y_AXIS);
Box box = new Box(BoxLayout.X_AXIS);
box.add(Box.createGlue());
box.add(label);
box.add(Box.createGlue());
labelBox.add(box);
labelBox.add(glue = Box.createGlue());
panel.add(labelBox, BorderLayout.SOUTH);
}
dial.updateAccessibleName();
setLayout(new BorderLayout());
add(panel, BorderLayout.NORTH);
}
public int reviseToAltValue(int val) { return val; }
public int getDefaultValue()
{
if (isSymmetric())
{
return (int)Math.ceil((getMin() + getMax()) / 2.0); // we do ceiling so we push to 64 on 0...127
}
else return getMin();
}
/** A useful utility function which returns the element in the sorted
(low to high) array A which is closest to VALUE. You could use this
to search arrays for alt values for rounding for example. */
public static int findClosestValue(int value, int[] a)
{
if (value < a[0]) { return a[0]; }
if (value > a[a.length-1]) { return a[a.length-1]; }
int lo = 0;
int hi = a.length - 1;
while (lo <= hi)
{
// this could obviously overflow if hi and lo are really big
int mid = (hi + lo) / 2;
if (value < a[mid])
hi = mid - 1;
else if (value > a[mid])
lo = mid + 1;
else
return a[mid];
}
return (a[lo] - value) < (value - a[hi]) ? a[lo] : a[hi];
}
// a hook for ASMHydrasynth
public int updateProposedState(int proposedState)
{
return proposedState;
}
class Dial extends JPanel
{
// What's going on? Is the user changing the dial?
public static final int STATUS_STATIC = 0;
public static final int STATUS_DIAL_DYNAMIC = 1;
int status = STATUS_STATIC;
Color staticColor;
// The largest vertical range that a dial ought to go.
public static final int MAX_EXTENT = 256;
// The typical vertical range that the dial goes. 128 is reasonable
public static final int MIN_EXTENT = 128;
// The state when the mouse was pressed
int startState;
// The mouse position when the mouse was pressed
int startX;
int startY;
// Is the mouse pressed? This is part of a mechanism for dealing with
// a stupidity in Java: if you PRESS in a widget, it'll be told. But if
// you then drag elsewhere and RELEASE, the widget is never told.
boolean mouseDown;
// how much should be subtracted from the value in the model before
// it is displayed onscreen?
int subtractForDisplay = 0;
// Field in the center of the dial
JLabel field = new JLabel("88888", SwingConstants.CENTER);
public Dimension getPreferredSize() { return new Dimension(Style.LABELLED_DIAL_WIDTH(), Style.LABELLED_DIAL_WIDTH()); }
public Dimension getMinimumSize() { return new Dimension(Style.LABELLED_DIAL_WIDTH(), Style.LABELLED_DIAL_WIDTH()); }
boolean enabled = true;
public void setEnabled(boolean val)
{
enabled = val;
field.setEnabled(val);
if (isVisible()) repaint();
}
void mouseReleased(MouseEvent e)
{
if (!enabled) return;
if (mouseDown)
{
status = STATUS_STATIC;
if (isVisible()) repaint();
mouseDown = false;
if (releaseListener != null)
Toolkit.getDefaultToolkit().removeAWTEventListener(releaseListener);
}
}
public int getProposedState(MouseEvent e)
{
int y = -(e.getY() - startY);
int min = getMin();
int max = getMax();
int range = (max - min + 1 );
double multiplicand = 1;
double extent = range;
if (extent < MIN_EXTENT) extent = MIN_EXTENT;
if (extent > MAX_EXTENT) extent = MAX_EXTENT;
multiplicand = extent / (double) range;
int proposedState = startState + (int)(y / multiplicand);
if (((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) &&
(((e.getModifiers() & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) ||
((e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK)))
{
proposedState = startState + (int)(y / multiplicand / 64);
}
else if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK)
{
proposedState = startState + (int)(y / multiplicand / 16);
}
else if (((e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK))
{
proposedState = startState + (int)(y / multiplicand / 4);
}
else if (((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) ||
((e.getModifiers() & InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK))
{
proposedState = reviseToAltValue(proposedState);
}
if (proposedState < min)
proposedState = min;
else if (proposedState > max)
proposedState = max;
return updateProposedState(proposedState);
}
public Dial(Color staticColor)
{
setFocusable(true);
setRequestFocusEnabled(false);
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
int state = getState();
int max = getMax();
int min = getMin();
int modifiers = e.getModifiersEx();
boolean shift = (modifiers & KeyEvent.SHIFT_DOWN_MASK) == KeyEvent.SHIFT_DOWN_MASK;
// boolean ctrl = (modifiers & KeyEvent.CTRL_DOWN_MASK) == KeyEvent.CTRL_DOWN_MASK;
// Can't use alt, MacOS uses it already for moving around
// boolean alt = (modifiers & KeyEvent.ALT_DOWN_MASK) == KeyEvent.ALT_DOWN_MASK;
int multiplier = 1;
if (shift) multiplier *= 16;
// if (ctrl) multiplier *= 256;
// if (alt) multiplier *= 256;
if (e.getKeyCode() == KeyEvent.VK_UP)
{
state += multiplier;
if (state > max) state = max;
setState(state);
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
state -= multiplier;
if (state < min) state = min;
setState(state);
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
state += multiplier * 256;
if (state > max) state = max;
setState(state);
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
state -= multiplier * 256;
if (state < min) state = min;
setState(state);
}
else if (e.getKeyCode() == KeyEvent.VK_SPACE)
{
setState(getDefaultValue());
}
else if (e.getKeyCode() == KeyEvent.VK_HOME)
{
setState(getMin());
}
else if (e.getKeyCode() == KeyEvent.VK_END)
{
setState(getMax());
}
}
});
this.staticColor = staticColor;
field.setFont(Style.DIAL_FONT());
field.setBackground(Style.BACKGROUND_COLOR()); // TRANSPARENT);
field.setForeground(Style.TEXT_COLOR());
addMouseWheelListener(new MouseWheelListener()
{
public void mouseWheelMoved(MouseWheelEvent e)
{
if (!enabled) return;
int val = getState() - e.getWheelRotation();
if (val > getMax()) val = getMax();
if (val < getMin()) val = getMin();
setState(val);
}
});
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
if (!enabled) return;
mouseDown = true;
startX = e.getX();
startY = e.getY();
startState = getState();
status = STATUS_DIAL_DYNAMIC;
if (isVisible()) repaint();
if (releaseListener != null)
Toolkit.getDefaultToolkit().removeAWTEventListener(releaseListener);
// This gunk fixes a BAD MISFEATURE in Java: mouseReleased isn't sent to the
// same component that received mouseClicked. What the ... ? Asinine.
// So we create a global event listener which checks for mouseReleased and
// calls our own private function. EVERYONE is going to do this.
Toolkit.getDefaultToolkit().addAWTEventListener( releaseListener = new AWTEventListener()
{
public void eventDispatched(AWTEvent e)
{
if (e instanceof MouseEvent && e.getID() == MouseEvent.MOUSE_RELEASED)
{
mouseReleased((MouseEvent)e);
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
}
MouseEvent lastRelease;
public void mouseReleased(MouseEvent e)
{
if (!enabled) return;
if (e == lastRelease) // we just had this event because we're in the AWT Event Listener. So we ignore it
return;
if (!updatesDynamically)
{
int proposedState = getProposedState(e);
// at present we're just going to use y. It's confusing to use either y or x.
if (startState != proposedState)
{
setState(proposedState);
}
}
status = STATUS_STATIC;
if (isVisible()) repaint();
if (releaseListener != null)
Toolkit.getDefaultToolkit().removeAWTEventListener(releaseListener);
lastRelease = e;
}
public void mouseClicked(MouseEvent e)
{
if (synth.isShowingMutation())
{
synth.mutationMap.setFree(key, !synth.mutationMap.isFree(key));
if (LabelledDial.this.isVisible()) LabelledDial.this.repaint();
}
else if (e.getClickCount() == 2)
{
setState(getDefaultValue());
}
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
if (!enabled) return;
int proposedState = getProposedState(e);
// at present we're just going to use y. It's confusing to use either y or x.
if (getState() != proposedState)
{
if (!updatesDynamically)
synth.setSendMIDI(false);
updatingDynamically = true;
setState(proposedState);
updatingDynamically = false;
if (!updatesDynamically)
synth.setSendMIDI(true);
}
}
});
setLayout(new BorderLayout());
add(field, BorderLayout.CENTER);
if (isVisible()) repaint();
}
AWTEventListener releaseListener = null;
/** Returns the actual square within which the Dial's circle
is drawn. */
public Rectangle getDrawSquare()
{
Insets insets = getInsets();
Dimension size = getSize();
int width = size.width - insets.left - insets.right;
int height = size.height - insets.top - insets.bottom;
// How big <SUF>
if (width > height)
{
// base it on height
int h = height;
int w = h;
int y = insets.top;
int x = insets.left + (width - w) / 2;
return new Rectangle(x, y, w, h);
}
else
{
// base it on width
int w = width;
int h = w;
int x = insets.left;
int y = insets.top + (height - h) / 2;
return new Rectangle(x, y, w, h);
}
}
public boolean getCanonicalSymmetric()
{
return subtractForDisplay == 64 || subtractForDisplay == 50 ||
getMax() == (0 - getMin()) ||
(getMax() == 127 && getMin() == -128) || (getMax() == 63 && getMin() == -64);
}
public double getCanonicalStartAngle()
{
if (isSymmetric())
{
return 90 + (270 / 2);
}
else
{
return 270;
}
}
public void paintComponent(Graphics g)
{
// revise label if needed
String val = (Style.showRaw ? ("" + getState()) : map(getState()));
if (!(val.equals(dial.field.getText())))
dial.field.setText(val);
super.paintComponent(g);
int min = getMin();
int max = getMax();
Graphics2D graphics = (Graphics2D) g;
RenderingHints oldHints = graphics.getRenderingHints();
Style.prepareGraphics(graphics);
Rectangle rect = getBounds();
rect.x = 0;
rect.y = 0;
graphics.setPaint(Style.BACKGROUND_COLOR());
graphics.fill(rect);
rect = getDrawSquare();
graphics.setPaint(Style.DIAL_UNSET_COLOR());
graphics.setStroke(Style.DIAL_THIN_STROKE());
Arc2D.Double arc = new Arc2D.Double();
double startAngle = getStartAngle();
double interval = -270;
arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), startAngle, interval, Arc2D.OPEN);
graphics.draw(arc);
if (!enabled)
{
graphics.setRenderingHints(oldHints);
return;
}
graphics.setStroke(Style.DIAL_THICK_STROKE());
arc = new Arc2D.Double();
int state = getState();
interval = -((state - min) / (double)(max - min) * 265) - 5;
if (status == STATUS_DIAL_DYNAMIC)
{
graphics.setPaint(Style.DIAL_DYNAMIC_COLOR());
if (state == min)
{
interval = 0;
// This is NO LONGER TRUE:
// interval = -5;
// If we're basically at zero, we still want to show a little bit while the user is scrolling so
// he gets some feedback.
//arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), 270, -5, Arc2D.OPEN);
}
else
{
//arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), 270, -((state - min) / (double)(max - min) * 265) - 5, Arc2D.OPEN);
}
}
else
{
graphics.setPaint(staticColor);
if (state == min)
{
interval = 0;
// do nothing. Here we'll literally draw a zero
}
else
{
//arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), 270, -((state - min) / (double)(max - min) * 265) - 5, Arc2D.OPEN);
}
}
arc.setArc(rect.getX() + Style.DIAL_STROKE_WIDTH() / 2, rect.getY() + Style.DIAL_STROKE_WIDTH()/2, rect.getWidth() - Style.DIAL_STROKE_WIDTH(), rect.getHeight() - Style.DIAL_STROKE_WIDTH(), startAngle, interval, Arc2D.OPEN);
graphics.draw(arc);
graphics.setRenderingHints(oldHints);
}
//// ACCESSIBILITY FOR THE BLIND
//// LabelledDial is a custom widget and must provide its own accessibility features.
//// Fortunately Java has good accessibility capabilities. Unfortunately they're a little
//// broken in that they rely on the assumption that you're using standard Swing widgets.
// We need a function which updates the name of our widget. It appears that accessible
// tools for the blind will announce the widget as "NAME ROLE" (as in "Envelope Attack Slider").
// Unfortunately we do not have an easy way to encorporate the enclosing Category into the name
// at this point. We'll add that later below.
void updateAccessibleName()
{
String str = "";
for(String l : labels)
str += (l + " ");
dial.getAccessibleContext().setAccessibleName(str);
}
// This is the top-level accessible context for the Dial. It gives accessibility information.
class AccessibleDial extends AccessibleJComponent implements AccessibleValue, AccessibleComponent
{
// Here we try to tack the Category onto the END of the accessible name so
// the user can skip it if he knows what it is.
public String getAccessibleName()
{
String name = super.getAccessibleName();
// Find enclosing Category
Component obj = LabelledDial.this;
while(obj != null)
{
if (obj instanceof Category)
{
return name + " " + ((Category)obj).getName() + ", " + map(getState());
}
else obj = obj.getParent();
}
return name + ", " + map(getState());
}
// Provide myself as the AccessibleValue (I implement that interface) so I don't
// need to have a separate object
public AccessibleValue getAccessibleValue()
{
return this;
}
// We must define a ROLE that our widget fulfills. We can't be a JPanel because
// that causes the system to freak. Notionally you're supposed to be
// be able to can provide custom roles, but in reality, if you do so, Java accessibility
// will simply break for your widget. So here we're borrowing the role from the closest
// widget to our own: a JSlider.
public AccessibleRole getAccessibleRole()
{
return ROLE; //ccessibleRole.SLIDER; // AccessibleRole.SLIDER;
}
// Add whether the user is frobbing me to my current state
public AccessibleStateSet getAccessibleStateSet()
{
AccessibleStateSet states = super.getAccessibleStateSet();
/*
if (dial.mouseDown)
{
states.add(AccessibleState.BUSY);
}
*/
return states;
}
// My current numerical value
public Number getCurrentAccessibleValue()
{
return Integer.valueOf(getState());
};
// You can't set my value
public boolean setCurrentAccessibleValue(Number n)
{
return false;
};
// My minimum numerical value
public Number getMinimumAccessibleValue()
{
return Integer.valueOf(getMin());
};
// My maximum numerical value
public Number getMaximumAccessibleValue()
{
return Integer.valueOf(getMax());
};
}
AccessibleContext accessibleContext = null;
// Generate and provide the context information when asked
public AccessibleContext getAccessibleContext()
{
if (accessibleContext == null)
{
accessibleContext = new AccessibleDial();
}
return accessibleContext;
}
protected void stateSet(int oldVal, int newVal)
{
AccessibleContext context = getAccessibleContext();
if (context != null)
{
context.firePropertyChange(AccessibleContext.ACCESSIBLE_VALUE_PROPERTY, Integer.valueOf(oldVal), Integer.valueOf(newVal));
context.firePropertyChange(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, "yo", "mama");
}
}
/// END ACCESSSIBILITY FOR THE BLIND
}
public static class DialRole extends AccessibleRole
{
public DialRole(String key)
{
super(key);
}
}
public static final DialRole ROLE = new DialRole("dial");
}
| f |
1429_3 | elastic/elasticsearch | 945 | libs/h3/src/main/java/org/elasticsearch/h3/Constants.java | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*
* This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License.
*
* Copyright 2016-2017, 2020 Uber Technologies, Inc.
*/
package org.elasticsearch.h3;
/**
* Constants used by more than one source code file.
*/
final class Constants {
/**
* sqrt(3) / 2.0
*/
public static double M_SQRT3_2 = 0.8660254037844386467637231707529361834714;
/**
* 2.0 * PI
*/
public static final double M_2PI = 6.28318530717958647692528676655900576839433;
/**
* max H3 resolution; H3 version 1 has 16 resolutions, numbered 0 through 15
*/
public static int MAX_H3_RES = 15;
/**
* The number of H3 base cells
*/
public static int NUM_BASE_CELLS = 122;
/**
* The number of vertices in a hexagon
*/
public static int NUM_HEX_VERTS = 6;
/**
* The number of vertices in a pentagon
*/
public static int NUM_PENT_VERTS = 5;
/**
* H3 index modes
*/
public static int H3_CELL_MODE = 1;
/**
* square root of 7
*/
public static final double M_SQRT7 = 2.6457513110645905905016157536392604257102;
/**
* scaling factor from hex2d resolution 0 unit length
* (or distance between adjacent cell center points
* on the plane) to gnomonic unit length.
*/
public static double RES0_U_GNOMONIC = 0.38196601125010500003;
/**
* rotation angle between Class II and Class III resolution axes
* (asin(sqrt(3.0 / 28.0)))
*/
public static double M_AP7_ROT_RADS = 0.333473172251832115336090755351601070065900389;
/**
* threshold epsilon
*/
public static double EPSILON = 0.0000000000000001;
}
| /**
* 2.0 * PI
*/ | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*
* This project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License.
*
* Copyright 2016-2017, 2020 Uber Technologies, Inc.
*/
package org.elasticsearch.h3;
/**
* Constants used by more than one source code file.
*/
final class Constants {
/**
* sqrt(3) / 2.0
*/
public static double M_SQRT3_2 = 0.8660254037844386467637231707529361834714;
/**
* 2.0 * PI <SUF>*/
public static final double M_2PI = 6.28318530717958647692528676655900576839433;
/**
* max H3 resolution; H3 version 1 has 16 resolutions, numbered 0 through 15
*/
public static int MAX_H3_RES = 15;
/**
* The number of H3 base cells
*/
public static int NUM_BASE_CELLS = 122;
/**
* The number of vertices in a hexagon
*/
public static int NUM_HEX_VERTS = 6;
/**
* The number of vertices in a pentagon
*/
public static int NUM_PENT_VERTS = 5;
/**
* H3 index modes
*/
public static int H3_CELL_MODE = 1;
/**
* square root of 7
*/
public static final double M_SQRT7 = 2.6457513110645905905016157536392604257102;
/**
* scaling factor from hex2d resolution 0 unit length
* (or distance between adjacent cell center points
* on the plane) to gnomonic unit length.
*/
public static double RES0_U_GNOMONIC = 0.38196601125010500003;
/**
* rotation angle between Class II and Class III resolution axes
* (asin(sqrt(3.0 / 28.0)))
*/
public static double M_AP7_ROT_RADS = 0.333473172251832115336090755351601070065900389;
/**
* threshold epsilon
*/
public static double EPSILON = 0.0000000000000001;
}
| f |
8268_15 | faramir/ZawodyWeb | 6,216 | www/src/main/java/pl/umk/mat/zawodyweb/www/ranking/RankingACM.java | /*
* Copyright (c) 2009-2014, ZawodyWeb Team
* All rights reserved.
*
* This file is distributable under the Simplified BSD license. See the terms
* of the Simplified BSD license in the documentation provided with this file.
*/
package pl.umk.mat.zawodyweb.www.ranking;
import java.sql.Timestamp;
import java.util.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import pl.umk.mat.zawodyweb.database.*;
import pl.umk.mat.zawodyweb.database.hibernate.HibernateUtil;
import pl.umk.mat.zawodyweb.database.pojo.*;
/**
* @author <a href="mailto:faramir@mat.umk.pl">Marek Nowicki</a>
* @version $Rev$ $Date: 2010-10-10 02:53:49 +0200 (N, 10 paź 2010)$
*/
public class RankingACM implements RankingInterface {
private final ResourceBundle messages = ResourceBundle.getBundle("pl.umk.mat.zawodyweb.www.Messages");
private class SolutionACM implements Comparable {
String abbrev;
long date;
long time;
long time_from_bombs;
int bombs;
String name;
boolean frozen;
public SolutionACM(String abbrev, long date, long time, long time_from_bombs, int bombs, String name, boolean frozen) {
this.abbrev = abbrev;
this.date = date;
this.time = time;
this.time_from_bombs = time_from_bombs;
this.bombs = bombs;
this.name = name;
this.frozen = frozen;
}
@Override
public int compareTo(Object o) {
if (this.date < ((SolutionACM) o).date) {
return -1;
}
if (this.date > ((SolutionACM) o).date) {
return 1;
}
return 0;
}
}
private class UserACM implements Comparable {
String login;
String firstname;
String lastname;
boolean loginOnly;
int id_user;
int points;
long totalTime;
List<SolutionACM> solutions;
public UserACM(int id_user, Users users) {
this.id_user = id_user;
this.points = 0;
this.totalTime = 0;
this.solutions = new ArrayList<>();
this.login = users.getLogin();
this.firstname = users.getFirstname();
this.lastname = users.getLastname();
this.loginOnly = users.getOnlylogin();
}
void add(int points, SolutionACM solutionACM) {
this.points += points;
this.totalTime += solutionACM.time + solutionACM.time_from_bombs;
this.solutions.add(solutionACM);
}
String getSolutionsForRanking() {
String r = "";
String text;
Collections.sort(this.solutions);
for (SolutionACM solutionACM : solutions) {
text = solutionACM.abbrev;
if (solutionACM.bombs >= 4) {
text += "(" + solutionACM.bombs + ")";
} else {
for (int i = 0; i < solutionACM.bombs; ++i) {
text += "*";
}
}
r += RankingUtils.formatText(text,
solutionACM.name + " [" + parseTime(solutionACM.time) + (solutionACM.time_from_bombs == 0 ? "" : "+" + parseTime(solutionACM.time_from_bombs)) + "]",
solutionACM.frozen ? "frozen" : null) + " ";
}
return r.trim();
}
@Override
public int compareTo(Object o) {
UserACM u2 = (UserACM) o;
if (this.points < u2.points) {
return 1;
}
if (this.points > u2.points) {
return -1;
}
if (this.totalTime > u2.totalTime) {
return 1;
}
if (this.totalTime < u2.totalTime) {
return -1;
}
int r;
r = RankingUtils.compareStrings(this.lastname, u2.lastname);
if (r != 0) {
return r;
}
r = RankingUtils.compareStrings(this.firstname, u2.firstname);
if (r != 0) {
return r;
}
return RankingUtils.compareStrings(this.login, u2.login);
}
}
private String parseTime(long time) {
long d, h, m, s;
d = time / (24 * 60 * 60);
time %= (24 * 60 * 60);
h = time / (60 * 60);
time %= (60 * 60);
m = time / 60;
time %= 60;
s = time;
if (d > 0) {
return String.format("%dd %02d:%02d:%02d", d, h, m, s);
} else if (h > 0) {
return String.format("%d:%02d:%02d", h, m, s);
} else {
return String.format("%d:%02d", m, s);
}
}
private RankingTable getRankingACM(int contest_id, Timestamp checkDate, boolean admin, Integer series_id) {
Session hibernateSession = HibernateUtil.getSessionFactory().getCurrentSession();
Timestamp checkTimestamp;
Timestamp visibleTimestamp;
UsersDAO usersDAO = DAOFactory.DEFAULT.buildUsersDAO();
SeriesDAO seriesDAO = DAOFactory.DEFAULT.buildSeriesDAO();
ProblemsDAO problemsDAO = DAOFactory.DEFAULT.buildProblemsDAO();
Map<Integer, UserACM> mapUserACM = new HashMap<>();
boolean allTests;
boolean frozenRanking = false;
boolean frozenSeria;
long lCheckDate = checkDate.getTime();
for (Series series : seriesDAO.findByContestsid(contest_id)) {
if ((series_id == null && series.getVisibleinranking() == false)
|| (series_id != null && series_id.equals(series.getId()) == false)) {
continue;
}
if (series.getStartdate().getTime() > lCheckDate) {
continue;
}
frozenSeria = false;
checkTimestamp = checkDate;
allTests = admin;
if (!admin && series.getFreezedate() != null) {
if (lCheckDate > series.getFreezedate().getTime() && (series.getUnfreezedate() == null || lCheckDate < series.getUnfreezedate().getTime())) {
checkTimestamp = new Timestamp(series.getFreezedate().getTime());
if (series.getUnfreezedate() != null) {
frozenRanking = true;
}
frozenSeria = true;
}
}
if (checkTimestamp.before(series.getStartdate())) {
visibleTimestamp = new Timestamp(0);
} else {
visibleTimestamp = new Timestamp(series.getStartdate().getTime());
}
if (series.getUnfreezedate() != null) {
if (checkDate.after(series.getUnfreezedate())) {
allTests = true;
}
}
for (Problems problems : problemsDAO.findBySeriesid(series.getId())) {
if (problems.getVisibleinranking() == false) {
continue;
}
// select sum(maxpoints) from tests where problemsid='7' and visibility=1
Number maxPoints;
Number testCount;
if (allTests) {
Object[] o = (Object[]) hibernateSession.createCriteria(Tests.class).setProjection(
Projections.projectionList().add(Projections.sum("maxpoints")).add(Projections.rowCount())).add(Restrictions.eq("problems.id", problems.getId())).uniqueResult();
maxPoints = (Number) o[0];
testCount = (Number) o[1];
} else {
Object[] o = (Object[]) hibernateSession.createCriteria(Tests.class).setProjection(
Projections.projectionList().add(Projections.sum("maxpoints")).add(Projections.rowCount())).add(Restrictions.and(Restrictions.eq("problems.id", problems.getId()), Restrictions.eq("visibility", 1))).uniqueResult();
maxPoints = (Number) o[0];
testCount = (Number) o[1];
}
if (maxPoints == null) {
maxPoints = 0; // To nie powinno się nigdy zdarzyć ;).. chyba, że nie ma testu przy zadaniu?
}
if (testCount == null) {
testCount = 0; // To nie powinno się zdarzyć nigdy.
}
Query query;
if (allTests == true) {
query = hibernateSession.createSQLQuery(""
+ "select usersid, min(sdate) sdate " // zapytanie zewnętrzne znajduję minimalną datę wysłania poprawnego rozwiązania dla każdego usera
+ "from submits "
+ "where id in ("
+ " select submits.id " // zapytanie wewnętrzne znajduje wszystkie id, które zdobyły maksa punktów
+ " from submits,results,tests "
+ " where submits.problemsid = :problemsId "
+ " and submits.id=results.submitsid "
+ " and tests.id = results.testsid "
+ " and results.status = :statusAcc "
+ " and submits.state = :stateDone "
+ " and sdate <= :currentTimestamp "
+ " and sdate >= :visibleTimestamp "
+ " and visibleInRanking=true"
//+ " and tests.visibility=1 "
+ " group by submits.id,usersid,sdate "
+ " having sum(points) = :maxPoints "
+ " and count(points) = :testCount "
+ " ) "
+ "group by usersid")
.setInteger("problemsId", problems.getId())
.setInteger("statusAcc", ResultsStatusEnum.ACC.getCode())
.setInteger("stateDone", SubmitsStateEnum.DONE.getCode())
.setInteger("maxPoints", maxPoints.intValue())
.setInteger("testCount", testCount.intValue())
.setTimestamp("currentTimestamp", checkTimestamp)
.setTimestamp("visibleTimestamp", visibleTimestamp);
} else {
query = hibernateSession.createSQLQuery(""
+ "select usersid, min(sdate) sdate "
+ "from submits "
+ "where id in ("
+ " select submits.id "
+ " from submits,results,tests "
+ " where submits.problemsid = :problemsId "
+ " and submits.id=results.submitsid "
+ " and tests.id = results.testsid "
+ " and results.status = :statusAcc "
+ " and submits.state = :stateDone "
+ " and sdate <= :currentTimestamp "
+ " and sdate >= :visibleTimestamp "
+ " and visibleInRanking=true"
+ " and tests.visibility=1 " // FIXME: should be ok
+ " group by submits.id,usersid,sdate "
+ " having sum(points) = :maxPoints "
+ " and count(points) = :testCount "
+ " ) "
+ "group by usersid")
.setInteger("problemsId", problems.getId())
.setInteger("statusAcc", ResultsStatusEnum.ACC.getCode())
.setInteger("stateDone", SubmitsStateEnum.DONE.getCode())
.setInteger("maxPoints", maxPoints.intValue())
.setInteger("testCount", testCount.intValue())
.setTimestamp("currentTimestamp", checkTimestamp)
.setTimestamp("visibleTimestamp", visibleTimestamp);
}
for (Object list : query.list()) { // tu jest zwrócona lista "zaakceptowanych" w danym momencie rozwiązań zadania
Object[] o = (Object[]) list;
Number bombs = (Number) hibernateSession.createCriteria(Submits.class).setProjection(Projections.rowCount()).add(Restrictions.eq("problems.id", (Number) problems.getId())).add(Restrictions.eq("users.id", (Number) o[0])).add(Restrictions.lt("sdate", (Timestamp) o[1])).uniqueResult();
if (bombs == null) {
bombs = 0;
}
UserACM user = mapUserACM.get((Integer) o[0]);
if (user == null) {
Integer user_id = (Integer) o[0];
Users users = usersDAO.getById(user_id);
user = new UserACM(user_id, users);
mapUserACM.put((Integer) o[0], user);
}
user.add(maxPoints.intValue(),
new SolutionACM(problems.getAbbrev(),
((Timestamp) o[1]).getTime(),
(maxPoints.equals(0) ? 0 : ((Timestamp) o[1]).getTime() - series.getStartdate().getTime()) / 1000,
series.getPenaltytime() * bombs.intValue(),
bombs.intValue(),
problems.getName(),
frozenSeria));
}
}
}
/*
* Tworzenie rankingu z danych
*/
List<UserACM> cre = new ArrayList<>();
cre.addAll(mapUserACM.values());
Collections.sort(cre);
/*
* nazwy kolumn
*/
List<String> columnsCaptions = new ArrayList<>();
columnsCaptions.add(messages.getString("points"));
columnsCaptions.add(messages.getString("time"));
columnsCaptions.add(messages.getString("solutions"));
/*
* nazwy klas css-owych dla kolumn
*/
List<String> columnsCSS = new ArrayList<>();
columnsCSS.add("small"); // points
columnsCSS.add("nowrap small"); // time
columnsCSS.add("big left"); // solutions
/*
* tabelka z rankingiem
*/
List<RankingEntry> vectorRankingEntry = new ArrayList<>();
int place = 0;
long totalTime = -1;
int points = Integer.MAX_VALUE;
for (UserACM user : cre) {
if (points > user.points || (points == user.points && totalTime < user.totalTime)) {
++place;
points = user.points;
totalTime = user.totalTime;
}
List<String> v = new ArrayList<>();
v.add(Integer.toString(user.points));
v.add(parseTime(user.totalTime));
v.add(user.getSolutionsForRanking());
vectorRankingEntry.add(new RankingEntry(place, user.firstname, user.lastname, user.login, user.loginOnly, v));
}
return new RankingTable(columnsCaptions, columnsCSS, vectorRankingEntry, frozenRanking);
}
@Override
public RankingTable getRanking(int contest_id, Timestamp checkDate, boolean admin) {
return getRankingACM(contest_id, checkDate, admin, null);
}
@Override
public RankingTable getRankingForSeries(int contest_id, int series_id, Timestamp checkDate, boolean admin) {
return getRankingACM(contest_id, checkDate, admin, series_id);
}
@Override
public List<Integer> getRankingSolutions(int contest_id, Integer series_id, Timestamp checkDate, boolean admin) {
Session hibernateSession = HibernateUtil.getSessionFactory().getCurrentSession();
Timestamp checkTimestamp;
Timestamp visibleTimestamp;
SeriesDAO seriesDAO = DAOFactory.DEFAULT.buildSeriesDAO();
ProblemsDAO problemsDAO = DAOFactory.DEFAULT.buildProblemsDAO();
List<Integer> submits = new ArrayList<>();
boolean allTests;
long lCheckDate = checkDate.getTime();
for (Series series : seriesDAO.findByContestsid(contest_id)) {
if ((series_id == null && series.getVisibleinranking() == false)
|| (series_id != null && series_id.equals(series.getId()) == false)) {
continue;
}
if (series.getStartdate().getTime() > lCheckDate) {
continue;
}
checkTimestamp = checkDate;
allTests = admin;
if (!admin && series.getFreezedate() != null) {
if (lCheckDate > series.getFreezedate().getTime() && (series.getUnfreezedate() == null || lCheckDate < series.getUnfreezedate().getTime())) {
checkTimestamp = new Timestamp(series.getFreezedate().getTime());
}
}
if (checkTimestamp.before(series.getStartdate())) {
visibleTimestamp = new Timestamp(0);
} else {
visibleTimestamp = new Timestamp(series.getStartdate().getTime());
}
if (series.getUnfreezedate() != null) {
if (checkDate.after(series.getUnfreezedate())) {
allTests = true;
}
}
for (Problems problems : problemsDAO.findBySeriesid(series.getId())) {
if (problems.getVisibleinranking() == false) {
continue;
}
// select sum(maxpoints) from tests where problemsid='7' and visibility=1
Number maxPoints;
Number testCount;
if (allTests) {
Object[] o = (Object[]) hibernateSession.createCriteria(Tests.class).setProjection(
Projections.projectionList().add(Projections.sum("maxpoints")).add(Projections.rowCount())).add(Restrictions.eq("problems.id", problems.getId())).uniqueResult();
maxPoints = (Number) o[0];
testCount = (Number) o[1];
} else {
Object[] o = (Object[]) hibernateSession.createCriteria(Tests.class).setProjection(
Projections.projectionList().add(Projections.sum("maxpoints")).add(Projections.rowCount())).add(Restrictions.and(Restrictions.eq("problems.id", problems.getId()), Restrictions.eq("visibility", 1))).uniqueResult();
maxPoints = (Number) o[0];
testCount = (Number) o[1];
}
if (maxPoints == null) {
maxPoints = 0; // To nie powinno się nigdy zdarzyć ;).. chyba, że nie ma testu przy zadaniu?
}
if (testCount == null) {
testCount = 0; // To nie powinno się zdarzyć nigdy.
}
Query query;
if (allTests == true) {
query = hibernateSession.createSQLQuery(""
+ "select min(id) sid " // zapytanie zewnętrzne znajduję minimalną datę wysłania poprawnego rozwiązania dla każdego usera
+ "from submits "
+ "where id in ("
+ " select submits.id " // zapytanie wewnętrzne znajduje wszystkie id, które zdobyły maksa punktów
+ " from submits,results,tests "
+ " where submits.problemsid = :problemsId "
+ " and submits.id = results.submitsid "
+ " and tests.id = results.testsid "
+ " and results.status = :statusAcc "
+ " and submits.state = :stateDone "
+ " and sdate <= :currentTimestamp "
+ " and sdate >= :visibleTimestamp "
+ " and visibleInRanking=true"
//+ " and tests.visibility=1 "
+ " group by submits.id,usersid,sdate "
+ " having sum(points) = :maxPoints "
+ " and count(points) = :testsCount "
+ " ) "
+ "group by usersid")
.setInteger("problemsId", problems.getId())
.setInteger("statusAcc", ResultsStatusEnum.ACC.getCode())
.setInteger("stateDone", SubmitsStateEnum.DONE.getCode())
.setInteger("maxPoints", maxPoints.intValue())
.setInteger("testCount", testCount.intValue())
.setTimestamp("currentTimestamp", checkTimestamp)
.setTimestamp("visibleTimestamp", visibleTimestamp);
} else {
query = hibernateSession.createSQLQuery(""
+ "select min(id) sid "
+ "from submits "
+ "where id in ("
+ " select submits.id "
+ " from submits,results,tests "
+ " where submits.problemsid = :problemsId "
+ " and submits.id = results.submitsid "
+ " and tests.id = results.testsid "
+ " and results.status = :statusAcc "
+ " and submits.state = :stateDone "
+ " and sdate <= :currentTimestamp "
+ " and sdate >= :visibleTimestamp "
+ " and visibleInRanking=true"
+ " and tests.visibility=1 " // FIXME: should be ok
+ " group by submits.id,usersid,sdate "
+ " having sum(points) = :maxPoints "
+ " and count(points) = :testCount "
+ " ) "
+ "group by usersid")
.setInteger("problemsId", problems.getId())
.setInteger("statusAcc", ResultsStatusEnum.ACC.getCode())
.setInteger("stateDone", SubmitsStateEnum.DONE.getCode())
.setInteger("maxPoints", maxPoints.intValue())
.setInteger("testCount", testCount.intValue())
.setTimestamp("currentTimestamp", checkTimestamp)
.setTimestamp("visibleTimestamp", visibleTimestamp);
}
for (Object id : query.list()) { // tu jest zwrócona lista "zaakceptowanych" w danym momencie rozwiązań zadania
submits.add((Integer) id);
}
}
}
return submits;
}
}
| // To nie powinno się nigdy zdarzyć ;).. chyba, że nie ma testu przy zadaniu? | /*
* Copyright (c) 2009-2014, ZawodyWeb Team
* All rights reserved.
*
* This file is distributable under the Simplified BSD license. See the terms
* of the Simplified BSD license in the documentation provided with this file.
*/
package pl.umk.mat.zawodyweb.www.ranking;
import java.sql.Timestamp;
import java.util.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import pl.umk.mat.zawodyweb.database.*;
import pl.umk.mat.zawodyweb.database.hibernate.HibernateUtil;
import pl.umk.mat.zawodyweb.database.pojo.*;
/**
* @author <a href="mailto:faramir@mat.umk.pl">Marek Nowicki</a>
* @version $Rev$ $Date: 2010-10-10 02:53:49 +0200 (N, 10 paź 2010)$
*/
public class RankingACM implements RankingInterface {
private final ResourceBundle messages = ResourceBundle.getBundle("pl.umk.mat.zawodyweb.www.Messages");
private class SolutionACM implements Comparable {
String abbrev;
long date;
long time;
long time_from_bombs;
int bombs;
String name;
boolean frozen;
public SolutionACM(String abbrev, long date, long time, long time_from_bombs, int bombs, String name, boolean frozen) {
this.abbrev = abbrev;
this.date = date;
this.time = time;
this.time_from_bombs = time_from_bombs;
this.bombs = bombs;
this.name = name;
this.frozen = frozen;
}
@Override
public int compareTo(Object o) {
if (this.date < ((SolutionACM) o).date) {
return -1;
}
if (this.date > ((SolutionACM) o).date) {
return 1;
}
return 0;
}
}
private class UserACM implements Comparable {
String login;
String firstname;
String lastname;
boolean loginOnly;
int id_user;
int points;
long totalTime;
List<SolutionACM> solutions;
public UserACM(int id_user, Users users) {
this.id_user = id_user;
this.points = 0;
this.totalTime = 0;
this.solutions = new ArrayList<>();
this.login = users.getLogin();
this.firstname = users.getFirstname();
this.lastname = users.getLastname();
this.loginOnly = users.getOnlylogin();
}
void add(int points, SolutionACM solutionACM) {
this.points += points;
this.totalTime += solutionACM.time + solutionACM.time_from_bombs;
this.solutions.add(solutionACM);
}
String getSolutionsForRanking() {
String r = "";
String text;
Collections.sort(this.solutions);
for (SolutionACM solutionACM : solutions) {
text = solutionACM.abbrev;
if (solutionACM.bombs >= 4) {
text += "(" + solutionACM.bombs + ")";
} else {
for (int i = 0; i < solutionACM.bombs; ++i) {
text += "*";
}
}
r += RankingUtils.formatText(text,
solutionACM.name + " [" + parseTime(solutionACM.time) + (solutionACM.time_from_bombs == 0 ? "" : "+" + parseTime(solutionACM.time_from_bombs)) + "]",
solutionACM.frozen ? "frozen" : null) + " ";
}
return r.trim();
}
@Override
public int compareTo(Object o) {
UserACM u2 = (UserACM) o;
if (this.points < u2.points) {
return 1;
}
if (this.points > u2.points) {
return -1;
}
if (this.totalTime > u2.totalTime) {
return 1;
}
if (this.totalTime < u2.totalTime) {
return -1;
}
int r;
r = RankingUtils.compareStrings(this.lastname, u2.lastname);
if (r != 0) {
return r;
}
r = RankingUtils.compareStrings(this.firstname, u2.firstname);
if (r != 0) {
return r;
}
return RankingUtils.compareStrings(this.login, u2.login);
}
}
private String parseTime(long time) {
long d, h, m, s;
d = time / (24 * 60 * 60);
time %= (24 * 60 * 60);
h = time / (60 * 60);
time %= (60 * 60);
m = time / 60;
time %= 60;
s = time;
if (d > 0) {
return String.format("%dd %02d:%02d:%02d", d, h, m, s);
} else if (h > 0) {
return String.format("%d:%02d:%02d", h, m, s);
} else {
return String.format("%d:%02d", m, s);
}
}
private RankingTable getRankingACM(int contest_id, Timestamp checkDate, boolean admin, Integer series_id) {
Session hibernateSession = HibernateUtil.getSessionFactory().getCurrentSession();
Timestamp checkTimestamp;
Timestamp visibleTimestamp;
UsersDAO usersDAO = DAOFactory.DEFAULT.buildUsersDAO();
SeriesDAO seriesDAO = DAOFactory.DEFAULT.buildSeriesDAO();
ProblemsDAO problemsDAO = DAOFactory.DEFAULT.buildProblemsDAO();
Map<Integer, UserACM> mapUserACM = new HashMap<>();
boolean allTests;
boolean frozenRanking = false;
boolean frozenSeria;
long lCheckDate = checkDate.getTime();
for (Series series : seriesDAO.findByContestsid(contest_id)) {
if ((series_id == null && series.getVisibleinranking() == false)
|| (series_id != null && series_id.equals(series.getId()) == false)) {
continue;
}
if (series.getStartdate().getTime() > lCheckDate) {
continue;
}
frozenSeria = false;
checkTimestamp = checkDate;
allTests = admin;
if (!admin && series.getFreezedate() != null) {
if (lCheckDate > series.getFreezedate().getTime() && (series.getUnfreezedate() == null || lCheckDate < series.getUnfreezedate().getTime())) {
checkTimestamp = new Timestamp(series.getFreezedate().getTime());
if (series.getUnfreezedate() != null) {
frozenRanking = true;
}
frozenSeria = true;
}
}
if (checkTimestamp.before(series.getStartdate())) {
visibleTimestamp = new Timestamp(0);
} else {
visibleTimestamp = new Timestamp(series.getStartdate().getTime());
}
if (series.getUnfreezedate() != null) {
if (checkDate.after(series.getUnfreezedate())) {
allTests = true;
}
}
for (Problems problems : problemsDAO.findBySeriesid(series.getId())) {
if (problems.getVisibleinranking() == false) {
continue;
}
// select sum(maxpoints) from tests where problemsid='7' and visibility=1
Number maxPoints;
Number testCount;
if (allTests) {
Object[] o = (Object[]) hibernateSession.createCriteria(Tests.class).setProjection(
Projections.projectionList().add(Projections.sum("maxpoints")).add(Projections.rowCount())).add(Restrictions.eq("problems.id", problems.getId())).uniqueResult();
maxPoints = (Number) o[0];
testCount = (Number) o[1];
} else {
Object[] o = (Object[]) hibernateSession.createCriteria(Tests.class).setProjection(
Projections.projectionList().add(Projections.sum("maxpoints")).add(Projections.rowCount())).add(Restrictions.and(Restrictions.eq("problems.id", problems.getId()), Restrictions.eq("visibility", 1))).uniqueResult();
maxPoints = (Number) o[0];
testCount = (Number) o[1];
}
if (maxPoints == null) {
maxPoints = 0; // To nie powinno się nigdy zdarzyć ;).. chyba, że nie ma testu przy zadaniu?
}
if (testCount == null) {
testCount = 0; // To nie powinno się zdarzyć nigdy.
}
Query query;
if (allTests == true) {
query = hibernateSession.createSQLQuery(""
+ "select usersid, min(sdate) sdate " // zapytanie zewnętrzne znajduję minimalną datę wysłania poprawnego rozwiązania dla każdego usera
+ "from submits "
+ "where id in ("
+ " select submits.id " // zapytanie wewnętrzne znajduje wszystkie id, które zdobyły maksa punktów
+ " from submits,results,tests "
+ " where submits.problemsid = :problemsId "
+ " and submits.id=results.submitsid "
+ " and tests.id = results.testsid "
+ " and results.status = :statusAcc "
+ " and submits.state = :stateDone "
+ " and sdate <= :currentTimestamp "
+ " and sdate >= :visibleTimestamp "
+ " and visibleInRanking=true"
//+ " and tests.visibility=1 "
+ " group by submits.id,usersid,sdate "
+ " having sum(points) = :maxPoints "
+ " and count(points) = :testCount "
+ " ) "
+ "group by usersid")
.setInteger("problemsId", problems.getId())
.setInteger("statusAcc", ResultsStatusEnum.ACC.getCode())
.setInteger("stateDone", SubmitsStateEnum.DONE.getCode())
.setInteger("maxPoints", maxPoints.intValue())
.setInteger("testCount", testCount.intValue())
.setTimestamp("currentTimestamp", checkTimestamp)
.setTimestamp("visibleTimestamp", visibleTimestamp);
} else {
query = hibernateSession.createSQLQuery(""
+ "select usersid, min(sdate) sdate "
+ "from submits "
+ "where id in ("
+ " select submits.id "
+ " from submits,results,tests "
+ " where submits.problemsid = :problemsId "
+ " and submits.id=results.submitsid "
+ " and tests.id = results.testsid "
+ " and results.status = :statusAcc "
+ " and submits.state = :stateDone "
+ " and sdate <= :currentTimestamp "
+ " and sdate >= :visibleTimestamp "
+ " and visibleInRanking=true"
+ " and tests.visibility=1 " // FIXME: should be ok
+ " group by submits.id,usersid,sdate "
+ " having sum(points) = :maxPoints "
+ " and count(points) = :testCount "
+ " ) "
+ "group by usersid")
.setInteger("problemsId", problems.getId())
.setInteger("statusAcc", ResultsStatusEnum.ACC.getCode())
.setInteger("stateDone", SubmitsStateEnum.DONE.getCode())
.setInteger("maxPoints", maxPoints.intValue())
.setInteger("testCount", testCount.intValue())
.setTimestamp("currentTimestamp", checkTimestamp)
.setTimestamp("visibleTimestamp", visibleTimestamp);
}
for (Object list : query.list()) { // tu jest zwrócona lista "zaakceptowanych" w danym momencie rozwiązań zadania
Object[] o = (Object[]) list;
Number bombs = (Number) hibernateSession.createCriteria(Submits.class).setProjection(Projections.rowCount()).add(Restrictions.eq("problems.id", (Number) problems.getId())).add(Restrictions.eq("users.id", (Number) o[0])).add(Restrictions.lt("sdate", (Timestamp) o[1])).uniqueResult();
if (bombs == null) {
bombs = 0;
}
UserACM user = mapUserACM.get((Integer) o[0]);
if (user == null) {
Integer user_id = (Integer) o[0];
Users users = usersDAO.getById(user_id);
user = new UserACM(user_id, users);
mapUserACM.put((Integer) o[0], user);
}
user.add(maxPoints.intValue(),
new SolutionACM(problems.getAbbrev(),
((Timestamp) o[1]).getTime(),
(maxPoints.equals(0) ? 0 : ((Timestamp) o[1]).getTime() - series.getStartdate().getTime()) / 1000,
series.getPenaltytime() * bombs.intValue(),
bombs.intValue(),
problems.getName(),
frozenSeria));
}
}
}
/*
* Tworzenie rankingu z danych
*/
List<UserACM> cre = new ArrayList<>();
cre.addAll(mapUserACM.values());
Collections.sort(cre);
/*
* nazwy kolumn
*/
List<String> columnsCaptions = new ArrayList<>();
columnsCaptions.add(messages.getString("points"));
columnsCaptions.add(messages.getString("time"));
columnsCaptions.add(messages.getString("solutions"));
/*
* nazwy klas css-owych dla kolumn
*/
List<String> columnsCSS = new ArrayList<>();
columnsCSS.add("small"); // points
columnsCSS.add("nowrap small"); // time
columnsCSS.add("big left"); // solutions
/*
* tabelka z rankingiem
*/
List<RankingEntry> vectorRankingEntry = new ArrayList<>();
int place = 0;
long totalTime = -1;
int points = Integer.MAX_VALUE;
for (UserACM user : cre) {
if (points > user.points || (points == user.points && totalTime < user.totalTime)) {
++place;
points = user.points;
totalTime = user.totalTime;
}
List<String> v = new ArrayList<>();
v.add(Integer.toString(user.points));
v.add(parseTime(user.totalTime));
v.add(user.getSolutionsForRanking());
vectorRankingEntry.add(new RankingEntry(place, user.firstname, user.lastname, user.login, user.loginOnly, v));
}
return new RankingTable(columnsCaptions, columnsCSS, vectorRankingEntry, frozenRanking);
}
@Override
public RankingTable getRanking(int contest_id, Timestamp checkDate, boolean admin) {
return getRankingACM(contest_id, checkDate, admin, null);
}
@Override
public RankingTable getRankingForSeries(int contest_id, int series_id, Timestamp checkDate, boolean admin) {
return getRankingACM(contest_id, checkDate, admin, series_id);
}
@Override
public List<Integer> getRankingSolutions(int contest_id, Integer series_id, Timestamp checkDate, boolean admin) {
Session hibernateSession = HibernateUtil.getSessionFactory().getCurrentSession();
Timestamp checkTimestamp;
Timestamp visibleTimestamp;
SeriesDAO seriesDAO = DAOFactory.DEFAULT.buildSeriesDAO();
ProblemsDAO problemsDAO = DAOFactory.DEFAULT.buildProblemsDAO();
List<Integer> submits = new ArrayList<>();
boolean allTests;
long lCheckDate = checkDate.getTime();
for (Series series : seriesDAO.findByContestsid(contest_id)) {
if ((series_id == null && series.getVisibleinranking() == false)
|| (series_id != null && series_id.equals(series.getId()) == false)) {
continue;
}
if (series.getStartdate().getTime() > lCheckDate) {
continue;
}
checkTimestamp = checkDate;
allTests = admin;
if (!admin && series.getFreezedate() != null) {
if (lCheckDate > series.getFreezedate().getTime() && (series.getUnfreezedate() == null || lCheckDate < series.getUnfreezedate().getTime())) {
checkTimestamp = new Timestamp(series.getFreezedate().getTime());
}
}
if (checkTimestamp.before(series.getStartdate())) {
visibleTimestamp = new Timestamp(0);
} else {
visibleTimestamp = new Timestamp(series.getStartdate().getTime());
}
if (series.getUnfreezedate() != null) {
if (checkDate.after(series.getUnfreezedate())) {
allTests = true;
}
}
for (Problems problems : problemsDAO.findBySeriesid(series.getId())) {
if (problems.getVisibleinranking() == false) {
continue;
}
// select sum(maxpoints) from tests where problemsid='7' and visibility=1
Number maxPoints;
Number testCount;
if (allTests) {
Object[] o = (Object[]) hibernateSession.createCriteria(Tests.class).setProjection(
Projections.projectionList().add(Projections.sum("maxpoints")).add(Projections.rowCount())).add(Restrictions.eq("problems.id", problems.getId())).uniqueResult();
maxPoints = (Number) o[0];
testCount = (Number) o[1];
} else {
Object[] o = (Object[]) hibernateSession.createCriteria(Tests.class).setProjection(
Projections.projectionList().add(Projections.sum("maxpoints")).add(Projections.rowCount())).add(Restrictions.and(Restrictions.eq("problems.id", problems.getId()), Restrictions.eq("visibility", 1))).uniqueResult();
maxPoints = (Number) o[0];
testCount = (Number) o[1];
}
if (maxPoints == null) {
maxPoints = 0; // To nie <SUF>
}
if (testCount == null) {
testCount = 0; // To nie powinno się zdarzyć nigdy.
}
Query query;
if (allTests == true) {
query = hibernateSession.createSQLQuery(""
+ "select min(id) sid " // zapytanie zewnętrzne znajduję minimalną datę wysłania poprawnego rozwiązania dla każdego usera
+ "from submits "
+ "where id in ("
+ " select submits.id " // zapytanie wewnętrzne znajduje wszystkie id, które zdobyły maksa punktów
+ " from submits,results,tests "
+ " where submits.problemsid = :problemsId "
+ " and submits.id = results.submitsid "
+ " and tests.id = results.testsid "
+ " and results.status = :statusAcc "
+ " and submits.state = :stateDone "
+ " and sdate <= :currentTimestamp "
+ " and sdate >= :visibleTimestamp "
+ " and visibleInRanking=true"
//+ " and tests.visibility=1 "
+ " group by submits.id,usersid,sdate "
+ " having sum(points) = :maxPoints "
+ " and count(points) = :testsCount "
+ " ) "
+ "group by usersid")
.setInteger("problemsId", problems.getId())
.setInteger("statusAcc", ResultsStatusEnum.ACC.getCode())
.setInteger("stateDone", SubmitsStateEnum.DONE.getCode())
.setInteger("maxPoints", maxPoints.intValue())
.setInteger("testCount", testCount.intValue())
.setTimestamp("currentTimestamp", checkTimestamp)
.setTimestamp("visibleTimestamp", visibleTimestamp);
} else {
query = hibernateSession.createSQLQuery(""
+ "select min(id) sid "
+ "from submits "
+ "where id in ("
+ " select submits.id "
+ " from submits,results,tests "
+ " where submits.problemsid = :problemsId "
+ " and submits.id = results.submitsid "
+ " and tests.id = results.testsid "
+ " and results.status = :statusAcc "
+ " and submits.state = :stateDone "
+ " and sdate <= :currentTimestamp "
+ " and sdate >= :visibleTimestamp "
+ " and visibleInRanking=true"
+ " and tests.visibility=1 " // FIXME: should be ok
+ " group by submits.id,usersid,sdate "
+ " having sum(points) = :maxPoints "
+ " and count(points) = :testCount "
+ " ) "
+ "group by usersid")
.setInteger("problemsId", problems.getId())
.setInteger("statusAcc", ResultsStatusEnum.ACC.getCode())
.setInteger("stateDone", SubmitsStateEnum.DONE.getCode())
.setInteger("maxPoints", maxPoints.intValue())
.setInteger("testCount", testCount.intValue())
.setTimestamp("currentTimestamp", checkTimestamp)
.setTimestamp("visibleTimestamp", visibleTimestamp);
}
for (Object id : query.list()) { // tu jest zwrócona lista "zaakceptowanych" w danym momencie rozwiązań zadania
submits.add((Integer) id);
}
}
}
return submits;
}
}
| f |
4582_0 | fpoon/jimp-textgen-java | 415 | src/me/fpoon/textgen/Textgen.java | /*
* PL:
* Program stworzony w ramach edukacji akademickiej na Politechnice Warszawskiej
* Program ten może być rozpowszechniany zgodnie z licencją GPLv3 - tekst licencji dostępny pod adresem http://www.gnu.org/licenses/gpl-3.0.txt
*
* EN:
* This program was made for educational purposes during my education on Warsaw University of Technology
* You can redistribute and modify the following program under the terms of GPLv3 license (http://www.gnu.org/licenses/gpl-3.0.txt)
*/
package me.fpoon.textgen;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.swing.JFrame;
import me.fpoon.textgen.bot.Bot;
import me.fpoon.textgen.gui.MainForm;
import me.fpoon.textgen.gui.DiagramFrame;
/**
*
* @author mariusz
*/
public class Textgen {
/**
*
*/
public static Bot bot;
/**
*
*/
public static DiagramFrame visualWnd;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
bot = new Bot(2);
JFrame mainWnd = (JFrame)new MainForm();
mainWnd.setVisible(true);
/*visualWnd = new DiagramFrame();
visualWnd.setVisible(true);*/
}
}
| /*
* PL:
* Program stworzony w ramach edukacji akademickiej na Politechnice Warszawskiej
* Program ten może być rozpowszechniany zgodnie z licencją GPLv3 - tekst licencji dostępny pod adresem http://www.gnu.org/licenses/gpl-3.0.txt
*
* EN:
* This program was made for educational purposes during my education on Warsaw University of Technology
* You can redistribute and modify the following program under the terms of GPLv3 license (http://www.gnu.org/licenses/gpl-3.0.txt)
*/ | /*
* PL:
* <SUF>*/
package me.fpoon.textgen;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.swing.JFrame;
import me.fpoon.textgen.bot.Bot;
import me.fpoon.textgen.gui.MainForm;
import me.fpoon.textgen.gui.DiagramFrame;
/**
*
* @author mariusz
*/
public class Textgen {
/**
*
*/
public static Bot bot;
/**
*
*/
public static DiagramFrame visualWnd;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
bot = new Bot(2);
JFrame mainWnd = (JFrame)new MainForm();
mainWnd.setVisible(true);
/*visualWnd = new DiagramFrame();
visualWnd.setVisible(true);*/
}
}
| f |
4530_3 | fratik/FratikB0T | 4,824 | commands/src/main/java/pl/fratik/commands/system/PopCommand.java | /*
* Copyright (C) 2019-2021 FratikB0T Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.fratik.commands.system;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.events.guild.GuildBanEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.interactions.components.text.TextInput;
import net.dv8tion.jda.api.interactions.components.text.TextInputStyle;
import net.dv8tion.jda.api.interactions.modals.Modal;
import net.dv8tion.jda.api.sharding.ShardManager;
import org.jetbrains.annotations.NotNull;
import pl.fratik.commands.entity.Blacklist;
import pl.fratik.commands.entity.BlacklistDao;
import pl.fratik.core.Globals;
import pl.fratik.core.Ustawienia;
import pl.fratik.core.cache.Cache;
import pl.fratik.core.cache.RedisCacheManager;
import pl.fratik.core.command.NewCommand;
import pl.fratik.core.command.NewCommandContext;
import pl.fratik.core.tlumaczenia.Language;
import pl.fratik.core.tlumaczenia.Tlumaczenia;
import pl.fratik.core.util.*;
import java.time.Instant;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static java.awt.Color.decode;
public class PopCommand extends NewCommand {
private static final String BUTTON_CLOSE = "CLOSE_POP_REQUEST";
private static final String POP_NEW_REQUEST = "POP_REQUEST";
private static final String POP_REQUEST_MODAL = "POP_REQ_MODAL";
private static final String POP_REQUEST_INPUT = "POP_REQUEST_INPUT";
private final ShardManager shardManager;
private final EventWaiter eventWaiter;
private final EventBus eventBus;
private final Tlumaczenia tlumaczenia;
private final BlacklistDao blacklistDao;
private final Cache<Blacklist> blacklistCache;
boolean bypass = false;
public PopCommand(ShardManager shardManager,
EventWaiter eventWaiter,
EventBus eventBus,
Tlumaczenia tlumaczenia,
BlacklistDao blacklistDao,
RedisCacheManager rcm) {
this.shardManager = shardManager;
this.eventWaiter = eventWaiter;
this.eventBus = eventBus;
this.tlumaczenia = tlumaczenia;
this.blacklistDao = blacklistDao;
blacklistCache = rcm.new CacheRetriever<Blacklist>(){}.getCache();
name = "pop";
cooldown = 10; // TODO: 22.02.19 pomoc 2.0
}
@Override
public boolean permissionCheck(NewCommandContext context) {
if (!context.getGuild().getSelfMember().hasPermission(Permission.CREATE_INSTANT_INVITE)) {
context.replyEphemeral(context.getTranslated("pop.no.perms"));
return false;
}
if (context.getChannel().getType() != ChannelType.TEXT) {
context.replyEphemeral(context.getTranslated("pop.only.text"));
return false;
}
return true;
}
@Override
public void onRegister() {
eventBus.register(this);
}
@Override
public void onUnregister() {
try {eventBus.unregister(this);} catch (Exception ignored) {/*lul*/}
}
@Override
public void execute(@NotNull NewCommandContext context) {
if (!Globals.inFratikDev) throw new IllegalStateException("nie na fdev");
context.defer(true);
Blacklist ubl = blacklistCache.get(context.getSender().getId(), blacklistDao::get);
if (ubl.isBlacklisted()) {
String tag = context.getShardManager().retrieveUserById(ubl.getExecutor()).complete().getAsTag();
context.sendMessage(context.getTranslated("pop.user.blacklisted", tag, ubl.getReason(), tag));
return;
}
Blacklist sbl = blacklistCache.get(context.getGuild().getId(), blacklistDao::get);
if (sbl.isBlacklisted()) {
String tag = context.getShardManager().retrieveUserById(sbl.getExecutor()).complete().getAsTag();
context.sendMessage(context.getTranslated("pop.server.blacklisted", tag, sbl.getReason(), tag));
return;
}
if (context.getGuild().getTimeCreated().toInstant().toEpochMilli() - Instant.now().toEpochMilli() > -1209600000
&& !bypass) {
context.sendMessage(context.getTranslated("pop.server.young"));
return;
}
if (!context.getGuild().getRolesByName(context.getTranslated("pop.role.name"), false).isEmpty()) {
context.sendMessage(context.getTranslated("pop.inprogress"));
return;
}
if (CommonUtil.isPomoc(shardManager, context.getGuild())) {
context.sendMessage(context.getTranslated("pop.pomoc.isset"));
if (UserUtil.isStaff(context.getMember(), shardManager)) {
TextChannel kanal = Objects.requireNonNull(shardManager.getGuildById(Ustawienia.instance.botGuild))
.getTextChannelById(Ustawienia.instance.popChannel);
if (kanal == null) throw new NullPointerException("nieprawidłowy popChannel");
List<Message> wiads = kanal.getHistory().retrievePast(50).complete();
for (Message mess : wiads) {
if (mess.getEmbeds().isEmpty()) continue;
//noinspection ConstantConditions
String id = mess.getEmbeds().get(0).getFooter().getText().split(" \\| ")[1];
if (id.equals(context.getGuild().getId())) {
context.sendMessage(mess.getEmbeds().get(0));
return;
}
}
}
return;
}
Message msg = context.sendMessage(context.getTranslated("pop.start"), ActionRow.of(Button.primary(POP_NEW_REQUEST,
context.getTranslated("pop.new.request.button"))));
ButtonWaiter bw = new ButtonWaiter(eventWaiter, context, msg.getIdLong(), null);
bw.setButtonHandler(e -> {
String id = POP_REQUEST_MODAL + e.getIdLong();
ModalWaiter mw = new ModalWaiter(eventWaiter, context, id, ModalWaiter.ResponseType.REPLY) {
@Override
public void create() {
eventWaiter.waitForEvent(ModalInteractionEvent.class, this::checkReaction,
this::handleReaction, 5, TimeUnit.MINUTES, this::clearReactions);
}
};
mw.setButtonHandler(ev -> {
Role role = context.getGuild().createRole().setColor(decode("#f11515"))
.setName(context.getTranslated("pop.role.name")).setMentionable(false).complete();
context.getChannel().asGuildMessageChannel().getPermissionContainer().getManager().putPermissionOverride(role,
EnumSet.of(Permission.MESSAGE_SEND, Permission.VIEW_CHANNEL), Set.of()).complete();
Invite invite = context.getChannel().asTextChannel().createInvite().setMaxAge(86400).setMaxUses(15)
.reason(context.getTranslated("pop.invite.reason")).complete();
//skonwertowane z js
String permissions = context.getMember().hasPermission(Permission.ADMINISTRATOR) ?
"[ADMIN]" : context.getMember().getPermissions().stream().map(Permission::getName)
.collect(Collectors.joining(", "));
String request = ev.getValue(POP_REQUEST_INPUT).getAsString();
EmbedBuilder eb = new EmbedBuilder()
.setAuthor(context.getSender().getAsTag())
.setFooter("Prośba pomocy! | " + context.getGuild().getId(),
context.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()
.replace(".webp", ".png") + "?size=128")
.addField("Treść prośby", request, false)
.addField("Uprawnienia", permissions, false)
.addField("Zaproszenie na serwer", "zostało wysłane w tej wiadomości.", false)
.addField("Aby zamknąć wiadomość, zareaguj 🗑.", "Pomoc zostanie uznana za gotową.",
false);
Guild fdev = shardManager.getGuildById(Ustawienia.instance.botGuild);
if (fdev == null) throw new IllegalStateException("bot nie na fdev");
TextChannel ch = fdev.getTextChannelById(Ustawienia.instance.popChannel);
if (ch == null) throw new IllegalStateException("nie ma popChannel/nieprawidłowy");
ch.sendMessage("<@&" + Ustawienia.instance.popRole + ">\nhttp://discord.gg/" +
invite.getCode()).setEmbeds(eb.build())
.setActionRow(Button.danger(BUTTON_CLOSE, "Zamknij prośbę"))
.mentionRoles(Ustawienia.instance.popRole).complete();
ev.getHook().sendMessage(context.getTranslated("pop.success")).queue();
TextChannel poplch = fdev.getTextChannelById(Ustawienia.instance.popLogChannel);
if (poplch == null) throw new IllegalStateException("nie ma popLogChannel/nieprawidłowy");
poplch.sendMessage(String.format("%s(%s) wysłał prośbę o pomoc dla serwera %s[%s]\nTreść pomocy to: `%s`." +
"\nJego uprawnienia to %s.",
UserUtil.formatDiscrim(context.getMember()), context.getSender().getId(),
context.getGuild().getName(), context.getGuild().getId(), request, permissions)).complete();
});
mw.setTimeoutHandler(() -> msg.editMessage(context.getTranslated("pop.aborted")).queue(null, x -> {}));
mw.create();
e.replyModal(Modal.create(id, context.getTranslated("pop.request.modal.title"))
.addActionRow(
TextInput.create(POP_REQUEST_INPUT,
context.getTranslated("pop.request.modal.input"), TextInputStyle.PARAGRAPH)
.setRequiredRange(15, 1000).build()
).build()).complete();
msg.editMessage(context.getTranslated("pop.continue.modal")).setComponents(Set.of()).queue(null, x -> {});
});
bw.setTimeoutHandler(() -> msg.editMessage(context.getTranslated("pop.aborted")).queue(null, x -> {}));
bw.create();
}
@Subscribe
public void onGuildBanEvent(GuildBanEvent e) {
Guild fdev = shardManager.getGuildById(Ustawienia.instance.botGuild);
if (fdev == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
TextChannel logi = fdev.getTextChannelById(Ustawienia.instance.popLogChannel);
if (logi == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
if (!UserUtil.isGadm(e.getUser(), shardManager)) return;
if (!CommonUtil.isPomoc(shardManager, e.getGuild())) return;
logi.sendMessage((String.format("%s(%s) dostał bana na serwerze %s[%s]. Czy nie należy się gban?",
UserUtil.formatDiscrim(e.getUser()), e.getUser().getId(),
e.getGuild().getName(), e.getGuild().getId()))).queue();
}
@Subscribe
public void onGuildMemberJoin(GuildMemberJoinEvent e) {
if (!Globals.inFratikDev) return;
Guild fdev = shardManager.getGuildById(Ustawienia.instance.botGuild);
if (fdev == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
TextChannel logi = fdev.getTextChannelById(Ustawienia.instance.popLogChannel);
if (logi == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
if (!UserUtil.isStaff(e.getMember(), shardManager)) return;
Role rola = null;
for (Language lang : Language.values()) {
if (lang == Language.DEFAULT) continue;
if (e.getGuild().getRoles().stream().map(Role::getName).collect(Collectors.toList())
.contains(tlumaczenia.get(lang, "pop.role.name"))) {
rola = e.getGuild().getRoles().stream().filter(r -> r.getName()
.equals(tlumaczenia.get(lang, "pop.role.name"))).findFirst().orElse(null);
break;
}
}
if (rola == null) return;
e.getGuild().addRoleToMember(e.getMember(), rola).queue();
logi.sendMessage((String.format("%s(%s) dołączył na" + " serwer %s[%s]", UserUtil.formatDiscrim(e.getMember()),
e.getUser().getId(), e.getGuild().getName(), e.getGuild().getId()))).queue();
}
@Subscribe
public void onReactionAdd(ButtonInteractionEvent e) {
Guild fdev = shardManager.getGuildById(Ustawienia.instance.botGuild);
if (fdev == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
TextChannel logi = fdev.getTextChannelById(Ustawienia.instance.popLogChannel);
if (logi == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
if (e.getChannel().getId().equals(Ustawienia.instance.popChannel) && e.getComponentId().equals(BUTTON_CLOSE)) {
e.deferEdit().queue();
Message msg;
try {
msg = e.getChannel().retrieveMessageById(e.getMessageIdLong()).complete();
} catch (Exception er) {
//wiadomosci nie ma
return;
}
User user = e.getUser();
//noinspection ConstantConditions
String id = msg.getEmbeds().get(0).getFooter().getText().split(" \\| ")[1];
Guild g = shardManager.getGuildById(id);
try {
msg.delete().complete();
logi.sendMessage((String.format("%s(%s) zamknął" + " prośbę o pomoc serwera %s[%s]",
UserUtil.formatDiscrim(user), user.getId(),
g != null ? g.getName() : "[bot nie na serwerze]", id))).queue();
} catch (Exception ignored) {/*lul*/}
if (g == null) return;
Role rola = null;
for (Language lang : Language.values()) {
if (g.getRoles().stream().map(Role::getName).collect(Collectors.toList())
.contains(tlumaczenia.get(lang, "pop.role.name"))) {
rola = g.getRoles().stream().filter(r -> r.getName()
.equals(tlumaczenia.get(lang, "pop.role.name"))).findFirst().orElse(null);
break;
}
}
if (rola == null) return;
rola.delete().queue();
}
}
}
| //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów | /*
* Copyright (C) 2019-2021 FratikB0T Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.fratik.commands.system;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.events.guild.GuildBanEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.interactions.components.text.TextInput;
import net.dv8tion.jda.api.interactions.components.text.TextInputStyle;
import net.dv8tion.jda.api.interactions.modals.Modal;
import net.dv8tion.jda.api.sharding.ShardManager;
import org.jetbrains.annotations.NotNull;
import pl.fratik.commands.entity.Blacklist;
import pl.fratik.commands.entity.BlacklistDao;
import pl.fratik.core.Globals;
import pl.fratik.core.Ustawienia;
import pl.fratik.core.cache.Cache;
import pl.fratik.core.cache.RedisCacheManager;
import pl.fratik.core.command.NewCommand;
import pl.fratik.core.command.NewCommandContext;
import pl.fratik.core.tlumaczenia.Language;
import pl.fratik.core.tlumaczenia.Tlumaczenia;
import pl.fratik.core.util.*;
import java.time.Instant;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static java.awt.Color.decode;
public class PopCommand extends NewCommand {
private static final String BUTTON_CLOSE = "CLOSE_POP_REQUEST";
private static final String POP_NEW_REQUEST = "POP_REQUEST";
private static final String POP_REQUEST_MODAL = "POP_REQ_MODAL";
private static final String POP_REQUEST_INPUT = "POP_REQUEST_INPUT";
private final ShardManager shardManager;
private final EventWaiter eventWaiter;
private final EventBus eventBus;
private final Tlumaczenia tlumaczenia;
private final BlacklistDao blacklistDao;
private final Cache<Blacklist> blacklistCache;
boolean bypass = false;
public PopCommand(ShardManager shardManager,
EventWaiter eventWaiter,
EventBus eventBus,
Tlumaczenia tlumaczenia,
BlacklistDao blacklistDao,
RedisCacheManager rcm) {
this.shardManager = shardManager;
this.eventWaiter = eventWaiter;
this.eventBus = eventBus;
this.tlumaczenia = tlumaczenia;
this.blacklistDao = blacklistDao;
blacklistCache = rcm.new CacheRetriever<Blacklist>(){}.getCache();
name = "pop";
cooldown = 10; // TODO: 22.02.19 pomoc 2.0
}
@Override
public boolean permissionCheck(NewCommandContext context) {
if (!context.getGuild().getSelfMember().hasPermission(Permission.CREATE_INSTANT_INVITE)) {
context.replyEphemeral(context.getTranslated("pop.no.perms"));
return false;
}
if (context.getChannel().getType() != ChannelType.TEXT) {
context.replyEphemeral(context.getTranslated("pop.only.text"));
return false;
}
return true;
}
@Override
public void onRegister() {
eventBus.register(this);
}
@Override
public void onUnregister() {
try {eventBus.unregister(this);} catch (Exception ignored) {/*lul*/}
}
@Override
public void execute(@NotNull NewCommandContext context) {
if (!Globals.inFratikDev) throw new IllegalStateException("nie na fdev");
context.defer(true);
Blacklist ubl = blacklistCache.get(context.getSender().getId(), blacklistDao::get);
if (ubl.isBlacklisted()) {
String tag = context.getShardManager().retrieveUserById(ubl.getExecutor()).complete().getAsTag();
context.sendMessage(context.getTranslated("pop.user.blacklisted", tag, ubl.getReason(), tag));
return;
}
Blacklist sbl = blacklistCache.get(context.getGuild().getId(), blacklistDao::get);
if (sbl.isBlacklisted()) {
String tag = context.getShardManager().retrieveUserById(sbl.getExecutor()).complete().getAsTag();
context.sendMessage(context.getTranslated("pop.server.blacklisted", tag, sbl.getReason(), tag));
return;
}
if (context.getGuild().getTimeCreated().toInstant().toEpochMilli() - Instant.now().toEpochMilli() > -1209600000
&& !bypass) {
context.sendMessage(context.getTranslated("pop.server.young"));
return;
}
if (!context.getGuild().getRolesByName(context.getTranslated("pop.role.name"), false).isEmpty()) {
context.sendMessage(context.getTranslated("pop.inprogress"));
return;
}
if (CommonUtil.isPomoc(shardManager, context.getGuild())) {
context.sendMessage(context.getTranslated("pop.pomoc.isset"));
if (UserUtil.isStaff(context.getMember(), shardManager)) {
TextChannel kanal = Objects.requireNonNull(shardManager.getGuildById(Ustawienia.instance.botGuild))
.getTextChannelById(Ustawienia.instance.popChannel);
if (kanal == null) throw new NullPointerException("nieprawidłowy popChannel");
List<Message> wiads = kanal.getHistory().retrievePast(50).complete();
for (Message mess : wiads) {
if (mess.getEmbeds().isEmpty()) continue;
//noinspection ConstantConditions
String id = mess.getEmbeds().get(0).getFooter().getText().split(" \\| ")[1];
if (id.equals(context.getGuild().getId())) {
context.sendMessage(mess.getEmbeds().get(0));
return;
}
}
}
return;
}
Message msg = context.sendMessage(context.getTranslated("pop.start"), ActionRow.of(Button.primary(POP_NEW_REQUEST,
context.getTranslated("pop.new.request.button"))));
ButtonWaiter bw = new ButtonWaiter(eventWaiter, context, msg.getIdLong(), null);
bw.setButtonHandler(e -> {
String id = POP_REQUEST_MODAL + e.getIdLong();
ModalWaiter mw = new ModalWaiter(eventWaiter, context, id, ModalWaiter.ResponseType.REPLY) {
@Override
public void create() {
eventWaiter.waitForEvent(ModalInteractionEvent.class, this::checkReaction,
this::handleReaction, 5, TimeUnit.MINUTES, this::clearReactions);
}
};
mw.setButtonHandler(ev -> {
Role role = context.getGuild().createRole().setColor(decode("#f11515"))
.setName(context.getTranslated("pop.role.name")).setMentionable(false).complete();
context.getChannel().asGuildMessageChannel().getPermissionContainer().getManager().putPermissionOverride(role,
EnumSet.of(Permission.MESSAGE_SEND, Permission.VIEW_CHANNEL), Set.of()).complete();
Invite invite = context.getChannel().asTextChannel().createInvite().setMaxAge(86400).setMaxUses(15)
.reason(context.getTranslated("pop.invite.reason")).complete();
//skonwertowane z js
String permissions = context.getMember().hasPermission(Permission.ADMINISTRATOR) ?
"[ADMIN]" : context.getMember().getPermissions().stream().map(Permission::getName)
.collect(Collectors.joining(", "));
String request = ev.getValue(POP_REQUEST_INPUT).getAsString();
EmbedBuilder eb = new EmbedBuilder()
.setAuthor(context.getSender().getAsTag())
.setFooter("Prośba pomocy! | " + context.getGuild().getId(),
context.getGuild().getJDA().getSelfUser().getEffectiveAvatarUrl()
.replace(".webp", ".png") + "?size=128")
.addField("Treść prośby", request, false)
.addField("Uprawnienia", permissions, false)
.addField("Zaproszenie na serwer", "zostało wysłane w tej wiadomości.", false)
.addField("Aby zamknąć wiadomość, zareaguj 🗑.", "Pomoc zostanie uznana za gotową.",
false);
Guild fdev = shardManager.getGuildById(Ustawienia.instance.botGuild);
if (fdev == null) throw new IllegalStateException("bot nie na fdev");
TextChannel ch = fdev.getTextChannelById(Ustawienia.instance.popChannel);
if (ch == null) throw new IllegalStateException("nie ma popChannel/nieprawidłowy");
ch.sendMessage("<@&" + Ustawienia.instance.popRole + ">\nhttp://discord.gg/" +
invite.getCode()).setEmbeds(eb.build())
.setActionRow(Button.danger(BUTTON_CLOSE, "Zamknij prośbę"))
.mentionRoles(Ustawienia.instance.popRole).complete();
ev.getHook().sendMessage(context.getTranslated("pop.success")).queue();
TextChannel poplch = fdev.getTextChannelById(Ustawienia.instance.popLogChannel);
if (poplch == null) throw new IllegalStateException("nie ma popLogChannel/nieprawidłowy");
poplch.sendMessage(String.format("%s(%s) wysłał prośbę o pomoc dla serwera %s[%s]\nTreść pomocy to: `%s`." +
"\nJego uprawnienia to %s.",
UserUtil.formatDiscrim(context.getMember()), context.getSender().getId(),
context.getGuild().getName(), context.getGuild().getId(), request, permissions)).complete();
});
mw.setTimeoutHandler(() -> msg.editMessage(context.getTranslated("pop.aborted")).queue(null, x -> {}));
mw.create();
e.replyModal(Modal.create(id, context.getTranslated("pop.request.modal.title"))
.addActionRow(
TextInput.create(POP_REQUEST_INPUT,
context.getTranslated("pop.request.modal.input"), TextInputStyle.PARAGRAPH)
.setRequiredRange(15, 1000).build()
).build()).complete();
msg.editMessage(context.getTranslated("pop.continue.modal")).setComponents(Set.of()).queue(null, x -> {});
});
bw.setTimeoutHandler(() -> msg.editMessage(context.getTranslated("pop.aborted")).queue(null, x -> {}));
bw.create();
}
@Subscribe
public void onGuildBanEvent(GuildBanEvent e) {
Guild fdev = shardManager.getGuildById(Ustawienia.instance.botGuild);
if (fdev == null) return; //nie możemy <SUF>
TextChannel logi = fdev.getTextChannelById(Ustawienia.instance.popLogChannel);
if (logi == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
if (!UserUtil.isGadm(e.getUser(), shardManager)) return;
if (!CommonUtil.isPomoc(shardManager, e.getGuild())) return;
logi.sendMessage((String.format("%s(%s) dostał bana na serwerze %s[%s]. Czy nie należy się gban?",
UserUtil.formatDiscrim(e.getUser()), e.getUser().getId(),
e.getGuild().getName(), e.getGuild().getId()))).queue();
}
@Subscribe
public void onGuildMemberJoin(GuildMemberJoinEvent e) {
if (!Globals.inFratikDev) return;
Guild fdev = shardManager.getGuildById(Ustawienia.instance.botGuild);
if (fdev == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
TextChannel logi = fdev.getTextChannelById(Ustawienia.instance.popLogChannel);
if (logi == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
if (!UserUtil.isStaff(e.getMember(), shardManager)) return;
Role rola = null;
for (Language lang : Language.values()) {
if (lang == Language.DEFAULT) continue;
if (e.getGuild().getRoles().stream().map(Role::getName).collect(Collectors.toList())
.contains(tlumaczenia.get(lang, "pop.role.name"))) {
rola = e.getGuild().getRoles().stream().filter(r -> r.getName()
.equals(tlumaczenia.get(lang, "pop.role.name"))).findFirst().orElse(null);
break;
}
}
if (rola == null) return;
e.getGuild().addRoleToMember(e.getMember(), rola).queue();
logi.sendMessage((String.format("%s(%s) dołączył na" + " serwer %s[%s]", UserUtil.formatDiscrim(e.getMember()),
e.getUser().getId(), e.getGuild().getName(), e.getGuild().getId()))).queue();
}
@Subscribe
public void onReactionAdd(ButtonInteractionEvent e) {
Guild fdev = shardManager.getGuildById(Ustawienia.instance.botGuild);
if (fdev == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
TextChannel logi = fdev.getTextChannelById(Ustawienia.instance.popLogChannel);
if (logi == null) return; //nie możemy throw'nąć bo to mogło być podczas ładowania shard'ów
if (e.getChannel().getId().equals(Ustawienia.instance.popChannel) && e.getComponentId().equals(BUTTON_CLOSE)) {
e.deferEdit().queue();
Message msg;
try {
msg = e.getChannel().retrieveMessageById(e.getMessageIdLong()).complete();
} catch (Exception er) {
//wiadomosci nie ma
return;
}
User user = e.getUser();
//noinspection ConstantConditions
String id = msg.getEmbeds().get(0).getFooter().getText().split(" \\| ")[1];
Guild g = shardManager.getGuildById(id);
try {
msg.delete().complete();
logi.sendMessage((String.format("%s(%s) zamknął" + " prośbę o pomoc serwera %s[%s]",
UserUtil.formatDiscrim(user), user.getId(),
g != null ? g.getName() : "[bot nie na serwerze]", id))).queue();
} catch (Exception ignored) {/*lul*/}
if (g == null) return;
Role rola = null;
for (Language lang : Language.values()) {
if (g.getRoles().stream().map(Role::getName).collect(Collectors.toList())
.contains(tlumaczenia.get(lang, "pop.role.name"))) {
rola = g.getRoles().stream().filter(r -> r.getName()
.equals(tlumaczenia.get(lang, "pop.role.name"))).findFirst().orElse(null);
break;
}
}
if (rola == null) return;
rola.delete().queue();
}
}
}
| f |
9379_11 | geraltdwf/University | 1,744 | Java/z34.java | import java.awt.*;
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class z34 {
public static void main(String[] args){
HumanList humanList = new HumanList(5);
humanList.displayList();
Scanner object = new Scanner(System.in);
String name = object.nextLine();
String name_2 = object.nextLine();
Integer wiek_xd = object.nextInt();
Human hujman = new Human(name, name_2, wiek_xd);
humanList.addToList(hujman);
Scanner object_2 = new Scanner(System.in);
String remove_name = object_2.nextLine();
humanList.removeFromList(remove_name);
humanList.youngDis();
}
}
class Human{
private String nazwisko;
String imie;
Integer wiek;
public Human(){
}
public Human(String nazwisko, String imie,Integer wiek){
this.nazwisko = nazwisko;
this.imie = imie;
this.wiek = wiek;
}
public Integer getWiek() {
return wiek;
}
public String getNazwisko(){
return nazwisko;
}
public String getImie(){
return imie;
}
}
class HumanList {
List<Human> lista = new ArrayList<>();
String[] imie = {"KAMIL", "TOMASZ", "MIKOLAJ", "MICHAL", "PANPAWEL", "ROMAN"};
String[] nazwisko = {"BORZYCH", "TEREFER", "MIRAKOWICZ", "MIRAKOWSKI", "PAZDZIOCH"};
public HumanList(int x) {
Random rand = new Random();
for (int i = 0; i < x; i++) {
this.lista.add(new Human(nazwisko[rand.nextInt(nazwisko.length)],imie[rand.nextInt(imie.length)], rand.nextInt(70)));
}
}
public void displayList() {
System.out.println("Lista ludzi:");
for (int i = 0; i < lista.size(); i++) {
System.out.format("| %-8s | %-8s | %d", lista.get(i).getNazwisko(), lista.get(i).getImie(), lista.get(i).getWiek());
System.out.println();
}
}
public void removeFromList(String nazwisko) {
boolean validate = false;
for (int i = 0; i < lista.size(); i++) {
if (nazwisko.equals(lista.get(i).getNazwisko())) {
System.out.println("Usuwam: " + lista.get(i).getNazwisko());
lista.remove(i);
validate = true;
break;
}
}
if (validate == false) {
System.out.println("nie ma takiej osoby");
}
}
public void addToList(Human human) {
boolean Validate = true;
for (int i = 0; i < lista.size(); i++) {
System.out.println(human.getNazwisko() + " == " + lista.get(i).getNazwisko());
if (human.getNazwisko().equals(lista.get(i).getNazwisko())) {
Validate = false;
System.out.println("xd");
break;
}
}
if (Validate == true) {
System.out.println("DODANE");
lista.add(human);
} else {
System.out.println(("Osoba o takim nazwisko juz jest"));
}
}
public void youngDis() {
int age = lista.get(0).getWiek();
int young_index = 0;
for (int i = 1; i < lista.size(); i++) {
if (lista.get(i).getWiek() < age) {
age = lista.get(i).getWiek();
young_index = i;
}
}
System.out.println("Najmlodsza oosba ma lat: " + lista.get(young_index).getWiek());
}
}
//%b dowolny interpretuje argument jako wartość logiczną
//%s dowolny interpretuje argument jako łańcuch znaków
//%d liczba całkowita interpretuje argument jako liczbę całkowitą
//%o liczba całkowita interpretuje argument jako liczbę całkowitą zapisaną w systemie ósemkowym
//%x liczba całkowita interpretuje argument jako liczbę całkowitą zapisaną w systemie szesnastkowym
//%f liczba zmiennoprzecinkowa interpretuje argument jako liczbę zmiennoprzecinkową
//%% - nie potrzebuje argumentu, jest to sposób na umieszczenie znaku % wewnątrz sformatowanego łańcucha znaków
//%n - nie potrzebuje argumentu, jest to sposób na umieszczenie znaku nowej linii wewnątrz sformatowanego łańcucha znaków
// - element będzie wyrównany do lewej strony,
// + liczba zawsze będzie zawierała znak (nawet jeśli jest dodatnia),
// 0 liczba będzie uzupełniona 0 do żądanej szerokości,
// ( liczby ujemne nie będą prezentowane ze znakiem, będą otoczone (),
// , użyj separatora do grupowania liczb. Ten separator zależny jest od lokalizacji.
//double someNumber = 12345.12;
//System.out.format(Locale.US, "%,.2f%n", someNumber);
// System.out.format(Locale.GERMAN, "%,.2f%n", someNumber);
// System.out.format(Locale.forLanguageTag("PL"), "%,.2f%n", someNumber);
// 12,345.12
// 12.345,12
// 12 345,12 | // ( liczby ujemne nie będą prezentowane ze znakiem, będą otoczone (),
| import java.awt.*;
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class z34 {
public static void main(String[] args){
HumanList humanList = new HumanList(5);
humanList.displayList();
Scanner object = new Scanner(System.in);
String name = object.nextLine();
String name_2 = object.nextLine();
Integer wiek_xd = object.nextInt();
Human hujman = new Human(name, name_2, wiek_xd);
humanList.addToList(hujman);
Scanner object_2 = new Scanner(System.in);
String remove_name = object_2.nextLine();
humanList.removeFromList(remove_name);
humanList.youngDis();
}
}
class Human{
private String nazwisko;
String imie;
Integer wiek;
public Human(){
}
public Human(String nazwisko, String imie,Integer wiek){
this.nazwisko = nazwisko;
this.imie = imie;
this.wiek = wiek;
}
public Integer getWiek() {
return wiek;
}
public String getNazwisko(){
return nazwisko;
}
public String getImie(){
return imie;
}
}
class HumanList {
List<Human> lista = new ArrayList<>();
String[] imie = {"KAMIL", "TOMASZ", "MIKOLAJ", "MICHAL", "PANPAWEL", "ROMAN"};
String[] nazwisko = {"BORZYCH", "TEREFER", "MIRAKOWICZ", "MIRAKOWSKI", "PAZDZIOCH"};
public HumanList(int x) {
Random rand = new Random();
for (int i = 0; i < x; i++) {
this.lista.add(new Human(nazwisko[rand.nextInt(nazwisko.length)],imie[rand.nextInt(imie.length)], rand.nextInt(70)));
}
}
public void displayList() {
System.out.println("Lista ludzi:");
for (int i = 0; i < lista.size(); i++) {
System.out.format("| %-8s | %-8s | %d", lista.get(i).getNazwisko(), lista.get(i).getImie(), lista.get(i).getWiek());
System.out.println();
}
}
public void removeFromList(String nazwisko) {
boolean validate = false;
for (int i = 0; i < lista.size(); i++) {
if (nazwisko.equals(lista.get(i).getNazwisko())) {
System.out.println("Usuwam: " + lista.get(i).getNazwisko());
lista.remove(i);
validate = true;
break;
}
}
if (validate == false) {
System.out.println("nie ma takiej osoby");
}
}
public void addToList(Human human) {
boolean Validate = true;
for (int i = 0; i < lista.size(); i++) {
System.out.println(human.getNazwisko() + " == " + lista.get(i).getNazwisko());
if (human.getNazwisko().equals(lista.get(i).getNazwisko())) {
Validate = false;
System.out.println("xd");
break;
}
}
if (Validate == true) {
System.out.println("DODANE");
lista.add(human);
} else {
System.out.println(("Osoba o takim nazwisko juz jest"));
}
}
public void youngDis() {
int age = lista.get(0).getWiek();
int young_index = 0;
for (int i = 1; i < lista.size(); i++) {
if (lista.get(i).getWiek() < age) {
age = lista.get(i).getWiek();
young_index = i;
}
}
System.out.println("Najmlodsza oosba ma lat: " + lista.get(young_index).getWiek());
}
}
//%b dowolny interpretuje argument jako wartość logiczną
//%s dowolny interpretuje argument jako łańcuch znaków
//%d liczba całkowita interpretuje argument jako liczbę całkowitą
//%o liczba całkowita interpretuje argument jako liczbę całkowitą zapisaną w systemie ósemkowym
//%x liczba całkowita interpretuje argument jako liczbę całkowitą zapisaną w systemie szesnastkowym
//%f liczba zmiennoprzecinkowa interpretuje argument jako liczbę zmiennoprzecinkową
//%% - nie potrzebuje argumentu, jest to sposób na umieszczenie znaku % wewnątrz sformatowanego łańcucha znaków
//%n - nie potrzebuje argumentu, jest to sposób na umieszczenie znaku nowej linii wewnątrz sformatowanego łańcucha znaków
// - element będzie wyrównany do lewej strony,
// + liczba zawsze będzie zawierała znak (nawet jeśli jest dodatnia),
// 0 liczba będzie uzupełniona 0 do żądanej szerokości,
// ( liczby <SUF>
// , użyj separatora do grupowania liczb. Ten separator zależny jest od lokalizacji.
//double someNumber = 12345.12;
//System.out.format(Locale.US, "%,.2f%n", someNumber);
// System.out.format(Locale.GERMAN, "%,.2f%n", someNumber);
// System.out.format(Locale.forLanguageTag("PL"), "%,.2f%n", someNumber);
// 12,345.12
// 12.345,12
// 12 345,12 | f |
3745_0 | golemfactory/yajapi | 2,071 | yajapi/src/main/java/network/golem/yajapi/adapter/SendAdapter.java | package network.golem.yajapi.adapter;
import network.golem.yajapi.activity.models.ExeScriptRequest;
import network.golem.yajapi.market.models.Agreement;
import network.golem.yajapi.market.models.AgreementProposal;
import network.golem.yajapi.market.models.Demand;
import network.golem.yajapi.market.models.Proposal;
import network.golem.yajapi.payment.models.Acceptance;
import network.golem.yajapi.payment.models.Account;
import network.golem.yajapi.payment.models.Allocation;
import network.golem.yajapi.payment.models.Rejection;
import java.math.BigDecimal;
import java.util.List;
public class SendAdapter {
private static SendAdapter instance;
public static synchronized SendAdapter getInstance() {
if (instance != null)
return instance;
instance = new SendAdapter();
return instance;
}
private final network.golem.yajapi.payment.apis.RequestorApi paymentRequestorApi = new network.golem.yajapi.payment.apis.RequestorApi();
private final network.golem.yajapi.activity.apis.RequestorStateApi activityRequestorStateApi = new network.golem.yajapi.activity.apis.RequestorStateApi();
private final network.golem.yajapi.activity.apis.RequestorControlApi activityRequestorControlApi = new network.golem.yajapi.activity.apis.RequestorControlApi();
private final network.golem.yajapi.market.apis.RequestorApi marketRequestorApi = new network.golem.yajapi.market.apis.RequestorApi();
private SendAdapter() {
ApiInitializer.initialize();
}
public synchronized List<Account> getSendAccounts() throws ApiException {
try {
return paymentRequestorApi.getSendAccounts();
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public synchronized Allocation createAllocation(Allocation allocation) throws ApiException {
try {
return paymentRequestorApi.createAllocation(allocation);
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String subscribeDemand(Demand demand) throws ApiException {
try {
String demandId = marketRequestorApi.subscribeDemand(demand);
if (demandId.charAt(0) == '"') { //nie wiem dlaczego ale Yagna dodaje ciapki
demandId = demandId.substring(1, demandId.length() - 1);
}
return demandId;
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String createAgreement(AgreementProposal agreementProposal) throws ApiException {
try {
String agreementId = marketRequestorApi.createAgreement(agreementProposal);
if (agreementId.charAt(0) == '"') { //nie wiem dlaczego ale Yagna dodaje ciapki
agreementId = agreementId.substring(1, agreementId.length() - 1);
}
return agreementId;
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized Agreement getAgreement(String agreementId) throws ApiException {
try {
return marketRequestorApi.getAgreement(agreementId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void confirmAgreement(String agreementId) throws ApiException {
try {
marketRequestorApi.confirmAgreement(agreementId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized Proposal getProposalOffer(String demandId, String proposalId) throws ApiException {
try {
return marketRequestorApi.getProposalOffer(demandId, proposalId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String counterProposalDemand(Proposal counterProposal, String demandId, String proposalId) throws ApiException {
try {
String counterProposalId = marketRequestorApi.counterProposalDemand(counterProposal, demandId, proposalId);
if (counterProposalId.charAt(0) == '"') { //nie wiem dlaczego ale Yagna dodaje ciapki
counterProposalId = counterProposalId.substring(1, counterProposalId.length() - 1);
}
return counterProposalId;
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String createActivity(String agreementId) throws ApiException {
try {
String activityId = activityRequestorControlApi.createActivity('"' + agreementId + '"');
if (activityId.charAt(0) == '"') {
activityId = activityId.substring(1, activityId.length() - 1);
}
return activityId;
} catch (network.golem.yajapi.activity.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void destroyActivity(String activityId) throws ApiException {
try {
activityRequestorControlApi.destroyActivity(activityId);
} catch (network.golem.yajapi.activity.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String exec(ExeScriptRequest script, String activityId) throws ApiException {
try {
String batchId = activityRequestorControlApi.exec(script, activityId);
if (batchId.charAt(0) == '"') {
batchId = batchId.substring(1, batchId.length()-1);
}
return batchId;
} catch (network.golem.yajapi.activity.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void unsubscribeDemand(String demandId) throws ApiException {
try {
marketRequestorApi.unsubscribeDemand(demandId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void releaseAllocation(String allocationId) throws ApiException {
try {
paymentRequestorApi.releaseAllocation(allocationId);
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void acceptInvoice(Acceptance acceptance, String invoiceId, BigDecimal timeout) throws ApiException {
try {
paymentRequestorApi.acceptInvoice(acceptance, invoiceId, timeout);
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public void rejectInvoice(Rejection rejection, String invoiceId, BigDecimal timeout) throws ApiException {
try {
paymentRequestorApi.rejectInvoice(rejection, invoiceId, timeout);
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public void terminateAgreement(String agreementId) throws ApiException {
try {
marketRequestorApi.terminateAgreement(agreementId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
}
| //nie wiem dlaczego ale Yagna dodaje ciapki | package network.golem.yajapi.adapter;
import network.golem.yajapi.activity.models.ExeScriptRequest;
import network.golem.yajapi.market.models.Agreement;
import network.golem.yajapi.market.models.AgreementProposal;
import network.golem.yajapi.market.models.Demand;
import network.golem.yajapi.market.models.Proposal;
import network.golem.yajapi.payment.models.Acceptance;
import network.golem.yajapi.payment.models.Account;
import network.golem.yajapi.payment.models.Allocation;
import network.golem.yajapi.payment.models.Rejection;
import java.math.BigDecimal;
import java.util.List;
public class SendAdapter {
private static SendAdapter instance;
public static synchronized SendAdapter getInstance() {
if (instance != null)
return instance;
instance = new SendAdapter();
return instance;
}
private final network.golem.yajapi.payment.apis.RequestorApi paymentRequestorApi = new network.golem.yajapi.payment.apis.RequestorApi();
private final network.golem.yajapi.activity.apis.RequestorStateApi activityRequestorStateApi = new network.golem.yajapi.activity.apis.RequestorStateApi();
private final network.golem.yajapi.activity.apis.RequestorControlApi activityRequestorControlApi = new network.golem.yajapi.activity.apis.RequestorControlApi();
private final network.golem.yajapi.market.apis.RequestorApi marketRequestorApi = new network.golem.yajapi.market.apis.RequestorApi();
private SendAdapter() {
ApiInitializer.initialize();
}
public synchronized List<Account> getSendAccounts() throws ApiException {
try {
return paymentRequestorApi.getSendAccounts();
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public synchronized Allocation createAllocation(Allocation allocation) throws ApiException {
try {
return paymentRequestorApi.createAllocation(allocation);
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String subscribeDemand(Demand demand) throws ApiException {
try {
String demandId = marketRequestorApi.subscribeDemand(demand);
if (demandId.charAt(0) == '"') { //nie wiem <SUF>
demandId = demandId.substring(1, demandId.length() - 1);
}
return demandId;
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String createAgreement(AgreementProposal agreementProposal) throws ApiException {
try {
String agreementId = marketRequestorApi.createAgreement(agreementProposal);
if (agreementId.charAt(0) == '"') { //nie wiem dlaczego ale Yagna dodaje ciapki
agreementId = agreementId.substring(1, agreementId.length() - 1);
}
return agreementId;
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized Agreement getAgreement(String agreementId) throws ApiException {
try {
return marketRequestorApi.getAgreement(agreementId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void confirmAgreement(String agreementId) throws ApiException {
try {
marketRequestorApi.confirmAgreement(agreementId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized Proposal getProposalOffer(String demandId, String proposalId) throws ApiException {
try {
return marketRequestorApi.getProposalOffer(demandId, proposalId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String counterProposalDemand(Proposal counterProposal, String demandId, String proposalId) throws ApiException {
try {
String counterProposalId = marketRequestorApi.counterProposalDemand(counterProposal, demandId, proposalId);
if (counterProposalId.charAt(0) == '"') { //nie wiem dlaczego ale Yagna dodaje ciapki
counterProposalId = counterProposalId.substring(1, counterProposalId.length() - 1);
}
return counterProposalId;
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String createActivity(String agreementId) throws ApiException {
try {
String activityId = activityRequestorControlApi.createActivity('"' + agreementId + '"');
if (activityId.charAt(0) == '"') {
activityId = activityId.substring(1, activityId.length() - 1);
}
return activityId;
} catch (network.golem.yajapi.activity.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void destroyActivity(String activityId) throws ApiException {
try {
activityRequestorControlApi.destroyActivity(activityId);
} catch (network.golem.yajapi.activity.ApiException e) {
throw new ApiException(e);
}
}
public synchronized String exec(ExeScriptRequest script, String activityId) throws ApiException {
try {
String batchId = activityRequestorControlApi.exec(script, activityId);
if (batchId.charAt(0) == '"') {
batchId = batchId.substring(1, batchId.length()-1);
}
return batchId;
} catch (network.golem.yajapi.activity.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void unsubscribeDemand(String demandId) throws ApiException {
try {
marketRequestorApi.unsubscribeDemand(demandId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void releaseAllocation(String allocationId) throws ApiException {
try {
paymentRequestorApi.releaseAllocation(allocationId);
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public synchronized void acceptInvoice(Acceptance acceptance, String invoiceId, BigDecimal timeout) throws ApiException {
try {
paymentRequestorApi.acceptInvoice(acceptance, invoiceId, timeout);
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public void rejectInvoice(Rejection rejection, String invoiceId, BigDecimal timeout) throws ApiException {
try {
paymentRequestorApi.rejectInvoice(rejection, invoiceId, timeout);
} catch (network.golem.yajapi.payment.ApiException e) {
throw new ApiException(e);
}
}
public void terminateAgreement(String agreementId) throws ApiException {
try {
marketRequestorApi.terminateAgreement(agreementId);
} catch (network.golem.yajapi.market.ApiException e) {
throw new ApiException(e);
}
}
}
| f |
1552_12 | google/guava | 6,645 | android/guava/src/com/google/common/collect/TreeRangeMap.java | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.CheckForNull;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know ( ]
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
| // we know ( ] | /*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.compose;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.MoreObjects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps.IteratorBasedAbstractMap;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.CheckForNull;
/**
* An implementation of {@code RangeMap} based on a {@code TreeMap}, supporting all optional
* operations.
*
* <p>Like all {@code RangeMap} implementations, this supports neither null keys nor null values.
*
* @author Louis Wasserman
* @since 14.0
*/
@SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
@GwtIncompatible // NavigableMap
@ElementTypesAreNonnullByDefault
public final class TreeRangeMap<K extends Comparable, V> implements RangeMap<K, V> {
private final NavigableMap<Cut<K>, RangeMapEntry<K, V>> entriesByLowerBound;
public static <K extends Comparable, V> TreeRangeMap<K, V> create() {
return new TreeRangeMap<>();
}
private TreeRangeMap() {
this.entriesByLowerBound = Maps.newTreeMap();
}
private static final class RangeMapEntry<K extends Comparable, V>
extends AbstractMapEntry<Range<K>, V> {
private final Range<K> range;
private final V value;
RangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
this(Range.create(lowerBound, upperBound), value);
}
RangeMapEntry(Range<K> range, V value) {
this.range = range;
this.value = value;
}
@Override
public Range<K> getKey() {
return range;
}
@Override
public V getValue() {
return value;
}
public boolean contains(K value) {
return range.contains(value);
}
Cut<K> getLowerBound() {
return range.lowerBound;
}
Cut<K> getUpperBound() {
return range.upperBound;
}
}
@Override
@CheckForNull
public V get(K key) {
Entry<Range<K>, V> entry = getEntry(key);
return (entry == null) ? null : entry.getValue();
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntry =
entriesByLowerBound.floorEntry(Cut.belowValue(key));
if (mapEntry != null && mapEntry.getValue().contains(key)) {
return mapEntry.getValue();
} else {
return null;
}
}
@Override
public void put(Range<K> range, V value) {
if (!range.isEmpty()) {
checkNotNull(value);
remove(range);
entriesByLowerBound.put(range.lowerBound, new RangeMapEntry<K, V>(range, value));
}
}
@Override
public void putCoalescing(Range<K> range, V value) {
// don't short-circuit if the range is empty - it may be between two ranges we can coalesce.
if (entriesByLowerBound.isEmpty()) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
put(coalescedRange, value);
}
/** Computes the coalesced range for the given range+value - does not mutate the map. */
private Range<K> coalescedRange(Range<K> range, V value) {
Range<K> coalescedRange = range;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.lowerEntry(range.lowerBound);
coalescedRange = coalesce(coalescedRange, value, lowerEntry);
Entry<Cut<K>, RangeMapEntry<K, V>> higherEntry =
entriesByLowerBound.floorEntry(range.upperBound);
coalescedRange = coalesce(coalescedRange, value, higherEntry);
return coalescedRange;
}
/** Returns the range that spans the given range and entry, if the entry can be coalesced. */
private static <K extends Comparable, V> Range<K> coalesce(
Range<K> range, V value, @CheckForNull Entry<Cut<K>, RangeMapEntry<K, V>> entry) {
if (entry != null
&& entry.getValue().getKey().isConnected(range)
&& entry.getValue().getValue().equals(value)) {
return range.span(entry.getValue().getKey());
}
return range;
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
for (Entry<Range<K>, ? extends V> entry : rangeMap.asMapOfRanges().entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
entriesByLowerBound.clear();
}
@Override
public Range<K> span() {
Entry<Cut<K>, RangeMapEntry<K, V>> firstEntry = entriesByLowerBound.firstEntry();
Entry<Cut<K>, RangeMapEntry<K, V>> lastEntry = entriesByLowerBound.lastEntry();
// Either both are null or neither is, but we check both to satisfy the nullness checker.
if (firstEntry == null || lastEntry == null) {
throw new NoSuchElementException();
}
return Range.create(
firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound);
}
private void putRangeMapEntry(Cut<K> lowerBound, Cut<K> upperBound, V value) {
entriesByLowerBound.put(lowerBound, new RangeMapEntry<K, V>(lowerBound, upperBound, value));
}
@Override
public void remove(Range<K> rangeToRemove) {
if (rangeToRemove.isEmpty()) {
return;
}
/*
* The comments for this method will use [ ] to indicate the bounds of rangeToRemove and ( ) to
* indicate the bounds of ranges in the range map.
*/
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryBelowToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.lowerBound);
if (mapEntryBelowToTruncate != null) {
// we know ( [
RangeMapEntry<K, V> rangeMapEntry = mapEntryBelowToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.lowerBound) > 0) {
// we know ( [ )
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( [ ] ), so insert the range ] ) back into the map --
// it's being split apart
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryBelowToTruncate.getValue().getValue());
}
// overwrite mapEntryToTruncateBelow with a truncated range
putRangeMapEntry(
rangeMapEntry.getLowerBound(),
rangeToRemove.lowerBound,
mapEntryBelowToTruncate.getValue().getValue());
}
}
Entry<Cut<K>, RangeMapEntry<K, V>> mapEntryAboveToTruncate =
entriesByLowerBound.lowerEntry(rangeToRemove.upperBound);
if (mapEntryAboveToTruncate != null) {
// we know <SUF>
RangeMapEntry<K, V> rangeMapEntry = mapEntryAboveToTruncate.getValue();
if (rangeMapEntry.getUpperBound().compareTo(rangeToRemove.upperBound) > 0) {
// we know ( ] ), and since we dealt with truncating below already,
// we know [ ( ] )
putRangeMapEntry(
rangeToRemove.upperBound,
rangeMapEntry.getUpperBound(),
mapEntryAboveToTruncate.getValue().getValue());
}
}
entriesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear();
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.values());
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new AsMapOfRanges(entriesByLowerBound.descendingMap().values());
}
private final class AsMapOfRanges extends IteratorBasedAbstractMap<Range<K>, V> {
final Iterable<Entry<Range<K>, V>> entryIterable;
@SuppressWarnings("unchecked") // it's safe to upcast iterables
AsMapOfRanges(Iterable<RangeMapEntry<K, V>> entryIterable) {
this.entryIterable = (Iterable) entryIterable;
}
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
if (key instanceof Range) {
Range<?> range = (Range<?>) key;
RangeMapEntry<K, V> rangeMapEntry = entriesByLowerBound.get(range.lowerBound);
if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) {
return rangeMapEntry.getValue();
}
}
return null;
}
@Override
public int size() {
return entriesByLowerBound.size();
}
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
return entryIterable.iterator();
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> subRange) {
if (subRange.equals(Range.all())) {
return this;
} else {
return new SubRangeMap(subRange);
}
}
@SuppressWarnings("unchecked")
private RangeMap<K, V> emptySubRangeMap() {
return (RangeMap<K, V>) (RangeMap<?, ?>) EMPTY_SUB_RANGE_MAP;
}
@SuppressWarnings("ConstantCaseForConstants") // This RangeMap is immutable.
private static final RangeMap<Comparable<?>, Object> EMPTY_SUB_RANGE_MAP =
new RangeMap<Comparable<?>, Object>() {
@Override
@CheckForNull
public Object get(Comparable<?> key) {
return null;
}
@Override
@CheckForNull
public Entry<Range<Comparable<?>>, Object> getEntry(Comparable<?> key) {
return null;
}
@Override
public Range<Comparable<?>> span() {
throw new NoSuchElementException();
}
@Override
public void put(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putCoalescing(Range<Comparable<?>> range, Object value) {
checkNotNull(range);
throw new IllegalArgumentException(
"Cannot insert range " + range + " into an empty subRangeMap");
}
@Override
public void putAll(RangeMap<Comparable<?>, ? extends Object> rangeMap) {
if (!rangeMap.asMapOfRanges().isEmpty()) {
throw new IllegalArgumentException(
"Cannot putAll(nonEmptyRangeMap) into an empty subRangeMap");
}
}
@Override
public void clear() {}
@Override
public void remove(Range<Comparable<?>> range) {
checkNotNull(range);
}
@Override
public Map<Range<Comparable<?>>, Object> asMapOfRanges() {
return Collections.emptyMap();
}
@Override
public Map<Range<Comparable<?>>, Object> asDescendingMapOfRanges() {
return Collections.emptyMap();
}
@Override
public RangeMap<Comparable<?>, Object> subRangeMap(Range<Comparable<?>> range) {
checkNotNull(range);
return this;
}
};
private class SubRangeMap implements RangeMap<K, V> {
private final Range<K> subRange;
SubRangeMap(Range<K> subRange) {
this.subRange = subRange;
}
@Override
@CheckForNull
public V get(K key) {
return subRange.contains(key) ? TreeRangeMap.this.get(key) : null;
}
@Override
@CheckForNull
public Entry<Range<K>, V> getEntry(K key) {
if (subRange.contains(key)) {
Entry<Range<K>, V> entry = TreeRangeMap.this.getEntry(key);
if (entry != null) {
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return null;
}
@Override
public Range<K> span() {
Cut<K> lowerBound;
Entry<Cut<K>, RangeMapEntry<K, V>> lowerEntry =
entriesByLowerBound.floorEntry(subRange.lowerBound);
if (lowerEntry != null
&& lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) {
lowerBound = subRange.lowerBound;
} else {
lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound);
if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) {
throw new NoSuchElementException();
}
}
Cut<K> upperBound;
Entry<Cut<K>, RangeMapEntry<K, V>> upperEntry =
entriesByLowerBound.lowerEntry(subRange.upperBound);
if (upperEntry == null) {
throw new NoSuchElementException();
} else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) {
upperBound = subRange.upperBound;
} else {
upperBound = upperEntry.getValue().getUpperBound();
}
return Range.create(lowerBound, upperBound);
}
@Override
public void put(Range<K> range, V value) {
checkArgument(
subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange);
TreeRangeMap.this.put(range, value);
}
@Override
public void putCoalescing(Range<K> range, V value) {
if (entriesByLowerBound.isEmpty() || !subRange.encloses(range)) {
put(range, value);
return;
}
Range<K> coalescedRange = coalescedRange(range, checkNotNull(value));
// only coalesce ranges within the subRange
put(coalescedRange.intersection(subRange), value);
}
@Override
public void putAll(RangeMap<K, ? extends V> rangeMap) {
if (rangeMap.asMapOfRanges().isEmpty()) {
return;
}
Range<K> span = rangeMap.span();
checkArgument(
subRange.encloses(span),
"Cannot putAll rangeMap with span %s into a subRangeMap(%s)",
span,
subRange);
TreeRangeMap.this.putAll(rangeMap);
}
@Override
public void clear() {
TreeRangeMap.this.remove(subRange);
}
@Override
public void remove(Range<K> range) {
if (range.isConnected(subRange)) {
TreeRangeMap.this.remove(range.intersection(subRange));
}
}
@Override
public RangeMap<K, V> subRangeMap(Range<K> range) {
if (!range.isConnected(subRange)) {
return emptySubRangeMap();
} else {
return TreeRangeMap.this.subRangeMap(range.intersection(subRange));
}
}
@Override
public Map<Range<K>, V> asMapOfRanges() {
return new SubRangeMapAsMap();
}
@Override
public Map<Range<K>, V> asDescendingMapOfRanges() {
return new SubRangeMapAsMap() {
@Override
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound
.headMap(subRange.upperBound, false)
.descendingMap()
.values()
.iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
if (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getUpperBound().compareTo(subRange.lowerBound) <= 0) {
return endOfData();
}
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
return endOfData();
}
};
}
};
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return asMapOfRanges().toString();
}
class SubRangeMapAsMap extends AbstractMap<Range<K>, V> {
@Override
public boolean containsKey(@CheckForNull Object key) {
return get(key) != null;
}
@Override
@CheckForNull
public V get(@CheckForNull Object key) {
try {
if (key instanceof Range) {
@SuppressWarnings("unchecked") // we catch ClassCastExceptions
Range<K> r = (Range<K>) key;
if (!subRange.encloses(r) || r.isEmpty()) {
return null;
}
RangeMapEntry<K, V> candidate = null;
if (r.lowerBound.compareTo(subRange.lowerBound) == 0) {
// r could be truncated on the left
Entry<Cut<K>, RangeMapEntry<K, V>> entry =
entriesByLowerBound.floorEntry(r.lowerBound);
if (entry != null) {
candidate = entry.getValue();
}
} else {
candidate = entriesByLowerBound.get(r.lowerBound);
}
if (candidate != null
&& candidate.getKey().isConnected(subRange)
&& candidate.getKey().intersection(subRange).equals(r)) {
return candidate.getValue();
}
}
} catch (ClassCastException e) {
return null;
}
return null;
}
@Override
@CheckForNull
public V remove(@CheckForNull Object key) {
V value = get(key);
if (value != null) {
// it's definitely in the map, so the cast and requireNonNull are safe
@SuppressWarnings("unchecked")
Range<K> range = (Range<K>) requireNonNull(key);
TreeRangeMap.this.remove(range);
return value;
}
return null;
}
@Override
public void clear() {
SubRangeMap.this.clear();
}
private boolean removeEntryIf(Predicate<? super Entry<Range<K>, V>> predicate) {
List<Range<K>> toRemove = Lists.newArrayList();
for (Entry<Range<K>, V> entry : entrySet()) {
if (predicate.apply(entry)) {
toRemove.add(entry.getKey());
}
}
for (Range<K> range : toRemove) {
TreeRangeMap.this.remove(range);
}
return !toRemove.isEmpty();
}
@Override
public Set<Range<K>> keySet() {
return new Maps.KeySet<Range<K>, V>(SubRangeMapAsMap.this) {
@Override
public boolean remove(@CheckForNull Object o) {
return SubRangeMapAsMap.this.remove(o) != null;
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<Range<K>>keyFunction()));
}
};
}
@Override
public Set<Entry<Range<K>, V>> entrySet() {
return new Maps.EntrySet<Range<K>, V>() {
@Override
Map<Range<K>, V> map() {
return SubRangeMapAsMap.this;
}
@Override
public Iterator<Entry<Range<K>, V>> iterator() {
return entryIterator();
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(not(in(c)));
}
@Override
public int size() {
return Iterators.size(iterator());
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
};
}
Iterator<Entry<Range<K>, V>> entryIterator() {
if (subRange.isEmpty()) {
return Iterators.emptyIterator();
}
Cut<K> cutToStart =
MoreObjects.firstNonNull(
entriesByLowerBound.floorKey(subRange.lowerBound), subRange.lowerBound);
final Iterator<RangeMapEntry<K, V>> backingItr =
entriesByLowerBound.tailMap(cutToStart, true).values().iterator();
return new AbstractIterator<Entry<Range<K>, V>>() {
@Override
@CheckForNull
protected Entry<Range<K>, V> computeNext() {
while (backingItr.hasNext()) {
RangeMapEntry<K, V> entry = backingItr.next();
if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) {
return endOfData();
} else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) {
// this might not be true e.g. at the start of the iteration
return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue());
}
}
return endOfData();
}
};
}
@Override
public Collection<V> values() {
return new Maps.Values<Range<K>, V>(this) {
@Override
public boolean removeAll(Collection<?> c) {
return removeEntryIf(compose(in(c), Maps.<V>valueFunction()));
}
@Override
public boolean retainAll(Collection<?> c) {
return removeEntryIf(compose(not(in(c)), Maps.<V>valueFunction()));
}
};
}
}
}
@Override
public boolean equals(@CheckForNull Object o) {
if (o instanceof RangeMap) {
RangeMap<?, ?> rangeMap = (RangeMap<?, ?>) o;
return asMapOfRanges().equals(rangeMap.asMapOfRanges());
}
return false;
}
@Override
public int hashCode() {
return asMapOfRanges().hashCode();
}
@Override
public String toString() {
return entriesByLowerBound.values().toString();
}
}
| f |
5112_10 | goxr3plus/Java-Google-Text-To-Speech | 830 | src/application/Trying_Different_Languages.java | package application;
import java.io.IOException;
import com.darkprograms.speech.synthesiser.SynthesiserV2;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.advanced.AdvancedPlayer;
/**
* This is where all begins .
*
* @author GOXR3PLUS
*
*/
public class Trying_Different_Languages {
//Create a Synthesizer instance
SynthesiserV2 synthesizer = new SynthesiserV2("AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw");
/**
* Constructor
*/
public Trying_Different_Languages() {
//Let's speak in English
speak("Hello Dear Friend !");
//Speak Chinese Fuckers
//speak("我可以说你想要的任何语言!");
//Let's Speak in Somalian
//speak("Waxaan ku hadli karaa luqad aad rabto!");
//Let's Speak in Hindi
//speak("मैं चाहता हूं कि कोई भी भाषा बोल सकता हूँ!");
//Let's Speak in Polish
//speak("Mogę mówić dowolnym językiem, którego chcesz!");
//Let's Speak in Persian ----- This doens't work for some reason i have to figure out ... ;(
//speak("من می توانم به هر زبان که می خواهید صحبت کنید!");
}
/**
* Calls the MaryTTS to say the given text
*
* @param text
*/
public void speak(String text) {
System.out.println(text);
//Create a new Thread because JLayer is running on the current Thread and will make the application to lag
Thread thread = new Thread(() -> {
try {
//Create a JLayer instance
AdvancedPlayer player = new AdvancedPlayer(synthesizer.getMP3Data(text));
player.play();
System.out.println("Successfully got back synthesizer data");
} catch (IOException | JavaLayerException e) {
e.printStackTrace(); //Print the exception ( we want to know , not hide below our finger , like many developers do...)
}
});
//We don't want the application to terminate before this Thread terminates
thread.setDaemon(false);
//Start the Thread
thread.start();
}
public static void main(String[] args) {
new Trying_Different_Languages();
}
}
| //speak("Mogę mówić dowolnym językiem, którego chcesz!"); | package application;
import java.io.IOException;
import com.darkprograms.speech.synthesiser.SynthesiserV2;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.advanced.AdvancedPlayer;
/**
* This is where all begins .
*
* @author GOXR3PLUS
*
*/
public class Trying_Different_Languages {
//Create a Synthesizer instance
SynthesiserV2 synthesizer = new SynthesiserV2("AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw");
/**
* Constructor
*/
public Trying_Different_Languages() {
//Let's speak in English
speak("Hello Dear Friend !");
//Speak Chinese Fuckers
//speak("我可以说你想要的任何语言!");
//Let's Speak in Somalian
//speak("Waxaan ku hadli karaa luqad aad rabto!");
//Let's Speak in Hindi
//speak("मैं चाहता हूं कि कोई भी भाषा बोल सकता हूँ!");
//Let's Speak in Polish
//speak("Mogę mówić <SUF>
//Let's Speak in Persian ----- This doens't work for some reason i have to figure out ... ;(
//speak("من می توانم به هر زبان که می خواهید صحبت کنید!");
}
/**
* Calls the MaryTTS to say the given text
*
* @param text
*/
public void speak(String text) {
System.out.println(text);
//Create a new Thread because JLayer is running on the current Thread and will make the application to lag
Thread thread = new Thread(() -> {
try {
//Create a JLayer instance
AdvancedPlayer player = new AdvancedPlayer(synthesizer.getMP3Data(text));
player.play();
System.out.println("Successfully got back synthesizer data");
} catch (IOException | JavaLayerException e) {
e.printStackTrace(); //Print the exception ( we want to know , not hide below our finger , like many developers do...)
}
});
//We don't want the application to terminate before this Thread terminates
thread.setDaemon(false);
//Start the Thread
thread.start();
}
public static void main(String[] args) {
new Trying_Different_Languages();
}
}
| f |
7984_2 | gre123/SMiP-Metody-Formalne- | 314 | SMiP/src/factory/PlaceTransitionFactory.java |
package factory;
import model.MyVertex;
import model.Place;
import model.Transition;
import org.apache.commons.collections15.Factory;
/**
* Najprostsza fabryka wierzchołków. Robi wierzchołki z kolejnymi ID od 0 wzwyż.
*
* @author Epifaniusz
*/
public class PlaceTransitionFactory implements Factory {
private static int place_n = 0;
private static int transition_n = 0;
public static void zeruj() {
place_n = 0;
transition_n = 0;
}
@Override
/**
* DO NOT USE, use create(boolean place to get type of vertex you wants)
*/
public Place create() {
return new Place((place_n++), "factorizedPlace");
}
public MyVertex create(Class type) {
if(type == Place.class){
return new Place((place_n++), "factorizedPlace");
}else if(type == Transition.class){
return new Transition(transition_n++);
}
return null; //wypada rzucić jakimś wyjątkiem tutaj
}
}
| //wypada rzucić jakimś wyjątkiem tutaj |
package factory;
import model.MyVertex;
import model.Place;
import model.Transition;
import org.apache.commons.collections15.Factory;
/**
* Najprostsza fabryka wierzchołków. Robi wierzchołki z kolejnymi ID od 0 wzwyż.
*
* @author Epifaniusz
*/
public class PlaceTransitionFactory implements Factory {
private static int place_n = 0;
private static int transition_n = 0;
public static void zeruj() {
place_n = 0;
transition_n = 0;
}
@Override
/**
* DO NOT USE, use create(boolean place to get type of vertex you wants)
*/
public Place create() {
return new Place((place_n++), "factorizedPlace");
}
public MyVertex create(Class type) {
if(type == Place.class){
return new Place((place_n++), "factorizedPlace");
}else if(type == Transition.class){
return new Transition(transition_n++);
}
return null; //wypada rzucić <SUF>
}
}
| f |
9842_1 | grzeprza/DistributedHierarchicalGraphNeuron | 424 | src/com/company/NeuralMemory.java | package com.company;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class NeuralMemory
{
private HashMap<Character, NeuralStructure> patterns;
public NeuralMemory(DrawWindow w) //Inicjalizatorem powinny być
{
patterns = new HashMap<>();
for(char letter = 'A'; letter <= 'Z'; letter++)
{
patterns.put(letter, new NeuralStructure(w.getDimensions()[0], w.getDimensions()[1], letter));
}
}
public NeuralMemory(int width, int height)
{
int[][] nullArray = new int[height][width];
patterns = new HashMap<>();
for(char letter = 'A'; letter <= 'Z'; letter++)
{
patterns.put(letter, new NeuralStructure(width, height, letter));
}
}
public void overwrite(int[][] newArray, char letter) //Czy to można zrobić lepiej?
{
try
{
patterns.get(letter).overwrite(newArray, letter);
}
catch(Exception e)
{
System.out.println("No letter found, probably.");
}
}
public HashMap<Character, NeuralStructure> getHashMap()
{
return patterns;
}
}
| //Czy to można zrobić lepiej?
| package com.company;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class NeuralMemory
{
private HashMap<Character, NeuralStructure> patterns;
public NeuralMemory(DrawWindow w) //Inicjalizatorem powinny być
{
patterns = new HashMap<>();
for(char letter = 'A'; letter <= 'Z'; letter++)
{
patterns.put(letter, new NeuralStructure(w.getDimensions()[0], w.getDimensions()[1], letter));
}
}
public NeuralMemory(int width, int height)
{
int[][] nullArray = new int[height][width];
patterns = new HashMap<>();
for(char letter = 'A'; letter <= 'Z'; letter++)
{
patterns.put(letter, new NeuralStructure(width, height, letter));
}
}
public void overwrite(int[][] newArray, char letter) //Czy to <SUF>
{
try
{
patterns.get(letter).overwrite(newArray, letter);
}
catch(Exception e)
{
System.out.println("No letter found, probably.");
}
}
public HashMap<Character, NeuralStructure> getHashMap()
{
return patterns;
}
}
| f |
7145_1 | gulp21/languagetool | 1,228 | languagetool-language-modules/pl/src/main/java/org/languagetool/rules/pl/PolishWordRepeatRule.java | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.pl;
import java.util.Collections;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.regex.Pattern;
import org.languagetool.rules.AdvancedWordRepeatRule;
import org.languagetool.rules.Example;
/**
* @author Marcin Miłkowski
*/
public class PolishWordRepeatRule extends AdvancedWordRepeatRule {
/**
* Excluded dictionary words.
*/
private static final Set<String> EXC_WORDS;
static {
final Set<String> tempSet = new HashSet<>();
tempSet.add("nie");
tempSet.add("tuż");
tempSet.add("aż");
tempSet.add("to");
tempSet.add("siebie");
tempSet.add("być");
tempSet.add("ani");
tempSet.add("ni");
tempSet.add("albo");
tempSet.add("lub");
tempSet.add("czy");
tempSet.add("bądź");
tempSet.add("jako");
tempSet.add("zł");
tempSet.add("np");
tempSet.add("coraz");
tempSet.add("bardzo");
tempSet.add("bardziej");
tempSet.add("proc");
tempSet.add("ten");
tempSet.add("jak");
tempSet.add("mln");
tempSet.add("tys");
tempSet.add("swój");
tempSet.add("mój");
tempSet.add("twój");
tempSet.add("nasz");
tempSet.add("wasz");
tempSet.add("i");
tempSet.add("zbyt");
tempSet.add("się");
EXC_WORDS = Collections.unmodifiableSet(tempSet);
}
/**
* Excluded part of speech classes.
*/
private static final Pattern EXC_POS = Pattern.compile("prep:.*|ppron.*");
/**
* Excluded non-words (special symbols, Roman numerals etc.)
*/
private static final Pattern EXC_NONWORDS = Pattern
.compile(""|>|<|&|[0-9].*|"
+ "M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$");
public PolishWordRepeatRule(final ResourceBundle messages) {
super(messages);
addExamplePair(Example.wrong("Mówiła długo, bo lubiła robić wszystko <marker>długo</marker>."),
Example.fixed("Mówiła długo, bo lubiła robić wszystko <marker>powoli</marker>."));
}
@Override
public final String getDescription() {
return "Powtórzenia wyrazów w zdaniu (monotonia stylistyczna)";
}
@Override
protected Pattern getExcludedNonWordsPattern() {
return EXC_NONWORDS;
}
@Override
protected Pattern getExcludedPos() {
return EXC_POS;
}
@Override
protected Set<String> getExcludedWordsPattern() {
return EXC_WORDS;
}
@Override
public final String getId() {
return "PL_WORD_REPEAT";
}
@Override
public final String getMessage() {
return "Powtórzony wyraz w zdaniu";
}
@Override
public final String getShortMessage() {
return "Powtórzenie wyrazu";
}
}
| /**
* @author Marcin Miłkowski
*/ | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.pl;
import java.util.Collections;
import java.util.HashSet;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.regex.Pattern;
import org.languagetool.rules.AdvancedWordRepeatRule;
import org.languagetool.rules.Example;
/**
* @author Marcin Miłkowski <SUF>*/
public class PolishWordRepeatRule extends AdvancedWordRepeatRule {
/**
* Excluded dictionary words.
*/
private static final Set<String> EXC_WORDS;
static {
final Set<String> tempSet = new HashSet<>();
tempSet.add("nie");
tempSet.add("tuż");
tempSet.add("aż");
tempSet.add("to");
tempSet.add("siebie");
tempSet.add("być");
tempSet.add("ani");
tempSet.add("ni");
tempSet.add("albo");
tempSet.add("lub");
tempSet.add("czy");
tempSet.add("bądź");
tempSet.add("jako");
tempSet.add("zł");
tempSet.add("np");
tempSet.add("coraz");
tempSet.add("bardzo");
tempSet.add("bardziej");
tempSet.add("proc");
tempSet.add("ten");
tempSet.add("jak");
tempSet.add("mln");
tempSet.add("tys");
tempSet.add("swój");
tempSet.add("mój");
tempSet.add("twój");
tempSet.add("nasz");
tempSet.add("wasz");
tempSet.add("i");
tempSet.add("zbyt");
tempSet.add("się");
EXC_WORDS = Collections.unmodifiableSet(tempSet);
}
/**
* Excluded part of speech classes.
*/
private static final Pattern EXC_POS = Pattern.compile("prep:.*|ppron.*");
/**
* Excluded non-words (special symbols, Roman numerals etc.)
*/
private static final Pattern EXC_NONWORDS = Pattern
.compile(""|>|<|&|[0-9].*|"
+ "M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$");
public PolishWordRepeatRule(final ResourceBundle messages) {
super(messages);
addExamplePair(Example.wrong("Mówiła długo, bo lubiła robić wszystko <marker>długo</marker>."),
Example.fixed("Mówiła długo, bo lubiła robić wszystko <marker>powoli</marker>."));
}
@Override
public final String getDescription() {
return "Powtórzenia wyrazów w zdaniu (monotonia stylistyczna)";
}
@Override
protected Pattern getExcludedNonWordsPattern() {
return EXC_NONWORDS;
}
@Override
protected Pattern getExcludedPos() {
return EXC_POS;
}
@Override
protected Set<String> getExcludedWordsPattern() {
return EXC_WORDS;
}
@Override
public final String getId() {
return "PL_WORD_REPEAT";
}
@Override
public final String getMessage() {
return "Powtórzony wyraz w zdaniu";
}
@Override
public final String getShortMessage() {
return "Powtórzenie wyrazu";
}
}
| f |
5260_0 | h4570/university | 1,457 | 2-semester-poj/zaj-6/Menu.java | /* Author: Sandro Sobczyński */
package com.company;
import java.util.ArrayList;
import java.util.Collections;
public class Menu {
public static void main(String[] args) {
ArrayList<Pizza> pizzas = new ArrayList<>();
pizzas.add(new PizzaDeluxe(11, "Prosciutto", 11, PizzaSize.Large, true, true));
pizzas.add(new PizzaWoogy(22, "Te są z drugim konstruktorem", 22, PizzaSize.Medium, false, false));
pizzas.add(new PizzaSpecial(33, "A teraz niestety po łebkach", 33, PizzaSize.Small, false, true));
pizzas.add(new PizzaDeluxe(44, "Bo moje dzieci są głodne", 44, PizzaSize.Small, false, true));
pizzas.add(new PizzaDeluxe(55, "I umrą, jak będę tyle pisał", 55));
pizzas.add(new PizzaDeluxe(222, "222", 222));
pizzas.add(new PizzaDeluxe(66, "66", 66));
pizzas.add(new PizzaDeluxe(88, "88", 88));
pizzas.add(new PizzaDeluxe(77, "77", 77));
pizzas.add(new PizzaDeluxe(99, "99", 99));
pizzas.add(new PizzaDeluxe(111, "111", 111));
pizzas.add(new PizzaDeluxe(333, "333", 333));
pizzas.add(new PizzaSpecial(3333, "3333", 3333));
pizzas.add(new PizzaDeluxe(555, "555", 555));
pizzas.add(new PizzaDeluxe(666, "666", 666));
pizzas.add(new PizzaDeluxe(1111, "1111", 1111));
pizzas.add(new PizzaDeluxe(777, "777", 777));
pizzas.add(new PizzaDeluxe(444, "444", 444));
pizzas.add(new PizzaSpecial(8888, "8888", 8888));
pizzas.add(new PizzaDeluxe(2222, "2222", 2222));
pizzas.add(new PizzaDeluxe(888, "888", 888));
pizzas.add(new PizzaSpecial(4444, "4444", 4444));
pizzas.add(new PizzaDeluxe(999, "999", 999));
pizzas.add(new PizzaSpecial(5555, "5555", 5555));
pizzas.add(new PizzaSpecial(9999, "9999", 9999));
pizzas.add(new PizzaSpecial(7777, "7777", 7777));
pizzas.add(new PizzaSpecial(6666, "6666", 6666));
pizzas.add(new PizzaSpecial(22222, "22222", 22222));
pizzas.add(new PizzaSpecial(11111, "11111", 11111));
pizzas.add(new PizzaWoogy(55555, "55555", 55555));
pizzas.add(new PizzaSpecial(33333, "33333", 33333));
pizzas.add(new PizzaWoogy(44444, "44444", 44444));
pizzas.add(new PizzaWoogy(77777, "77777", 77777));
pizzas.add(new PizzaWoogy(444444, "444444", 444444));
pizzas.add(new PizzaWoogy(66666, "66666", 66666));
pizzas.add(new PizzaWoogy(555555, "555555", 555555));
pizzas.add(new PizzaWoogy(99999, "99999", 99999));
pizzas.add(new PizzaWoogy(111111, "111111", 111111));
pizzas.add(new PizzaWoogy(88888, "88888", 88888));
pizzas.add(new PizzaWoogy(333333, "333333", 333333));
pizzas.add(new PizzaWoogy(222222, "222222", 222222));
Collections.sort(pizzas);
for (Pizza pizza : pizzas)
System.out.println(pizza);
}
}
| /* Author: Sandro Sobczyński */ | /* Author: Sandro Sobczyński <SUF>*/
package com.company;
import java.util.ArrayList;
import java.util.Collections;
public class Menu {
public static void main(String[] args) {
ArrayList<Pizza> pizzas = new ArrayList<>();
pizzas.add(new PizzaDeluxe(11, "Prosciutto", 11, PizzaSize.Large, true, true));
pizzas.add(new PizzaWoogy(22, "Te są z drugim konstruktorem", 22, PizzaSize.Medium, false, false));
pizzas.add(new PizzaSpecial(33, "A teraz niestety po łebkach", 33, PizzaSize.Small, false, true));
pizzas.add(new PizzaDeluxe(44, "Bo moje dzieci są głodne", 44, PizzaSize.Small, false, true));
pizzas.add(new PizzaDeluxe(55, "I umrą, jak będę tyle pisał", 55));
pizzas.add(new PizzaDeluxe(222, "222", 222));
pizzas.add(new PizzaDeluxe(66, "66", 66));
pizzas.add(new PizzaDeluxe(88, "88", 88));
pizzas.add(new PizzaDeluxe(77, "77", 77));
pizzas.add(new PizzaDeluxe(99, "99", 99));
pizzas.add(new PizzaDeluxe(111, "111", 111));
pizzas.add(new PizzaDeluxe(333, "333", 333));
pizzas.add(new PizzaSpecial(3333, "3333", 3333));
pizzas.add(new PizzaDeluxe(555, "555", 555));
pizzas.add(new PizzaDeluxe(666, "666", 666));
pizzas.add(new PizzaDeluxe(1111, "1111", 1111));
pizzas.add(new PizzaDeluxe(777, "777", 777));
pizzas.add(new PizzaDeluxe(444, "444", 444));
pizzas.add(new PizzaSpecial(8888, "8888", 8888));
pizzas.add(new PizzaDeluxe(2222, "2222", 2222));
pizzas.add(new PizzaDeluxe(888, "888", 888));
pizzas.add(new PizzaSpecial(4444, "4444", 4444));
pizzas.add(new PizzaDeluxe(999, "999", 999));
pizzas.add(new PizzaSpecial(5555, "5555", 5555));
pizzas.add(new PizzaSpecial(9999, "9999", 9999));
pizzas.add(new PizzaSpecial(7777, "7777", 7777));
pizzas.add(new PizzaSpecial(6666, "6666", 6666));
pizzas.add(new PizzaSpecial(22222, "22222", 22222));
pizzas.add(new PizzaSpecial(11111, "11111", 11111));
pizzas.add(new PizzaWoogy(55555, "55555", 55555));
pizzas.add(new PizzaSpecial(33333, "33333", 33333));
pizzas.add(new PizzaWoogy(44444, "44444", 44444));
pizzas.add(new PizzaWoogy(77777, "77777", 77777));
pizzas.add(new PizzaWoogy(444444, "444444", 444444));
pizzas.add(new PizzaWoogy(66666, "66666", 66666));
pizzas.add(new PizzaWoogy(555555, "555555", 555555));
pizzas.add(new PizzaWoogy(99999, "99999", 99999));
pizzas.add(new PizzaWoogy(111111, "111111", 111111));
pizzas.add(new PizzaWoogy(88888, "88888", 88888));
pizzas.add(new PizzaWoogy(333333, "333333", 333333));
pizzas.add(new PizzaWoogy(222222, "222222", 222222));
Collections.sort(pizzas);
for (Pizza pizza : pizzas)
System.out.println(pizza);
}
}
| f |
4425_0 | hankav21/zarzadzanie_zoo | 977 | aplikacja_zoo/Magazyn.java | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
interface ObslugaMagazynu{
public void wyswietlWszystko(Magazyn magazyn);
public void wyswietl_ilosc_w_magazynie(Magazyn magazyn, Jedzenie jedzenie);
public void wyswietl_ilosc_w_magazynie(Magazyn magazyn, String jedzenie);
public void wyswietl_ilosc_w_magazynie_na_diete(Magazyn magazyn, Dieta dieta);
}
interface DostepMagazyn{
public void dodaj_do_magazynu(Jedzenie jedzenie, Integer ilosc);
public Integer zwroc_ilosc_paszy(String jedzenie);
public Integer zwroc_ilosc_paszy(Jedzenie jedzenie);
}
public class Magazyn implements DostepMagazyn{
HashMap<Jedzenie, Integer> pasza_ilosc;
public Magazyn() {
this.pasza_ilosc = new HashMap<>();
}
public void dodaj_do_magazynu(Jedzenie jedzenie, Integer ilosc){
Integer obecna_ilosc = pasza_ilosc.get(jedzenie);
if(obecna_ilosc == null) {
pasza_ilosc.put(jedzenie, ilosc);
// BazaDanych bd = BazaDanych.pobierzInstancje();
BazaDanych.dodaj_nowy_rodaj_jedzenia(jedzenie);
}
else pasza_ilosc.put(jedzenie, obecna_ilosc + ilosc);
}
public Integer zwroc_ilosc_paszy(String jedzenie){
for (Map.Entry<Jedzenie, Integer> entry : pasza_ilosc.entrySet()) {
Jedzenie j = entry.getKey();
if(j.getNazwa().equals(jedzenie)) return entry.getValue();
}
return -1;
}
public void pobierz_z_magazynu(Dieta dieta){
if(czy_jest_wystarczajaca_ilosc_jedzenia_w_magazynie(dieta)) {
for (Map.Entry<Jedzenie, Integer> entry : dieta.produkt_gramy.entrySet()) {
Jedzenie jedzenie = entry.getKey();
int ilosc = entry.getValue();
if (this.pasza_ilosc.containsKey(jedzenie)) {
int aktualnaIlosc = this.pasza_ilosc.get(jedzenie);
this.pasza_ilosc.put(jedzenie, aktualnaIlosc - ilosc);
} else {
this.pasza_ilosc.put(jedzenie, ilosc);
}
}
}
}
public boolean czy_jest_wystarczajaca_ilosc_jedzenia_w_magazynie(Dieta dieta){
for (Map.Entry<Jedzenie, Integer> entry : pasza_ilosc.entrySet()) {
Jedzenie j = entry.getKey();
Integer iloscJedzeniaWMagazynie = entry.getValue();
if (dieta.czy_jest_to_jedzenie_w_diecie(j) == true) {
Integer wymaganaIloscJedzenia = dieta.ile_jest_tego_jedzenia_w_diecie(j);
if((iloscJedzeniaWMagazynie - wymaganaIloscJedzenia) <= 0) return false;
}
}
return true;
}
public Integer zwroc_ilosc_paszy(Jedzenie jedzenie){
return pasza_ilosc.get(jedzenie);
}
}
| // BazaDanych bd = BazaDanych.pobierzInstancje(); | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
interface ObslugaMagazynu{
public void wyswietlWszystko(Magazyn magazyn);
public void wyswietl_ilosc_w_magazynie(Magazyn magazyn, Jedzenie jedzenie);
public void wyswietl_ilosc_w_magazynie(Magazyn magazyn, String jedzenie);
public void wyswietl_ilosc_w_magazynie_na_diete(Magazyn magazyn, Dieta dieta);
}
interface DostepMagazyn{
public void dodaj_do_magazynu(Jedzenie jedzenie, Integer ilosc);
public Integer zwroc_ilosc_paszy(String jedzenie);
public Integer zwroc_ilosc_paszy(Jedzenie jedzenie);
}
public class Magazyn implements DostepMagazyn{
HashMap<Jedzenie, Integer> pasza_ilosc;
public Magazyn() {
this.pasza_ilosc = new HashMap<>();
}
public void dodaj_do_magazynu(Jedzenie jedzenie, Integer ilosc){
Integer obecna_ilosc = pasza_ilosc.get(jedzenie);
if(obecna_ilosc == null) {
pasza_ilosc.put(jedzenie, ilosc);
// BazaDanych bd <SUF>
BazaDanych.dodaj_nowy_rodaj_jedzenia(jedzenie);
}
else pasza_ilosc.put(jedzenie, obecna_ilosc + ilosc);
}
public Integer zwroc_ilosc_paszy(String jedzenie){
for (Map.Entry<Jedzenie, Integer> entry : pasza_ilosc.entrySet()) {
Jedzenie j = entry.getKey();
if(j.getNazwa().equals(jedzenie)) return entry.getValue();
}
return -1;
}
public void pobierz_z_magazynu(Dieta dieta){
if(czy_jest_wystarczajaca_ilosc_jedzenia_w_magazynie(dieta)) {
for (Map.Entry<Jedzenie, Integer> entry : dieta.produkt_gramy.entrySet()) {
Jedzenie jedzenie = entry.getKey();
int ilosc = entry.getValue();
if (this.pasza_ilosc.containsKey(jedzenie)) {
int aktualnaIlosc = this.pasza_ilosc.get(jedzenie);
this.pasza_ilosc.put(jedzenie, aktualnaIlosc - ilosc);
} else {
this.pasza_ilosc.put(jedzenie, ilosc);
}
}
}
}
public boolean czy_jest_wystarczajaca_ilosc_jedzenia_w_magazynie(Dieta dieta){
for (Map.Entry<Jedzenie, Integer> entry : pasza_ilosc.entrySet()) {
Jedzenie j = entry.getKey();
Integer iloscJedzeniaWMagazynie = entry.getValue();
if (dieta.czy_jest_to_jedzenie_w_diecie(j) == true) {
Integer wymaganaIloscJedzenia = dieta.ile_jest_tego_jedzenia_w_diecie(j);
if((iloscJedzeniaWMagazynie - wymaganaIloscJedzenia) <= 0) return false;
}
}
return true;
}
public Integer zwroc_ilosc_paszy(Jedzenie jedzenie){
return pasza_ilosc.get(jedzenie);
}
}
| f |
6575_9 | hbakiewicz/WooRepl | 2,912 | src/eventlog/TEventJournal.java | package eventlog;
import java.io.IOException;
import static java.lang.String.format;
import static java.lang.System.getProperty;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import static java.util.logging.Level.INFO;
import java.util.logging.LogManager;
import static java.util.logging.LogManager.getLogManager;
import java.util.logging.Logger;
/**
* Będąca Sigletonem klasa dostarcza mechanizmów logowania zdarzeń w ramach aplikacji. Możliwe jest
* zarówno zapisanie niezaleznego komunikatu tekstowego, jak i komunikatu wraz z wyjątkiem. Klasa do
* realizacji swoich celów korzysta z metod Logging API Javy. <br>
* Zdarzenia zapisywane są do pliku w postaci XML. Lokalizacja pliku, jego maksymalny rozmiar oraz
* długość kolejki plików są możliwe do skonfigurowania podczas wywołania fcji init(). Zapisywane są
* zdarzenia o ważności co najmniej INFO. <br>
* Aby możliwe było korzystanie z tej klasy, musi ona zostać zainicjowana, najlepiej przy starcie
* aplikacji, przy użyciu funkcji init(). Następnie należy odwoływać się do utworzonego obiektu
* poprzez wywołania fcji getJournal().
*
*
*/
class TEventJournal implements IEventJournal
{
private static TEventJournal Journal = null;
private Logger LocalLogger = null;
private FileHandler LocalFileHandler = null;
private boolean LogActive = false;
private boolean AdditionalConsoleOutput = false;
/**
* Tworzy obiekt dziennika na podstawie przekazanych parametrów.
*
* @param _params
* obiekt dostarczający parametrów do utworzenia logu.
* @throws EEventLogException
*/
TEventJournal(IJournalConfigParams _params) throws EEventLogException
{
String fName = _params.getLogFileName();
LogManager lm = getLogManager();
LocalLogger = Logger.getLogger(_params.getLogName());
lm.addLogger(LocalLogger);
try
{
if (_params.getFileCount() > 0)
fName += "%g";
fName += ".log";
if (_params.getFileLogSize() > 0 && _params.getFileCount() > 0)
LocalFileHandler = new FileHandler(fName, _params.getFileLogSize(), _params
.getFileCount(), true);
else if (_params.getFileLogSize() > 0)
LocalFileHandler = new FileHandler(fName, _params.getFileLogSize(), 1, true);
else
LocalFileHandler = new FileHandler(fName, true);
LocalFileHandler.setFormatter(new TMsgFormatter());
// LocalFileHandler.setFormatter(new XMLFormatter());
LocalLogger.addHandler(LocalFileHandler);
LocalFileHandler.setLevel(_params.getLevel());
LocalLogger.setLevel(_params.getLevel());
}
catch (SecurityException e)
{
e.printStackTrace();
throw new EEventLogException("Błąd bezpieczeństwa podczas tworzenia logu zdarzeń", e);
}
catch (IOException e)
{
e.printStackTrace();
throw new EEventLogException("Błąd wejścia/wyjścia podczas tworzenia logu zdarzeń", e);
}
LocalLogger.log(INFO, "Start logu");
LogActive = true;
}
/**
* Inicjalizuje statyczny obiekt klasy według przekazanych parametrów. Musi być wywołana, żeby
* możliwe było korzystanie z dziennika zdarzeń. Wystarczy jednorazowe wywołanie tej funkcji,
* kolejne wywołania sż ignorowane.
*
* @param _params
* parametry do utworzenia logu.
* @throws EEventLogException
*/
public static void initJournal(IJournalConfigParams _params) throws EEventLogException
{
if (Journal == null)
Journal = new TEventJournal(_params);
}
/**
* Zwraca utworzony funkcją init() obiekt klasy dziennika.<br>
* UWAGA: może zwrócić null, jeżeli nie było wcześniejszego wywołania funkcji init().
*
* @return referencję do statycznego obiektu klasy.
*/
public static TEventJournal getJournal()
{
return Journal;
}
/**
* Decyduje czy w przypadku logowania wyjątku funkcją logEvent() dodatkowo ma być wywołana
* funkcja printStackTrace() z obiektu wyjątku.
*
* @param _consoleOutput
* true włącza dodatkowe wypisywanie na konsolę informacji, false wyłącza
*/
public void setAdditionalConsoleOutput(boolean _consoleOutput)
{
AdditionalConsoleOutput = _consoleOutput;
}
/**
* Zapisuje do dziennika zdarzenie składające się wyłącznie z komunikatu tekstowego.
*
* @param _severity
* "waga" komunikatu, używane są oznaczenia z java.util.logging.Level.
* @param _msg
* komunikat do zapisania
*/
public void logEvent(Level _severity, String _msg)
{
if (!LogActive)
return;
LocalLogger.log(_severity, _msg);
}
/**
* Zapisuje do logu zdarzenie składające się komunikatu tekstowego i wyjątku. Zależnie od
* ustawienia AdditionalConsoleOutput na konsolę będzie dodatkowo wysyłana zawartość wyjątku
* metodą printStackTrace(), lub nie.
*
* @param _severity
* "waga" komunikatu
* @param _msg
* wiadomość do zapisania
* @param _th
* obiekt wyjątku do zapisania do dziennika
*/
public void logEvent(Level _severity, String _msg, Throwable _th)
{
if (!LogActive)
return;
LocalLogger.log(_severity, _msg, _th);
if (AdditionalConsoleOutput)
_th.printStackTrace();
notifyExcListTab(_severity, _msg, _th);
}
public void logBytes(Level _severity, String _description, byte[] _bytes)
{
if (!LogActive)
return;
String msg = createByteMessage(_description, _bytes);
LocalLogger.log(_severity, msg);
}
/**
* Tworzy komunikat tekstowy z podesłanej tablicy bajtów. Komunikat
* prezentuje bajty w postaci czytelnej.
*
* @param _bytes
* @return
*/
private String createByteMessage(String _description, byte[] _bytes)
{
final int MAX_RECORDS_PER_LINE = 25;
StringBuilder sb = new StringBuilder();
String line;
String tab = format("%12s", "");
String lineSeparator = getProperty("line.separator", "\r\n");
// najpierw nagłówek
sb.append(_description + lineSeparator);
// a teraz kolejne linie
for (int y = 0; y < _bytes.length;){
String line1 = "", line2 = "", line3 = "", line4 = "", line5 = "", lineSep = "";
// składane z kolejnych rekordów
for (int records = 0; records < MAX_RECORDS_PER_LINE && y < _bytes.length; ++records, ++y)
{
line1 += format("[%-3d] |", y);
lineSep += "======|";
line2 += format("0x%02X |", _bytes[y]);
line3 += format("%-5d |", (int) (_bytes[y]) & 0xFF);
line4 += format("%-5d |", (int) (_bytes[y]));
line5 += format("\'%1c\' |", _bytes[y] >= 0x20 ? (char)_bytes[y] : ' ');
}
line = tab + line1 + lineSeparator
//
+ tab + lineSep + lineSeparator
//
+ tab + line2 + lineSeparator
//
+ tab + line3 + lineSeparator
//
+ tab + line4 + lineSeparator
//
+ tab + line5 + lineSeparator;
sb.append(line);
}
return sb.toString();
}
public Logger getLogger()
{
return LocalLogger;
}
private ArrayList<IExceptionListener> locExcListTab = new ArrayList<>();
@Override
public synchronized void addExceptionListener(IExceptionListener list)
{
for (IExceptionListener locExcListTab1 : locExcListTab) {
if (locExcListTab1 == list) {
return;
}
}
locExcListTab.add(list);
}
@Override
public synchronized void removeExceptionListener(IExceptionListener list)
{
for (int i = 0; i < locExcListTab.size(); i++)
{
if (locExcListTab.get(i) == list)
{
locExcListTab.remove(i);
return;
}
}
}
private synchronized IExceptionListener[] getListenerTab()
{
IExceptionListener[] retTab = new IExceptionListener[locExcListTab.size()];
for (int i = 0; i < locExcListTab.size(); i++)
{
retTab[i] = locExcListTab.get(i);
}
return retTab;
}
private void notifyExcListTab(Level _severity, String _msg, Throwable _th)
{
IExceptionListener[] tab = getListenerTab();
for (IExceptionListener tab1 : tab) {
tab1.notifyException(_severity, _msg, _th);
}
}
}
| // składane z kolejnych rekordów
| package eventlog;
import java.io.IOException;
import static java.lang.String.format;
import static java.lang.System.getProperty;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import static java.util.logging.Level.INFO;
import java.util.logging.LogManager;
import static java.util.logging.LogManager.getLogManager;
import java.util.logging.Logger;
/**
* Będąca Sigletonem klasa dostarcza mechanizmów logowania zdarzeń w ramach aplikacji. Możliwe jest
* zarówno zapisanie niezaleznego komunikatu tekstowego, jak i komunikatu wraz z wyjątkiem. Klasa do
* realizacji swoich celów korzysta z metod Logging API Javy. <br>
* Zdarzenia zapisywane są do pliku w postaci XML. Lokalizacja pliku, jego maksymalny rozmiar oraz
* długość kolejki plików są możliwe do skonfigurowania podczas wywołania fcji init(). Zapisywane są
* zdarzenia o ważności co najmniej INFO. <br>
* Aby możliwe było korzystanie z tej klasy, musi ona zostać zainicjowana, najlepiej przy starcie
* aplikacji, przy użyciu funkcji init(). Następnie należy odwoływać się do utworzonego obiektu
* poprzez wywołania fcji getJournal().
*
*
*/
class TEventJournal implements IEventJournal
{
private static TEventJournal Journal = null;
private Logger LocalLogger = null;
private FileHandler LocalFileHandler = null;
private boolean LogActive = false;
private boolean AdditionalConsoleOutput = false;
/**
* Tworzy obiekt dziennika na podstawie przekazanych parametrów.
*
* @param _params
* obiekt dostarczający parametrów do utworzenia logu.
* @throws EEventLogException
*/
TEventJournal(IJournalConfigParams _params) throws EEventLogException
{
String fName = _params.getLogFileName();
LogManager lm = getLogManager();
LocalLogger = Logger.getLogger(_params.getLogName());
lm.addLogger(LocalLogger);
try
{
if (_params.getFileCount() > 0)
fName += "%g";
fName += ".log";
if (_params.getFileLogSize() > 0 && _params.getFileCount() > 0)
LocalFileHandler = new FileHandler(fName, _params.getFileLogSize(), _params
.getFileCount(), true);
else if (_params.getFileLogSize() > 0)
LocalFileHandler = new FileHandler(fName, _params.getFileLogSize(), 1, true);
else
LocalFileHandler = new FileHandler(fName, true);
LocalFileHandler.setFormatter(new TMsgFormatter());
// LocalFileHandler.setFormatter(new XMLFormatter());
LocalLogger.addHandler(LocalFileHandler);
LocalFileHandler.setLevel(_params.getLevel());
LocalLogger.setLevel(_params.getLevel());
}
catch (SecurityException e)
{
e.printStackTrace();
throw new EEventLogException("Błąd bezpieczeństwa podczas tworzenia logu zdarzeń", e);
}
catch (IOException e)
{
e.printStackTrace();
throw new EEventLogException("Błąd wejścia/wyjścia podczas tworzenia logu zdarzeń", e);
}
LocalLogger.log(INFO, "Start logu");
LogActive = true;
}
/**
* Inicjalizuje statyczny obiekt klasy według przekazanych parametrów. Musi być wywołana, żeby
* możliwe było korzystanie z dziennika zdarzeń. Wystarczy jednorazowe wywołanie tej funkcji,
* kolejne wywołania sż ignorowane.
*
* @param _params
* parametry do utworzenia logu.
* @throws EEventLogException
*/
public static void initJournal(IJournalConfigParams _params) throws EEventLogException
{
if (Journal == null)
Journal = new TEventJournal(_params);
}
/**
* Zwraca utworzony funkcją init() obiekt klasy dziennika.<br>
* UWAGA: może zwrócić null, jeżeli nie było wcześniejszego wywołania funkcji init().
*
* @return referencję do statycznego obiektu klasy.
*/
public static TEventJournal getJournal()
{
return Journal;
}
/**
* Decyduje czy w przypadku logowania wyjątku funkcją logEvent() dodatkowo ma być wywołana
* funkcja printStackTrace() z obiektu wyjątku.
*
* @param _consoleOutput
* true włącza dodatkowe wypisywanie na konsolę informacji, false wyłącza
*/
public void setAdditionalConsoleOutput(boolean _consoleOutput)
{
AdditionalConsoleOutput = _consoleOutput;
}
/**
* Zapisuje do dziennika zdarzenie składające się wyłącznie z komunikatu tekstowego.
*
* @param _severity
* "waga" komunikatu, używane są oznaczenia z java.util.logging.Level.
* @param _msg
* komunikat do zapisania
*/
public void logEvent(Level _severity, String _msg)
{
if (!LogActive)
return;
LocalLogger.log(_severity, _msg);
}
/**
* Zapisuje do logu zdarzenie składające się komunikatu tekstowego i wyjątku. Zależnie od
* ustawienia AdditionalConsoleOutput na konsolę będzie dodatkowo wysyłana zawartość wyjątku
* metodą printStackTrace(), lub nie.
*
* @param _severity
* "waga" komunikatu
* @param _msg
* wiadomość do zapisania
* @param _th
* obiekt wyjątku do zapisania do dziennika
*/
public void logEvent(Level _severity, String _msg, Throwable _th)
{
if (!LogActive)
return;
LocalLogger.log(_severity, _msg, _th);
if (AdditionalConsoleOutput)
_th.printStackTrace();
notifyExcListTab(_severity, _msg, _th);
}
public void logBytes(Level _severity, String _description, byte[] _bytes)
{
if (!LogActive)
return;
String msg = createByteMessage(_description, _bytes);
LocalLogger.log(_severity, msg);
}
/**
* Tworzy komunikat tekstowy z podesłanej tablicy bajtów. Komunikat
* prezentuje bajty w postaci czytelnej.
*
* @param _bytes
* @return
*/
private String createByteMessage(String _description, byte[] _bytes)
{
final int MAX_RECORDS_PER_LINE = 25;
StringBuilder sb = new StringBuilder();
String line;
String tab = format("%12s", "");
String lineSeparator = getProperty("line.separator", "\r\n");
// najpierw nagłówek
sb.append(_description + lineSeparator);
// a teraz kolejne linie
for (int y = 0; y < _bytes.length;){
String line1 = "", line2 = "", line3 = "", line4 = "", line5 = "", lineSep = "";
// składane z <SUF>
for (int records = 0; records < MAX_RECORDS_PER_LINE && y < _bytes.length; ++records, ++y)
{
line1 += format("[%-3d] |", y);
lineSep += "======|";
line2 += format("0x%02X |", _bytes[y]);
line3 += format("%-5d |", (int) (_bytes[y]) & 0xFF);
line4 += format("%-5d |", (int) (_bytes[y]));
line5 += format("\'%1c\' |", _bytes[y] >= 0x20 ? (char)_bytes[y] : ' ');
}
line = tab + line1 + lineSeparator
//
+ tab + lineSep + lineSeparator
//
+ tab + line2 + lineSeparator
//
+ tab + line3 + lineSeparator
//
+ tab + line4 + lineSeparator
//
+ tab + line5 + lineSeparator;
sb.append(line);
}
return sb.toString();
}
public Logger getLogger()
{
return LocalLogger;
}
private ArrayList<IExceptionListener> locExcListTab = new ArrayList<>();
@Override
public synchronized void addExceptionListener(IExceptionListener list)
{
for (IExceptionListener locExcListTab1 : locExcListTab) {
if (locExcListTab1 == list) {
return;
}
}
locExcListTab.add(list);
}
@Override
public synchronized void removeExceptionListener(IExceptionListener list)
{
for (int i = 0; i < locExcListTab.size(); i++)
{
if (locExcListTab.get(i) == list)
{
locExcListTab.remove(i);
return;
}
}
}
private synchronized IExceptionListener[] getListenerTab()
{
IExceptionListener[] retTab = new IExceptionListener[locExcListTab.size()];
for (int i = 0; i < locExcListTab.size(); i++)
{
retTab[i] = locExcListTab.get(i);
}
return retTab;
}
private void notifyExcListTab(Level _severity, String _msg, Throwable _th)
{
IExceptionListener[] tab = getListenerTab();
for (IExceptionListener tab1 : tab) {
tab1.notifyException(_severity, _msg, _th);
}
}
}
| t |
7930_0 | herbalrp/PSTKM1 | 715 | PSTKM/src/pstkm/Link.java | package pstkm;
public class Link {
private Integer ID;
private Integer startNode;
private Integer endNode;
private Integer numberOfFibres; // TODO: Czy na pewno tutaj jest to liczba fajberow? // zgodnie z tym co Mycek napisał tak
private Float costOfFibre;
private Integer numberOfLambdas; //number of lambdas in a fiber
public Link(Integer ID, Integer startNode, Integer endNode, Integer numberOfFibres, Float costOfFibre, Integer numberOfLambdas)
{
this.ID=ID;
this.startNode=startNode;
this.endNode=endNode;
this.numberOfFibres=numberOfFibres;
this.costOfFibre=costOfFibre;
this.numberOfLambdas=numberOfLambdas;
}
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
ID = iD;
}
public Integer getStartNode() {
return startNode;
}
public void setStartNode(Integer startNode) {
this.startNode = startNode;
}
public Integer getEndNode() {
return endNode;
}
public void setEndNode(Integer endNode) {
this.endNode = endNode;
}
public Integer getNumberOfFibres() {
return numberOfFibres;
}
public void setNumberOfFibres(Integer numberOfFibres) {
this.numberOfFibres = numberOfFibres;
}
public Float getCostOfFibre() {
return costOfFibre;
}
public void setCostOfFibre(Float costOfFibre) {
this.costOfFibre = costOfFibre;
}
public Integer getNumberOfLambdas() {
return numberOfLambdas;
}
public void setNumberOfLambdas(Integer numberOfLambdas) {
this.numberOfLambdas = numberOfLambdas;
}
@Override
public String toString() {
return "Link [ID=" + ID + ", startNode=" + startNode + ", endNode=" + endNode + ", numberOfFibres="
+ numberOfFibres + ", costOfFibre=" + costOfFibre + ", numberOfLambdas=" + numberOfLambdas + "]";
}
}
| // TODO: Czy na pewno tutaj jest to liczba fajberow? // zgodnie z tym co Mycek napisał tak | package pstkm;
public class Link {
private Integer ID;
private Integer startNode;
private Integer endNode;
private Integer numberOfFibres; // TODO: Czy <SUF>
private Float costOfFibre;
private Integer numberOfLambdas; //number of lambdas in a fiber
public Link(Integer ID, Integer startNode, Integer endNode, Integer numberOfFibres, Float costOfFibre, Integer numberOfLambdas)
{
this.ID=ID;
this.startNode=startNode;
this.endNode=endNode;
this.numberOfFibres=numberOfFibres;
this.costOfFibre=costOfFibre;
this.numberOfLambdas=numberOfLambdas;
}
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
ID = iD;
}
public Integer getStartNode() {
return startNode;
}
public void setStartNode(Integer startNode) {
this.startNode = startNode;
}
public Integer getEndNode() {
return endNode;
}
public void setEndNode(Integer endNode) {
this.endNode = endNode;
}
public Integer getNumberOfFibres() {
return numberOfFibres;
}
public void setNumberOfFibres(Integer numberOfFibres) {
this.numberOfFibres = numberOfFibres;
}
public Float getCostOfFibre() {
return costOfFibre;
}
public void setCostOfFibre(Float costOfFibre) {
this.costOfFibre = costOfFibre;
}
public Integer getNumberOfLambdas() {
return numberOfLambdas;
}
public void setNumberOfLambdas(Integer numberOfLambdas) {
this.numberOfLambdas = numberOfLambdas;
}
@Override
public String toString() {
return "Link [ID=" + ID + ", startNode=" + startNode + ", endNode=" + endNode + ", numberOfFibres="
+ numberOfFibres + ", costOfFibre=" + costOfFibre + ", numberOfLambdas=" + numberOfLambdas + "]";
}
}
| f |
9992_5 | hubertgabrys/ocr | 7,176 | src/obrazy/Classification.java | package obrazy;
//<editor-fold defaultstate="collapsed" desc="IMPORT">
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Deque;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
//</editor-fold>
/**
*
* @author Hubert
*/
public class Classification {
//<editor-fold defaultstate="collapsed" desc="dbTraining">
/**
* Trening w celu utworzenia bazy danych.
*
* 1. Utorzenie listy typu String. 2. Przekazanie do listy nazw wszystkich
* plików z rozszerzeniem .png z katalogu zawierającego graficzne pliki
* treningowe. 3. Program pobiera i usuwa z listy pierwszy plik do typu
* BufferedImage. 4. Dokonana zostaje segmentacja obrazu. 5. Ekstrakcja cech
* wybraną metodą. 6. Wektor cech zapisywany macierzy która posłuży jako baza
* danych. 7. Gdy lista jest pusta baza danych jest gotowa i zostaje zapisana
* do pliku.
*/
public static void dbTraining() {
ObjectOutputStream oos = null;
try {
Deque<String> lista = new LinkedList<String>();
lista.add("data/OCR/training/ArialNormal.png");
lista.add("data/OCR/training/CourierNewNormal.png");
lista.add("data/OCR/training/TimesNewRomanNormal.png");
lista.add("data/OCR/training/VerdanaNormal.png");
int[][] database2D = new int[lista.size() * 93][];
int[][][] database3D = new int[lista.size() * 93][][];
int[][][][] database4D = new int[lista.size() * 93][][][];
int iterator = 0;
while (!lista.isEmpty()) {
BufferedImage[][] trainingImage = Segmentation.metoda1(ImageIO.read(new File(lista.removeFirst())));
for (int i = 0; i < trainingImage.length; i++) {
for (int j = 0; j < trainingImage[i].length; j++, iterator++) {
database4D[iterator] = Extraction.byNrOfNeighbours(trainingImage[i][j]);
database3D[iterator] = Extraction.byDiagonals(trainingImage[i][j]);
database2D[iterator] = Extraction.bySquares(trainingImage[i][j]);
}
}
}
oos = new ObjectOutputStream(new FileOutputStream("data/OCR/database2D.dat"));
oos.writeObject(database2D);
oos.close();
oos = new ObjectOutputStream(new FileOutputStream("data/OCR/database3D.dat"));
oos.writeObject(database3D);
oos.close();
oos = new ObjectOutputStream(new FileOutputStream("data/OCR/database4D.dat"));
oos.writeObject(database4D);
oos.close();
} catch (IOException ex) {
Logger.getLogger(Classification.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
oos.close();
} catch (IOException ex) {
Logger.getLogger(Classification.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Porównanie wektora cech z bazą danych">
/**
* Metoda porównuje wektor cech znaku z bazą danych.
*
* @param vector1D Wektor cech znaku.
* @param NN1 Jeśli prawda to zastosowany zostanie algorytm klasyfikacji 1NN,
* jeśli fałsz to algorytm kNN.
* @param euklides Jeśli prawda to zostanie zastosowana metryka euklidesowa,
* jeśli fałsz to Manhattan.
* @return Znak wyjściowy.
*/
public static char compareVectorWithDatabase(int[] vector1D, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data/OCR/database2D.dat"));
int[][] database = (int[][]) ois.readObject();
ois.close();
//Metryki
double[] metryki = new double[database.length];
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
metryki[i] = metrEukl(vector1D, database[i]);
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
metryki[i] = metrManh(vector1D, database[i]);
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
public static char compareVectorWithDatabase(int[][] vector2D, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data/OCR/database3D.dat"));
int[][][] database = (int[][][]) ois.readObject();
ois.close();
//Metryki
double[] metryki = new double[database.length];
for (int i = 0; i < metryki.length; i++) {
metryki[i] = 1e6;
}
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if (vector2D.length == database[i].length) {
metryki[i] = metrEukl(vector2D, database[i]);
}
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if (vector2D.length == database[i].length) {
metryki[i] = metrManh(vector2D, database[i]);
}
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
public static char compareVectorWithDatabase(int[][][] vector3D, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data/OCR/database4D.dat"));
int[][][][] database = (int[][][][]) ois.readObject();
ois.close();
//Metryki
double[] metryki = new double[database.length];
for (int i = 0; i < metryki.length; i++) {
metryki[i] = 1e6;
}
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if ((vector3D[0].length == database[i][0].length) && (vector3D[1].length == database[i][1].length)) {
metryki[i] = metrEukl(vector3D, database[i]);
}
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if ((vector3D[0].length == database[i][0].length) && (vector3D[1].length == database[i][1].length)) {
metryki[i] = metrManh(vector3D, database[i]);
}
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
/**
* Metoda porównuje wektor cech znaku z bazą danych.
*
* @param vector1D Wektor cech znaku.
* @param database2D Baza danych klasyfikatorów.
* @param NN1 Jeśli prawda to zastosowany zostanie algorytm klasyfikacji 1NN,
* jeśli fałsz to algorytm kNN.
* @param euklides Jeśli prawda to zostanie zastosowana metryka euklidesowa,
* jeśli fałsz to Manhattan.
* @return Znak wyjściowy.
*/
public static char compareVectorWithDatabase(int[] vector1D, int[][] database, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
//Metryki
double[] metryki = new double[database.length];
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
metryki[i] = metrEukl(vector1D, database[i]);
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
metryki[i] = metrManh(vector1D, database[i]);
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
public static char compareVectorWithDatabase(int[][] vector2D, int[][][] database, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
//Metryki
double[] metryki = new double[database.length];
for (int i = 0; i < metryki.length; i++) {
metryki[i] = 1e6;
}
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if (vector2D.length == database[i].length) {
metryki[i] = metrEukl(vector2D, database[i]);
}
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if (vector2D.length == database[i].length) {
metryki[i] = metrManh(vector2D, database[i]);
}
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
public static char compareVectorWithDatabase(int[][][] vector3D, int[][][][] database, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
//Metryki
double[] metryki = new double[database.length];
for (int i = 0; i < metryki.length; i++) {
metryki[i] = 1e6;
}
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if ((vector3D[0].length == database[i][0].length) && (vector3D[1].length == database[i][1].length)) {
metryki[i] = metrEukl(vector3D, database[i]);
}
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if ((vector3D[0].length == database[i][0].length) && (vector3D[1].length == database[i][1].length)) {
metryki[i] = metrManh(vector3D, database[i]);
}
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Metryki">
private static double metrEukl(int[] vector, int[] database) {
double suma = 0;
for (int i = 0; i < database.length; i++) {
suma += Math.pow((vector[i] - database[i]), 2);
}
return Math.sqrt(suma);
}
private static int metrManh(int[] vector, int[] database) {
int suma = 0;
for (int i = 0; i < database.length; i++) {
suma += Math.abs(vector[i] - database[i]);
}
return suma;
}
private static double metrEukl(int[][] vector, int[][] database) {
double suma = 0;
for (int i = 0; i < database.length; i++) {
for (int j = 0; j < database[i].length; j++) {
suma += Math.pow((vector[i][j] - database[i][j]), 2);
}
}
return Math.sqrt(suma);
}
private static int metrManh(int[][] vector, int[][] database) {
int suma = 0;
for (int i = 0; i < database.length; i++) {
for (int j = 0; j < database[i].length; j++) {
suma += Math.abs(vector[i][j] - database[i][j]);
}
}
return suma;
}
private static double metrEukl(int[][][] vector, int[][][] database) {
double suma = 0;
for (int i = 0; i < database.length; i++) {
for (int j = 0; j < database[i].length; j++) {
for (int k = 0; k < database[i][j].length; k++) {
suma += Math.pow((vector[i][j][k] - database[i][j][k]), 2);
}
}
}
return Math.sqrt(suma);
}
private static int metrManh(int[][][] vector, int[][][] database) {
int suma = 0;
for (int i = 0; i < database.length; i++) {
for (int j = 0; j < database[i].length; j++) {
for (int k = 0; k < database[i][j].length; k++) {
suma += Math.abs(vector[i][j][k] - database[i][j][k]);
}
}
}
return suma;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="1NN">
/**
* Znajduje minimalną wartość metryki i zwraca jej pozycję w tablicy.
*
* @param metryki Tablica z metrykami.
* @return Znak.
*/
private static char NN1(double[] metryki) {
double[] szukacz = new double[2];
szukacz[0] = metryki[0];
szukacz[1] = 0;
for (int i = 1; i < metryki.length; i++) {
if (metryki[i] < szukacz[0]) {
szukacz[0] = metryki[i];
szukacz[1] = i;
}
}
return findChar((int) szukacz[1]);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="kNN">
/**
* Znajduje k minimalnych wartości metryki. Sprawdza jakim znakom odpowiadają
* i wybiera znak najczęściej występujący.
*
* @param metryki Tablica z metrykami.
* @param k Liczba minimlanych wartości.
* @return Znak.
*/
private static char kNN(double[] metryki, int k) {
//Tworzymy tablicę z minimami.
double[][] minima = new double[k][2];
//Szukacz znajduje minimalną wartość w tablicy. W komórce [0] wartość, a w komórce [1] jej indeks w tablicy.
double[] szukacz = new double[2];
//Jako minimalną wartość przypisuję pierwszą wartość z tablicy metryki.
szukacz[0] = metryki[0];
szukacz[1] = 0;
//Przeszukuję całą tablicę metryki w poszukiwaniu minimalnej wartości.
for (int i = 1; i < metryki.length; i++) {
if (metryki[i] < szukacz[0]) {
szukacz[0] = metryki[i];
szukacz[1] = i;
}
}
//Znalezioną minimalną wartość i jej indeks wpisuję do pierwszej komórki tablicy minima.
minima[0][0] = szukacz[0];
minima[0][1] = szukacz[1];
//Szukam kolejnych minimalnych wartości k-1 razy tak aby zapełnić tablicę minima.
for (int i = 1; i < k; i++) {
//Jako minimalną wartość przypisuję pierwszą wartość z tablicy metryki.
szukacz[0] = metryki[0];
szukacz[1] = 0;
//Przeszukuję całą tablicę metryki w poszukiwaniu minimalnej wartości większej od wartośći z pozycji minima[k-1];
for (int j = 1; j < metryki.length; j++) {
if ((metryki[j] < szukacz[0]) && metryki[j] > minima[i - 1][0]) {
szukacz[0] = metryki[j];
szukacz[1] = j;
}
}
minima[i][0] = szukacz[0];
minima[i][1] = szukacz[1];
}
//Wypisuję minima i znaki im odpowiadające
// for (int i = 0; i < k; i++) {
// System.out.print(minima[i][0] + " " + findChar((int) minima[i][1]) + ", ");
// }
int[] tally = new int[128];
for (int i = 0; i < tally.length; i++) {
tally[i] = 0;
}
for (int i = 0; i < minima.length; i++) {
tally[findChar((int) minima[i][1])]++;
}
int maxIndex = 0;
for (int i = 1; i < tally.length; i++) {
if (tally[i] > tally[maxIndex]) {
maxIndex = i;
}
}
//System.out.println(" Najczęściej występuje: " + (char) maxIndex);
return (char) maxIndex;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="findChar">
/**
* Metoda na podstawie indeksu w tabeli rozponaje znak.
*
* @param index Indeks.
* @return Znak.
*/
private static char findChar(int index) {
char[] trainingLettersArray = new char[93];
trainingLettersArray[0] = 'Q';
trainingLettersArray[1] = 'W';
trainingLettersArray[2] = 'E';
trainingLettersArray[3] = 'R';
trainingLettersArray[4] = 'T';
trainingLettersArray[5] = 'Y';
trainingLettersArray[6] = 'U';
trainingLettersArray[7] = 'I';
trainingLettersArray[8] = 'O';
trainingLettersArray[9] = 'P';
trainingLettersArray[10] = 'A';
trainingLettersArray[11] = 'S';
trainingLettersArray[12] = 'D';
trainingLettersArray[13] = 'F';
trainingLettersArray[14] = 'G';
trainingLettersArray[15] = 'H';
trainingLettersArray[16] = 'J';
trainingLettersArray[17] = 'K';
trainingLettersArray[18] = 'L';
trainingLettersArray[19] = 'Z';
trainingLettersArray[20] = 'X';
trainingLettersArray[21] = 'C';
trainingLettersArray[22] = 'V';
trainingLettersArray[23] = 'B';
trainingLettersArray[24] = 'N';
trainingLettersArray[25] = 'M';
trainingLettersArray[26] = 'q';
trainingLettersArray[27] = 'w';
trainingLettersArray[28] = 'e';
trainingLettersArray[29] = 'r';
trainingLettersArray[30] = 't';
trainingLettersArray[31] = 'y';
trainingLettersArray[32] = 'u';
trainingLettersArray[33] = 'i';
trainingLettersArray[34] = 'o';
trainingLettersArray[35] = 'p';
trainingLettersArray[36] = 'a';
trainingLettersArray[37] = 's';
trainingLettersArray[38] = 'd';
trainingLettersArray[39] = 'f';
trainingLettersArray[40] = 'g';
trainingLettersArray[41] = 'h';
trainingLettersArray[42] = 'j';
trainingLettersArray[43] = 'k';
trainingLettersArray[44] = 'l';
trainingLettersArray[45] = 'z';
trainingLettersArray[46] = 'x';
trainingLettersArray[47] = 'c';
trainingLettersArray[48] = 'v';
trainingLettersArray[49] = 'b';
trainingLettersArray[50] = 'n';
trainingLettersArray[51] = 'm';
trainingLettersArray[52] = '`';
trainingLettersArray[53] = '1';
trainingLettersArray[54] = '2';
trainingLettersArray[55] = '3';
trainingLettersArray[56] = '4';
trainingLettersArray[57] = '5';
trainingLettersArray[58] = '6';
trainingLettersArray[59] = '7';
trainingLettersArray[60] = '8';
trainingLettersArray[61] = '9';
trainingLettersArray[62] = '0';
trainingLettersArray[63] = '-';
trainingLettersArray[64] = '=';
trainingLettersArray[65] = '[';
trainingLettersArray[66] = ']';
trainingLettersArray[67] = '\\';
trainingLettersArray[68] = ';';
trainingLettersArray[69] = '\'';
trainingLettersArray[70] = ',';
trainingLettersArray[71] = '.';
trainingLettersArray[72] = '/';
trainingLettersArray[73] = '~';
trainingLettersArray[74] = '!';
trainingLettersArray[75] = '@';
trainingLettersArray[76] = '#';
trainingLettersArray[77] = '$';
trainingLettersArray[78] = '%';
trainingLettersArray[79] = '^';
trainingLettersArray[80] = '&';
trainingLettersArray[81] = '*';
trainingLettersArray[82] = '(';
trainingLettersArray[83] = ')';
trainingLettersArray[84] = '_';
trainingLettersArray[85] = '+';
trainingLettersArray[86] = '{';
trainingLettersArray[87] = '}';
trainingLettersArray[88] = '|';
trainingLettersArray[89] = ':';
trainingLettersArray[90] = '<';
trainingLettersArray[91] = '>';
trainingLettersArray[92] = '?';
if (index > 92) {
index %= 93;
}
return trainingLettersArray[index];
}
//</editor-fold>
} | /**
* Metoda porównuje wektor cech znaku z bazą danych.
*
* @param vector1D Wektor cech znaku.
* @param NN1 Jeśli prawda to zastosowany zostanie algorytm klasyfikacji 1NN,
* jeśli fałsz to algorytm kNN.
* @param euklides Jeśli prawda to zostanie zastosowana metryka euklidesowa,
* jeśli fałsz to Manhattan.
* @return Znak wyjściowy.
*/ | package obrazy;
//<editor-fold defaultstate="collapsed" desc="IMPORT">
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Deque;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
//</editor-fold>
/**
*
* @author Hubert
*/
public class Classification {
//<editor-fold defaultstate="collapsed" desc="dbTraining">
/**
* Trening w celu utworzenia bazy danych.
*
* 1. Utorzenie listy typu String. 2. Przekazanie do listy nazw wszystkich
* plików z rozszerzeniem .png z katalogu zawierającego graficzne pliki
* treningowe. 3. Program pobiera i usuwa z listy pierwszy plik do typu
* BufferedImage. 4. Dokonana zostaje segmentacja obrazu. 5. Ekstrakcja cech
* wybraną metodą. 6. Wektor cech zapisywany macierzy która posłuży jako baza
* danych. 7. Gdy lista jest pusta baza danych jest gotowa i zostaje zapisana
* do pliku.
*/
public static void dbTraining() {
ObjectOutputStream oos = null;
try {
Deque<String> lista = new LinkedList<String>();
lista.add("data/OCR/training/ArialNormal.png");
lista.add("data/OCR/training/CourierNewNormal.png");
lista.add("data/OCR/training/TimesNewRomanNormal.png");
lista.add("data/OCR/training/VerdanaNormal.png");
int[][] database2D = new int[lista.size() * 93][];
int[][][] database3D = new int[lista.size() * 93][][];
int[][][][] database4D = new int[lista.size() * 93][][][];
int iterator = 0;
while (!lista.isEmpty()) {
BufferedImage[][] trainingImage = Segmentation.metoda1(ImageIO.read(new File(lista.removeFirst())));
for (int i = 0; i < trainingImage.length; i++) {
for (int j = 0; j < trainingImage[i].length; j++, iterator++) {
database4D[iterator] = Extraction.byNrOfNeighbours(trainingImage[i][j]);
database3D[iterator] = Extraction.byDiagonals(trainingImage[i][j]);
database2D[iterator] = Extraction.bySquares(trainingImage[i][j]);
}
}
}
oos = new ObjectOutputStream(new FileOutputStream("data/OCR/database2D.dat"));
oos.writeObject(database2D);
oos.close();
oos = new ObjectOutputStream(new FileOutputStream("data/OCR/database3D.dat"));
oos.writeObject(database3D);
oos.close();
oos = new ObjectOutputStream(new FileOutputStream("data/OCR/database4D.dat"));
oos.writeObject(database4D);
oos.close();
} catch (IOException ex) {
Logger.getLogger(Classification.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
oos.close();
} catch (IOException ex) {
Logger.getLogger(Classification.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Porównanie wektora cech z bazą danych">
/**
* Metoda porównuje wektor <SUF>*/
public static char compareVectorWithDatabase(int[] vector1D, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data/OCR/database2D.dat"));
int[][] database = (int[][]) ois.readObject();
ois.close();
//Metryki
double[] metryki = new double[database.length];
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
metryki[i] = metrEukl(vector1D, database[i]);
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
metryki[i] = metrManh(vector1D, database[i]);
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
public static char compareVectorWithDatabase(int[][] vector2D, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data/OCR/database3D.dat"));
int[][][] database = (int[][][]) ois.readObject();
ois.close();
//Metryki
double[] metryki = new double[database.length];
for (int i = 0; i < metryki.length; i++) {
metryki[i] = 1e6;
}
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if (vector2D.length == database[i].length) {
metryki[i] = metrEukl(vector2D, database[i]);
}
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if (vector2D.length == database[i].length) {
metryki[i] = metrManh(vector2D, database[i]);
}
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
public static char compareVectorWithDatabase(int[][][] vector3D, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data/OCR/database4D.dat"));
int[][][][] database = (int[][][][]) ois.readObject();
ois.close();
//Metryki
double[] metryki = new double[database.length];
for (int i = 0; i < metryki.length; i++) {
metryki[i] = 1e6;
}
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if ((vector3D[0].length == database[i][0].length) && (vector3D[1].length == database[i][1].length)) {
metryki[i] = metrEukl(vector3D, database[i]);
}
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if ((vector3D[0].length == database[i][0].length) && (vector3D[1].length == database[i][1].length)) {
metryki[i] = metrManh(vector3D, database[i]);
}
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
/**
* Metoda porównuje wektor cech znaku z bazą danych.
*
* @param vector1D Wektor cech znaku.
* @param database2D Baza danych klasyfikatorów.
* @param NN1 Jeśli prawda to zastosowany zostanie algorytm klasyfikacji 1NN,
* jeśli fałsz to algorytm kNN.
* @param euklides Jeśli prawda to zostanie zastosowana metryka euklidesowa,
* jeśli fałsz to Manhattan.
* @return Znak wyjściowy.
*/
public static char compareVectorWithDatabase(int[] vector1D, int[][] database, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
//Metryki
double[] metryki = new double[database.length];
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
metryki[i] = metrEukl(vector1D, database[i]);
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
metryki[i] = metrManh(vector1D, database[i]);
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
public static char compareVectorWithDatabase(int[][] vector2D, int[][][] database, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
//Metryki
double[] metryki = new double[database.length];
for (int i = 0; i < metryki.length; i++) {
metryki[i] = 1e6;
}
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if (vector2D.length == database[i].length) {
metryki[i] = metrEukl(vector2D, database[i]);
}
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if (vector2D.length == database[i].length) {
metryki[i] = metrManh(vector2D, database[i]);
}
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
public static char compareVectorWithDatabase(int[][][] vector3D, int[][][][] database, Boolean NN1, Boolean euklides) throws IOException, ClassNotFoundException {
char charOut;
//Metryki
double[] metryki = new double[database.length];
for (int i = 0; i < metryki.length; i++) {
metryki[i] = 1e6;
}
if (euklides) {//Metryka euklidesowa
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if ((vector3D[0].length == database[i][0].length) && (vector3D[1].length == database[i][1].length)) {
metryki[i] = metrEukl(vector3D, database[i]);
}
}
} else {//Metryka Manhattan
for (int i = 0; i < database.length; i++) {
//Warunek wyklucza wektory o długości innnej niż rekordy w bazie danych
if ((vector3D[0].length == database[i][0].length) && (vector3D[1].length == database[i][1].length)) {
metryki[i] = metrManh(vector3D, database[i]);
}
}
}
//Metoda klasyfikacji
if (NN1) {
charOut = NN1(metryki);
} else {
charOut = kNN(metryki, 3);
}
return charOut;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Metryki">
private static double metrEukl(int[] vector, int[] database) {
double suma = 0;
for (int i = 0; i < database.length; i++) {
suma += Math.pow((vector[i] - database[i]), 2);
}
return Math.sqrt(suma);
}
private static int metrManh(int[] vector, int[] database) {
int suma = 0;
for (int i = 0; i < database.length; i++) {
suma += Math.abs(vector[i] - database[i]);
}
return suma;
}
private static double metrEukl(int[][] vector, int[][] database) {
double suma = 0;
for (int i = 0; i < database.length; i++) {
for (int j = 0; j < database[i].length; j++) {
suma += Math.pow((vector[i][j] - database[i][j]), 2);
}
}
return Math.sqrt(suma);
}
private static int metrManh(int[][] vector, int[][] database) {
int suma = 0;
for (int i = 0; i < database.length; i++) {
for (int j = 0; j < database[i].length; j++) {
suma += Math.abs(vector[i][j] - database[i][j]);
}
}
return suma;
}
private static double metrEukl(int[][][] vector, int[][][] database) {
double suma = 0;
for (int i = 0; i < database.length; i++) {
for (int j = 0; j < database[i].length; j++) {
for (int k = 0; k < database[i][j].length; k++) {
suma += Math.pow((vector[i][j][k] - database[i][j][k]), 2);
}
}
}
return Math.sqrt(suma);
}
private static int metrManh(int[][][] vector, int[][][] database) {
int suma = 0;
for (int i = 0; i < database.length; i++) {
for (int j = 0; j < database[i].length; j++) {
for (int k = 0; k < database[i][j].length; k++) {
suma += Math.abs(vector[i][j][k] - database[i][j][k]);
}
}
}
return suma;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="1NN">
/**
* Znajduje minimalną wartość metryki i zwraca jej pozycję w tablicy.
*
* @param metryki Tablica z metrykami.
* @return Znak.
*/
private static char NN1(double[] metryki) {
double[] szukacz = new double[2];
szukacz[0] = metryki[0];
szukacz[1] = 0;
for (int i = 1; i < metryki.length; i++) {
if (metryki[i] < szukacz[0]) {
szukacz[0] = metryki[i];
szukacz[1] = i;
}
}
return findChar((int) szukacz[1]);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="kNN">
/**
* Znajduje k minimalnych wartości metryki. Sprawdza jakim znakom odpowiadają
* i wybiera znak najczęściej występujący.
*
* @param metryki Tablica z metrykami.
* @param k Liczba minimlanych wartości.
* @return Znak.
*/
private static char kNN(double[] metryki, int k) {
//Tworzymy tablicę z minimami.
double[][] minima = new double[k][2];
//Szukacz znajduje minimalną wartość w tablicy. W komórce [0] wartość, a w komórce [1] jej indeks w tablicy.
double[] szukacz = new double[2];
//Jako minimalną wartość przypisuję pierwszą wartość z tablicy metryki.
szukacz[0] = metryki[0];
szukacz[1] = 0;
//Przeszukuję całą tablicę metryki w poszukiwaniu minimalnej wartości.
for (int i = 1; i < metryki.length; i++) {
if (metryki[i] < szukacz[0]) {
szukacz[0] = metryki[i];
szukacz[1] = i;
}
}
//Znalezioną minimalną wartość i jej indeks wpisuję do pierwszej komórki tablicy minima.
minima[0][0] = szukacz[0];
minima[0][1] = szukacz[1];
//Szukam kolejnych minimalnych wartości k-1 razy tak aby zapełnić tablicę minima.
for (int i = 1; i < k; i++) {
//Jako minimalną wartość przypisuję pierwszą wartość z tablicy metryki.
szukacz[0] = metryki[0];
szukacz[1] = 0;
//Przeszukuję całą tablicę metryki w poszukiwaniu minimalnej wartości większej od wartośći z pozycji minima[k-1];
for (int j = 1; j < metryki.length; j++) {
if ((metryki[j] < szukacz[0]) && metryki[j] > minima[i - 1][0]) {
szukacz[0] = metryki[j];
szukacz[1] = j;
}
}
minima[i][0] = szukacz[0];
minima[i][1] = szukacz[1];
}
//Wypisuję minima i znaki im odpowiadające
// for (int i = 0; i < k; i++) {
// System.out.print(minima[i][0] + " " + findChar((int) minima[i][1]) + ", ");
// }
int[] tally = new int[128];
for (int i = 0; i < tally.length; i++) {
tally[i] = 0;
}
for (int i = 0; i < minima.length; i++) {
tally[findChar((int) minima[i][1])]++;
}
int maxIndex = 0;
for (int i = 1; i < tally.length; i++) {
if (tally[i] > tally[maxIndex]) {
maxIndex = i;
}
}
//System.out.println(" Najczęściej występuje: " + (char) maxIndex);
return (char) maxIndex;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="findChar">
/**
* Metoda na podstawie indeksu w tabeli rozponaje znak.
*
* @param index Indeks.
* @return Znak.
*/
private static char findChar(int index) {
char[] trainingLettersArray = new char[93];
trainingLettersArray[0] = 'Q';
trainingLettersArray[1] = 'W';
trainingLettersArray[2] = 'E';
trainingLettersArray[3] = 'R';
trainingLettersArray[4] = 'T';
trainingLettersArray[5] = 'Y';
trainingLettersArray[6] = 'U';
trainingLettersArray[7] = 'I';
trainingLettersArray[8] = 'O';
trainingLettersArray[9] = 'P';
trainingLettersArray[10] = 'A';
trainingLettersArray[11] = 'S';
trainingLettersArray[12] = 'D';
trainingLettersArray[13] = 'F';
trainingLettersArray[14] = 'G';
trainingLettersArray[15] = 'H';
trainingLettersArray[16] = 'J';
trainingLettersArray[17] = 'K';
trainingLettersArray[18] = 'L';
trainingLettersArray[19] = 'Z';
trainingLettersArray[20] = 'X';
trainingLettersArray[21] = 'C';
trainingLettersArray[22] = 'V';
trainingLettersArray[23] = 'B';
trainingLettersArray[24] = 'N';
trainingLettersArray[25] = 'M';
trainingLettersArray[26] = 'q';
trainingLettersArray[27] = 'w';
trainingLettersArray[28] = 'e';
trainingLettersArray[29] = 'r';
trainingLettersArray[30] = 't';
trainingLettersArray[31] = 'y';
trainingLettersArray[32] = 'u';
trainingLettersArray[33] = 'i';
trainingLettersArray[34] = 'o';
trainingLettersArray[35] = 'p';
trainingLettersArray[36] = 'a';
trainingLettersArray[37] = 's';
trainingLettersArray[38] = 'd';
trainingLettersArray[39] = 'f';
trainingLettersArray[40] = 'g';
trainingLettersArray[41] = 'h';
trainingLettersArray[42] = 'j';
trainingLettersArray[43] = 'k';
trainingLettersArray[44] = 'l';
trainingLettersArray[45] = 'z';
trainingLettersArray[46] = 'x';
trainingLettersArray[47] = 'c';
trainingLettersArray[48] = 'v';
trainingLettersArray[49] = 'b';
trainingLettersArray[50] = 'n';
trainingLettersArray[51] = 'm';
trainingLettersArray[52] = '`';
trainingLettersArray[53] = '1';
trainingLettersArray[54] = '2';
trainingLettersArray[55] = '3';
trainingLettersArray[56] = '4';
trainingLettersArray[57] = '5';
trainingLettersArray[58] = '6';
trainingLettersArray[59] = '7';
trainingLettersArray[60] = '8';
trainingLettersArray[61] = '9';
trainingLettersArray[62] = '0';
trainingLettersArray[63] = '-';
trainingLettersArray[64] = '=';
trainingLettersArray[65] = '[';
trainingLettersArray[66] = ']';
trainingLettersArray[67] = '\\';
trainingLettersArray[68] = ';';
trainingLettersArray[69] = '\'';
trainingLettersArray[70] = ',';
trainingLettersArray[71] = '.';
trainingLettersArray[72] = '/';
trainingLettersArray[73] = '~';
trainingLettersArray[74] = '!';
trainingLettersArray[75] = '@';
trainingLettersArray[76] = '#';
trainingLettersArray[77] = '$';
trainingLettersArray[78] = '%';
trainingLettersArray[79] = '^';
trainingLettersArray[80] = '&';
trainingLettersArray[81] = '*';
trainingLettersArray[82] = '(';
trainingLettersArray[83] = ')';
trainingLettersArray[84] = '_';
trainingLettersArray[85] = '+';
trainingLettersArray[86] = '{';
trainingLettersArray[87] = '}';
trainingLettersArray[88] = '|';
trainingLettersArray[89] = ':';
trainingLettersArray[90] = '<';
trainingLettersArray[91] = '>';
trainingLettersArray[92] = '?';
if (index > 92) {
index %= 93;
}
return trainingLettersArray[index];
}
//</editor-fold>
} | t |
9114_2 | hun7err/simple-text-editor | 1,712 | src/com/simpletexteditor/Window.java | /**
*
*/
package com.simpletexteditor;
import java.awt.BorderLayout;
/*import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;*/
//import java.awt.Font;
//import java.awt.Color;
//import java.awt.Component;
import java.awt.Toolkit;
import java.io.IOException;
//import java.awt.event.KeyEvent;
//import java.awt.image.*;
//import javax.imageio.ImageIO;
import javax.swing.*;
import org.fife.ui.rsyntaxtextarea.Theme;
/**
* @author hun7er
*
*/
///////////////////////////
/*
to-do:
- jak się uda to menu kontekstowe do zakładek
- replace i replaceAll (jedno okno)
- Makefile (z generowaniem .jar do bin/ włącznie), pamiętać o classpath
- ew. zmiana stylu
Jest godzina 2:00, muszę wstać na 6:00 i spakować walizkę (czyli pewnie koło 5:00).
Damn you, Java...
*/
//////////////////////////
public class Window {
private JFrame frame = null,
searchFrame = null,
searchAndReplaceFrame = null,
changeThemeFrame = null,
aboutFrame = null;
private String curSkin = "Gemini"/*"Graphite","Dust","Mariner","Gemini","Autumn"*/,
curEditorSkin = "default";
private int width, height;
private JPanel panel;
private JTabbedPane tabs;
private Menu menu;
private JTextField searchField, replacementField;
private JCheckBox regexCB;
private JCheckBox matchCaseCB;
public JFrame getSearchFrame() {
return searchFrame;
}
public JFrame getSearchAndReplaceFrame() {
return searchAndReplaceFrame;
}
public JFrame getAboutFrame() {
return aboutFrame;
}
public JFrame getChangeThemeFrame() {
return changeThemeFrame;
}
public JPanel getPanel() {
return panel;
}
public JTextField getReplacementField() {
return replacementField;
}
public Menu getMenu() {
return menu;
}
public JCheckBox getRegexCB() {
return regexCB;
}
public JCheckBox getMatchCaseCB() {
return matchCaseCB;
}
public JTabbedPane getTabs() {
return tabs;
}
public JTextField getSearchField() {
return searchField;
}
public JFrame getFrame() {
return frame;
}
public void setAboutFrame(JFrame f) {
aboutFrame = f;
}
public void setSearchField(JTextField f) {
searchField = f;
}
public void setReplacementField(JTextField f) {
replacementField = f;
}
public void setMatchCaseCB(JCheckBox c) {
matchCaseCB = c;
}
public void setRegexCB(JCheckBox c) {
regexCB = c;
}
public void setFrame(JFrame f) {
frame = f;
}
public void setSearchFrame(JFrame f) {
searchFrame = f;
}
public void setSearchAndReplaceFrame(JFrame f) {
searchAndReplaceFrame = f;
}
public void setChangeThemeFrame(JFrame f) {
changeThemeFrame = f;
}
public void setSkin(String name) throws Exception {
curSkin = name;
//JFrame.setDefaultLookAndFeelDecorated(true);
try {
UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.Substance"+curSkin+"LookAndFeel");
} catch (Exception e) {
throw new Exception(e);
}
}
public void setCurEditorSkin(String name) {
curEditorSkin = name;
}
public String getCurrentSkin() {
return curSkin;
}
public String getCurrentEditorSkin() {
return curEditorSkin;
}
private void createControls() {
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//if (icon != null) frame.setIconImage(icon);
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("res/icon.png"));
//frame.setBackground(Color.GREEN);
panel = new JPanel(new java.awt.BorderLayout()); // works, yay \o/
//panel.setBackground(Color.RED);
tabs = new JTabbedPane();
menu = new Menu(new WindowActionHandler(this));
panel.add(menu.getMenuBar(), BorderLayout.PAGE_START);
panel.add(tabs, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
}
public void changeEditorTheme(String name) {
setCurEditorSkin(name);
for(int i = 0; i < AppManager.getDocuments().size(); i++) {
try {
Theme theme = Theme.load(getClass().getResourceAsStream("res/" + name + ".xml"));
theme.apply(AppManager.getDocuments().get(i).getEditor());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public Window(int w, int h) throws Exception {
width = w;
height = h;
JFrame.setDefaultLookAndFeelDecorated(true);
try {
setSkin(this.getCurrentSkin());
} catch (Exception e) {
throw new Exception(e);
}
frame = new JFrame("Simple Text Editor");
createControls();
}
}
| /*
to-do:
- jak się uda to menu kontekstowe do zakładek
- replace i replaceAll (jedno okno)
- Makefile (z generowaniem .jar do bin/ włącznie), pamiętać o classpath
- ew. zmiana stylu
Jest godzina 2:00, muszę wstać na 6:00 i spakować walizkę (czyli pewnie koło 5:00).
Damn you, Java...
*/ | /**
*
*/
package com.simpletexteditor;
import java.awt.BorderLayout;
/*import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;*/
//import java.awt.Font;
//import java.awt.Color;
//import java.awt.Component;
import java.awt.Toolkit;
import java.io.IOException;
//import java.awt.event.KeyEvent;
//import java.awt.image.*;
//import javax.imageio.ImageIO;
import javax.swing.*;
import org.fife.ui.rsyntaxtextarea.Theme;
/**
* @author hun7er
*
*/
///////////////////////////
/*
to-do:
- <SUF>*/
//////////////////////////
public class Window {
private JFrame frame = null,
searchFrame = null,
searchAndReplaceFrame = null,
changeThemeFrame = null,
aboutFrame = null;
private String curSkin = "Gemini"/*"Graphite","Dust","Mariner","Gemini","Autumn"*/,
curEditorSkin = "default";
private int width, height;
private JPanel panel;
private JTabbedPane tabs;
private Menu menu;
private JTextField searchField, replacementField;
private JCheckBox regexCB;
private JCheckBox matchCaseCB;
public JFrame getSearchFrame() {
return searchFrame;
}
public JFrame getSearchAndReplaceFrame() {
return searchAndReplaceFrame;
}
public JFrame getAboutFrame() {
return aboutFrame;
}
public JFrame getChangeThemeFrame() {
return changeThemeFrame;
}
public JPanel getPanel() {
return panel;
}
public JTextField getReplacementField() {
return replacementField;
}
public Menu getMenu() {
return menu;
}
public JCheckBox getRegexCB() {
return regexCB;
}
public JCheckBox getMatchCaseCB() {
return matchCaseCB;
}
public JTabbedPane getTabs() {
return tabs;
}
public JTextField getSearchField() {
return searchField;
}
public JFrame getFrame() {
return frame;
}
public void setAboutFrame(JFrame f) {
aboutFrame = f;
}
public void setSearchField(JTextField f) {
searchField = f;
}
public void setReplacementField(JTextField f) {
replacementField = f;
}
public void setMatchCaseCB(JCheckBox c) {
matchCaseCB = c;
}
public void setRegexCB(JCheckBox c) {
regexCB = c;
}
public void setFrame(JFrame f) {
frame = f;
}
public void setSearchFrame(JFrame f) {
searchFrame = f;
}
public void setSearchAndReplaceFrame(JFrame f) {
searchAndReplaceFrame = f;
}
public void setChangeThemeFrame(JFrame f) {
changeThemeFrame = f;
}
public void setSkin(String name) throws Exception {
curSkin = name;
//JFrame.setDefaultLookAndFeelDecorated(true);
try {
UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.Substance"+curSkin+"LookAndFeel");
} catch (Exception e) {
throw new Exception(e);
}
}
public void setCurEditorSkin(String name) {
curEditorSkin = name;
}
public String getCurrentSkin() {
return curSkin;
}
public String getCurrentEditorSkin() {
return curEditorSkin;
}
private void createControls() {
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//if (icon != null) frame.setIconImage(icon);
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("res/icon.png"));
//frame.setBackground(Color.GREEN);
panel = new JPanel(new java.awt.BorderLayout()); // works, yay \o/
//panel.setBackground(Color.RED);
tabs = new JTabbedPane();
menu = new Menu(new WindowActionHandler(this));
panel.add(menu.getMenuBar(), BorderLayout.PAGE_START);
panel.add(tabs, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
}
public void changeEditorTheme(String name) {
setCurEditorSkin(name);
for(int i = 0; i < AppManager.getDocuments().size(); i++) {
try {
Theme theme = Theme.load(getClass().getResourceAsStream("res/" + name + ".xml"));
theme.apply(AppManager.getDocuments().get(i).getEditor());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public Window(int w, int h) throws Exception {
width = w;
height = h;
JFrame.setDefaultLookAndFeelDecorated(true);
try {
setSkin(this.getCurrentSkin());
} catch (Exception e) {
throw new Exception(e);
}
frame = new JFrame("Simple Text Editor");
createControls();
}
}
| f |
8221_34 | hycomsa/mokka | 6,912 | src/mokka/src/main/java/pl/hycom/mokka/util/query/Q.java | package pl.hycom.mokka.util.query;
import org.apache.commons.lang3.StringUtils;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
/**
* Utilowa klasa pomocnicza wspierajaca budowe zapytan SQL. Klasa wiaze zapytanie od razu z parametrami
* dzieki czemu poprawia czytelnosc zapytan sql. Dodatkowo ma metody wspomagajace generowanie kodow SQL
* dzieki czemu mozna skrocic i ujednolicic np sprawdzanie nieustawienia flagi.
*
* Zapytanie zaczynamy budowac zawsze od:
* Q q = Q.select("pole, pole")...
*
* Wiekszosc metod zwraca siebie co pomaga 'chainowac' zapytani, np:
*
* Q q = Q.select("foo").from("bar").where("foo = ?, 1).and(Q.before("start", new Date());
*
* Kontrakt: Metody na obiekcie zawsze modyfikuja biezacy obiekt i po modyfikacji go zwracaja, nigdy
* nie generuja nowego obiektu, do tego sa przeznaczone tylko metody statyczne, wyjatkiem jest metoda clone/copy()
* zwracajaca kopie biezacego obiektu
*
* @author mariusz hagi (hagi@amg.net.pl)
* @id CL-1030.013.084
*/
public class Q {
public static final String IS_NULL_OR = " is null OR ";
public static final String GREATER_EQUAL = " >= ?)";
public static final String LESS_EQUAL = " <= ?)";
protected String select = StringUtils.EMPTY;
protected String from = StringUtils.EMPTY;
protected String orderby = StringUtils.EMPTY;
protected String groupby = StringUtils.EMPTY;
protected Integer startingIndex = null;
protected Integer maxResults = null;
protected StringBuilder where = new StringBuilder();
protected List<Object> params = new ArrayList<>();
/** Flaga okreslajaca, ze jest to podzapytanie, nie dodajemy wtedy select i from przy generowaniu query */
protected boolean subquery = false;
private Q() {
} // disabled
private Q(String where) {
this.where.append(where);
this.subquery = true;
}
private Q(String where, Object... params) {
this.where.append(where);
this.params.addAll(Arrays.asList(params));
this.subquery = true;
}
public static Q select(String query) {
Q q = new Q();
q.select = query;
return q;
}
public static Q empty() {
Q q = new Q();
q.subquery = true;
return q;
}
/**
* sekcja FROM zapytania, mozna uzyc wielokrotnie np. q.from("foo).from("bar")
* polecam uzywanie krotkich aliasow przy kilku tabelach, np: q.from("v_declare_price_p v, dcs_shop_proposition p")
* i uzywanie pozniej aliasow przy polach dla zwiekszenia czytelnosci
*
* @param from
* @return
*/
public Q from(String... from) {
this.from += (this.from.length() > 0 ? ", " : StringUtils.EMPTY) + StringUtils.join(from, ", ");
return this;
}
/**
* sekcja ORDER BY zapytania, mozna uzyc wielokrotnie np. q.orderby("foo).orderby("bar", "blah desc")
*
* @param orderbys
* okresla po czym sortowac
* @return biezacy obiekt, ulatwia 'chainowanie'
*/
public Q orderby(String... orderbys) {
this.orderby += (this.orderby.length() > 0 ? ", " : StringUtils.EMPTY) + StringUtils.join(orderbys, ", ");
return this;
}
/**
* sekcja ORDER BY z parametrami, ze wzgledu na dodawanie parametrow, powinna byc wywolywana w naturalnym porzadku
* (statyczne orderby moze byc dolaczane wczesniej), czyli
* q.and(...).orderby(...)
* a nie q.orderby(...).and(...)
*
* @param orderby
* okresla po czym sortowac
* @param params
* wartosci parametrow dla orderby
* @return biezacy obiekt, ulatwia 'chainowanie'
*/
public Q orderbyWithParams(String orderby, Object... params) {
this.orderby += (this.orderby.length() > 0 ? ", " : StringUtils.EMPTY) + orderby;
this.params.addAll(Arrays.asList(params));
return this;
}
/**
* sekcja GROUP BY zapytania
*
* @param groupby
* okresla po czym grupować
* @return biezacy obiekt, ulatwia 'chainowanie'
*/
public Q groupby(String groupby) {
this.groupby = groupby;
return this;
}
public Q and(String query, Object... params) {
append(" AND ", query, params);
return this;
}
public Q and(Q... q) {
for (int i = 0; i < q.length; i++) {
append(" AND ", q[i].query(), q[i].params());
}
return this;
}
public Q or(String query, Object... params) {
append(" OR ", query, params);
return this;
}
public Q or(Q q) {
append(" OR ", q.query(), q.params());
return this;
}
public Q where(String query, Object... params) {
append(" ", query, params);
return this;
}
public Q where(Q q) {
append(" ", q.query(), q.params());
return this;
}
/**
* Zagniedzone ANDy: Q1 AND Q2 AND Q3... np:
* q.where(Q.ands(....).or(Q.ands(...))
*
* @param qs
* @return
*/
public static Q ands(Q... qs) {
Q q = new Q(qs[0].query(), qs[0].params());
if (qs.length > 1) {
for (int i = 1; i < qs.length; i++) {
q.and(qs[i]);
}
}
return q;
}
/**
* Nested ORs: Q1 OR Q2 OR Q3...
*
* @param qs
* @return
*/
public static Q ors(Q... qs) {
Q q = new Q(qs[0].query(), qs[0].params());
if (qs.length > 1) {
for (int i = 1; i < qs.length; i++) {
q.or(qs[i]);
}
}
return q;
}
/**
* Do generowania podzapytan
*/
public static Q stmt(String query, Object... params) {
return new Q("(" + query + ")", params);
}
public static Q exists(Q sub) {
return new Q("exists (" + sub.query() + ")", sub.params());
}
public static Q notExists(Q sub) {
return new Q("not exists (" + sub.query() + ")", sub.params());
}
/**
* Do generowania podzapytan
*/
public static Q sub(String query, Object... params) {
return new Q("(" + query + ")", params);
}
/**
* Generuje: {field} = ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo = ?", foo)
*
* ale moze byc przydatne przy zahniezdzaniu:
*
* q.and(Q.eq("foo", foo).or("blah > 3"))
* sql: AND (foo = ? OR blah > 3)
*
* zamiast: q.and(Q.stmt("foo = ?", foo).or("blah > 3"))
*/
public static Q eq(String field, Object value) {
return new Q(field + " = ?", value);
}
/**
* Generuje: {field} < ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo < ?", foo)
*
* ale moze byc przydatne przy dynamicznych polach
*
* q.and(Q.ls(foo, 12))
* zamiast: q.and(foo + " < ?", 12)
*/
public static Q lt(String field, Object value) {
return new Q(field + " < ?", value);
}
/**
* Generuje: {field} > ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo > ?", foo)
*
* ale moze byc przydatne przy dynamicznych polach
*
* q.and(Q.ls(foo, 12))
* zamiast: q.and(foo + " > ?", 12)
*/
public static Q gt(String field, Object value) {
return new Q(field + " > ?", value);
}
/**
* Generuje: {field} <= ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo <= ?", foo)
*
* ale moze byc przydatne przy dynamicznych polach
*
* q.and(Q.ls(foo, 12))
* zamiast: q.and(foo + " <= ?", 12)
*/
public static Q le(String field, Object value) {
return new Q(field + " <= ?", value);
}
/**
* Generuje: {field} >= ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo >= ?", foo)
*
* ale moze byc przydatne przy dynamicznych polach
*
* q.and(Q.ls(foo, 12))
* zamiast: q.and(foo + " >= ?", 12)
*/
public static Q ge(String field, Object value) {
return new Q(field + " >= ?", value);
}
/**
* Sprawdzanie nieustawienia flagi: {field} is null OR {field} = 0
*
* @param field
* nazwa pola
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q not(String field) {
return new Q("(" + field + IS_NULL_OR + field + " = 0)");
}
/**
* Sprawdzanie nulla: {field} is null
*
* @param field
* nazwa pola
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q isNull(String field) {
return new Q(field + " is null");
}
/**
* Sprawdzanie nulla dla kazdego z podanych pol: {field1} is null and {field2} is null and ...
*
* @param fields
* nazwy pol
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q nulls(String... fields) {
Q q = Q.isNull(fields[0]);
if (fields.length > 1) {
for (int i = 1; i < fields.length; i++) {
q.and(Q.isNull(fields[i]));
}
}
return q;
}
/**
* Sprawdzanie nulla: {field} is not null
*
* @param field
* nazwa pola
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q notNull(String field) {
return new Q(field + " is not null");
}
/**
* Generuje: {field} like ? %{value}%
*/
public static Q like(String field, Object value) {
return new Q(field + " like ?", StringUtils.replaceChars(value.toString(), '*', '%'));
}
/**
* Sprawdzanie ustawienia flagi: {field} = 1
*
* @param field
* nazwa pola
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q is(String field) {
return new Q(field + " = 1");
}
/**
* Data przed: {field} <= ?
* dla ewentualnego nulla uzyj <code>Q.validFrom</code>
*
* @param field
* nazwa pola
* @param date
* stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q before(String field, Date date) {
return new Q(field + " <= ?", new Timestamp(date.getTime()));
}
/**
* Data po: {field} >= ?
* dla ewentualnego nulla uzyj <code>Q.validTo</code>
*
* @param field
* nazwa pola
* @param date
* stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q after(String field, Date date) {
return new Q(field + " >= ?", new Timestamp(date.getTime()));
}
/**
* Wstawiamy pole okreslajace date waznosci do: {field} is null or {field} >= ?(stamp)
* Bez nulla uzyj <code>Q.after</code>
*
* @param field
* nazwa pola
* @param date
* stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validTo(String field, Date date) {
return new Q("(" + field + IS_NULL_OR + field + GREATER_EQUAL, new Timestamp(date.getTime()));
}
/**
* Wstawiamy pole okreslajace date waznosci od: {field} is null or {field} <= ?(stamp)
* Bez nulla uzyj <code>Q.before</code>
*
* @param field
* nazwa pola
* @param date
* stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validFrom(String field, Date date) {
return new Q("(" + field + IS_NULL_OR + field + LESS_EQUAL, new Timestamp(date.getTime()));
}
/**
* Wstawiamy pole okreslajace date waznosci do: {field} is null or {field} >= ?(stamp)
* Bez nulla uzyj <code>Q.after</code>
*
* @param field
* nazwa pola
* @param time
* stamp w milisekundach
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validTo(String field, long time) {
return new Q("(" + field + IS_NULL_OR + field + GREATER_EQUAL, new Timestamp(time));
}
/**
* Wstawiamy pole okreslajace date waznosci od: {field} is null or {field} <= ?(stamp)
* Bez nulla uzyj <code>Q.before</code>
*
* @param field
* nazwa pola
* @param time
* stamp w milisekundach
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validFrom(String field, long time) {
return new Q("(" + field + IS_NULL_OR + field + LESS_EQUAL, new Timestamp(time));
}
/**
* Wstawiamy pole okreslajace date waznosci do: {field} is null or {field} >= ?(stamp)
* Bez nulla uzyj <code>Q.after</code>
*
* @param field
* nazwa pola
* @param stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validTo(String field, Timestamp stamp) {
return new Q("(" + field + IS_NULL_OR + field + GREATER_EQUAL, stamp);
}
/**
* Wstawiamy pole okreslajace date waznosci od: {field} is null or {field} <= ?(stamp)
* Bez nulla uzyj <code>Q.before</code>
*
* @param field
* nazwa pola
* @param stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validFrom(String field, Timestamp stamp) {
return new Q("(" + field + IS_NULL_OR + field + LESS_EQUAL, stamp);
}
/**
* Wstawiamy pola okreslajace date waznosci od i do:
* ({field} is null or {field} <= ?(stamp)) and ({field} is null or {field} >= ?(stamp))
* Pojedyncze sprawdzenia: <code>Q.validFrom</code>, <code>
* @param fieldFrom pole okreslajace date waznosci od
* @param fieldTo pole okreslajace date waznosci do
* @param stamp timestamp
*
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q valid(String fieldFrom, String fieldTo, Timestamp stamp) {
return Q.validFrom(fieldFrom, stamp)
.and(Q.validTo(fieldTo, stamp));
}
/**
* Wstawia konstrukcje: {field} in (?, ?,...)
*
* @param field
* nazwa pola
* @param items
* lista parametrow
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q in(String field, Collection<? extends Object> items) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
sb.append(i > 0 ? ", ?" : "?");
}
Q q = new Q(field + " IN (" + sb + ")");
q.params.addAll(items);
return q;
}
/**
* Wstawia bezposrednio wartosci dla konstrukcji IN: {field} in (1, 19, 2,...)
* nadaje sie tylko dla listy wartosci numerycznych
*
* @param field
* nazwa pola
* @param items
* lista parametrow
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q directIn(String field, List<? extends Object> items) {
return new Q(field + " IN (" + StringUtils.join(items, ", ") + ")");
}
/**
* W zaleznosci od wartosci parametru condition generowane jest zapytanie
* sprawdzajace czy flaga jest ustawiona (dla wartosci <code>true</code>):
* {field} = 1
*
* lub czy nie jest (dla wartosci <code>false</code>)
* {field} is null OR {field} = 0
*
* @param field
* nazwa pola
* @param condition
* warunek okreslajacy, ktory warunek sql generowac
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q conditional(String field, boolean condition) {
return condition ? Q.is(field) : Q.not(field);
}
public static Q contains(String field, String match, boolean ignorecase) {
return new Q(ignorecase ? "upper(" + field + ") LIKE ?" : field + " LIKE ?", "%" + (ignorecase ?
match.toUpperCase(Locale.getDefault()) : match) + "%");
}
public static Q notContains(String field, String notMatch, boolean ignorecase) {
return new Q(ignorecase ? "upper(" + field + ") NOT LIKE ?" : field + " NOT LIKE ?", "%" + (ignorecase ?
notMatch.toUpperCase(Locale.getDefault()) : notMatch) + "%");
}
protected void append(String prefix, String query, Object... params) {
where.append(where.length() == 0 ? " " : prefix)
.append("(")
.append(query)
.append(")");
if (params != null && params.length > 0) {
List<Object> paramList = Arrays.asList(params);
this.params.addAll(paramList.stream()
.map(o -> o != null && o.getClass()
.isEnum() ? o.toString() : o)
.collect(Collectors.toList()));
}
}
public Q startingIndex(Integer startingIndex) {
this.startingIndex = startingIndex;
return this;
}
public Q maxResults(Integer maxResults) {
this.maxResults = maxResults;
return this;
}
/**
* Generuje nowy obiekt Q na podstawie swoich wartosci, lista parametrow nie jest lista
* klonowanych wartosci.
*/
public Q copy() {
Q n = new Q();
n.select = select;
n.from = from;
n.orderby = orderby;
n.groupby = groupby;
n.where.append(where.toString());
n.params.addAll(paramsAsList());
n.subquery = subquery;
return n;
}
@Override
public String toString() {
return "Query[" + query() + "], params [" + StringUtils.join(params(), ", ") + "]";
}
/**
* Metoda ma za zadanie przekonwertowac znaczniki '?' lub '?{numer}' na
* odpowiednie wynikajace z ilosci parametrow
*
* @param in
* @return
*/
private String replaceMarks(String in) { // TODO: better method?
String[] ins = in.split("\\?\\d*", -1); // gratulacje dla projektanta
// parametrow splita, ugh
if (ins.length == 1) {
return in; // brak markerow
}
StringBuilder sb = new StringBuilder(ins[0]);
for (int i = 1; i < ins.length; i++) {
sb.append("?" + (i - 1))
.append(ins[i]);
}
return sb.toString();
}
/**
* Query dla executa
*
* @return
*/
public String query() {
return replaceMarks((select.length() > 0 && !subquery ? "SELECT " + select + " " : StringUtils.EMPTY) + (
from.length() > 0 && !subquery ? "FROM " + from + " " : StringUtils.EMPTY) + (
where.length() > 0 && !subquery ? "WHERE " : StringUtils.EMPTY) + where + (groupby.length() > 0 ?
" GROUP BY " + groupby : StringUtils.EMPTY) + (orderby.length() > 0 ? " ORDER BY " + orderby :
StringUtils.EMPTY));
}
/**
* Parametry dla executa
*
* @return
*/
public Object[] params() {
return params.toArray();
}
public List<Object> paramsAsList() {
return params;
}
/**
* Query z podstawionymi parametrami. Konwertowane sa parametry typu Timestamp oraz String.
*
* @return
*/
public String queryWithParams() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sqlToDateFormat = "TO_DATE('%s', 'yyyy-mm-dd HH24:MI:SS')";
String query = query();
for (Object p : paramsAsList()) {
if (p instanceof String) {
p = "'" + p + "'";
} else if (p instanceof Timestamp) {
p = String.format(sqlToDateFormat, dateFormat.format((Timestamp) p));
}
query = query.replaceFirst("\\?", String.valueOf(p));
}
return query;
}
Integer getStartingIndex() {
return startingIndex;
}
Integer getMaxResults() {
return maxResults;
}
}
| /**
* Metoda ma za zadanie przekonwertowac znaczniki '?' lub '?{numer}' na
* odpowiednie wynikajace z ilosci parametrow
*
* @param in
* @return
*/ | package pl.hycom.mokka.util.query;
import org.apache.commons.lang3.StringUtils;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
/**
* Utilowa klasa pomocnicza wspierajaca budowe zapytan SQL. Klasa wiaze zapytanie od razu z parametrami
* dzieki czemu poprawia czytelnosc zapytan sql. Dodatkowo ma metody wspomagajace generowanie kodow SQL
* dzieki czemu mozna skrocic i ujednolicic np sprawdzanie nieustawienia flagi.
*
* Zapytanie zaczynamy budowac zawsze od:
* Q q = Q.select("pole, pole")...
*
* Wiekszosc metod zwraca siebie co pomaga 'chainowac' zapytani, np:
*
* Q q = Q.select("foo").from("bar").where("foo = ?, 1).and(Q.before("start", new Date());
*
* Kontrakt: Metody na obiekcie zawsze modyfikuja biezacy obiekt i po modyfikacji go zwracaja, nigdy
* nie generuja nowego obiektu, do tego sa przeznaczone tylko metody statyczne, wyjatkiem jest metoda clone/copy()
* zwracajaca kopie biezacego obiektu
*
* @author mariusz hagi (hagi@amg.net.pl)
* @id CL-1030.013.084
*/
public class Q {
public static final String IS_NULL_OR = " is null OR ";
public static final String GREATER_EQUAL = " >= ?)";
public static final String LESS_EQUAL = " <= ?)";
protected String select = StringUtils.EMPTY;
protected String from = StringUtils.EMPTY;
protected String orderby = StringUtils.EMPTY;
protected String groupby = StringUtils.EMPTY;
protected Integer startingIndex = null;
protected Integer maxResults = null;
protected StringBuilder where = new StringBuilder();
protected List<Object> params = new ArrayList<>();
/** Flaga okreslajaca, ze jest to podzapytanie, nie dodajemy wtedy select i from przy generowaniu query */
protected boolean subquery = false;
private Q() {
} // disabled
private Q(String where) {
this.where.append(where);
this.subquery = true;
}
private Q(String where, Object... params) {
this.where.append(where);
this.params.addAll(Arrays.asList(params));
this.subquery = true;
}
public static Q select(String query) {
Q q = new Q();
q.select = query;
return q;
}
public static Q empty() {
Q q = new Q();
q.subquery = true;
return q;
}
/**
* sekcja FROM zapytania, mozna uzyc wielokrotnie np. q.from("foo).from("bar")
* polecam uzywanie krotkich aliasow przy kilku tabelach, np: q.from("v_declare_price_p v, dcs_shop_proposition p")
* i uzywanie pozniej aliasow przy polach dla zwiekszenia czytelnosci
*
* @param from
* @return
*/
public Q from(String... from) {
this.from += (this.from.length() > 0 ? ", " : StringUtils.EMPTY) + StringUtils.join(from, ", ");
return this;
}
/**
* sekcja ORDER BY zapytania, mozna uzyc wielokrotnie np. q.orderby("foo).orderby("bar", "blah desc")
*
* @param orderbys
* okresla po czym sortowac
* @return biezacy obiekt, ulatwia 'chainowanie'
*/
public Q orderby(String... orderbys) {
this.orderby += (this.orderby.length() > 0 ? ", " : StringUtils.EMPTY) + StringUtils.join(orderbys, ", ");
return this;
}
/**
* sekcja ORDER BY z parametrami, ze wzgledu na dodawanie parametrow, powinna byc wywolywana w naturalnym porzadku
* (statyczne orderby moze byc dolaczane wczesniej), czyli
* q.and(...).orderby(...)
* a nie q.orderby(...).and(...)
*
* @param orderby
* okresla po czym sortowac
* @param params
* wartosci parametrow dla orderby
* @return biezacy obiekt, ulatwia 'chainowanie'
*/
public Q orderbyWithParams(String orderby, Object... params) {
this.orderby += (this.orderby.length() > 0 ? ", " : StringUtils.EMPTY) + orderby;
this.params.addAll(Arrays.asList(params));
return this;
}
/**
* sekcja GROUP BY zapytania
*
* @param groupby
* okresla po czym grupować
* @return biezacy obiekt, ulatwia 'chainowanie'
*/
public Q groupby(String groupby) {
this.groupby = groupby;
return this;
}
public Q and(String query, Object... params) {
append(" AND ", query, params);
return this;
}
public Q and(Q... q) {
for (int i = 0; i < q.length; i++) {
append(" AND ", q[i].query(), q[i].params());
}
return this;
}
public Q or(String query, Object... params) {
append(" OR ", query, params);
return this;
}
public Q or(Q q) {
append(" OR ", q.query(), q.params());
return this;
}
public Q where(String query, Object... params) {
append(" ", query, params);
return this;
}
public Q where(Q q) {
append(" ", q.query(), q.params());
return this;
}
/**
* Zagniedzone ANDy: Q1 AND Q2 AND Q3... np:
* q.where(Q.ands(....).or(Q.ands(...))
*
* @param qs
* @return
*/
public static Q ands(Q... qs) {
Q q = new Q(qs[0].query(), qs[0].params());
if (qs.length > 1) {
for (int i = 1; i < qs.length; i++) {
q.and(qs[i]);
}
}
return q;
}
/**
* Nested ORs: Q1 OR Q2 OR Q3...
*
* @param qs
* @return
*/
public static Q ors(Q... qs) {
Q q = new Q(qs[0].query(), qs[0].params());
if (qs.length > 1) {
for (int i = 1; i < qs.length; i++) {
q.or(qs[i]);
}
}
return q;
}
/**
* Do generowania podzapytan
*/
public static Q stmt(String query, Object... params) {
return new Q("(" + query + ")", params);
}
public static Q exists(Q sub) {
return new Q("exists (" + sub.query() + ")", sub.params());
}
public static Q notExists(Q sub) {
return new Q("not exists (" + sub.query() + ")", sub.params());
}
/**
* Do generowania podzapytan
*/
public static Q sub(String query, Object... params) {
return new Q("(" + query + ")", params);
}
/**
* Generuje: {field} = ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo = ?", foo)
*
* ale moze byc przydatne przy zahniezdzaniu:
*
* q.and(Q.eq("foo", foo).or("blah > 3"))
* sql: AND (foo = ? OR blah > 3)
*
* zamiast: q.and(Q.stmt("foo = ?", foo).or("blah > 3"))
*/
public static Q eq(String field, Object value) {
return new Q(field + " = ?", value);
}
/**
* Generuje: {field} < ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo < ?", foo)
*
* ale moze byc przydatne przy dynamicznych polach
*
* q.and(Q.ls(foo, 12))
* zamiast: q.and(foo + " < ?", 12)
*/
public static Q lt(String field, Object value) {
return new Q(field + " < ?", value);
}
/**
* Generuje: {field} > ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo > ?", foo)
*
* ale moze byc przydatne przy dynamicznych polach
*
* q.and(Q.ls(foo, 12))
* zamiast: q.and(foo + " > ?", 12)
*/
public static Q gt(String field, Object value) {
return new Q(field + " > ?", value);
}
/**
* Generuje: {field} <= ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo <= ?", foo)
*
* ale moze byc przydatne przy dynamicznych polach
*
* q.and(Q.ls(foo, 12))
* zamiast: q.and(foo + " <= ?", 12)
*/
public static Q le(String field, Object value) {
return new Q(field + " <= ?", value);
}
/**
* Generuje: {field} >= ?
* Raczej zalecane wpisanie wprost (czytelniej):
*
* q.and("foo >= ?", foo)
*
* ale moze byc przydatne przy dynamicznych polach
*
* q.and(Q.ls(foo, 12))
* zamiast: q.and(foo + " >= ?", 12)
*/
public static Q ge(String field, Object value) {
return new Q(field + " >= ?", value);
}
/**
* Sprawdzanie nieustawienia flagi: {field} is null OR {field} = 0
*
* @param field
* nazwa pola
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q not(String field) {
return new Q("(" + field + IS_NULL_OR + field + " = 0)");
}
/**
* Sprawdzanie nulla: {field} is null
*
* @param field
* nazwa pola
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q isNull(String field) {
return new Q(field + " is null");
}
/**
* Sprawdzanie nulla dla kazdego z podanych pol: {field1} is null and {field2} is null and ...
*
* @param fields
* nazwy pol
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q nulls(String... fields) {
Q q = Q.isNull(fields[0]);
if (fields.length > 1) {
for (int i = 1; i < fields.length; i++) {
q.and(Q.isNull(fields[i]));
}
}
return q;
}
/**
* Sprawdzanie nulla: {field} is not null
*
* @param field
* nazwa pola
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q notNull(String field) {
return new Q(field + " is not null");
}
/**
* Generuje: {field} like ? %{value}%
*/
public static Q like(String field, Object value) {
return new Q(field + " like ?", StringUtils.replaceChars(value.toString(), '*', '%'));
}
/**
* Sprawdzanie ustawienia flagi: {field} = 1
*
* @param field
* nazwa pola
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q is(String field) {
return new Q(field + " = 1");
}
/**
* Data przed: {field} <= ?
* dla ewentualnego nulla uzyj <code>Q.validFrom</code>
*
* @param field
* nazwa pola
* @param date
* stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q before(String field, Date date) {
return new Q(field + " <= ?", new Timestamp(date.getTime()));
}
/**
* Data po: {field} >= ?
* dla ewentualnego nulla uzyj <code>Q.validTo</code>
*
* @param field
* nazwa pola
* @param date
* stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q after(String field, Date date) {
return new Q(field + " >= ?", new Timestamp(date.getTime()));
}
/**
* Wstawiamy pole okreslajace date waznosci do: {field} is null or {field} >= ?(stamp)
* Bez nulla uzyj <code>Q.after</code>
*
* @param field
* nazwa pola
* @param date
* stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validTo(String field, Date date) {
return new Q("(" + field + IS_NULL_OR + field + GREATER_EQUAL, new Timestamp(date.getTime()));
}
/**
* Wstawiamy pole okreslajace date waznosci od: {field} is null or {field} <= ?(stamp)
* Bez nulla uzyj <code>Q.before</code>
*
* @param field
* nazwa pola
* @param date
* stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validFrom(String field, Date date) {
return new Q("(" + field + IS_NULL_OR + field + LESS_EQUAL, new Timestamp(date.getTime()));
}
/**
* Wstawiamy pole okreslajace date waznosci do: {field} is null or {field} >= ?(stamp)
* Bez nulla uzyj <code>Q.after</code>
*
* @param field
* nazwa pola
* @param time
* stamp w milisekundach
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validTo(String field, long time) {
return new Q("(" + field + IS_NULL_OR + field + GREATER_EQUAL, new Timestamp(time));
}
/**
* Wstawiamy pole okreslajace date waznosci od: {field} is null or {field} <= ?(stamp)
* Bez nulla uzyj <code>Q.before</code>
*
* @param field
* nazwa pola
* @param time
* stamp w milisekundach
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validFrom(String field, long time) {
return new Q("(" + field + IS_NULL_OR + field + LESS_EQUAL, new Timestamp(time));
}
/**
* Wstawiamy pole okreslajace date waznosci do: {field} is null or {field} >= ?(stamp)
* Bez nulla uzyj <code>Q.after</code>
*
* @param field
* nazwa pola
* @param stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validTo(String field, Timestamp stamp) {
return new Q("(" + field + IS_NULL_OR + field + GREATER_EQUAL, stamp);
}
/**
* Wstawiamy pole okreslajace date waznosci od: {field} is null or {field} <= ?(stamp)
* Bez nulla uzyj <code>Q.before</code>
*
* @param field
* nazwa pola
* @param stamp
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q validFrom(String field, Timestamp stamp) {
return new Q("(" + field + IS_NULL_OR + field + LESS_EQUAL, stamp);
}
/**
* Wstawiamy pola okreslajace date waznosci od i do:
* ({field} is null or {field} <= ?(stamp)) and ({field} is null or {field} >= ?(stamp))
* Pojedyncze sprawdzenia: <code>Q.validFrom</code>, <code>
* @param fieldFrom pole okreslajace date waznosci od
* @param fieldTo pole okreslajace date waznosci do
* @param stamp timestamp
*
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q valid(String fieldFrom, String fieldTo, Timestamp stamp) {
return Q.validFrom(fieldFrom, stamp)
.and(Q.validTo(fieldTo, stamp));
}
/**
* Wstawia konstrukcje: {field} in (?, ?,...)
*
* @param field
* nazwa pola
* @param items
* lista parametrow
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q in(String field, Collection<? extends Object> items) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
sb.append(i > 0 ? ", ?" : "?");
}
Q q = new Q(field + " IN (" + sb + ")");
q.params.addAll(items);
return q;
}
/**
* Wstawia bezposrednio wartosci dla konstrukcji IN: {field} in (1, 19, 2,...)
* nadaje sie tylko dla listy wartosci numerycznych
*
* @param field
* nazwa pola
* @param items
* lista parametrow
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q directIn(String field, List<? extends Object> items) {
return new Q(field + " IN (" + StringUtils.join(items, ", ") + ")");
}
/**
* W zaleznosci od wartosci parametru condition generowane jest zapytanie
* sprawdzajace czy flaga jest ustawiona (dla wartosci <code>true</code>):
* {field} = 1
*
* lub czy nie jest (dla wartosci <code>false</code>)
* {field} is null OR {field} = 0
*
* @param field
* nazwa pola
* @param condition
* warunek okreslajacy, ktory warunek sql generowac
* @return obiekt zawierajacy zapytanie i parametry, nigdy <code>null</code>
*/
public static Q conditional(String field, boolean condition) {
return condition ? Q.is(field) : Q.not(field);
}
public static Q contains(String field, String match, boolean ignorecase) {
return new Q(ignorecase ? "upper(" + field + ") LIKE ?" : field + " LIKE ?", "%" + (ignorecase ?
match.toUpperCase(Locale.getDefault()) : match) + "%");
}
public static Q notContains(String field, String notMatch, boolean ignorecase) {
return new Q(ignorecase ? "upper(" + field + ") NOT LIKE ?" : field + " NOT LIKE ?", "%" + (ignorecase ?
notMatch.toUpperCase(Locale.getDefault()) : notMatch) + "%");
}
protected void append(String prefix, String query, Object... params) {
where.append(where.length() == 0 ? " " : prefix)
.append("(")
.append(query)
.append(")");
if (params != null && params.length > 0) {
List<Object> paramList = Arrays.asList(params);
this.params.addAll(paramList.stream()
.map(o -> o != null && o.getClass()
.isEnum() ? o.toString() : o)
.collect(Collectors.toList()));
}
}
public Q startingIndex(Integer startingIndex) {
this.startingIndex = startingIndex;
return this;
}
public Q maxResults(Integer maxResults) {
this.maxResults = maxResults;
return this;
}
/**
* Generuje nowy obiekt Q na podstawie swoich wartosci, lista parametrow nie jest lista
* klonowanych wartosci.
*/
public Q copy() {
Q n = new Q();
n.select = select;
n.from = from;
n.orderby = orderby;
n.groupby = groupby;
n.where.append(where.toString());
n.params.addAll(paramsAsList());
n.subquery = subquery;
return n;
}
@Override
public String toString() {
return "Query[" + query() + "], params [" + StringUtils.join(params(), ", ") + "]";
}
/**
* Metoda ma za <SUF>*/
private String replaceMarks(String in) { // TODO: better method?
String[] ins = in.split("\\?\\d*", -1); // gratulacje dla projektanta
// parametrow splita, ugh
if (ins.length == 1) {
return in; // brak markerow
}
StringBuilder sb = new StringBuilder(ins[0]);
for (int i = 1; i < ins.length; i++) {
sb.append("?" + (i - 1))
.append(ins[i]);
}
return sb.toString();
}
/**
* Query dla executa
*
* @return
*/
public String query() {
return replaceMarks((select.length() > 0 && !subquery ? "SELECT " + select + " " : StringUtils.EMPTY) + (
from.length() > 0 && !subquery ? "FROM " + from + " " : StringUtils.EMPTY) + (
where.length() > 0 && !subquery ? "WHERE " : StringUtils.EMPTY) + where + (groupby.length() > 0 ?
" GROUP BY " + groupby : StringUtils.EMPTY) + (orderby.length() > 0 ? " ORDER BY " + orderby :
StringUtils.EMPTY));
}
/**
* Parametry dla executa
*
* @return
*/
public Object[] params() {
return params.toArray();
}
public List<Object> paramsAsList() {
return params;
}
/**
* Query z podstawionymi parametrami. Konwertowane sa parametry typu Timestamp oraz String.
*
* @return
*/
public String queryWithParams() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sqlToDateFormat = "TO_DATE('%s', 'yyyy-mm-dd HH24:MI:SS')";
String query = query();
for (Object p : paramsAsList()) {
if (p instanceof String) {
p = "'" + p + "'";
} else if (p instanceof Timestamp) {
p = String.format(sqlToDateFormat, dateFormat.format((Timestamp) p));
}
query = query.replaceFirst("\\?", String.valueOf(p));
}
return query;
}
Integer getStartingIndex() {
return startingIndex;
}
Integer getMaxResults() {
return maxResults;
}
}
| f |
6260_1 | infoshareacademy/java8-exercises | 187 | src/main/java/_2_date/_2_exercise/ApiExercise.java | package _2_date._2_exercise;
public class ApiExercise {
// TODO: exercise 1 - LocalDate API
// 1. Utwórz datę reprezentującą twoje urodziny
// 2. Sprawdź jaki to był dzień tygodnia oraz który dzień roku
// 3. Utwórz dzisiejszą datę
// 4. Od utworzonej daty odejmij ilość dni równą rokowi Twojego urodzenia
// 5. Po dodaniu sprawdź jaki jest to miesiąc, czy jest to weekend oraz czy jest to rok przestępny
public static void main(String[] args) {
}
}
| // 1. Utwórz datę reprezentującą twoje urodziny | package _2_date._2_exercise;
public class ApiExercise {
// TODO: exercise 1 - LocalDate API
// 1. Utwórz <SUF>
// 2. Sprawdź jaki to był dzień tygodnia oraz który dzień roku
// 3. Utwórz dzisiejszą datę
// 4. Od utworzonej daty odejmij ilość dni równą rokowi Twojego urodzenia
// 5. Po dodaniu sprawdź jaki jest to miesiąc, czy jest to weekend oraz czy jest to rok przestępny
public static void main(String[] args) {
}
}
| f |
6854_0 | infoshareacademy/jjdzr6-mistrzowie-vabank | 858 | src/main/java/com/infoshareacademy/mistrzowieVaBank/dto/CartInfo.java | package com.infoshareacademy.mistrzowieVaBank.dto;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class CartInfo {
private int orderNum;
private CustomerInfo customerInfo;
private final List<CartLineInfo> cartLines = new ArrayList<CartLineInfo>();
public int getOrderNum() {
return orderNum;
}
public void setOrderNum(int orderNum) {
this.orderNum = orderNum;
}
public CustomerInfo getCustomerInfo() {
return customerInfo;
}
public void setCustomerInfo(CustomerInfo customerInfo) {
this.customerInfo = customerInfo;
}
public List<CartLineInfo> getCartLines() {
return this.cartLines;
}
private CartLineInfo findLineById(Long id) {
for (CartLineInfo line : this.cartLines) {
if (line.getWineInfo().getId().equals(id)) {
return line;
}
}
return null;
}
public void addProduct(WineInfo wineInfo, int quantity) {
CartLineInfo line = this.findLineById(wineInfo.getId());
if (line == null) {
line = new CartLineInfo();
line.setQuantity(0);
line.setProductInfo(wineInfo);
this.cartLines.add(line);
}
int newQuantity = line.getQuantity() + quantity;
if (newQuantity <= 0) {
this.cartLines.remove(line);
} else {
line.setQuantity(newQuantity);
}
}
public void updateProduct(Long id, int quantity) {
CartLineInfo line = this.findLineById(id);
if (line != null) {
if (quantity <= 0) {
this.cartLines.remove(line);
} else {
line.setQuantity(quantity);
}
}
}
public void removeProduct(WineInfo wineInfo) {
CartLineInfo line = this.findLineById(wineInfo.getId());
if (line != null) {
this.cartLines.remove(line);
}
}
public boolean isEmpty() {
return this.cartLines.isEmpty();
}
public boolean isValidCustomer() {
return this.customerInfo != null && this.customerInfo.isValid();
}
public int getQuantityTotal() {
int quantity = 0;
for (CartLineInfo line : this.cartLines) {
quantity += line.getQuantity();
}
return quantity;
}
public BigDecimal getAmountTotal() {
BigDecimal total = BigDecimal.ZERO;
for (CartLineInfo line : this.cartLines) {
total = total.add(line.getAmount());
}
return total;
}
//TODO nie działa, dlaczego?
public void updateQuantity(CartInfo cartForm) {
if (cartForm != null) {
List<CartLineInfo> lines = cartForm.getCartLines();
for (CartLineInfo line : lines) {
this.updateProduct(line.getWineInfo().getId(), line.getQuantity());
}
}
}
} | //TODO nie działa, dlaczego? | package com.infoshareacademy.mistrzowieVaBank.dto;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class CartInfo {
private int orderNum;
private CustomerInfo customerInfo;
private final List<CartLineInfo> cartLines = new ArrayList<CartLineInfo>();
public int getOrderNum() {
return orderNum;
}
public void setOrderNum(int orderNum) {
this.orderNum = orderNum;
}
public CustomerInfo getCustomerInfo() {
return customerInfo;
}
public void setCustomerInfo(CustomerInfo customerInfo) {
this.customerInfo = customerInfo;
}
public List<CartLineInfo> getCartLines() {
return this.cartLines;
}
private CartLineInfo findLineById(Long id) {
for (CartLineInfo line : this.cartLines) {
if (line.getWineInfo().getId().equals(id)) {
return line;
}
}
return null;
}
public void addProduct(WineInfo wineInfo, int quantity) {
CartLineInfo line = this.findLineById(wineInfo.getId());
if (line == null) {
line = new CartLineInfo();
line.setQuantity(0);
line.setProductInfo(wineInfo);
this.cartLines.add(line);
}
int newQuantity = line.getQuantity() + quantity;
if (newQuantity <= 0) {
this.cartLines.remove(line);
} else {
line.setQuantity(newQuantity);
}
}
public void updateProduct(Long id, int quantity) {
CartLineInfo line = this.findLineById(id);
if (line != null) {
if (quantity <= 0) {
this.cartLines.remove(line);
} else {
line.setQuantity(quantity);
}
}
}
public void removeProduct(WineInfo wineInfo) {
CartLineInfo line = this.findLineById(wineInfo.getId());
if (line != null) {
this.cartLines.remove(line);
}
}
public boolean isEmpty() {
return this.cartLines.isEmpty();
}
public boolean isValidCustomer() {
return this.customerInfo != null && this.customerInfo.isValid();
}
public int getQuantityTotal() {
int quantity = 0;
for (CartLineInfo line : this.cartLines) {
quantity += line.getQuantity();
}
return quantity;
}
public BigDecimal getAmountTotal() {
BigDecimal total = BigDecimal.ZERO;
for (CartLineInfo line : this.cartLines) {
total = total.add(line.getAmount());
}
return total;
}
//TODO nie <SUF>
public void updateQuantity(CartInfo cartForm) {
if (cartForm != null) {
List<CartLineInfo> lines = cartForm.getCartLines();
for (CartLineInfo line : lines) {
this.updateProduct(line.getWineInfo().getId(), line.getQuantity());
}
}
}
} | f |
9374_0 | instytut-badan-edukacyjnych/platforma-testow | 719 | LoremIpsum/src/main/java/pl/edu/ibe/loremipsum/tablet/task/TaskService.java | /*
* This file is part of Test Platform.
*
* Test Platform is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Test Platform is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Test Platform; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Ten plik jest częścią Platformy Testów.
*
* Platforma Testów jest wolnym oprogramowaniem; możesz go rozprowadzać dalej
* i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU,
* wydanej przez Fundację Wolnego Oprogramowania - według wersji 2 tej
* Licencji lub (według twojego wyboru) którejś z późniejszych wersji.
*
* Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on
* użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej
* gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH
* ZASTOSOWAŃ. W celu uzyskania bliższych informacji sięgnij do
* Powszechnej Licencji Publicznej GNU.
*
* Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz
* Powszechnej Licencji Publicznej GNU (GNU General Public License);
* jeśli nie - napisz do Free Software Foundation, Inc., 59 Temple
* Place, Fifth Floor, Boston, MA 02110-1301 USA
*/
package pl.edu.ibe.loremipsum.tablet.task;
import pl.edu.ibe.loremipsum.tablet.base.ServiceProvider;
import pl.edu.ibe.loremipsum.tools.BaseService;
/**
* Created by adam on 05.06.14.
*/
public class TaskService extends BaseService {
public static boolean photoTaken;
/**
* Creates service with context
*
* @param services Services provider
*/
public TaskService(ServiceProvider services) {
super(services);
}
}
| /*
* This file is part of Test Platform.
*
* Test Platform is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Test Platform is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Test Platform; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Ten plik jest częścią Platformy Testów.
*
* Platforma Testów jest wolnym oprogramowaniem; możesz go rozprowadzać dalej
* i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU,
* wydanej przez Fundację Wolnego Oprogramowania - według wersji 2 tej
* Licencji lub (według twojego wyboru) którejś z późniejszych wersji.
*
* Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on
* użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej
* gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH
* ZASTOSOWAŃ. W celu uzyskania bliższych informacji sięgnij do
* Powszechnej Licencji Publicznej GNU.
*
* Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz
* Powszechnej Licencji Publicznej GNU (GNU General Public License);
* jeśli nie - napisz do Free Software Foundation, Inc., 59 Temple
* Place, Fifth Floor, Boston, MA 02110-1301 USA
*/ | /*
* This file is <SUF>*/
package pl.edu.ibe.loremipsum.tablet.task;
import pl.edu.ibe.loremipsum.tablet.base.ServiceProvider;
import pl.edu.ibe.loremipsum.tools.BaseService;
/**
* Created by adam on 05.06.14.
*/
public class TaskService extends BaseService {
public static boolean photoTaken;
/**
* Creates service with context
*
* @param services Services provider
*/
public TaskService(ServiceProvider services) {
super(services);
}
}
| f |
6604_0 | iwokonl/Cv-Doswiaczenie | 129 | Wzorce Projektowe/Dekorator/src/Notifier/FB.java | package Notifier;
public class FB implements Notifier{
Notifier notifier;
public FB(Notifier notifier){
this.notifier = notifier;
}
@Override
public void send() {
// notifier.send();
System.out.println("Wysłano do fb");//jeśli to tutaj by było to automatycznie przejdzie do kolejnego zapakowanego obiektu i zrobi to na końcu
notifier.send();
}
}
| //jeśli to tutaj by było to automatycznie przejdzie do kolejnego zapakowanego obiektu i zrobi to na końcu | package Notifier;
public class FB implements Notifier{
Notifier notifier;
public FB(Notifier notifier){
this.notifier = notifier;
}
@Override
public void send() {
// notifier.send();
System.out.println("Wysłano do fb");//jeśli to <SUF>
notifier.send();
}
}
| f |
7708_0 | izoslav/gui-serf | 521 | magazyny/src/Main.java | import model.*;
public class Main {
public static void main(String[] args) {
Menu m = new Menu();
m.uruchom();
}
private void test() throws Exception {
Magazyn magazyn = new Magazyn();
Pomieszczenie p1 = new Pomieszczenie(10, true);
Pomieszczenie p2 = new Pomieszczenie(2, 3, 4, true);
magazyn.dodajPomieszczenie(p2); // najpierw większe
magazyn.dodajPomieszczenie(p1); // potem mniejsze
System.out.println(magazyn);
Samochod s1 = new Samochod("Mazda", 12, 2, "gaz");
Rower r1 = new Rower("BMX", 3, 4, "tarczowe", 0);
Rower r2 = new Rower("Składak", 2, 5, "cokolwiek", 4);
Motocykl m1 = new Motocykl("HONDAAAAAA", 7, 1, true);
Motocykl m2 = new Motocykl("SU-ZU-KIII", 8, 2, false);
System.out.println(s1);
System.out.println(r1);
System.out.println(r2);
System.out.println(m1);
System.out.println(m2);
// p1.dodajPrzedmiot(s1); // rzuca wyjątek! samochód za duży, żeby dodać!
p1.dodajPrzedmiot(r1);
p1.dodajPrzedmiot(r2);
// p1.dodajPrzedmiot(m1); // rzuca wyjątek! r1+r2+m1 = 12 > 10 rozmiar pomieszczenia
}
}
| // p1.dodajPrzedmiot(s1); // rzuca wyjątek! samochód za duży, żeby dodać!
| import model.*;
public class Main {
public static void main(String[] args) {
Menu m = new Menu();
m.uruchom();
}
private void test() throws Exception {
Magazyn magazyn = new Magazyn();
Pomieszczenie p1 = new Pomieszczenie(10, true);
Pomieszczenie p2 = new Pomieszczenie(2, 3, 4, true);
magazyn.dodajPomieszczenie(p2); // najpierw większe
magazyn.dodajPomieszczenie(p1); // potem mniejsze
System.out.println(magazyn);
Samochod s1 = new Samochod("Mazda", 12, 2, "gaz");
Rower r1 = new Rower("BMX", 3, 4, "tarczowe", 0);
Rower r2 = new Rower("Składak", 2, 5, "cokolwiek", 4);
Motocykl m1 = new Motocykl("HONDAAAAAA", 7, 1, true);
Motocykl m2 = new Motocykl("SU-ZU-KIII", 8, 2, false);
System.out.println(s1);
System.out.println(r1);
System.out.println(r2);
System.out.println(m1);
System.out.println(m2);
// p1.dodajPrzedmiot(s1); // <SUF>
p1.dodajPrzedmiot(r1);
p1.dodajPrzedmiot(r2);
// p1.dodajPrzedmiot(m1); // rzuca wyjątek! r1+r2+m1 = 12 > 10 rozmiar pomieszczenia
}
}
| f |
6302_2 | jaceksen/firstApp | 665 | app/src/main/java/pl/jaceksen/firstapp/MainActivity.java | package pl.jaceksen.firstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView txtDisplay;
Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtDisplay= (TextView) findViewById(R.id.txtDisplay);
txtDisplay.setText("Tekst from Main.");
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
//button2 (test)
// button2.setText("Tekst z layoutu");
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextView txtDisplay= (TextView) findViewById(R.id.txtDisplay);
txtDisplay.setText("Kliknięcie z kodu.");
}
});
}
protected void onStart(){
super.onStart();
Toast.makeText(this,"OnStart",Toast.LENGTH_LONG).show();
}
protected void onRestart(){
super.onRestart();
Toast.makeText(this,"OnRestart",Toast.LENGTH_LONG).show();
}
protected void onPause(){
super.onPause();
Toast.makeText(this,"OnPause",Toast.LENGTH_LONG).show();
}
protected void onStop(){
super.onStop();
Toast.makeText(this,"OnStop",Toast.LENGTH_LONG).show();
}
protected void onResume(){
super.onResume();
Toast.makeText(this,"OnResume",Toast.LENGTH_LONG).show();
}
protected void onDestroy(){
super.onDestroy();
Toast.makeText(this,"OnDestroy",Toast.LENGTH_LONG).show();
}
public void buClick(View view) {
// TextView txtDisplay= (TextView) findViewById(R.id.txtDisplay);
// txtDisplay.setText("Przycisk był kliknięty.");
// txtDisplay.setText("aaaaaa");
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra("name","Jacek Seń");
intent.putExtra("age","45");
startActivity(intent);
}
}
| // txtDisplay.setText("Przycisk był kliknięty."); | package pl.jaceksen.firstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView txtDisplay;
Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtDisplay= (TextView) findViewById(R.id.txtDisplay);
txtDisplay.setText("Tekst from Main.");
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
//button2 (test)
// button2.setText("Tekst z layoutu");
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextView txtDisplay= (TextView) findViewById(R.id.txtDisplay);
txtDisplay.setText("Kliknięcie z kodu.");
}
});
}
protected void onStart(){
super.onStart();
Toast.makeText(this,"OnStart",Toast.LENGTH_LONG).show();
}
protected void onRestart(){
super.onRestart();
Toast.makeText(this,"OnRestart",Toast.LENGTH_LONG).show();
}
protected void onPause(){
super.onPause();
Toast.makeText(this,"OnPause",Toast.LENGTH_LONG).show();
}
protected void onStop(){
super.onStop();
Toast.makeText(this,"OnStop",Toast.LENGTH_LONG).show();
}
protected void onResume(){
super.onResume();
Toast.makeText(this,"OnResume",Toast.LENGTH_LONG).show();
}
protected void onDestroy(){
super.onDestroy();
Toast.makeText(this,"OnDestroy",Toast.LENGTH_LONG).show();
}
public void buClick(View view) {
// TextView txtDisplay= (TextView) findViewById(R.id.txtDisplay);
// txtDisplay.setText("Przycisk był <SUF>
// txtDisplay.setText("aaaaaa");
Intent intent = new Intent(this, Main2Activity.class);
intent.putExtra("name","Jacek Seń");
intent.putExtra("age","45");
startActivity(intent);
}
}
| f |
3998_0 | jaehyungjeon/AlgorithmNew | 498 | algorithm/src/algorithm/BaekJoon_8710.java | package algorithm;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/*
Question : Kozik pragnie zostać koszykarzem. Po rozmowie z trenerem okazało się, że jest za niski. Kozik jest jednak tak zdeterminowany, że chce spełnić wymagania trenera,
nawet jeśli okazałoby się to oszustwem. Wpadł więc na genialny pomysł robienia sobie guzów na głowie, aż osiągnie wymagany wzrost. Zauważył, że przy każdym uderzeniu guz się powiększa o m cm.
Kozik zastanawia się ile minimalnie razy będzie musiał się uderzyć.
input
180 202 10
output
3
Solution : 1. 두 값의 차를 10으로 나누었을 때, 나머지가 남으면 최소 개수는 +1을 더해주어야 한다.
*/
public class BaekJoon_8710 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Long k = Long.parseLong(st.nextToken());
Long w = Long.parseLong(st.nextToken());
Long m = Long.parseLong(st.nextToken());
w -= k;
if(w % m == 0) System.out.println(w/m);
else System.out.println(w/m + 1);
}
} | /*
Question : Kozik pragnie zostać koszykarzem. Po rozmowie z trenerem okazało się, że jest za niski. Kozik jest jednak tak zdeterminowany, że chce spełnić wymagania trenera,
nawet jeśli okazałoby się to oszustwem. Wpadł więc na genialny pomysł robienia sobie guzów na głowie, aż osiągnie wymagany wzrost. Zauważył, że przy każdym uderzeniu guz się powiększa o m cm.
Kozik zastanawia się ile minimalnie razy będzie musiał się uderzyć.
input
180 202 10
output
3
Solution : 1. 두 값의 차를 10으로 나누었을 때, 나머지가 남으면 최소 개수는 +1을 더해주어야 한다.
*/ | package algorithm;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/*
Question : Kozik <SUF>*/
public class BaekJoon_8710 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Long k = Long.parseLong(st.nextToken());
Long w = Long.parseLong(st.nextToken());
Long m = Long.parseLong(st.nextToken());
w -= k;
if(w % m == 0) System.out.println(w/m);
else System.out.println(w/m + 1);
}
} | f |
9140_5 | jakubkotecki6/CarRental | 1,281 | src/main/java/pl/sda/carrental/service/RentService.java | package pl.sda.carrental.service;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import pl.sda.carrental.exceptionHandling.ObjectNotFoundInRepositoryException;
import pl.sda.carrental.exceptionHandling.RentAlreadyExistsForReservationException;
import pl.sda.carrental.model.DTO.RentDTO;
import pl.sda.carrental.model.Employee;
import pl.sda.carrental.model.Rent;
import pl.sda.carrental.model.Reservation;
import pl.sda.carrental.repository.EmployeeRepository;
import pl.sda.carrental.repository.RentRepository;
import pl.sda.carrental.repository.ReservationRepository;
import java.util.List;
@Service
@RequiredArgsConstructor
public class RentService {
private final RentRepository rentRepository;
private final ReservationRepository reservationRepository;
private final EmployeeRepository employeeRepository;
/**
* Gets all Rent objects
*
* @return List of all Rent objects
*/
public List<Rent> allRents() {
return rentRepository.findAll();
}
/**
* The save method is responsible for creating a new rent based on the provided RentDTO and saving it to the repository
*
* @param rentDTO An object containing rent data
* @return The newly created and saved rent object
*/
@Transactional
public Rent save(RentDTO rentDTO) {
Rent rent = new Rent();
updateRentDetails(rentDTO, rent);
return rentRepository.save(rent);
}
/**
* The editRent method is a transactional operation that allows for the modification of an existing rent based on the provided
* rent ID and updated rent details in the RentDTO. It retrieves the rent by ID from the repository, updates its details using
* the updateRentDetails method, deletes the existing rent, and then saves the modified rent back to the repository
*
* @param id The identifier of the rent to be edited
* @param rentDTO An object containing updated rent data
* @return The modified rent object
* @throws ObjectNotFoundInRepositoryException if no rent is found with the provided ID
*/
@Transactional
public Rent editRent(Long id, RentDTO rentDTO) {
Rent rent = rentRepository.findById(id)
.orElseThrow(() ->
new ObjectNotFoundInRepositoryException("No rent under ID #" + id));
updateRentDetails(rentDTO, rent);
rentRepository.deleteById(id);
return rentRepository.save(rent);
}
/**
* Deletes Rent object using ID
*
* @param id The identifier of the rent to be deleted
* @throws ObjectNotFoundInRepositoryException if no rent is found with the provided ID
*/
@Transactional
public void deleteRentById(Long id) {
rentRepository.findById(id)
.orElseThrow(() -> new ObjectNotFoundInRepositoryException("No rent under ID #" + id));
rentRepository.deleteById(id);
}
/**
* The updateRentDetails method is responsible for updating the details of a Rent object based on the information provided in the RentDTO.
* It checks if a rent already exists for the specified reservation ID, updates the associated employee, comments, rent date, and
* reservation for the given Rent object
*
* @param rentDTO An object containing updated rent data
* @param rent The Rent object to be updated
* @throws RentAlreadyExistsForReservationException if a rent already exists for the specified reservation ID
* @throws ObjectNotFoundInRepositoryException if no employee or reservation is found with the provided ID
*/
private void updateRentDetails(RentDTO rentDTO, Rent rent) {
List<Long> reservationsIds = rentRepository.findRentalsWithReservationId(rentDTO.reservationId());
if(!reservationsIds.isEmpty()) {
throw new RentAlreadyExistsForReservationException("Rent already exists for reservation with id "
+ rentDTO.reservationId());
}
Employee foundEmployee = employeeRepository.findById(rentDTO.employeeId())
.orElseThrow(() -> new ObjectNotFoundInRepositoryException("No employee under ID #"
+ rentDTO.employeeId()));
rent.setEmployee(foundEmployee);
rent.setComments(rentDTO.comments());
rent.setRentDate(rentDTO.rentDate());
// ======== tutaj nie muszę ustawiać rezerwację? ==========
Reservation reservationFromRepository = reservationRepository.findById(rentDTO.reservationId())
.orElseThrow(() -> new ObjectNotFoundInRepositoryException("Reservation with id "
+ rentDTO.reservationId() + " not found"));
rent.setReservation(reservationFromRepository);
// ======================================================
}
}
| // ======== tutaj nie muszę ustawiać rezerwację? ========== | package pl.sda.carrental.service;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import pl.sda.carrental.exceptionHandling.ObjectNotFoundInRepositoryException;
import pl.sda.carrental.exceptionHandling.RentAlreadyExistsForReservationException;
import pl.sda.carrental.model.DTO.RentDTO;
import pl.sda.carrental.model.Employee;
import pl.sda.carrental.model.Rent;
import pl.sda.carrental.model.Reservation;
import pl.sda.carrental.repository.EmployeeRepository;
import pl.sda.carrental.repository.RentRepository;
import pl.sda.carrental.repository.ReservationRepository;
import java.util.List;
@Service
@RequiredArgsConstructor
public class RentService {
private final RentRepository rentRepository;
private final ReservationRepository reservationRepository;
private final EmployeeRepository employeeRepository;
/**
* Gets all Rent objects
*
* @return List of all Rent objects
*/
public List<Rent> allRents() {
return rentRepository.findAll();
}
/**
* The save method is responsible for creating a new rent based on the provided RentDTO and saving it to the repository
*
* @param rentDTO An object containing rent data
* @return The newly created and saved rent object
*/
@Transactional
public Rent save(RentDTO rentDTO) {
Rent rent = new Rent();
updateRentDetails(rentDTO, rent);
return rentRepository.save(rent);
}
/**
* The editRent method is a transactional operation that allows for the modification of an existing rent based on the provided
* rent ID and updated rent details in the RentDTO. It retrieves the rent by ID from the repository, updates its details using
* the updateRentDetails method, deletes the existing rent, and then saves the modified rent back to the repository
*
* @param id The identifier of the rent to be edited
* @param rentDTO An object containing updated rent data
* @return The modified rent object
* @throws ObjectNotFoundInRepositoryException if no rent is found with the provided ID
*/
@Transactional
public Rent editRent(Long id, RentDTO rentDTO) {
Rent rent = rentRepository.findById(id)
.orElseThrow(() ->
new ObjectNotFoundInRepositoryException("No rent under ID #" + id));
updateRentDetails(rentDTO, rent);
rentRepository.deleteById(id);
return rentRepository.save(rent);
}
/**
* Deletes Rent object using ID
*
* @param id The identifier of the rent to be deleted
* @throws ObjectNotFoundInRepositoryException if no rent is found with the provided ID
*/
@Transactional
public void deleteRentById(Long id) {
rentRepository.findById(id)
.orElseThrow(() -> new ObjectNotFoundInRepositoryException("No rent under ID #" + id));
rentRepository.deleteById(id);
}
/**
* The updateRentDetails method is responsible for updating the details of a Rent object based on the information provided in the RentDTO.
* It checks if a rent already exists for the specified reservation ID, updates the associated employee, comments, rent date, and
* reservation for the given Rent object
*
* @param rentDTO An object containing updated rent data
* @param rent The Rent object to be updated
* @throws RentAlreadyExistsForReservationException if a rent already exists for the specified reservation ID
* @throws ObjectNotFoundInRepositoryException if no employee or reservation is found with the provided ID
*/
private void updateRentDetails(RentDTO rentDTO, Rent rent) {
List<Long> reservationsIds = rentRepository.findRentalsWithReservationId(rentDTO.reservationId());
if(!reservationsIds.isEmpty()) {
throw new RentAlreadyExistsForReservationException("Rent already exists for reservation with id "
+ rentDTO.reservationId());
}
Employee foundEmployee = employeeRepository.findById(rentDTO.employeeId())
.orElseThrow(() -> new ObjectNotFoundInRepositoryException("No employee under ID #"
+ rentDTO.employeeId()));
rent.setEmployee(foundEmployee);
rent.setComments(rentDTO.comments());
rent.setRentDate(rentDTO.rentDate());
// ======== tutaj <SUF>
Reservation reservationFromRepository = reservationRepository.findById(rentDTO.reservationId())
.orElseThrow(() -> new ObjectNotFoundInRepositoryException("Reservation with id "
+ rentDTO.reservationId() + " not found"));
rent.setReservation(reservationFromRepository);
// ======================================================
}
}
| f |
7270_4 | jakufort/BattleSimulation | 2,159 | src/main/java/gui/BoardPanel.java | package gui;
import agents.AgentType;
import javafx.geometry.Point2D;
import javafx.util.Pair;
import utils.AgentInTree;
import utils.SquareSize;
import utils.flyweight.FlyweightFactory;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Jakub Fortunka on 08.11.14.
*
*/
public class BoardPanel extends JPanel {
public Cursor cursor;
public AffineTransform at = new AffineTransform();
private ArrayList<Pair<AgentType,BufferedImage>> images = new ArrayList<>();
public int x1, y1, x2, y2;
public MyAgent selectedAgent = null;
public MyAgent clickedAgent = null;
public JPanel innerBoard;
private ArrayList<MyAgent> agentsList = new ArrayList<>();
public boolean simulationStarted = false;
public BoardPanel() {
super();
setBackground(Color.WHITE);
int WIDTH = 700;
int HEIGHT = 400;
setPreferredSize(new Dimension(WIDTH, HEIGHT));
innerBoard = new Board();
}
/**
* method generates new board
* @param height height of new board
* @param width width of new board
*/
public void generateBoard(int height, int width) {
at = new AffineTransform();
//at.scale(0.19, 0.19);
at.scale(1,1);
setPreferredSize(new Dimension(width*(SquareSize.getInstance().getValue())+10, height*(SquareSize.getInstance().getValue())+10));
innerBoard.setPreferredSize(new Dimension(width*(SquareSize.getInstance().getValue())+1, height*(SquareSize.getInstance().getValue())+1));
add(innerBoard);
innerBoard.revalidate();
innerBoard.repaint();
}
/**
* method resets scale of AffineTransform which is used to rescaling board
*/
public void resetScale() {
at = new AffineTransform();
at.scale(1,1);
innerBoard.revalidate();
innerBoard.repaint();
}
/**
* method responsible for drawing agents on board
* @param agents s
*/
public void drawAgents(java.util.List<AgentInTree> agents) {
ArrayList<MyAgent> lst = new ArrayList<>();
for (AgentInTree agent : agents) {
if (agent.getAgentName().equals("obstacle")) {
if (!agentsList.parallelStream().anyMatch(o -> o.getAgent().p.equals(agent.p))) {
lst.add(new MyAgent(Color.GREEN,agent));
} else {
lst.add((MyAgent)agentsList.parallelStream().filter(o -> o.getAgent().p.equals(agent.p)).toArray()[0]);
}
} else {
if (agentsList.parallelStream().anyMatch(e -> e.getAgent().getAgentName().equals(agent.getAgentName()))) {
MyAgent a = ((MyAgent) agentsList
.parallelStream()
.filter(l -> l.getAgent().getAgentName().equals(agent.getAgentName()))
.toArray()[0]);
a.setAgent(agent);
if (simulationStarted) {
if (a.pointBuffer != null)
a.pointBuffer = null;
}
lst.add(a);
//continue;
} else {
switch (agent.side) {
case Blues:
lst.add(new MyAgent(Color.BLUE, agent));
break;
case Reds:
lst.add(new MyAgent(Color.RED, agent));
break;
default:
break;
}
}
}
}
agentsList.clear();
agentsList = lst;
innerBoard.revalidate();
innerBoard.repaint();
}
public List<MyAgent> getMyAgents() {
return Collections.unmodifiableList(agentsList);
}
public Point2D getBoardSize() {
return new Point2D(innerBoard.getPreferredSize().getWidth(),innerBoard.getPreferredSize().getHeight());
}
public class Board extends JPanel {
@Override
//TODO Pojawiają się wyjątki sygnalizujące rysowanie poza planszą (javax.swing.JComponent.paintToOffscreen)
public void paint(Graphics g) {
super.paint(g);
for(MyAgent s : getMyAgents()) {
s.paint(g);
}
if (cursor != null)
setCursor(cursor);
}
}
/**
* Class which represents agent on board (holds color and reference to his state (position))
*/
public class MyAgent extends JComponent {
private Color c;
private AgentInTree agent;
public boolean isClicked = false;
private Point2D pointBuffer = null;
public MyAgent(Color c, AgentInTree agent) {
this.c = c;
this.agent = agent;
}
public AgentInTree getAgent() {
return agent;
}
public Point2D getPoint() {
return pointBuffer==null ? agent.p : pointBuffer;
}
public void setPoint(Point2D point) {
pointBuffer = point;
//pointOnBoard = point;
}
public void setAgent(AgentInTree agent) {
this.agent = agent;
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
AffineTransform old = g2d.getTransform();
g2d.transform(at);
g2d.setColor(this.c);
//g2d.fillOval((int)pointOnBoard.getX(),(int)pointOnBoard.getY(),agent.type.getSize(),agent.type.getSize());
BufferedImage image;
if (!images.stream().anyMatch(p -> p.getKey().equals(agent.type))) {
image = FlyweightFactory.getFactory().getIcon(agent.type.getImagePath());
images.add(new Pair<>(agent.type,image));
} else {
image = images.stream().filter( p -> p.getKey().equals(agent.type)).findFirst().get().getValue();
}
if (pointBuffer == null) {
//System.out.println("Position: " + agent.p);
g2d.fillOval((int) agent.p.getX(), (int) agent.p.getY(), agent.type.getSize(), agent.type.getSize());
g2d.drawImage(image, (int) agent.p.getX(), (int) agent.p.getY(), null);
if (isClicked)
paintSelection(g2d,agent.p);
} else {
g2d.fillOval((int) pointBuffer.getX(), (int) pointBuffer.getY(), agent.type.getSize(), agent.type.getSize());
g2d.drawImage(image, (int) pointBuffer.getX(), (int) pointBuffer.getY(), null);
if (isClicked)
paintSelection(g2d,pointBuffer);
}
//g2d.drawImage(image,(int)agent.p.getX()*SQUARESIZE,(int)agent.p.getY()*SQUARESIZE,null);
//g2d.drawImage(image,(int)pointOnBoard.getX(),(int)pointOnBoard.getY(),null);
g2d.setTransform(old);
}
private void paintSelection(Graphics2D g, Point2D point) {
if (agent.type != AgentType.OBSTACLE) {
g.setColor(Color.GREEN);
g.setStroke(new BasicStroke(2.0f));
g.drawOval((int) point.getX(), (int) point.getY(), agent.type.getSize(), agent.type.getSize());
}
}
}
}
| //TODO Pojawiają się wyjątki sygnalizujące rysowanie poza planszą (javax.swing.JComponent.paintToOffscreen) | package gui;
import agents.AgentType;
import javafx.geometry.Point2D;
import javafx.util.Pair;
import utils.AgentInTree;
import utils.SquareSize;
import utils.flyweight.FlyweightFactory;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Jakub Fortunka on 08.11.14.
*
*/
public class BoardPanel extends JPanel {
public Cursor cursor;
public AffineTransform at = new AffineTransform();
private ArrayList<Pair<AgentType,BufferedImage>> images = new ArrayList<>();
public int x1, y1, x2, y2;
public MyAgent selectedAgent = null;
public MyAgent clickedAgent = null;
public JPanel innerBoard;
private ArrayList<MyAgent> agentsList = new ArrayList<>();
public boolean simulationStarted = false;
public BoardPanel() {
super();
setBackground(Color.WHITE);
int WIDTH = 700;
int HEIGHT = 400;
setPreferredSize(new Dimension(WIDTH, HEIGHT));
innerBoard = new Board();
}
/**
* method generates new board
* @param height height of new board
* @param width width of new board
*/
public void generateBoard(int height, int width) {
at = new AffineTransform();
//at.scale(0.19, 0.19);
at.scale(1,1);
setPreferredSize(new Dimension(width*(SquareSize.getInstance().getValue())+10, height*(SquareSize.getInstance().getValue())+10));
innerBoard.setPreferredSize(new Dimension(width*(SquareSize.getInstance().getValue())+1, height*(SquareSize.getInstance().getValue())+1));
add(innerBoard);
innerBoard.revalidate();
innerBoard.repaint();
}
/**
* method resets scale of AffineTransform which is used to rescaling board
*/
public void resetScale() {
at = new AffineTransform();
at.scale(1,1);
innerBoard.revalidate();
innerBoard.repaint();
}
/**
* method responsible for drawing agents on board
* @param agents s
*/
public void drawAgents(java.util.List<AgentInTree> agents) {
ArrayList<MyAgent> lst = new ArrayList<>();
for (AgentInTree agent : agents) {
if (agent.getAgentName().equals("obstacle")) {
if (!agentsList.parallelStream().anyMatch(o -> o.getAgent().p.equals(agent.p))) {
lst.add(new MyAgent(Color.GREEN,agent));
} else {
lst.add((MyAgent)agentsList.parallelStream().filter(o -> o.getAgent().p.equals(agent.p)).toArray()[0]);
}
} else {
if (agentsList.parallelStream().anyMatch(e -> e.getAgent().getAgentName().equals(agent.getAgentName()))) {
MyAgent a = ((MyAgent) agentsList
.parallelStream()
.filter(l -> l.getAgent().getAgentName().equals(agent.getAgentName()))
.toArray()[0]);
a.setAgent(agent);
if (simulationStarted) {
if (a.pointBuffer != null)
a.pointBuffer = null;
}
lst.add(a);
//continue;
} else {
switch (agent.side) {
case Blues:
lst.add(new MyAgent(Color.BLUE, agent));
break;
case Reds:
lst.add(new MyAgent(Color.RED, agent));
break;
default:
break;
}
}
}
}
agentsList.clear();
agentsList = lst;
innerBoard.revalidate();
innerBoard.repaint();
}
public List<MyAgent> getMyAgents() {
return Collections.unmodifiableList(agentsList);
}
public Point2D getBoardSize() {
return new Point2D(innerBoard.getPreferredSize().getWidth(),innerBoard.getPreferredSize().getHeight());
}
public class Board extends JPanel {
@Override
//TODO Pojawiają <SUF>
public void paint(Graphics g) {
super.paint(g);
for(MyAgent s : getMyAgents()) {
s.paint(g);
}
if (cursor != null)
setCursor(cursor);
}
}
/**
* Class which represents agent on board (holds color and reference to his state (position))
*/
public class MyAgent extends JComponent {
private Color c;
private AgentInTree agent;
public boolean isClicked = false;
private Point2D pointBuffer = null;
public MyAgent(Color c, AgentInTree agent) {
this.c = c;
this.agent = agent;
}
public AgentInTree getAgent() {
return agent;
}
public Point2D getPoint() {
return pointBuffer==null ? agent.p : pointBuffer;
}
public void setPoint(Point2D point) {
pointBuffer = point;
//pointOnBoard = point;
}
public void setAgent(AgentInTree agent) {
this.agent = agent;
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
AffineTransform old = g2d.getTransform();
g2d.transform(at);
g2d.setColor(this.c);
//g2d.fillOval((int)pointOnBoard.getX(),(int)pointOnBoard.getY(),agent.type.getSize(),agent.type.getSize());
BufferedImage image;
if (!images.stream().anyMatch(p -> p.getKey().equals(agent.type))) {
image = FlyweightFactory.getFactory().getIcon(agent.type.getImagePath());
images.add(new Pair<>(agent.type,image));
} else {
image = images.stream().filter( p -> p.getKey().equals(agent.type)).findFirst().get().getValue();
}
if (pointBuffer == null) {
//System.out.println("Position: " + agent.p);
g2d.fillOval((int) agent.p.getX(), (int) agent.p.getY(), agent.type.getSize(), agent.type.getSize());
g2d.drawImage(image, (int) agent.p.getX(), (int) agent.p.getY(), null);
if (isClicked)
paintSelection(g2d,agent.p);
} else {
g2d.fillOval((int) pointBuffer.getX(), (int) pointBuffer.getY(), agent.type.getSize(), agent.type.getSize());
g2d.drawImage(image, (int) pointBuffer.getX(), (int) pointBuffer.getY(), null);
if (isClicked)
paintSelection(g2d,pointBuffer);
}
//g2d.drawImage(image,(int)agent.p.getX()*SQUARESIZE,(int)agent.p.getY()*SQUARESIZE,null);
//g2d.drawImage(image,(int)pointOnBoard.getX(),(int)pointOnBoard.getY(),null);
g2d.setTransform(old);
}
private void paintSelection(Graphics2D g, Point2D point) {
if (agent.type != AgentType.OBSTACLE) {
g.setColor(Color.GREEN);
g.setStroke(new BasicStroke(2.0f));
g.drawOval((int) point.getX(), (int) point.getY(), agent.type.getSize(), agent.type.getSize());
}
}
}
}
| f |
5663_1 | jan-klos/ArtificialCity | 1,323 | Lane.java |
public class Lane {
public Cell[] cellList;
public int howManyToLeft; //ile pasow do lewa
public int howManyToRight;
public int length;
private int speedLimit;
public Lane[] left;
public Lane[] right;
public Lane[] forward;
public V begin;
public V end;
public boolean clDir; // zwrot listy komórek na potrzeby ruchu pieszych, gdzie krawedzie są dwukierunkowe
public Lane(int n, V _begin, V _end, int laneNr, int _howManyToRight, int _howManyToLeft) {
cellList = new Cell[n];
length = n;
howManyToRight = _howManyToRight;
howManyToLeft = _howManyToLeft;
for (int i = 0; i < n; i++) {
cellList[i] = createCell(i, n, _begin, _end, laneNr, n - i);
}
speedLimit = 3;
begin = _begin;
end = _end;
}
public Lane(Lane l)
{
cellList = new Cell[l.cellList.length];
int n = l.cellList.length;
howManyToRight = l.howManyToRight;
howManyToLeft = l.howManyToLeft;
for (int i = 0; i < n; i++) {
cellList[i] = createCell(i, n, l.begin, l.end, 0, n - i);
}
speedLimit = 3;
begin = l.begin;
end = l.end;
}
private Cell createCell(int i, int n, V begin, V end, int laneNr, int howManyCellsToCrossroad) {
double x;
double y;
switch (laneNr) {
case 0: x = Math.abs(end.getX() - begin.getX());
y = Math.abs(end.getY() - begin.getY());
break;
case 1: x = Math.abs(end.getX() - begin.getX());
y = Math.abs(end.getY() - begin.getY());
break;
case 2: x = Math.abs(end.getX() - begin.getX());
y = Math.abs(end.getY() - begin.getY());
break;
default: x = Math.abs(end.getX() - begin.getX());
y = Math.abs(end.getY() - begin.getY());
break;
}
x = (1f / n) * x;
y = (1f / n) * y;
if(end.getX() >= begin.getX() && (end.getY() >= begin.getY()))
return new Cell((begin.getX()+ x * i), (begin.getY() + y * i), howManyCellsToCrossroad, i);
else if(end.getX() >= begin.getX() && (end.getY() < begin.getY()))
return new Cell((begin.getX()+ x * i), (begin.getY() - y * i), howManyCellsToCrossroad, i);
else if(end.getX() < begin.getX() && (end.getY() < begin.getY()))
return new Cell((begin.getX()- x * i), (begin.getY() - y * i), howManyCellsToCrossroad, i);
else
return new Cell((begin.getX()- x * i), (begin.getY() + y * i), howManyCellsToCrossroad, i);
}
public String toString() {
String output = "";
for(int j = 0; j < length; j++) {
output += cellList[j].toString();
}
output += "\n------------------------------\n";
return output;
}
public void setSpeedLimit(int _speedLimit) { speedLimit = _speedLimit; }
public int getSpeedLimit() { return speedLimit; }
public int getHowManyToRight() { return howManyToRight; }
public int getHowManyToLeft() { return howManyToLeft; }
public V getBegin()
{
if (clDir)
{
return begin;
}
else
{
return end;
}
}
public V getEnd()
{
if (clDir)
{
return end;
}
else
{
return begin;
}
}
}
| // zwrot listy komórek na potrzeby ruchu pieszych, gdzie krawedzie są dwukierunkowe |
public class Lane {
public Cell[] cellList;
public int howManyToLeft; //ile pasow do lewa
public int howManyToRight;
public int length;
private int speedLimit;
public Lane[] left;
public Lane[] right;
public Lane[] forward;
public V begin;
public V end;
public boolean clDir; // zwrot listy <SUF>
public Lane(int n, V _begin, V _end, int laneNr, int _howManyToRight, int _howManyToLeft) {
cellList = new Cell[n];
length = n;
howManyToRight = _howManyToRight;
howManyToLeft = _howManyToLeft;
for (int i = 0; i < n; i++) {
cellList[i] = createCell(i, n, _begin, _end, laneNr, n - i);
}
speedLimit = 3;
begin = _begin;
end = _end;
}
public Lane(Lane l)
{
cellList = new Cell[l.cellList.length];
int n = l.cellList.length;
howManyToRight = l.howManyToRight;
howManyToLeft = l.howManyToLeft;
for (int i = 0; i < n; i++) {
cellList[i] = createCell(i, n, l.begin, l.end, 0, n - i);
}
speedLimit = 3;
begin = l.begin;
end = l.end;
}
private Cell createCell(int i, int n, V begin, V end, int laneNr, int howManyCellsToCrossroad) {
double x;
double y;
switch (laneNr) {
case 0: x = Math.abs(end.getX() - begin.getX());
y = Math.abs(end.getY() - begin.getY());
break;
case 1: x = Math.abs(end.getX() - begin.getX());
y = Math.abs(end.getY() - begin.getY());
break;
case 2: x = Math.abs(end.getX() - begin.getX());
y = Math.abs(end.getY() - begin.getY());
break;
default: x = Math.abs(end.getX() - begin.getX());
y = Math.abs(end.getY() - begin.getY());
break;
}
x = (1f / n) * x;
y = (1f / n) * y;
if(end.getX() >= begin.getX() && (end.getY() >= begin.getY()))
return new Cell((begin.getX()+ x * i), (begin.getY() + y * i), howManyCellsToCrossroad, i);
else if(end.getX() >= begin.getX() && (end.getY() < begin.getY()))
return new Cell((begin.getX()+ x * i), (begin.getY() - y * i), howManyCellsToCrossroad, i);
else if(end.getX() < begin.getX() && (end.getY() < begin.getY()))
return new Cell((begin.getX()- x * i), (begin.getY() - y * i), howManyCellsToCrossroad, i);
else
return new Cell((begin.getX()- x * i), (begin.getY() + y * i), howManyCellsToCrossroad, i);
}
public String toString() {
String output = "";
for(int j = 0; j < length; j++) {
output += cellList[j].toString();
}
output += "\n------------------------------\n";
return output;
}
public void setSpeedLimit(int _speedLimit) { speedLimit = _speedLimit; }
public int getSpeedLimit() { return speedLimit; }
public int getHowManyToRight() { return howManyToRight; }
public int getHowManyToLeft() { return howManyToLeft; }
public V getBegin()
{
if (clDir)
{
return begin;
}
else
{
return end;
}
}
public V getEnd()
{
if (clDir)
{
return end;
}
else
{
return begin;
}
}
}
| t |
285_15 | jdown/jdownloader | 1,271 | trunk/src/jd/plugins/hoster/FrogUpCom.java | // jDownloader - Downloadmanager
// Copyright (C) 2009 JD-Team support@jdownloader.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "frogup.com" }, urls = { "http://[\\w\\.]*?frogup\\.com/plik/pokaz/.*?/[0-9]+" }, flags = { 0 })
public class FrogUpCom extends PluginForHost {
public FrogUpCom(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://www.frogup.com/kontakt/";
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
if (br.containsHTML("Aby obejrzeć i pobrać plik - musisz się")) throw new PluginException(LinkStatus.ERROR_FATAL, "Only downloadable for registered users");
// Values to submit to the server
String id = new Regex(downloadLink.getDownloadURL(), "/pokaz/.*?/([0-9]+)").getMatch(0);
String name = new Regex(downloadLink.getDownloadURL(), "plik/pokaz/(.*?)/").getMatch(0);
if (name == null || id == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
name = Encoding.htmlDecode(name.trim().toLowerCase());
id = Encoding.urlEncode(id);
// Without this it doesn't work, this is very important!!
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.postPage("http://www.frogup.com/plik/pobierzURL", "name=" + name + "&id=" + id);
String dllink = br.getRegex("data\":\"(.*?)\"").getMatch(0);
if (dllink == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
dllink = dllink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, -13);
dl.startDownload();
}
@Override
public AvailableStatus requestFileInformation(DownloadLink downloadLink) throws IOException, PluginException {
this.setBrowserExclusive();
br.setCustomCharset("utf-8");
br.getPage(downloadLink.getDownloadURL());
if (br.containsHTML("404\\.gif")) throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
String filesize = br.getRegex("Rozmiar pliku:</span> <span class=.*?>(.*?)</span>").getMatch(0);
String filename = br.getRegex("Pełna nazwa pliku.*?<strong>(.*?)</strong>").getMatch(0);
if (filename == null || filesize == null) throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
downloadLink.setName(filename.trim());
downloadLink.setDownloadSize(SizeFormatter.getSize(filesize));
return AvailableStatus.TRUE;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
@Override
public void resetPluginGlobals() {
}
} | //www.frogup.com/plik/pobierzURL", "name=" + name + "&id=" + id);
| // jDownloader - Downloadmanager
// Copyright (C) 2009 JD-Team support@jdownloader.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "frogup.com" }, urls = { "http://[\\w\\.]*?frogup\\.com/plik/pokaz/.*?/[0-9]+" }, flags = { 0 })
public class FrogUpCom extends PluginForHost {
public FrogUpCom(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://www.frogup.com/kontakt/";
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
if (br.containsHTML("Aby obejrzeć i pobrać plik - musisz się")) throw new PluginException(LinkStatus.ERROR_FATAL, "Only downloadable for registered users");
// Values to submit to the server
String id = new Regex(downloadLink.getDownloadURL(), "/pokaz/.*?/([0-9]+)").getMatch(0);
String name = new Regex(downloadLink.getDownloadURL(), "plik/pokaz/(.*?)/").getMatch(0);
if (name == null || id == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
name = Encoding.htmlDecode(name.trim().toLowerCase());
id = Encoding.urlEncode(id);
// Without this it doesn't work, this is very important!!
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
br.postPage("http://www.frogup.com/plik/pobierzURL", "name=" <SUF>
String dllink = br.getRegex("data\":\"(.*?)\"").getMatch(0);
if (dllink == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
dllink = dllink.replace("\\", "");
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, true, -13);
dl.startDownload();
}
@Override
public AvailableStatus requestFileInformation(DownloadLink downloadLink) throws IOException, PluginException {
this.setBrowserExclusive();
br.setCustomCharset("utf-8");
br.getPage(downloadLink.getDownloadURL());
if (br.containsHTML("404\\.gif")) throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
String filesize = br.getRegex("Rozmiar pliku:</span> <span class=.*?>(.*?)</span>").getMatch(0);
String filename = br.getRegex("Pełna nazwa pliku.*?<strong>(.*?)</strong>").getMatch(0);
if (filename == null || filesize == null) throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
downloadLink.setName(filename.trim());
downloadLink.setDownloadSize(SizeFormatter.getSize(filesize));
return AvailableStatus.TRUE;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
@Override
public void resetPluginGlobals() {
}
} | f |
2427_8 | jitlogic/zorka | 2,301 | zorka-common/src/main/java/com/jitlogic/zorka/common/collector/TraceMetadataIndexer.java | package com.jitlogic.zorka.common.collector;
import com.jitlogic.zorka.common.cbor.BufferedTraceDataProcessor;
import com.jitlogic.zorka.common.cbor.TraceDataProcessor;
import com.jitlogic.zorka.common.cbor.TraceRecordFlags;
import com.jitlogic.zorka.common.tracedata.SymbolRegistry;
import com.jitlogic.zorka.common.tracedata.SymbolicMethod;
import com.jitlogic.zorka.common.tracedata.TraceMarker;
import com.jitlogic.zorka.common.util.ZorkaUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static com.jitlogic.zorka.common.collector.SymbolDataExtractor.extractSymbolData;
/** Extracts additional metadata needed to properly index trace. */
public class TraceMetadataIndexer implements TraceDataProcessor {
/** Current call stack depth */
private int stackDepth = 0;
/** Start position (of currently processed chunk) */
private int startOffs = 0;
/** Current position (in currently processed chunk) */
private int currentPos = 0;
/** Last noticed method ID */
private int lastMethodId;
private long traceId1;
private long traceId2;
private int chunkNum;
/** Indexing result */
private List<TraceChunkData> result = new ArrayList<TraceChunkData>();
/** Top of trace stack */
private TraceChunkData top;
private SymbolRegistry registry;
private BufferedTraceDataProcessor output;
/** Last received start time */
private long tstart = Long.MAX_VALUE;
/** Last received stop time */
private long tstop = Long.MIN_VALUE;
private Map<Long,TraceDataResultException> exceptions = new TreeMap<Long, TraceDataResultException>();
public TraceMetadataIndexer(SymbolRegistry registry, BufferedTraceDataProcessor output) {
this.registry = registry;
this.output = output;
}
public void init(long traceId1, long traceId2, int chunkNum) {
startOffs += currentPos;
this.traceId1 = traceId1;
this.traceId2 = traceId2;
this.chunkNum = chunkNum;
}
public List<TraceChunkData> getChunks() {
return result;
}
@Override
public void stringRef(int symbolId, String symbol) {
if (output != null) output.stringRef(symbolId, symbol);
}
@Override
public void methodRef(int symbolId, int classId, int methodId, int signatureId) {
if (output != null) output.methodRef(symbolId, classId, methodId, signatureId);
}
/** Trace push */
private void push(TraceChunkData tcd) {
if (top != null) tcd.setParent(top);
top = tcd;
}
/** Trace pop */
private void pop(int pos) {
if (top != null) {
TraceChunkData c = top;
c.setTstart(tstart);
c.setTstop(tstop);
if (c.getParentId() == 0 && top.getParent() != null) {
c.setParentId(top.getParent().getSpanId());
}
int len = pos - c.getStartOffs();
if (len > 0) {
byte[] traceData = output.chunk(c.getStartOffs(), len);
c.setTraceData(ZorkaUtil.gzip(traceData));
c.setSymbolData(extractSymbolData(registry, traceData));
}
// TODO uwaga: tylko zakończone fragmenty są zapisywane; zaimplementować tymczasowy zapis niezakończonych fragmentów;
if (top.getParent() == null || !top.hasFlag(TraceMarker.SENT_MARK)) {
result.add(c);
}
top = top.getParent();
if (top != null) {
top.addRecs(c.getRecs());
top.addErrors(c.getErrors());
top.addCalls(c.getCalls());
}
}
}
@Override
public void traceStart(int pos, long tstart, int methodId) {
if (output != null) pos = output.size();
stackDepth++;
this.currentPos = pos;
this.tstart = tstart;
this.lastMethodId = methodId;
if (top != null) top.addMethod(methodId);
if (output != null) output.traceStart(pos, tstart, methodId);
}
@Override
public void traceEnd(int pos, long tstop, long calls, int flags) {
if (output != null) {
output.traceEnd(pos, tstop, calls, flags);
pos = output.size();
}
this.currentPos = pos;
this.tstop = tstop;
if (top != null) {
top.addCalls((int)calls+1);
top.addRecs(1);
top.setFlags(flags);
if (0 != (flags & TraceMarker.ERROR_MARK)) {
top.addErrors(1);
if (top.getStackDepth() == stackDepth) top.setError(true);
}
if (top.getStackDepth() == stackDepth) {
top.setTstop(tstop);
top.setDuration(top.getTstop()-top.getTstart());
pop(pos);
}
}
stackDepth--;
}
@Override
public void traceBegin(long tstamp, int ttypeId, long spanId, long parentId) {
TraceChunkData c = new TraceChunkData(traceId1, traceId2,
parentId != 0 ? parentId : (top != null ? top.getSpanId() : 0),
spanId, chunkNum);
c.setStackDepth(stackDepth);
c.setTstart(tstart);
c.setTstamp(tstamp);
c.setStartOffs(this.currentPos);
c.addMethod(lastMethodId);
SymbolicMethod mdef = registry.methodDef(lastMethodId);
c.setKlass(registry.symbolName(mdef.getClassId()));
c.setMethod(registry.symbolName(mdef.getMethodId()));
c.setTtypeId(ttypeId);
c.setTtype(registry.symbolName(ttypeId));
push(c);
if (output != null) output.traceBegin(tstamp, ttypeId, spanId, parentId);
}
@Override
public void traceAttr(int attrId, Object attrVal) {
//System.out.println("Attr: " + registry.symbolName(attrId) + "(" + attrId + ") -> " + attrVal);
String attrName = registry.symbolName(attrId);
if (attrName != null && top != null) top.getAttrs().put(attrName, ""+attrVal);
if (output != null) output.traceAttr(attrId, attrVal);
}
@Override
public void traceAttr(int ttypeId, int attrId, Object attrVal) {
String attrName = registry.symbolName(attrId);
for (TraceChunkData c = top; c != null; c = c.getParent()) {
if (c.getTtypeId() == ttypeId) {
c.getAttrs().put(attrName, ""+attrVal);
}
}
if (output != null) output.traceAttr(attrId, attrVal);
}
@Override
public void exception(long excId, int classId, String message, long cause, List<int[]> stackTrace, Map<Integer, Object> attrs) {
TraceDataResultException ex = new TraceDataResultException(excId, registry.symbolName(classId), message);
for (int[] si : stackTrace) {
ex.getStack().add(String.format("%s.%s (%s:%d)", registry.symbolName(si[0]),
registry.symbolName(si[1]), registry.symbolName(si[2]), si[3]));
}
exceptions.put(ex.getId(), ex);
if (top != null && top.getStackDepth() == stackDepth) top.setException(ex);
if (output != null) output.exception(excId, classId, message, cause, stackTrace, attrs);
}
@Override
public void exceptionRef(long excId) {
if (top != null && top.getStackDepth() == stackDepth && exceptions.containsKey(excId)) {
top.setException(exceptions.get(excId));
}
if (output != null) output.exceptionRef(excId);
}
}
| // TODO uwaga: tylko zakończone fragmenty są zapisywane; zaimplementować tymczasowy zapis niezakończonych fragmentów; | package com.jitlogic.zorka.common.collector;
import com.jitlogic.zorka.common.cbor.BufferedTraceDataProcessor;
import com.jitlogic.zorka.common.cbor.TraceDataProcessor;
import com.jitlogic.zorka.common.cbor.TraceRecordFlags;
import com.jitlogic.zorka.common.tracedata.SymbolRegistry;
import com.jitlogic.zorka.common.tracedata.SymbolicMethod;
import com.jitlogic.zorka.common.tracedata.TraceMarker;
import com.jitlogic.zorka.common.util.ZorkaUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static com.jitlogic.zorka.common.collector.SymbolDataExtractor.extractSymbolData;
/** Extracts additional metadata needed to properly index trace. */
public class TraceMetadataIndexer implements TraceDataProcessor {
/** Current call stack depth */
private int stackDepth = 0;
/** Start position (of currently processed chunk) */
private int startOffs = 0;
/** Current position (in currently processed chunk) */
private int currentPos = 0;
/** Last noticed method ID */
private int lastMethodId;
private long traceId1;
private long traceId2;
private int chunkNum;
/** Indexing result */
private List<TraceChunkData> result = new ArrayList<TraceChunkData>();
/** Top of trace stack */
private TraceChunkData top;
private SymbolRegistry registry;
private BufferedTraceDataProcessor output;
/** Last received start time */
private long tstart = Long.MAX_VALUE;
/** Last received stop time */
private long tstop = Long.MIN_VALUE;
private Map<Long,TraceDataResultException> exceptions = new TreeMap<Long, TraceDataResultException>();
public TraceMetadataIndexer(SymbolRegistry registry, BufferedTraceDataProcessor output) {
this.registry = registry;
this.output = output;
}
public void init(long traceId1, long traceId2, int chunkNum) {
startOffs += currentPos;
this.traceId1 = traceId1;
this.traceId2 = traceId2;
this.chunkNum = chunkNum;
}
public List<TraceChunkData> getChunks() {
return result;
}
@Override
public void stringRef(int symbolId, String symbol) {
if (output != null) output.stringRef(symbolId, symbol);
}
@Override
public void methodRef(int symbolId, int classId, int methodId, int signatureId) {
if (output != null) output.methodRef(symbolId, classId, methodId, signatureId);
}
/** Trace push */
private void push(TraceChunkData tcd) {
if (top != null) tcd.setParent(top);
top = tcd;
}
/** Trace pop */
private void pop(int pos) {
if (top != null) {
TraceChunkData c = top;
c.setTstart(tstart);
c.setTstop(tstop);
if (c.getParentId() == 0 && top.getParent() != null) {
c.setParentId(top.getParent().getSpanId());
}
int len = pos - c.getStartOffs();
if (len > 0) {
byte[] traceData = output.chunk(c.getStartOffs(), len);
c.setTraceData(ZorkaUtil.gzip(traceData));
c.setSymbolData(extractSymbolData(registry, traceData));
}
// TODO uwaga: <SUF>
if (top.getParent() == null || !top.hasFlag(TraceMarker.SENT_MARK)) {
result.add(c);
}
top = top.getParent();
if (top != null) {
top.addRecs(c.getRecs());
top.addErrors(c.getErrors());
top.addCalls(c.getCalls());
}
}
}
@Override
public void traceStart(int pos, long tstart, int methodId) {
if (output != null) pos = output.size();
stackDepth++;
this.currentPos = pos;
this.tstart = tstart;
this.lastMethodId = methodId;
if (top != null) top.addMethod(methodId);
if (output != null) output.traceStart(pos, tstart, methodId);
}
@Override
public void traceEnd(int pos, long tstop, long calls, int flags) {
if (output != null) {
output.traceEnd(pos, tstop, calls, flags);
pos = output.size();
}
this.currentPos = pos;
this.tstop = tstop;
if (top != null) {
top.addCalls((int)calls+1);
top.addRecs(1);
top.setFlags(flags);
if (0 != (flags & TraceMarker.ERROR_MARK)) {
top.addErrors(1);
if (top.getStackDepth() == stackDepth) top.setError(true);
}
if (top.getStackDepth() == stackDepth) {
top.setTstop(tstop);
top.setDuration(top.getTstop()-top.getTstart());
pop(pos);
}
}
stackDepth--;
}
@Override
public void traceBegin(long tstamp, int ttypeId, long spanId, long parentId) {
TraceChunkData c = new TraceChunkData(traceId1, traceId2,
parentId != 0 ? parentId : (top != null ? top.getSpanId() : 0),
spanId, chunkNum);
c.setStackDepth(stackDepth);
c.setTstart(tstart);
c.setTstamp(tstamp);
c.setStartOffs(this.currentPos);
c.addMethod(lastMethodId);
SymbolicMethod mdef = registry.methodDef(lastMethodId);
c.setKlass(registry.symbolName(mdef.getClassId()));
c.setMethod(registry.symbolName(mdef.getMethodId()));
c.setTtypeId(ttypeId);
c.setTtype(registry.symbolName(ttypeId));
push(c);
if (output != null) output.traceBegin(tstamp, ttypeId, spanId, parentId);
}
@Override
public void traceAttr(int attrId, Object attrVal) {
//System.out.println("Attr: " + registry.symbolName(attrId) + "(" + attrId + ") -> " + attrVal);
String attrName = registry.symbolName(attrId);
if (attrName != null && top != null) top.getAttrs().put(attrName, ""+attrVal);
if (output != null) output.traceAttr(attrId, attrVal);
}
@Override
public void traceAttr(int ttypeId, int attrId, Object attrVal) {
String attrName = registry.symbolName(attrId);
for (TraceChunkData c = top; c != null; c = c.getParent()) {
if (c.getTtypeId() == ttypeId) {
c.getAttrs().put(attrName, ""+attrVal);
}
}
if (output != null) output.traceAttr(attrId, attrVal);
}
@Override
public void exception(long excId, int classId, String message, long cause, List<int[]> stackTrace, Map<Integer, Object> attrs) {
TraceDataResultException ex = new TraceDataResultException(excId, registry.symbolName(classId), message);
for (int[] si : stackTrace) {
ex.getStack().add(String.format("%s.%s (%s:%d)", registry.symbolName(si[0]),
registry.symbolName(si[1]), registry.symbolName(si[2]), si[3]));
}
exceptions.put(ex.getId(), ex);
if (top != null && top.getStackDepth() == stackDepth) top.setException(ex);
if (output != null) output.exception(excId, classId, message, cause, stackTrace, attrs);
}
@Override
public void exceptionRef(long excId) {
if (top != null && top.getStackDepth() == stackDepth && exceptions.containsKey(excId)) {
top.setException(exceptions.get(excId));
}
if (output != null) output.exceptionRef(excId);
}
}
| f |
2804_1 | jonasz-lazar-pwr/library-management-system | 4,279 | src/RegisterWindow.java | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.*;
import java.sql.Connection;
public class RegisterWindow extends JFrame implements FocusListener, ActionListener {
private final String jdbcUrl;
private final String dbUsername;
private final String dbPassword;
private MyTextField firstNameField;
private MyTextField lastNameField;
private MyTextField addressField;
private MyTextField phoneField;
private MyTextField cardNumberField;
private MyTextField mailField;
private MyTextField usernameField;
private MyPasswordField passwordField;
private MyButton registerButton;
private JPanel textFieldPanel;
private JPanel buttonsPanel;
public RegisterWindow(String jdbcUrl, String dbUsername, String dbPassword) {
this.jdbcUrl = jdbcUrl;
this.dbUsername = dbUsername;
this.dbPassword = dbPassword;
initComponents();
// Ustawienia okna
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("System obsługi biblioteki - rejestracja");
setSize(500, 500);
setLocationRelativeTo(null);
setResizable(false);
setLayout(null);
getContentPane().setBackground(Color.DARK_GRAY);
setVisible(true);
requestFocusInWindow();
add(textFieldPanel);
add(buttonsPanel);
}
private void initComponents() {
textFieldPanel = new JPanel();
textFieldPanel.setBounds(145, 15, 200, 365);
textFieldPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 10));
textFieldPanel.setBackground(Color.LIGHT_GRAY);
textFieldPanel.setOpaque(false);
// Dodanie pól tekstowych
firstNameField = new MyTextField("Imię");
firstNameField.setPreferredSize(new Dimension(200, 35));
firstNameField.addFocusListener(this);
textFieldPanel.add(firstNameField);
lastNameField = new MyTextField("Nazwisko");
lastNameField.setPreferredSize(new Dimension(200, 35));
lastNameField.addFocusListener(this);
textFieldPanel.add(lastNameField);
addressField = new MyTextField("Adres zamieszkania");
addressField.setPreferredSize(new Dimension(200, 35));
addressField.addFocusListener(this);
textFieldPanel.add(addressField);
phoneField = new MyTextField("Numer telefonu");
phoneField.setPreferredSize(new Dimension(200, 35));
phoneField.addFocusListener(this);
textFieldPanel.add(phoneField);
mailField = new MyTextField("Adres e-mail");
mailField.setPreferredSize(new Dimension(200, 35));
mailField.addFocusListener(this);
textFieldPanel.add(mailField);
cardNumberField = new MyTextField("Numer karty bibliotecznej");
cardNumberField.setPreferredSize(new Dimension(200, 35));
cardNumberField.addFocusListener(this);
textFieldPanel.add(cardNumberField);
usernameField = new MyTextField("Login");
usernameField.setPreferredSize(new Dimension(200, 35));
usernameField.addFocusListener(this);
textFieldPanel.add(usernameField);
passwordField = new MyPasswordField("Hasło");
passwordField.setPreferredSize(new Dimension(200,35));
passwordField.addFocusListener(this);
textFieldPanel.add(passwordField);
buttonsPanel = new JPanel();
buttonsPanel.setBounds(80, 380, 340, 65);
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 10));
buttonsPanel.setBackground(Color.LIGHT_GRAY);
buttonsPanel.setOpaque(false);
MyButton cancelButton = new MyButton("Anuluj");
cancelButton.setPreferredSize(new Dimension(150, 45));
cancelButton.addActionListener(e -> {
SwingUtilities.invokeLater(() -> new LoginWindow(jdbcUrl, dbUsername, dbPassword));
dispose();
});
buttonsPanel.add(cancelButton);
// Przycisk odpowiedzialny za rejestrowanie nowego użytkownika
registerButton = new MyButton("Utwórz konto");
registerButton.setPreferredSize(new Dimension(150, 45));
registerButton.addActionListener(this);
buttonsPanel.add(registerButton);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == registerButton) {
String validationMessage = validateFields();
if (validationMessage.isEmpty()) {
// Walidacja pól zakończyła się sukcesem
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
String address = addressField.getText();
String phone = phoneField.getText();
String cardNumber = cardNumberField.getText();
String email = mailField.getText();
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
try {
Connection connection = DriverManager.getConnection(jdbcUrl, dbUsername, dbPassword);
String query = "INSERT INTO Users (FirstName, LastName, Address, PhoneNumber, CardNumber, Email, Login, UserPassword, UserRole) VALUES (?, ?, ?, ?, ?, ?, ?, MD5(?), ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, firstName);
preparedStatement.setString(2, lastName);
preparedStatement.setString(3, address);
preparedStatement.setString(4, phone);
preparedStatement.setString(5, cardNumber);
preparedStatement.setString(6, email);
preparedStatement.setString(7, username);
preparedStatement.setString(8, password);
preparedStatement.setString(9, "czytelnik");
int rowsAdded = preparedStatement.executeUpdate();
System.out.println(rowsAdded + " wiersz(y) dodano.");
JOptionPane.showMessageDialog(RegisterWindow.this, "Zarejestrowano użytkownika, teraz możesz się zalogować", "Koniec rejestracji", JOptionPane.INFORMATION_MESSAGE);
SwingUtilities.invokeLater(() -> new LoginWindow(jdbcUrl, dbUsername, dbPassword));
dispose();
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Wystąpił błąd podczas rejestracji użytkownika.", "Błąd", JOptionPane.ERROR_MESSAGE);
}
} else {
// Wyświetl komunikat o błędzie walidacji pól
JOptionPane.showMessageDialog(this, validationMessage, "Błąd walidacji", JOptionPane.ERROR_MESSAGE);
}
}
}
private String validateFields() {
StringBuilder validationMessage = new StringBuilder();
if (validateNonDefault(firstNameField, "Imię")) {
validationMessage.append("Pole Imię nie może pozostać puste.\n");
} else if (!validateName(firstNameField.getText()) || containsSpaces(firstNameField.getText())) {
validationMessage.append("Błędne imię. Imię powinno zaczynać się z dużej litery i składać z liter. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(lastNameField, "Nazwisko")) {
validationMessage.append("Pole Nazwisko nie może pozostać puste.\n");
} else if (!validateName(lastNameField.getText()) || containsSpaces(lastNameField.getText())) {
validationMessage.append("Błędne nazwisko. Nazwisko powinno zaczynać się z dużej litery i składać z liter. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(addressField, "Adres zamieszkania")) {
validationMessage.append("Pole Adres zamieszkania nie może pozostać puste.\n");
} else if (!validateAddress(addressField.getText()) || containsSpaces(addressField.getText())) {
validationMessage.append("Błędny adres zamieszkania. Poprawny format: ul./al./pl./os. nazwa numer, miasto. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(phoneField, "Numer telefonu")) {
validationMessage.append("Pole Numer telefonu nie może pozostać puste.\n");
} else if (!validatePhone(phoneField.getText()) || containsSpaces(phoneField.getText())) {
validationMessage.append("Błędny numer telefonu. Poprawny format: +48 xxx xxx xxx. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(mailField, "Adres e-mail")) {
validationMessage.append("Pole Adres e-mail nie może pozostać puste.\n");
} else if (!validateEmail(mailField.getText()) || containsSpaces(mailField.getText())) {
validationMessage.append("Błędny adres email. Poprawny format: user@example.com. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(cardNumberField, "Numer karty bibliotecznej")) {
validationMessage.append("Pole Numer karty bibliotecznej nie może pozostać puste.\n");
} else if (!validateCardNumber(cardNumberField.getText()) || containsSpaces(cardNumberField.getText())) {
validationMessage.append("Błędny numer karty bibliotecznej. Poprawny format: Axxxxx. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(usernameField, "Login")) {
validationMessage.append("Pole Login nie może pozostać puste.\n");
} else if (!validateUsername(usernameField.getText()) || containsSpaces(usernameField.getText())) {
validationMessage.append("Błędny login. Login nie może zawierać spacji i musi mieć od 4 do 20 znaków. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(passwordField, "Hasło")) {
validationMessage.append("Pole Hasło nie może pozostać puste.\n");
} else if (!validatePassword(new String(passwordField.getPassword())) || containsSpaces(new String(passwordField.getPassword()))) {
validationMessage.append("Błędne hasło. Hasło musi zawierać minimum 8 znaków, przynajmniej jedną cyfrę, jedną małą literę, jedną dużą literę, jeden znak specjalny oraz brak spacji.\n");
}
return validationMessage.toString();
}
private boolean containsSpaces(String text) {
return text.trim().length() != text.length();
}
private boolean validateNonDefault(JTextField field, String defaultValue) {
return field.getText().trim().equals(defaultValue);
}
private boolean validateName(String name) {
return name.matches("[A-ZĄĆĘŁŃÓŚŹŻ][a-ząćęłńóśźż]+");
}
private boolean validateAddress(String address) {
return address.matches("^(ul\\.|al\\.|pl\\.|os\\.) [A-ZĄĆĘŁŃÓŚŹŻa-ząćęłńóśźż]+( \\d+[a-z]*)*, [A-ZĄĆĘŁŃÓŚŹŻa-ząćęłńóśźż]+");
}
private boolean validatePhone(String phone) {
return phone.matches("\\+48 \\d{3} \\d{3} \\d{3}");
}
private boolean validateEmail(String email) {
return email.matches(".*@.*\\..*");
}
private boolean validateCardNumber(String cardNumber) {
return cardNumber.matches("[A-Z]\\d{5}");
}
private boolean validateUsername(String username) {
return !username.contains(" ") && username.length() >= 4 && username.length() <= 20;
}
private boolean validatePassword(String password) {
return password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=!])(?=\\S+$).{8,}$");
}
@Override
public void focusGained(FocusEvent e) {
if (e.getSource() == firstNameField) {
if (firstNameField.getText().equals("Imię")) {
firstNameField.setText("");
}
} else if (e.getSource() == lastNameField) {
if (lastNameField.getText().equals("Nazwisko")) {
lastNameField.setText("");
}
} else if (e.getSource() == addressField) {
if (addressField.getText().equals("Adres zamieszkania")) {
addressField.setText("");
}
} else if (e.getSource() == phoneField) {
if (phoneField.getText().equals("Numer telefonu")) {
phoneField.setText("");
}
} else if (e.getSource() == mailField) {
if (mailField.getText().equals("Adres e-mail")) {
mailField.setText("");
}
} else if (e.getSource() == cardNumberField) {
if (cardNumberField.getText().equals("Numer karty bibliotecznej")) {
cardNumberField.setText("");
}
} else if (e.getSource() == usernameField) {
if (usernameField.getText().equals("Login")) {
usernameField.setText("");
}
} else if (e.getSource() == passwordField) {
String passwordText = new String(passwordField.getPassword());
if (passwordText.equals("Hasło")) {
passwordField.setEchoChar('\u2022');
passwordField.setText("");
}
}
}
@Override
public void focusLost(FocusEvent e) {
if (e.getSource() == firstNameField) {
if (firstNameField.getText().isEmpty()) {
firstNameField.setText("Imię");
}
} else if (e.getSource() == lastNameField) {
if (lastNameField.getText().isEmpty()) {
lastNameField.setText("Nazwisko");
}
} else if (e.getSource() == addressField) {
if (addressField.getText().isEmpty()) {
addressField.setText("Adres zamieszkania");
}
} else if (e.getSource() == phoneField) {
if (phoneField.getText().isEmpty()) {
phoneField.setText("Numer telefonu");
}
} else if (e.getSource() == mailField) {
if (mailField.getText().isEmpty()) {
mailField.setText("Adres e-mail");
}
} else if (e.getSource() == cardNumberField) {
if (cardNumberField.getText().isEmpty()) {
cardNumberField.setText("Numer karty bibliotecznej");
}
} else if (e.getSource() == usernameField) {
if (usernameField.getText().isEmpty()) {
usernameField.setText("Login");
}
} else if (e.getSource() == passwordField) {
String passwordText = new String(passwordField.getPassword());
if (passwordText.isEmpty()) {
passwordField.setEchoChar((char) 0);
passwordField.setText("Hasło");
}
}
}
}
| // Przycisk odpowiedzialny za rejestrowanie nowego użytkownika | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.*;
import java.sql.Connection;
public class RegisterWindow extends JFrame implements FocusListener, ActionListener {
private final String jdbcUrl;
private final String dbUsername;
private final String dbPassword;
private MyTextField firstNameField;
private MyTextField lastNameField;
private MyTextField addressField;
private MyTextField phoneField;
private MyTextField cardNumberField;
private MyTextField mailField;
private MyTextField usernameField;
private MyPasswordField passwordField;
private MyButton registerButton;
private JPanel textFieldPanel;
private JPanel buttonsPanel;
public RegisterWindow(String jdbcUrl, String dbUsername, String dbPassword) {
this.jdbcUrl = jdbcUrl;
this.dbUsername = dbUsername;
this.dbPassword = dbPassword;
initComponents();
// Ustawienia okna
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("System obsługi biblioteki - rejestracja");
setSize(500, 500);
setLocationRelativeTo(null);
setResizable(false);
setLayout(null);
getContentPane().setBackground(Color.DARK_GRAY);
setVisible(true);
requestFocusInWindow();
add(textFieldPanel);
add(buttonsPanel);
}
private void initComponents() {
textFieldPanel = new JPanel();
textFieldPanel.setBounds(145, 15, 200, 365);
textFieldPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 10));
textFieldPanel.setBackground(Color.LIGHT_GRAY);
textFieldPanel.setOpaque(false);
// Dodanie pól tekstowych
firstNameField = new MyTextField("Imię");
firstNameField.setPreferredSize(new Dimension(200, 35));
firstNameField.addFocusListener(this);
textFieldPanel.add(firstNameField);
lastNameField = new MyTextField("Nazwisko");
lastNameField.setPreferredSize(new Dimension(200, 35));
lastNameField.addFocusListener(this);
textFieldPanel.add(lastNameField);
addressField = new MyTextField("Adres zamieszkania");
addressField.setPreferredSize(new Dimension(200, 35));
addressField.addFocusListener(this);
textFieldPanel.add(addressField);
phoneField = new MyTextField("Numer telefonu");
phoneField.setPreferredSize(new Dimension(200, 35));
phoneField.addFocusListener(this);
textFieldPanel.add(phoneField);
mailField = new MyTextField("Adres e-mail");
mailField.setPreferredSize(new Dimension(200, 35));
mailField.addFocusListener(this);
textFieldPanel.add(mailField);
cardNumberField = new MyTextField("Numer karty bibliotecznej");
cardNumberField.setPreferredSize(new Dimension(200, 35));
cardNumberField.addFocusListener(this);
textFieldPanel.add(cardNumberField);
usernameField = new MyTextField("Login");
usernameField.setPreferredSize(new Dimension(200, 35));
usernameField.addFocusListener(this);
textFieldPanel.add(usernameField);
passwordField = new MyPasswordField("Hasło");
passwordField.setPreferredSize(new Dimension(200,35));
passwordField.addFocusListener(this);
textFieldPanel.add(passwordField);
buttonsPanel = new JPanel();
buttonsPanel.setBounds(80, 380, 340, 65);
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 10));
buttonsPanel.setBackground(Color.LIGHT_GRAY);
buttonsPanel.setOpaque(false);
MyButton cancelButton = new MyButton("Anuluj");
cancelButton.setPreferredSize(new Dimension(150, 45));
cancelButton.addActionListener(e -> {
SwingUtilities.invokeLater(() -> new LoginWindow(jdbcUrl, dbUsername, dbPassword));
dispose();
});
buttonsPanel.add(cancelButton);
// Przycisk odpowiedzialny <SUF>
registerButton = new MyButton("Utwórz konto");
registerButton.setPreferredSize(new Dimension(150, 45));
registerButton.addActionListener(this);
buttonsPanel.add(registerButton);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == registerButton) {
String validationMessage = validateFields();
if (validationMessage.isEmpty()) {
// Walidacja pól zakończyła się sukcesem
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
String address = addressField.getText();
String phone = phoneField.getText();
String cardNumber = cardNumberField.getText();
String email = mailField.getText();
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
try {
Connection connection = DriverManager.getConnection(jdbcUrl, dbUsername, dbPassword);
String query = "INSERT INTO Users (FirstName, LastName, Address, PhoneNumber, CardNumber, Email, Login, UserPassword, UserRole) VALUES (?, ?, ?, ?, ?, ?, ?, MD5(?), ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, firstName);
preparedStatement.setString(2, lastName);
preparedStatement.setString(3, address);
preparedStatement.setString(4, phone);
preparedStatement.setString(5, cardNumber);
preparedStatement.setString(6, email);
preparedStatement.setString(7, username);
preparedStatement.setString(8, password);
preparedStatement.setString(9, "czytelnik");
int rowsAdded = preparedStatement.executeUpdate();
System.out.println(rowsAdded + " wiersz(y) dodano.");
JOptionPane.showMessageDialog(RegisterWindow.this, "Zarejestrowano użytkownika, teraz możesz się zalogować", "Koniec rejestracji", JOptionPane.INFORMATION_MESSAGE);
SwingUtilities.invokeLater(() -> new LoginWindow(jdbcUrl, dbUsername, dbPassword));
dispose();
}
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Wystąpił błąd podczas rejestracji użytkownika.", "Błąd", JOptionPane.ERROR_MESSAGE);
}
} else {
// Wyświetl komunikat o błędzie walidacji pól
JOptionPane.showMessageDialog(this, validationMessage, "Błąd walidacji", JOptionPane.ERROR_MESSAGE);
}
}
}
private String validateFields() {
StringBuilder validationMessage = new StringBuilder();
if (validateNonDefault(firstNameField, "Imię")) {
validationMessage.append("Pole Imię nie może pozostać puste.\n");
} else if (!validateName(firstNameField.getText()) || containsSpaces(firstNameField.getText())) {
validationMessage.append("Błędne imię. Imię powinno zaczynać się z dużej litery i składać z liter. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(lastNameField, "Nazwisko")) {
validationMessage.append("Pole Nazwisko nie może pozostać puste.\n");
} else if (!validateName(lastNameField.getText()) || containsSpaces(lastNameField.getText())) {
validationMessage.append("Błędne nazwisko. Nazwisko powinno zaczynać się z dużej litery i składać z liter. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(addressField, "Adres zamieszkania")) {
validationMessage.append("Pole Adres zamieszkania nie może pozostać puste.\n");
} else if (!validateAddress(addressField.getText()) || containsSpaces(addressField.getText())) {
validationMessage.append("Błędny adres zamieszkania. Poprawny format: ul./al./pl./os. nazwa numer, miasto. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(phoneField, "Numer telefonu")) {
validationMessage.append("Pole Numer telefonu nie może pozostać puste.\n");
} else if (!validatePhone(phoneField.getText()) || containsSpaces(phoneField.getText())) {
validationMessage.append("Błędny numer telefonu. Poprawny format: +48 xxx xxx xxx. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(mailField, "Adres e-mail")) {
validationMessage.append("Pole Adres e-mail nie może pozostać puste.\n");
} else if (!validateEmail(mailField.getText()) || containsSpaces(mailField.getText())) {
validationMessage.append("Błędny adres email. Poprawny format: user@example.com. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(cardNumberField, "Numer karty bibliotecznej")) {
validationMessage.append("Pole Numer karty bibliotecznej nie może pozostać puste.\n");
} else if (!validateCardNumber(cardNumberField.getText()) || containsSpaces(cardNumberField.getText())) {
validationMessage.append("Błędny numer karty bibliotecznej. Poprawny format: Axxxxx. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(usernameField, "Login")) {
validationMessage.append("Pole Login nie może pozostać puste.\n");
} else if (!validateUsername(usernameField.getText()) || containsSpaces(usernameField.getText())) {
validationMessage.append("Błędny login. Login nie może zawierać spacji i musi mieć od 4 do 20 znaków. Nie może zawierać spacji na początku lub na końcu.\n");
}
if (validateNonDefault(passwordField, "Hasło")) {
validationMessage.append("Pole Hasło nie może pozostać puste.\n");
} else if (!validatePassword(new String(passwordField.getPassword())) || containsSpaces(new String(passwordField.getPassword()))) {
validationMessage.append("Błędne hasło. Hasło musi zawierać minimum 8 znaków, przynajmniej jedną cyfrę, jedną małą literę, jedną dużą literę, jeden znak specjalny oraz brak spacji.\n");
}
return validationMessage.toString();
}
private boolean containsSpaces(String text) {
return text.trim().length() != text.length();
}
private boolean validateNonDefault(JTextField field, String defaultValue) {
return field.getText().trim().equals(defaultValue);
}
private boolean validateName(String name) {
return name.matches("[A-ZĄĆĘŁŃÓŚŹŻ][a-ząćęłńóśźż]+");
}
private boolean validateAddress(String address) {
return address.matches("^(ul\\.|al\\.|pl\\.|os\\.) [A-ZĄĆĘŁŃÓŚŹŻa-ząćęłńóśźż]+( \\d+[a-z]*)*, [A-ZĄĆĘŁŃÓŚŹŻa-ząćęłńóśźż]+");
}
private boolean validatePhone(String phone) {
return phone.matches("\\+48 \\d{3} \\d{3} \\d{3}");
}
private boolean validateEmail(String email) {
return email.matches(".*@.*\\..*");
}
private boolean validateCardNumber(String cardNumber) {
return cardNumber.matches("[A-Z]\\d{5}");
}
private boolean validateUsername(String username) {
return !username.contains(" ") && username.length() >= 4 && username.length() <= 20;
}
private boolean validatePassword(String password) {
return password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=!])(?=\\S+$).{8,}$");
}
@Override
public void focusGained(FocusEvent e) {
if (e.getSource() == firstNameField) {
if (firstNameField.getText().equals("Imię")) {
firstNameField.setText("");
}
} else if (e.getSource() == lastNameField) {
if (lastNameField.getText().equals("Nazwisko")) {
lastNameField.setText("");
}
} else if (e.getSource() == addressField) {
if (addressField.getText().equals("Adres zamieszkania")) {
addressField.setText("");
}
} else if (e.getSource() == phoneField) {
if (phoneField.getText().equals("Numer telefonu")) {
phoneField.setText("");
}
} else if (e.getSource() == mailField) {
if (mailField.getText().equals("Adres e-mail")) {
mailField.setText("");
}
} else if (e.getSource() == cardNumberField) {
if (cardNumberField.getText().equals("Numer karty bibliotecznej")) {
cardNumberField.setText("");
}
} else if (e.getSource() == usernameField) {
if (usernameField.getText().equals("Login")) {
usernameField.setText("");
}
} else if (e.getSource() == passwordField) {
String passwordText = new String(passwordField.getPassword());
if (passwordText.equals("Hasło")) {
passwordField.setEchoChar('\u2022');
passwordField.setText("");
}
}
}
@Override
public void focusLost(FocusEvent e) {
if (e.getSource() == firstNameField) {
if (firstNameField.getText().isEmpty()) {
firstNameField.setText("Imię");
}
} else if (e.getSource() == lastNameField) {
if (lastNameField.getText().isEmpty()) {
lastNameField.setText("Nazwisko");
}
} else if (e.getSource() == addressField) {
if (addressField.getText().isEmpty()) {
addressField.setText("Adres zamieszkania");
}
} else if (e.getSource() == phoneField) {
if (phoneField.getText().isEmpty()) {
phoneField.setText("Numer telefonu");
}
} else if (e.getSource() == mailField) {
if (mailField.getText().isEmpty()) {
mailField.setText("Adres e-mail");
}
} else if (e.getSource() == cardNumberField) {
if (cardNumberField.getText().isEmpty()) {
cardNumberField.setText("Numer karty bibliotecznej");
}
} else if (e.getSource() == usernameField) {
if (usernameField.getText().isEmpty()) {
usernameField.setText("Login");
}
} else if (e.getSource() == passwordField) {
String passwordText = new String(passwordField.getPassword());
if (passwordText.isEmpty()) {
passwordField.setEchoChar((char) 0);
passwordField.setText("Hasło");
}
}
}
}
| t |
4607_0 | jurek1029/Yolo_fighter0 | 1,049 | src/com/example/yolo_fighter/YoloPlayerInfo.java | package com.example.yolo_fighter;
//@TODO używanie getterów i setterów okazuje się być ~2x wolniejsze niż bezpośrednie odwołania --> http://blog.leocad.io/why-you-shouldnt-use-getters-and-setters-on-android/
public class YoloPlayerInfo {
private int ID;
private String name;
private int race;
private int level;
private int XP;
private int coins;
private int units;
private int ST1;
private int ST2;
private int ST3;
private int ST4;
private String skill1;
private String skill2;
private String weapon;
private int SK1EQ;
private int SK2EQ;
private int SK3EQ;
private int WEQ;
public int getXP() {
return XP;
}
public void setXP(int xP) {
XP = xP;
}
public int getCoins() {
return coins;
}
public void setCoins(int coins) {
this.coins = coins;
}
public int getST1() {
return ST1;
}
public void setST1(int sT1) {
ST1 = sT1;
}
public int getST2() {
return ST2;
}
public void setST2(int sT2) {
ST2 = sT2;
}
public int getST3() {
return ST3;
}
public void setST3(int sT3) {
ST3 = sT3;
}
public int getST4() {
return ST4;
}
public void setST4(int sT4) {
ST4 = sT4;
}
public String getSkill1() {
return skill1;
}
public void setSkill1(String skill1) {
this.skill1 = skill1;
}
public String getSkill2() {
return skill2;
}
public void setSkill2(String skill2) {
this.skill2 = skill2;
}
public String getWeapon() {
return weapon;
}
public void setWeapon(String weapon) {
this.weapon = weapon;
}
public int getSK1EQ() {
return SK1EQ;
}
public void setSK1EQ(int sK1EQ) {
SK1EQ = sK1EQ;
}
public int getSK2EQ() {
return SK2EQ;
}
public void setSK2EQ(int sK2EQ) {
SK2EQ = sK2EQ;
}
public int getSK3EQ() {
return SK3EQ;
}
public void setSK3EQ(int sK3EQ) {
SK3EQ = sK3EQ;
}
public int getWEQ() {
return WEQ;
}
public void setWEQ(int wEQ) {
WEQ = wEQ;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRace() {
return race;
}
public void setRace(int race) {
this.race = race;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getUnits() {
return units;
}
public void setUnits(int units) {
this.units = units;
}
}
| //@TODO używanie getterów i setterów okazuje się być ~2x wolniejsze niż bezpośrednie odwołania --> http://blog.leocad.io/why-you-shouldnt-use-getters-and-setters-on-android/ | package com.example.yolo_fighter;
//@TODO używanie <SUF>
public class YoloPlayerInfo {
private int ID;
private String name;
private int race;
private int level;
private int XP;
private int coins;
private int units;
private int ST1;
private int ST2;
private int ST3;
private int ST4;
private String skill1;
private String skill2;
private String weapon;
private int SK1EQ;
private int SK2EQ;
private int SK3EQ;
private int WEQ;
public int getXP() {
return XP;
}
public void setXP(int xP) {
XP = xP;
}
public int getCoins() {
return coins;
}
public void setCoins(int coins) {
this.coins = coins;
}
public int getST1() {
return ST1;
}
public void setST1(int sT1) {
ST1 = sT1;
}
public int getST2() {
return ST2;
}
public void setST2(int sT2) {
ST2 = sT2;
}
public int getST3() {
return ST3;
}
public void setST3(int sT3) {
ST3 = sT3;
}
public int getST4() {
return ST4;
}
public void setST4(int sT4) {
ST4 = sT4;
}
public String getSkill1() {
return skill1;
}
public void setSkill1(String skill1) {
this.skill1 = skill1;
}
public String getSkill2() {
return skill2;
}
public void setSkill2(String skill2) {
this.skill2 = skill2;
}
public String getWeapon() {
return weapon;
}
public void setWeapon(String weapon) {
this.weapon = weapon;
}
public int getSK1EQ() {
return SK1EQ;
}
public void setSK1EQ(int sK1EQ) {
SK1EQ = sK1EQ;
}
public int getSK2EQ() {
return SK2EQ;
}
public void setSK2EQ(int sK2EQ) {
SK2EQ = sK2EQ;
}
public int getSK3EQ() {
return SK3EQ;
}
public void setSK3EQ(int sK3EQ) {
SK3EQ = sK3EQ;
}
public int getWEQ() {
return WEQ;
}
public void setWEQ(int wEQ) {
WEQ = wEQ;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRace() {
return race;
}
public void setRace(int race) {
this.race = race;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getUnits() {
return units;
}
public void setUnits(int units) {
this.units = units;
}
}
| f |
3127_2 | jzywiecki/io-project | 833 | server/src/main/java/com/example/server/services/UserService.java | package com.example.server.services;
import com.example.server.auth.JwtUtil;
import com.example.server.dto.RoomDto;
import com.example.server.exceptions.UserNotFoundException;
import com.example.server.model.Role;
import com.example.server.model.Room;
import com.example.server.model.User;
import com.example.server.repositories.RoomRepository;
import com.example.server.repositories.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class UserService {
/**
* User repository.
*/
private final UserRepository userRepository;
private final RoomRepository roomRepository;
private final MailService mailService;
/**
* Assign users to the room.
* @param emails the user emails list.
*/
public void setUsersInTheRoom(Long roomId, List<String> emails) {
Room room = roomRepository.getReferenceById(roomId);
String msgContent;
for (String email : emails) {
Optional<User> user = userRepository.findByEmail(email);
if (user.isPresent()) {
room.getJoinedUsers().add(user.get());
msgContent = "Zaloguj się: ";
} else {
User newUser = User.builder()
.email(email)
.active(false)
.role(Role.STUDENT)
.build();
userRepository.save(newUser);
room.getJoinedUsers().add(newUser);
msgContent = "Zarejestruj się: ";
}
String msg = "Dodano Cię do pokoju " + room.getName() + "(" + room.getDescription() + ")" + ".\n"
+ msgContent + "http://54.166.152.243/login, aby zagłosować.\n"
+ "Masz czas do: " + room.getDeadlineDate().toString() + " " + room.getDeadlineTime().toString();
mailService.send(email, "Dodano Cię do pokoju " + room.getName(), msg);
}
roomRepository.save(room);
}
/**
* Get all rooms where user is a member.
* @param userId the user id.
* @return the rooms of a user.
*/
public List<RoomDto> getUserRooms(final Long userId) {
User user = userRepository
.findById(userId)
.orElseThrow(
() -> new UserNotFoundException("User with id: "
+ userId
+ " not found.")
);
List<Room> userRooms = userRepository.getJoinedRooms(userId);
return userRooms.stream()
.map((room) -> new RoomDto(
room.getId(),
room.getName(),
room.getDescription(),
room.getDeadlineDate(),
room.getDeadlineTime()
))
.collect(Collectors.toList());
}
}
| //54.166.152.243/login, aby zagłosować.\n" | package com.example.server.services;
import com.example.server.auth.JwtUtil;
import com.example.server.dto.RoomDto;
import com.example.server.exceptions.UserNotFoundException;
import com.example.server.model.Role;
import com.example.server.model.Room;
import com.example.server.model.User;
import com.example.server.repositories.RoomRepository;
import com.example.server.repositories.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@AllArgsConstructor
public class UserService {
/**
* User repository.
*/
private final UserRepository userRepository;
private final RoomRepository roomRepository;
private final MailService mailService;
/**
* Assign users to the room.
* @param emails the user emails list.
*/
public void setUsersInTheRoom(Long roomId, List<String> emails) {
Room room = roomRepository.getReferenceById(roomId);
String msgContent;
for (String email : emails) {
Optional<User> user = userRepository.findByEmail(email);
if (user.isPresent()) {
room.getJoinedUsers().add(user.get());
msgContent = "Zaloguj się: ";
} else {
User newUser = User.builder()
.email(email)
.active(false)
.role(Role.STUDENT)
.build();
userRepository.save(newUser);
room.getJoinedUsers().add(newUser);
msgContent = "Zarejestruj się: ";
}
String msg = "Dodano Cię do pokoju " + room.getName() + "(" + room.getDescription() + ")" + ".\n"
+ msgContent + "http://54.166.152.243/login, aby <SUF>
+ "Masz czas do: " + room.getDeadlineDate().toString() + " " + room.getDeadlineTime().toString();
mailService.send(email, "Dodano Cię do pokoju " + room.getName(), msg);
}
roomRepository.save(room);
}
/**
* Get all rooms where user is a member.
* @param userId the user id.
* @return the rooms of a user.
*/
public List<RoomDto> getUserRooms(final Long userId) {
User user = userRepository
.findById(userId)
.orElseThrow(
() -> new UserNotFoundException("User with id: "
+ userId
+ " not found.")
);
List<Room> userRooms = userRepository.getJoinedRooms(userId);
return userRooms.stream()
.map((room) -> new RoomDto(
room.getId(),
room.getName(),
room.getDescription(),
room.getDeadlineDate(),
room.getDeadlineTime()
))
.collect(Collectors.toList());
}
}
| f |
3487_2 | kSuroweczka/Zombie | 307 | src/com/company/Sprite.java | package com.company;
import javax.swing.*;
import java.awt.*;
public interface Sprite {
/**
* Rysuje postać
* @param g
* @param parent
*/
void draw(Graphics g, JPanel parent);
/**
* Przechodzi do następnej klatki
*/
void next();
/**
* Czy już zniknął z ekranu
* @return
*/
default boolean isVisible(){return true;}
/**
* Czy punkt o współrzędnych _x, _y leży w obszarze postaci -
* czyli czy trafiliśmy ją strzelając w punkcie o tych współrzednych
* @param _x
* @param _y
* @return
*/
default boolean isHit(int _x,int _y){return false;}
/** Czy jest bliżej widza niż other, czyli w naszym przypadku czy jest większy,
* czyli ma wiekszą skalę...
*
* @param other
* @return
*/
default boolean isCloser(Sprite other){return false;}
}
| /**
* Czy już zniknął z ekranu
* @return
*/ | package com.company;
import javax.swing.*;
import java.awt.*;
public interface Sprite {
/**
* Rysuje postać
* @param g
* @param parent
*/
void draw(Graphics g, JPanel parent);
/**
* Przechodzi do następnej klatki
*/
void next();
/**
* Czy już zniknął <SUF>*/
default boolean isVisible(){return true;}
/**
* Czy punkt o współrzędnych _x, _y leży w obszarze postaci -
* czyli czy trafiliśmy ją strzelając w punkcie o tych współrzednych
* @param _x
* @param _y
* @return
*/
default boolean isHit(int _x,int _y){return false;}
/** Czy jest bliżej widza niż other, czyli w naszym przypadku czy jest większy,
* czyli ma wiekszą skalę...
*
* @param other
* @return
*/
default boolean isCloser(Sprite other){return false;}
}
| t |
6156_3 | kamil5555579/tinder-java | 4,697 | src/loginSystem/DataPanel.java | package loginSystem;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.SwingWorker;
import javax.swing.border.LineBorder;
import com.mysql.jdbc.Connection;
import mainApp.CardFrame2;
import utilities.PTextField;
import utilities.SqlConnection;
import javax.swing.SwingConstants;
import java.awt.ComponentOrientation;
import javax.swing.border.EtchedBorder;
class DataPanel extends JPanel
{
private JButton btnRegister;
private JComboBox comboBox;
private PTextField txtAge;
private JTextPane txtDescription;
private PTextField txtName;
private PTextField txtSurname;
private JButton imgButton;
private JLabel imgLabel;
private JComboBox comboBox_2;
private int id;
SqlConnection sqlConn = new SqlConnection();
private JFileChooser fileChooser = new JFileChooser();
private File f=null;
private InputStream is=null;
Connection conn;
Image img;
public DataPanel(JPanel panel, JFrame frame) {
//ustawienia panelu
setBounds(100, 100, 700, 600);
setBackground(new Color(255, 105, 180));
setBorder(new LineBorder(new Color(255, 20, 147), 3, true));
setLayout(null);
//opis
txtDescription = new JTextPane();
txtDescription.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
txtDescription.setCaretColor(new Color(0, 0, 0));
txtDescription.setBounds(135, 240, 215, 210);
txtDescription.setBackground(new Color(240, 240, 240));
add(txtDescription);
txtDescription.setFont(new Font("Dialog", Font.ITALIC, 12));
txtDescription.setBorder(null);
//wybór płci
String[] gender = {"Płeć", "Mężczyzna", "Kobieta",
"Inna" };
comboBox = new JComboBox(gender);
comboBox.setBackground(new Color(240, 240, 240));
comboBox.setBounds(135, 137, 215, 30);
add(comboBox);
comboBox.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
//wybór wydziału
String[] faculty = {"Wydział", "Architektury","Administracji", "Budownictwa", "Chemii","EITI","Elektryczny", "Fizyki", "IBHIŚ","Matematyki","Mechatroniki", "MEL","SiMR","Transportu","Zarządzania"
,"Inny" };
comboBox_2 = new JComboBox(faculty);
comboBox_2.setBackground(new Color(255, 255, 255));
comboBox_2.setBorder(null);
comboBox_2.setBounds(135, 185, 215, 30);
comboBox_2.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
comboBox_2.setBackground(new Color(240, 240, 240));
add(comboBox_2);
//wiek
txtAge = new PTextField("Wiek");
txtAge.setBorder(null);
txtAge.setBounds(362, 137, 215, 30);
add(txtAge);
txtAge.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
txtAge.setBackground(new Color(240, 240, 240));
//txtAge.setBackground(new Color(255, 240, 245));
txtAge.setColumns(10);
//imię
txtName = new PTextField("Imię");
txtName.setBorder(null);
txtName.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
txtName.setColumns(10);
txtName.setBackground(new Color(240, 240, 240));
txtName.setBounds(135, 94, 215, 30);
add(txtName);
//nazwisko
txtSurname = new PTextField("Nazwisko");
txtSurname.setBorder(null);
txtSurname.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
txtSurname.setColumns(10);
txtSurname.setBackground(new Color(240, 240, 240));
txtSurname.setBounds(362, 95, 215, 30);
add(txtSurname);
//zdjecie
imgButton = new JButton("Wybierz zdjęcie");
imgButton.setHorizontalAlignment(SwingConstants.LEFT);
imgButton.setBackground(new Color(255, 255, 255));
imgButton.setBorder(null);
imgButton.setBackground(new Color(240, 240, 240));
imgButton.setBounds(360, 185, 215, 30);
add(imgButton);
imgLabel = new JLabel("");
imgLabel.setBounds(360,240,215,215);
add(imgLabel);
imgButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
int retval = fileChooser.showOpenDialog(null);
if (retval == JFileChooser.APPROVE_OPTION) {
f = fileChooser.getSelectedFile();
String path = f.getAbsolutePath();
ImageIcon icon = new ImageIcon(path);
img = new ImageIcon(icon.getImage().getScaledInstance(400, 400, Image.SCALE_SMOOTH)).getImage();
Image imgTemp = icon.getImage().getScaledInstance(215, 215, Image.SCALE_SMOOTH);
imgLabel.setIcon(new ImageIcon(imgTemp));
}
}});
//label Fill your data
JLabel lblTinder = new JLabel("Stwórz swój profil!");
lblTinder.setForeground(Color.WHITE);
lblTinder.setFont(new Font("LM Sans 10", Font.BOLD | Font.ITALIC, 42));
lblTinder.setBounds(155, 12, 410, 65);
add(lblTinder);
//zapisanie i przejscie do aplikacji
btnRegister = new JButton("Zapisz");
btnRegister.setBackground(new Color(255, 240, 245));
btnRegister.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 18));
btnRegister.setBounds(120, 490, 475, 40);
btnRegister.setBorder(null);
add(btnRegister);
btnRegister.addActionListener( new ActionListener()
{
String firstname;
String lastname;
String university;
String gender;
int age;
String description;
@Override
public void actionPerformed(ActionEvent e) {
try {
firstname = txtName.getText();
lastname = txtSurname.getText();
university = (String) comboBox_2.getSelectedItem();
gender = (String) comboBox.getSelectedItem();
age = Integer.parseInt(txtAge.getText());
description = txtDescription.getText();
if(txtName.getText().equals("Imię")||txtSurname.getText().equals("Nazwisko")) {
if (txtName.getText().equals("Imię")) {
JOptionPane.showMessageDialog(
null,"Nie podano imienia. Podaj imię!",
"Błąd uzupełniania danych",
JOptionPane.ERROR_MESSAGE);
}
if (txtSurname.getText().equals("Nazwisko")) {
JOptionPane.showMessageDialog(
null,"Nie podano nazwiska. Podaj nazwisko!",
"Błąd uzupełniania danych",
JOptionPane.ERROR_MESSAGE);
}
}else {
if (f==null) {
JOptionPane.showMessageDialog(
null,"Nie wybrano zdjęcia. Wybierz zdjęcie!",
"Błąd uzupełniania danych",
JOptionPane.ERROR_MESSAGE);
}else {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
BufferedImage bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics().drawImage(img, 0, 0 , null);
ImageIO.write( bufferedImage, "gif", os);
is = new ByteArrayInputStream(os.toByteArray());
os.close();
save(firstname, lastname, university, is, frame, gender, age, description);
System.out.println("Zapisano");
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(
null,"Błąd dostępu do pliku.",
"Błąd dostępu do danych",
JOptionPane.ERROR_MESSAGE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} catch (NumberFormatException e2) {
JOptionPane.showMessageDialog(
null,"Nie możesz w ten sposób ustawić swoich danych!",
"Błąd zapisu danych",
JOptionPane.ERROR_MESSAGE);
}
}});
add(btnRegister);
JLabel lblOpowiedzOSobie = new JLabel("Opowiedz o sobie");
lblOpowiedzOSobie.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
lblOpowiedzOSobie.setBounds(165, 220, 180, 25);
add(lblOpowiedzOSobie);
}
//przekazanie id użytkownika
void setId(int id)
{
this.id = id;
}
//zapisanie danych i przejście do aplikacji
public void save(String firstname, String lastname, String university, InputStream is, JFrame frame, String gender, int age, String description)
{
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){
@Override
protected Void doInBackground() throws Exception {
conn = sqlConn.connect();
PreparedStatement prep;
prep = conn.prepareStatement("INSERT INTO userdata (user_id, firstname, lastname, university, gender, age, image, description) VALUES (?,?,?,?,?,?,?,?)");
prep.setLong(1, id);
prep.setString(2, firstname);
prep.setString(3, lastname);
prep.setString(4, university);
prep.setString(5, gender);
prep.setInt(6, age);
prep.setBinaryStream(7,is, (int) f.length());
prep.setString(8, description);
prep.executeUpdate();
return null;
}
@Override
protected void done() {
try {
CardFrame2 newFrame = new CardFrame2(id);
newFrame.setVisible(true);
if (conn!= null)
conn.close();
frame.dispose();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(
null,"Błąd zapisu danych",
"Błąd zapisu danych",
JOptionPane.ERROR_MESSAGE);
}
}
};
worker.execute();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
Rectangle2D r2=new Rectangle2D.Double(0,0,getWidth(),getHeight());
Color c0=new Color(255,0,128), c1= new Color(255,128,0);
GradientPaint gp = new GradientPaint(150, 200, c1, 450, 200, c0, false);
g2.setPaint(gp);
g2.fill(r2);
g2.setPaint(new Color(240, 240, 240)); //szary
g2.fill(new RoundRectangle2D.Double(115, 80, 485, 400, 40, 40));
g2.setPaint(new Color(255, 240, 245)); // jasnorozowy
g2.fill(new RoundRectangle2D.Double(110, 485, 495, 50, 40, 40));
}
}
| //przekazanie id użytkownika | package loginSystem;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.SwingWorker;
import javax.swing.border.LineBorder;
import com.mysql.jdbc.Connection;
import mainApp.CardFrame2;
import utilities.PTextField;
import utilities.SqlConnection;
import javax.swing.SwingConstants;
import java.awt.ComponentOrientation;
import javax.swing.border.EtchedBorder;
class DataPanel extends JPanel
{
private JButton btnRegister;
private JComboBox comboBox;
private PTextField txtAge;
private JTextPane txtDescription;
private PTextField txtName;
private PTextField txtSurname;
private JButton imgButton;
private JLabel imgLabel;
private JComboBox comboBox_2;
private int id;
SqlConnection sqlConn = new SqlConnection();
private JFileChooser fileChooser = new JFileChooser();
private File f=null;
private InputStream is=null;
Connection conn;
Image img;
public DataPanel(JPanel panel, JFrame frame) {
//ustawienia panelu
setBounds(100, 100, 700, 600);
setBackground(new Color(255, 105, 180));
setBorder(new LineBorder(new Color(255, 20, 147), 3, true));
setLayout(null);
//opis
txtDescription = new JTextPane();
txtDescription.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
txtDescription.setCaretColor(new Color(0, 0, 0));
txtDescription.setBounds(135, 240, 215, 210);
txtDescription.setBackground(new Color(240, 240, 240));
add(txtDescription);
txtDescription.setFont(new Font("Dialog", Font.ITALIC, 12));
txtDescription.setBorder(null);
//wybór płci
String[] gender = {"Płeć", "Mężczyzna", "Kobieta",
"Inna" };
comboBox = new JComboBox(gender);
comboBox.setBackground(new Color(240, 240, 240));
comboBox.setBounds(135, 137, 215, 30);
add(comboBox);
comboBox.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
//wybór wydziału
String[] faculty = {"Wydział", "Architektury","Administracji", "Budownictwa", "Chemii","EITI","Elektryczny", "Fizyki", "IBHIŚ","Matematyki","Mechatroniki", "MEL","SiMR","Transportu","Zarządzania"
,"Inny" };
comboBox_2 = new JComboBox(faculty);
comboBox_2.setBackground(new Color(255, 255, 255));
comboBox_2.setBorder(null);
comboBox_2.setBounds(135, 185, 215, 30);
comboBox_2.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
comboBox_2.setBackground(new Color(240, 240, 240));
add(comboBox_2);
//wiek
txtAge = new PTextField("Wiek");
txtAge.setBorder(null);
txtAge.setBounds(362, 137, 215, 30);
add(txtAge);
txtAge.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
txtAge.setBackground(new Color(240, 240, 240));
//txtAge.setBackground(new Color(255, 240, 245));
txtAge.setColumns(10);
//imię
txtName = new PTextField("Imię");
txtName.setBorder(null);
txtName.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
txtName.setColumns(10);
txtName.setBackground(new Color(240, 240, 240));
txtName.setBounds(135, 94, 215, 30);
add(txtName);
//nazwisko
txtSurname = new PTextField("Nazwisko");
txtSurname.setBorder(null);
txtSurname.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
txtSurname.setColumns(10);
txtSurname.setBackground(new Color(240, 240, 240));
txtSurname.setBounds(362, 95, 215, 30);
add(txtSurname);
//zdjecie
imgButton = new JButton("Wybierz zdjęcie");
imgButton.setHorizontalAlignment(SwingConstants.LEFT);
imgButton.setBackground(new Color(255, 255, 255));
imgButton.setBorder(null);
imgButton.setBackground(new Color(240, 240, 240));
imgButton.setBounds(360, 185, 215, 30);
add(imgButton);
imgLabel = new JLabel("");
imgLabel.setBounds(360,240,215,215);
add(imgLabel);
imgButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
int retval = fileChooser.showOpenDialog(null);
if (retval == JFileChooser.APPROVE_OPTION) {
f = fileChooser.getSelectedFile();
String path = f.getAbsolutePath();
ImageIcon icon = new ImageIcon(path);
img = new ImageIcon(icon.getImage().getScaledInstance(400, 400, Image.SCALE_SMOOTH)).getImage();
Image imgTemp = icon.getImage().getScaledInstance(215, 215, Image.SCALE_SMOOTH);
imgLabel.setIcon(new ImageIcon(imgTemp));
}
}});
//label Fill your data
JLabel lblTinder = new JLabel("Stwórz swój profil!");
lblTinder.setForeground(Color.WHITE);
lblTinder.setFont(new Font("LM Sans 10", Font.BOLD | Font.ITALIC, 42));
lblTinder.setBounds(155, 12, 410, 65);
add(lblTinder);
//zapisanie i przejscie do aplikacji
btnRegister = new JButton("Zapisz");
btnRegister.setBackground(new Color(255, 240, 245));
btnRegister.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 18));
btnRegister.setBounds(120, 490, 475, 40);
btnRegister.setBorder(null);
add(btnRegister);
btnRegister.addActionListener( new ActionListener()
{
String firstname;
String lastname;
String university;
String gender;
int age;
String description;
@Override
public void actionPerformed(ActionEvent e) {
try {
firstname = txtName.getText();
lastname = txtSurname.getText();
university = (String) comboBox_2.getSelectedItem();
gender = (String) comboBox.getSelectedItem();
age = Integer.parseInt(txtAge.getText());
description = txtDescription.getText();
if(txtName.getText().equals("Imię")||txtSurname.getText().equals("Nazwisko")) {
if (txtName.getText().equals("Imię")) {
JOptionPane.showMessageDialog(
null,"Nie podano imienia. Podaj imię!",
"Błąd uzupełniania danych",
JOptionPane.ERROR_MESSAGE);
}
if (txtSurname.getText().equals("Nazwisko")) {
JOptionPane.showMessageDialog(
null,"Nie podano nazwiska. Podaj nazwisko!",
"Błąd uzupełniania danych",
JOptionPane.ERROR_MESSAGE);
}
}else {
if (f==null) {
JOptionPane.showMessageDialog(
null,"Nie wybrano zdjęcia. Wybierz zdjęcie!",
"Błąd uzupełniania danych",
JOptionPane.ERROR_MESSAGE);
}else {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
BufferedImage bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
bufferedImage.getGraphics().drawImage(img, 0, 0 , null);
ImageIO.write( bufferedImage, "gif", os);
is = new ByteArrayInputStream(os.toByteArray());
os.close();
save(firstname, lastname, university, is, frame, gender, age, description);
System.out.println("Zapisano");
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(
null,"Błąd dostępu do pliku.",
"Błąd dostępu do danych",
JOptionPane.ERROR_MESSAGE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} catch (NumberFormatException e2) {
JOptionPane.showMessageDialog(
null,"Nie możesz w ten sposób ustawić swoich danych!",
"Błąd zapisu danych",
JOptionPane.ERROR_MESSAGE);
}
}});
add(btnRegister);
JLabel lblOpowiedzOSobie = new JLabel("Opowiedz o sobie");
lblOpowiedzOSobie.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 14));
lblOpowiedzOSobie.setBounds(165, 220, 180, 25);
add(lblOpowiedzOSobie);
}
//przekazanie id <SUF>
void setId(int id)
{
this.id = id;
}
//zapisanie danych i przejście do aplikacji
public void save(String firstname, String lastname, String university, InputStream is, JFrame frame, String gender, int age, String description)
{
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){
@Override
protected Void doInBackground() throws Exception {
conn = sqlConn.connect();
PreparedStatement prep;
prep = conn.prepareStatement("INSERT INTO userdata (user_id, firstname, lastname, university, gender, age, image, description) VALUES (?,?,?,?,?,?,?,?)");
prep.setLong(1, id);
prep.setString(2, firstname);
prep.setString(3, lastname);
prep.setString(4, university);
prep.setString(5, gender);
prep.setInt(6, age);
prep.setBinaryStream(7,is, (int) f.length());
prep.setString(8, description);
prep.executeUpdate();
return null;
}
@Override
protected void done() {
try {
CardFrame2 newFrame = new CardFrame2(id);
newFrame.setVisible(true);
if (conn!= null)
conn.close();
frame.dispose();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(
null,"Błąd zapisu danych",
"Błąd zapisu danych",
JOptionPane.ERROR_MESSAGE);
}
}
};
worker.execute();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
Rectangle2D r2=new Rectangle2D.Double(0,0,getWidth(),getHeight());
Color c0=new Color(255,0,128), c1= new Color(255,128,0);
GradientPaint gp = new GradientPaint(150, 200, c1, 450, 200, c0, false);
g2.setPaint(gp);
g2.fill(r2);
g2.setPaint(new Color(240, 240, 240)); //szary
g2.fill(new RoundRectangle2D.Double(115, 80, 485, 400, 40, 40));
g2.setPaint(new Color(255, 240, 245)); // jasnorozowy
g2.fill(new RoundRectangle2D.Double(110, 485, 495, 50, 40, 40));
}
}
| t |
7187_1 | kamilbrzezinski/java-od-podstaw | 505 | modul-05/konkatenacja-stringow/src/main/java/org/example/Main.java | package org.example;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
// String name = "Kamil";
// String lastName = "Brzeziński";
// int age = 35;
//
// String text = "Mam na imię ";
// text = text.concat(name);
// text = text.concat(". Mam ");
// text = text.concat(String.valueOf(age));
// text = text.concat(" lat.");
//
// System.out.println(text);
// System.out.println("Mam na imię " + name + " a na nazwisko "
// + lastName + ". Mam " + age + " lat.");
// System.out.println("Mam " + (33 + 2) + " lat.");
// System.out.println(33 + 2 + " to mój wiek.");
List<String> names = new ArrayList<>();
names.add("Kamil");
names.add("Mariusz");
names.add("Dominik");
// String joinedNames = String.join(";", names);
// System.out.println(joinedNames);
StringJoiner joiner = new StringJoiner("-");
joiner.add("Kamil");
joiner.add("Mariusz");
joiner.add("Rafał");
System.out.println(joiner);
// StringBuilder builder = new StringBuilder();
// StringBuffer buffer = new StringBuffer();
// thread - safe
// for (String name : names) {
// builder.append(name.toUpperCase());
// builder.append(", ");
// }
// K A M I L -> 5
// 0 1 2 3 4
// builder.delete(builder.length()-2, builder.length()-1);
//
// System.out.println(builder);
}
} | // String lastName = "Brzeziński"; | package org.example;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
// String name = "Kamil";
// String lastName <SUF>
// int age = 35;
//
// String text = "Mam na imię ";
// text = text.concat(name);
// text = text.concat(". Mam ");
// text = text.concat(String.valueOf(age));
// text = text.concat(" lat.");
//
// System.out.println(text);
// System.out.println("Mam na imię " + name + " a na nazwisko "
// + lastName + ". Mam " + age + " lat.");
// System.out.println("Mam " + (33 + 2) + " lat.");
// System.out.println(33 + 2 + " to mój wiek.");
List<String> names = new ArrayList<>();
names.add("Kamil");
names.add("Mariusz");
names.add("Dominik");
// String joinedNames = String.join(";", names);
// System.out.println(joinedNames);
StringJoiner joiner = new StringJoiner("-");
joiner.add("Kamil");
joiner.add("Mariusz");
joiner.add("Rafał");
System.out.println(joiner);
// StringBuilder builder = new StringBuilder();
// StringBuffer buffer = new StringBuffer();
// thread - safe
// for (String name : names) {
// builder.append(name.toUpperCase());
// builder.append(", ");
// }
// K A M I L -> 5
// 0 1 2 3 4
// builder.delete(builder.length()-2, builder.length()-1);
//
// System.out.println(builder);
}
} | f |
6827_2 | karaa-m/bitbay | 663 | src/main/java/pl/kara/bitbay/api_caller/engine/impl/BitBayRequestExecutorImpl.java | package pl.kara.bitbay.api_caller.engine.impl;
import com.google.common.collect.ImmutableMap;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import pl.kara.bitbay.api_caller.BitBayRequestExecutor;
import pl.kara.bitbay.api_caller.engine.url.BitBayPostUrlCreator;
import pl.kara.bitbay.api_caller.request.BitBayHttpRequestFactory;
import pl.kara.bitbay.authentication.AuthenticationKeys;
import pl.kara.bitbay.reflection.FieldStringValueExtractor;
import pl.kara.bitbay.api_caller.engine.body_creator.PostBodyCreator;
import pl.kara.bitbay.authentication.Authenticator;
/**
* Klasa ktora mapuje przesyłane obiekty i docelowo wykonuje request
*/
@Slf4j
@AllArgsConstructor
public final class BitBayRequestExecutorImpl implements BitBayRequestExecutor {
private final RestTemplate restTemplate;
private final Authenticator authenticator;
private final PostBodyCreator postBodyCreator;
@Override
public <T> ResponseEntity<T> post(final Object postObject, final AuthenticationKeys authenticationKeys, final Class<T> returnType) {
final ImmutableMap<String, String> fieldNamesWithValues = FieldStringValueExtractor.fieldNamesWithValues(postObject);
final String bitBayBody = postBodyCreator.createBitBayBody(fieldNamesWithValues);
final String bitBayPostURL = BitBayPostUrlCreator.fromPostBody(bitBayBody);
final String signedAPIHash = authenticator.signPostBody(bitBayBody, authenticationKeys);
final HttpEntity<MultiValueMap<String, String>> request = BitBayHttpRequestFactory.createRequest(signedAPIHash, authenticationKeys);
final ResponseEntity<T> responseFromBitBay = restTemplate.postForEntity(bitBayPostURL, request, returnType);
//TODO BUG dlaczego to nie dziala ?
//TODO logowac debug response bo lepiej sie pisze
// log.info("Response BODY from BitBay API:",responseFromBitBay.getBody());
// log.info("Response Headers from BitBay API:",responseFromBitBay.getHeaders());
return responseFromBitBay;
}
}
| //TODO logowac debug response bo lepiej sie pisze | package pl.kara.bitbay.api_caller.engine.impl;
import com.google.common.collect.ImmutableMap;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import pl.kara.bitbay.api_caller.BitBayRequestExecutor;
import pl.kara.bitbay.api_caller.engine.url.BitBayPostUrlCreator;
import pl.kara.bitbay.api_caller.request.BitBayHttpRequestFactory;
import pl.kara.bitbay.authentication.AuthenticationKeys;
import pl.kara.bitbay.reflection.FieldStringValueExtractor;
import pl.kara.bitbay.api_caller.engine.body_creator.PostBodyCreator;
import pl.kara.bitbay.authentication.Authenticator;
/**
* Klasa ktora mapuje przesyłane obiekty i docelowo wykonuje request
*/
@Slf4j
@AllArgsConstructor
public final class BitBayRequestExecutorImpl implements BitBayRequestExecutor {
private final RestTemplate restTemplate;
private final Authenticator authenticator;
private final PostBodyCreator postBodyCreator;
@Override
public <T> ResponseEntity<T> post(final Object postObject, final AuthenticationKeys authenticationKeys, final Class<T> returnType) {
final ImmutableMap<String, String> fieldNamesWithValues = FieldStringValueExtractor.fieldNamesWithValues(postObject);
final String bitBayBody = postBodyCreator.createBitBayBody(fieldNamesWithValues);
final String bitBayPostURL = BitBayPostUrlCreator.fromPostBody(bitBayBody);
final String signedAPIHash = authenticator.signPostBody(bitBayBody, authenticationKeys);
final HttpEntity<MultiValueMap<String, String>> request = BitBayHttpRequestFactory.createRequest(signedAPIHash, authenticationKeys);
final ResponseEntity<T> responseFromBitBay = restTemplate.postForEntity(bitBayPostURL, request, returnType);
//TODO BUG dlaczego to nie dziala ?
//TODO logowac <SUF>
// log.info("Response BODY from BitBay API:",responseFromBitBay.getBody());
// log.info("Response Headers from BitBay API:",responseFromBitBay.getHeaders());
return responseFromBitBay;
}
}
| f |
5660_1 | kartytko/CrowdPressure | 611 | CrowdPressure/src/simulation/Position.java | package simulation;
import static java.lang.Math.sqrt;
// Klasa opisująca pozycję (punkt) na płaszczyźnie.
// Używana różnież do opisu wektorów (traktowanie wektorów jako wektory wodzące - wówczas punkt klasy Position pokazuje,
// gdzie znajduje się grot strzałki wektora.
public class Position {
private double x_;
private double y_;
public Position(double x, double y){
x_ = x;
y_ = y;
}
public double calculateDistance (Position other){
double differenceX = this.getX_()-other.getX_();
double differenceY = this.getY_()-other.getY_();
return sqrt(differenceX*differenceX + differenceY*differenceY);
}
public double calculateLenght(){
return sqrt((x_*x_+y_*y_));
}
public Position normalize (Position other){
double distance = calculateDistance(other);
double x = this.x_ - other.getX_();
double y = this.y_ - other.getY_();
if(distance!=0){
x = x/distance;
y = y/distance;
}
return new Position(x, y);
}
public Position multiply (Position p){
double x = this.x_*p.getX_();
double y = this.y_*p.getY_();
return new Position(x, y);
}
public Position multiply (double number){
double x = this.getX_()*number;
double y = this.getY_()*number;
return new Position(x, y);
}
public Position add(Position p){
return new Position(this.x_+p.getX_(), this.y_+p.getY_());
}
public Position subtract(Position p){
return new Position(this.x_-p.getX_(), this.y_-p.getY_());
}
public double getX_() {
return x_;
}
public void setX_(double x_) {
this.x_ = x_;
}
public double getY_() {
return y_;
}
public void setY_(double y_) {
this.y_ = y_;
}
}
| // Używana różnież do opisu wektorów (traktowanie wektorów jako wektory wodzące - wówczas punkt klasy Position pokazuje, | package simulation;
import static java.lang.Math.sqrt;
// Klasa opisująca pozycję (punkt) na płaszczyźnie.
// Używana różnież <SUF>
// gdzie znajduje się grot strzałki wektora.
public class Position {
private double x_;
private double y_;
public Position(double x, double y){
x_ = x;
y_ = y;
}
public double calculateDistance (Position other){
double differenceX = this.getX_()-other.getX_();
double differenceY = this.getY_()-other.getY_();
return sqrt(differenceX*differenceX + differenceY*differenceY);
}
public double calculateLenght(){
return sqrt((x_*x_+y_*y_));
}
public Position normalize (Position other){
double distance = calculateDistance(other);
double x = this.x_ - other.getX_();
double y = this.y_ - other.getY_();
if(distance!=0){
x = x/distance;
y = y/distance;
}
return new Position(x, y);
}
public Position multiply (Position p){
double x = this.x_*p.getX_();
double y = this.y_*p.getY_();
return new Position(x, y);
}
public Position multiply (double number){
double x = this.getX_()*number;
double y = this.getY_()*number;
return new Position(x, y);
}
public Position add(Position p){
return new Position(this.x_+p.getX_(), this.y_+p.getY_());
}
public Position subtract(Position p){
return new Position(this.x_-p.getX_(), this.y_-p.getY_());
}
public double getX_() {
return x_;
}
public void setX_(double x_) {
this.x_ = x_;
}
public double getY_() {
return y_;
}
public void setY_(double y_) {
this.y_ = y_;
}
}
| t |
7899_7 | kdn251/interviews | 289 | leetcode/binary-search/GuessNumberHigherOrLower.java | // We are playing the Guess Game. The game is as follows:
// I pick a number from 1 to n. You have to guess which number I picked.
// Every time you guess wrong, I'll tell you whether the number is higher or lower.
// You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
// -1 : My number is lower
// 1 : My number is higher
// 0 : Congrats! You got it!
// Example:
// n = 10, I pick 6.
// Return 6.
public class GuessNumberHigherOrLower extends GuessGame {
public int guessNumber(int n) {
int left = 1;
int right = n;
while(left <= right) {
int mid = left + (right - left) / 2;
if(guess(mid) == 0) {
return mid;
} else if(guess(mid) > 0) {
left = mid + 1;
} else {
right = mid;
}
}
return -1;
}
}
| // n = 10, I pick 6. | // We are playing the Guess Game. The game is as follows:
// I pick a number from 1 to n. You have to guess which number I picked.
// Every time you guess wrong, I'll tell you whether the number is higher or lower.
// You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
// -1 : My number is lower
// 1 : My number is higher
// 0 : Congrats! You got it!
// Example:
// n = <SUF>
// Return 6.
public class GuessNumberHigherOrLower extends GuessGame {
public int guessNumber(int n) {
int left = 1;
int right = n;
while(left <= right) {
int mid = left + (right - left) / 2;
if(guess(mid) == 0) {
return mid;
} else if(guess(mid) > 0) {
left = mid + 1;
} else {
right = mid;
}
}
return -1;
}
}
| f |
5923_0 | kgn04/nye_game_java | 3,545 | src/main/java/Data.java | import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Data {
public static ArrayList<Player> players = new ArrayList<>();
public static ArrayList<String> passwords = new ArrayList<>();
public static ArrayList<Integer> indexesOfChosen = new ArrayList<>();
public static ArrayList<Integer> indexesOfImpostors = new ArrayList<>();
public static ArrayList<String> tasks = new ArrayList<>();
public static int crewmates = 0;
public static int impostors = 0;
public static boolean isThrownOut = false;
public static int indexOfDetective = 0;
public static int indexOfDefender = 0;
public static boolean isDetectiveDead = false;
public static boolean isChecked = false;
public static boolean resurectionUsed = false;
public static void generateData() {
createPlayers();
createTasks();
}
private static void createPlayers() {
players.add(new Player("red"));
players.add(new Player("blue"));
players.add(new Player("green"));
players.add(new Player("pink"));
players.add(new Player("orange"));
players.add(new Player("yellow"));
players.add(new Player("black"));
players.add(new Player("white"));
players.add(new Player("purple"));
players.add(new Player("brown"));
players.add(new Player("cyan"));
players.add(new Player("lime"));
players.add(new Player("maroon"));
players.add(new Player("rose"));
players.add(new Player("banana"));
players.add(new Player("gray"));
players.add(new Player("tan"));
players.add(new Player("coral"));
players.add(new Player("fortegreen"));
}
private static void createTasks() {
tasks.add("Wypij szota bez popity.");
tasks.add("Zadzwon do kogos i zaspiewaj sto lat.");
tasks.add("Zrob 5 pompek.");
tasks.add("Wypij cytrynowego szota z poker facem.");
tasks.add("Zjedz lyzeczke majonezu.");
tasks.add("Zanuc jakaś piosenke, ktoś musi ja zgadnać.");
tasks.add("Odwzoruj zdj na insta osoby z twoich relacji.");
tasks.add("Zrob 15 pajacykow.");
tasks.add("Zrob 10 przysiadow.");
tasks.add("Przejdz przez caly pokoj z ksiazka na glowie.");
tasks.add("Niech kazdy sprzeda ci sledzia.");
tasks.add("Przytul osobe najblizej ciebie.");
tasks.add("Nie odzywaj sie do nastepnego zadania.");
tasks.add("Wyrecytuj czwarta zwrotke hymnu.");
tasks.add("Wymień wszystkich sasiadów Polski.");
tasks.add("Nie ruszaj sie poki kazdy nie wykona zadania.");
tasks.add("Do konca rundy mow tylko po niemiecku.");
tasks.add("Do konca rundy mow do melodii \"Sto lat\".");
tasks.add("Niech kazdy chetny cie ozdobi.");
tasks.add("Beatboxuj do zakonczenia zadan przez innych.");
tasks.add("Pocaluj swoja stope.");
tasks.add("Opowiedz kawal.");
tasks.add("Rob deske poki inni nie skoncza zadan.");
tasks.add("Trzymaj w ustach kostke lodu poki sie nie roztopi.");
tasks.add("Pocaluj w czolo osobe najblizej ciebie.");
tasks.add("Umyj rece osobie najblizej ciebie.");
tasks.add("Zatancz breakdance.");
tasks.add("Pocaluj każdego gracza w czolo.");
tasks.add("Do konca rundy mow jak Dzoana Krupa.");
tasks.add("Przytul każdego gracza.");
tasks.add("Wez na barana osobe najblizej ciebie.");
tasks.add("Chodz na kolanach przez 2 rundy.");
tasks.add("Stoj na prawej nodze poki wszyscy nie skoncza zadan.");
tasks.add("Powiedz nazwe swojej miejscowosci od tylu.");
tasks.add("Wez dlugopis w usta i podpisz sie na kartce.");
tasks.add("Przeliteruj swoje imie swoim cialem.");
tasks.add("Zatancz choreografie z gangnam style.");
tasks.add("Nie uzywaj slowa \"Nie\" do konca rundy.");
tasks.add("Do konca rundy poruszaj sie w zwolnionym tempie.");
tasks.add("Tancz do konca rundy.");
tasks.add("Zatancz kaczuszki.");
tasks.add("Wypij 2 szoty.");
tasks.add("Krec niewidzialnym hula-hopem do konca zadan.");
tasks.add("Chodz na czworaka do konca rundy.");
tasks.add("Zrób mostek.");
tasks.add("Wykonaj taska wymyslonego przez reszte grupy.");
tasks.add("Zatancz ze szczotka.");
tasks.add("Niech najbliższy gracz napisze do kogo chce z twojego ig.");
tasks.add("Miej zamkniete oczy do konca rundy.");
tasks.add("Pokaz innym wszystkie rzeczy ze swojego portfela.");
tasks.add("Pokaa swoja ostatnia wiadomosc na msg.");
tasks.add("Wypij szota bez uzycia rak.");
tasks.add("Do konca rundy uzywaj \"Kurwa\" zamiast kropki.");
tasks.add("Papuguj do konca rundy osobe najblizej ciebie.");
tasks.add("Pokaz magiczna sztuczke.");
tasks.add("Zacytuj dode.");
tasks.add("Daj sie spoliczkowac osobie najblizej ciebie.");
tasks.add("Zafreestyluj 8 linijek.");
tasks.add("Kalambury bez powtorzen: przyslowie.");
tasks.add("Do konca zadan nasladuj zwierze ktore ktos powie.");
tasks.add("Kalambury bez powtorzen: jedzenie.");
tasks.add("Kalambury bez powtorzen: zanuc.");
tasks.add("Kalambury bez powtorzen: panstwo.");
tasks.add("Zaspiewaj hymn o osobie najblizej ciebie.");
tasks.add("Lez na brzuchu na podlodze do konca rundy.");
tasks.add("Niech ktos dokonczy rozpoczety przez ciebie hit internetu.");
tasks.add("Powiedz bezblednie \"Stol z powylamywanymi nogami\".");
tasks.add("Wypij lyzeczke oliwy.");
tasks.add("Powiedz bez otwierania ust jakies slowo aby ktos zgadnal.");
tasks.add("Obroc sie 10 razy dookola.");
tasks.add("Powiedz bezblednie \"Konstantynopolitanczykowianeczka\".");
}
public static String randomRTask() {
return tasks.get(new Random().nextInt(tasks.size()));
}
public static ImageIcon resize(ImageIcon image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(// ww w . jav a2 s. c o m
new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image.getImage(), 0, 0, width, height, null);
g2d.dispose();
return new ImageIcon(bi);
}
public static void drawImpostors() {
int n;
for (int i=0; i<indexesOfImpostors.size(); i++) {
while (indexesOfImpostors.contains(indexesOfChosen.get(n = new Random().nextInt(indexesOfChosen.size()))));
indexesOfImpostors.set(i, indexesOfChosen.get(n));
}
Data.impostors = indexesOfImpostors.size();
Data.crewmates = indexesOfChosen.size() - impostors;
while (indexesOfImpostors.contains(indexesOfChosen.get(n = new Random().nextInt(indexesOfChosen.size()))));
indexOfDetective = indexesOfChosen.get(n);
while (indexesOfImpostors.contains(indexesOfChosen.get(n = new Random().nextInt(indexesOfChosen.size()))) || indexOfDetective == indexesOfChosen.get(n));
indexOfDefender = indexesOfChosen.get(n);
}
public static void serialize() {
for (Player p : players)
passwords.add(p.getPassword());
Gson gson = new Gson();
String json = gson.toJson(indexesOfChosen);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("chosen.json")))) {
bw.write(json);
} catch (Exception e) {
e.printStackTrace();
}
String json1 = gson.toJson(passwords);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("passwords.json")))) {
bw.write(json1);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void deserialize() {
try { Scanner skaner = new Scanner(new File("chosen.json"));
String json = skaner.nextLine();
Type listType = new TypeToken<ArrayList<Integer>>() {
}.getType();
indexesOfChosen = new Gson().fromJson(json, listType);
} catch (Exception e) {
e.printStackTrace();
}
try { Scanner skaner = new Scanner(new File("passwords.json"));
String json = skaner.nextLine();
Type listType = new TypeToken<ArrayList<String>>() {
}.getType();
passwords = new Gson().fromJson(json, listType);
} catch (Exception e) {
e.printStackTrace();
}
for (int i=0; i<players.size(); i++)
players.get(i).setPassword(passwords.get(i));
}
private static synchronized void playSound(final String path) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
new File(path));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public static void playTasksSound() {
playSound("sounds/tasks1.wav");
}
public static void playDefenderSound() {
playSound("sounds/defender1.wav");
}
public static void playDetectiveSound() {
playSound("sounds/detective1.wav");
}
public static void playImpostorsSound() {
playSound("sounds/impostors1.wav");
}
public static void playDeathSound() {
playSound("sounds/death.wav");
}
public static void playCrewmatesVictorySound() {
playSound("sounds/crewmates_victory.wav");
}
public static void playImpostorsVictorySound() {
playSound("sounds/impostors_victory.wav");
}
public static void playSusSound() {
playSound("sounds/sus.wav");
}
public static void playEmergencyMeetingSound() {
playSound("sounds/emergency_meeting.wav");
}
public static void playVoteOutSound() {
playSound("sounds/vote_out.wav");
}
public static void playVotedOutSound() {
playSound("sounds/voted_out.wav");
}
public static void playDoorSound() {
playSound("sounds/door.wav");
}
public static void playButtonSound() {
playSound("sounds/button1.wav");
}
public static void playRegisteredSound() {
playSound("sounds/registered.wav");
}
public static void playRemovedSound() {
playSound("sounds/removed.wav");
}
} | // ww w . jav a2 s. c o m | import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Data {
public static ArrayList<Player> players = new ArrayList<>();
public static ArrayList<String> passwords = new ArrayList<>();
public static ArrayList<Integer> indexesOfChosen = new ArrayList<>();
public static ArrayList<Integer> indexesOfImpostors = new ArrayList<>();
public static ArrayList<String> tasks = new ArrayList<>();
public static int crewmates = 0;
public static int impostors = 0;
public static boolean isThrownOut = false;
public static int indexOfDetective = 0;
public static int indexOfDefender = 0;
public static boolean isDetectiveDead = false;
public static boolean isChecked = false;
public static boolean resurectionUsed = false;
public static void generateData() {
createPlayers();
createTasks();
}
private static void createPlayers() {
players.add(new Player("red"));
players.add(new Player("blue"));
players.add(new Player("green"));
players.add(new Player("pink"));
players.add(new Player("orange"));
players.add(new Player("yellow"));
players.add(new Player("black"));
players.add(new Player("white"));
players.add(new Player("purple"));
players.add(new Player("brown"));
players.add(new Player("cyan"));
players.add(new Player("lime"));
players.add(new Player("maroon"));
players.add(new Player("rose"));
players.add(new Player("banana"));
players.add(new Player("gray"));
players.add(new Player("tan"));
players.add(new Player("coral"));
players.add(new Player("fortegreen"));
}
private static void createTasks() {
tasks.add("Wypij szota bez popity.");
tasks.add("Zadzwon do kogos i zaspiewaj sto lat.");
tasks.add("Zrob 5 pompek.");
tasks.add("Wypij cytrynowego szota z poker facem.");
tasks.add("Zjedz lyzeczke majonezu.");
tasks.add("Zanuc jakaś piosenke, ktoś musi ja zgadnać.");
tasks.add("Odwzoruj zdj na insta osoby z twoich relacji.");
tasks.add("Zrob 15 pajacykow.");
tasks.add("Zrob 10 przysiadow.");
tasks.add("Przejdz przez caly pokoj z ksiazka na glowie.");
tasks.add("Niech kazdy sprzeda ci sledzia.");
tasks.add("Przytul osobe najblizej ciebie.");
tasks.add("Nie odzywaj sie do nastepnego zadania.");
tasks.add("Wyrecytuj czwarta zwrotke hymnu.");
tasks.add("Wymień wszystkich sasiadów Polski.");
tasks.add("Nie ruszaj sie poki kazdy nie wykona zadania.");
tasks.add("Do konca rundy mow tylko po niemiecku.");
tasks.add("Do konca rundy mow do melodii \"Sto lat\".");
tasks.add("Niech kazdy chetny cie ozdobi.");
tasks.add("Beatboxuj do zakonczenia zadan przez innych.");
tasks.add("Pocaluj swoja stope.");
tasks.add("Opowiedz kawal.");
tasks.add("Rob deske poki inni nie skoncza zadan.");
tasks.add("Trzymaj w ustach kostke lodu poki sie nie roztopi.");
tasks.add("Pocaluj w czolo osobe najblizej ciebie.");
tasks.add("Umyj rece osobie najblizej ciebie.");
tasks.add("Zatancz breakdance.");
tasks.add("Pocaluj każdego gracza w czolo.");
tasks.add("Do konca rundy mow jak Dzoana Krupa.");
tasks.add("Przytul każdego gracza.");
tasks.add("Wez na barana osobe najblizej ciebie.");
tasks.add("Chodz na kolanach przez 2 rundy.");
tasks.add("Stoj na prawej nodze poki wszyscy nie skoncza zadan.");
tasks.add("Powiedz nazwe swojej miejscowosci od tylu.");
tasks.add("Wez dlugopis w usta i podpisz sie na kartce.");
tasks.add("Przeliteruj swoje imie swoim cialem.");
tasks.add("Zatancz choreografie z gangnam style.");
tasks.add("Nie uzywaj slowa \"Nie\" do konca rundy.");
tasks.add("Do konca rundy poruszaj sie w zwolnionym tempie.");
tasks.add("Tancz do konca rundy.");
tasks.add("Zatancz kaczuszki.");
tasks.add("Wypij 2 szoty.");
tasks.add("Krec niewidzialnym hula-hopem do konca zadan.");
tasks.add("Chodz na czworaka do konca rundy.");
tasks.add("Zrób mostek.");
tasks.add("Wykonaj taska wymyslonego przez reszte grupy.");
tasks.add("Zatancz ze szczotka.");
tasks.add("Niech najbliższy gracz napisze do kogo chce z twojego ig.");
tasks.add("Miej zamkniete oczy do konca rundy.");
tasks.add("Pokaz innym wszystkie rzeczy ze swojego portfela.");
tasks.add("Pokaa swoja ostatnia wiadomosc na msg.");
tasks.add("Wypij szota bez uzycia rak.");
tasks.add("Do konca rundy uzywaj \"Kurwa\" zamiast kropki.");
tasks.add("Papuguj do konca rundy osobe najblizej ciebie.");
tasks.add("Pokaz magiczna sztuczke.");
tasks.add("Zacytuj dode.");
tasks.add("Daj sie spoliczkowac osobie najblizej ciebie.");
tasks.add("Zafreestyluj 8 linijek.");
tasks.add("Kalambury bez powtorzen: przyslowie.");
tasks.add("Do konca zadan nasladuj zwierze ktore ktos powie.");
tasks.add("Kalambury bez powtorzen: jedzenie.");
tasks.add("Kalambury bez powtorzen: zanuc.");
tasks.add("Kalambury bez powtorzen: panstwo.");
tasks.add("Zaspiewaj hymn o osobie najblizej ciebie.");
tasks.add("Lez na brzuchu na podlodze do konca rundy.");
tasks.add("Niech ktos dokonczy rozpoczety przez ciebie hit internetu.");
tasks.add("Powiedz bezblednie \"Stol z powylamywanymi nogami\".");
tasks.add("Wypij lyzeczke oliwy.");
tasks.add("Powiedz bez otwierania ust jakies slowo aby ktos zgadnal.");
tasks.add("Obroc sie 10 razy dookola.");
tasks.add("Powiedz bezblednie \"Konstantynopolitanczykowianeczka\".");
}
public static String randomRTask() {
return tasks.get(new Random().nextInt(tasks.size()));
}
public static ImageIcon resize(ImageIcon image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(// ww <SUF>
new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image.getImage(), 0, 0, width, height, null);
g2d.dispose();
return new ImageIcon(bi);
}
public static void drawImpostors() {
int n;
for (int i=0; i<indexesOfImpostors.size(); i++) {
while (indexesOfImpostors.contains(indexesOfChosen.get(n = new Random().nextInt(indexesOfChosen.size()))));
indexesOfImpostors.set(i, indexesOfChosen.get(n));
}
Data.impostors = indexesOfImpostors.size();
Data.crewmates = indexesOfChosen.size() - impostors;
while (indexesOfImpostors.contains(indexesOfChosen.get(n = new Random().nextInt(indexesOfChosen.size()))));
indexOfDetective = indexesOfChosen.get(n);
while (indexesOfImpostors.contains(indexesOfChosen.get(n = new Random().nextInt(indexesOfChosen.size()))) || indexOfDetective == indexesOfChosen.get(n));
indexOfDefender = indexesOfChosen.get(n);
}
public static void serialize() {
for (Player p : players)
passwords.add(p.getPassword());
Gson gson = new Gson();
String json = gson.toJson(indexesOfChosen);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("chosen.json")))) {
bw.write(json);
} catch (Exception e) {
e.printStackTrace();
}
String json1 = gson.toJson(passwords);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("passwords.json")))) {
bw.write(json1);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void deserialize() {
try { Scanner skaner = new Scanner(new File("chosen.json"));
String json = skaner.nextLine();
Type listType = new TypeToken<ArrayList<Integer>>() {
}.getType();
indexesOfChosen = new Gson().fromJson(json, listType);
} catch (Exception e) {
e.printStackTrace();
}
try { Scanner skaner = new Scanner(new File("passwords.json"));
String json = skaner.nextLine();
Type listType = new TypeToken<ArrayList<String>>() {
}.getType();
passwords = new Gson().fromJson(json, listType);
} catch (Exception e) {
e.printStackTrace();
}
for (int i=0; i<players.size(); i++)
players.get(i).setPassword(passwords.get(i));
}
private static synchronized void playSound(final String path) {
new Thread(new Runnable() {
public void run() {
try {
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(
new File(path));
clip.open(inputStream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public static void playTasksSound() {
playSound("sounds/tasks1.wav");
}
public static void playDefenderSound() {
playSound("sounds/defender1.wav");
}
public static void playDetectiveSound() {
playSound("sounds/detective1.wav");
}
public static void playImpostorsSound() {
playSound("sounds/impostors1.wav");
}
public static void playDeathSound() {
playSound("sounds/death.wav");
}
public static void playCrewmatesVictorySound() {
playSound("sounds/crewmates_victory.wav");
}
public static void playImpostorsVictorySound() {
playSound("sounds/impostors_victory.wav");
}
public static void playSusSound() {
playSound("sounds/sus.wav");
}
public static void playEmergencyMeetingSound() {
playSound("sounds/emergency_meeting.wav");
}
public static void playVoteOutSound() {
playSound("sounds/vote_out.wav");
}
public static void playVotedOutSound() {
playSound("sounds/voted_out.wav");
}
public static void playDoorSound() {
playSound("sounds/door.wav");
}
public static void playButtonSound() {
playSound("sounds/button1.wav");
}
public static void playRegisteredSound() {
playSound("sounds/registered.wav");
}
public static void playRemovedSound() {
playSound("sounds/removed.wav");
}
} | f |
5644_27 | klolo/java8-stream-free-exercises | 6,328 | src/main/java/pl/klolo/workshops/logic/WorkShop.java | package pl.klolo.workshops.logic;
import pl.klolo.workshops.domain.*;
import pl.klolo.workshops.domain.Currency;
import pl.klolo.workshops.mock.HoldingMockGenerator;
import pl.klolo.workshops.mock.UserMockGenerator;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.String.format;
import static java.util.stream.Collectors.*;
import static java.util.stream.Collectors.toSet;
class WorkShop {
/**
* Lista holdingów wczytana z mocka.
*/
private final List<Holding> holdings;
private final Predicate<User> isWoman = user -> user.getSex().equals(Sex.WOMAN);
private Predicate<User> isMan = m -> m.getSex() == Sex.MAN;
WorkShop() {
final HoldingMockGenerator holdingMockGenerator = new HoldingMockGenerator();
holdings = holdingMockGenerator.generate();
}
/**
* Metoda zwraca liczbę holdingów w których jest przynajmniej jedna firma.
*/
long getHoldingsWhereAreCompanies() {
return holdings.stream()
.filter(holding -> holding.getCompanies().size() > 0)
.count();
}
/**
* Zwraca nazwy wszystkich holdingów pisane z małej litery w formie listy.
*/
List<String> getHoldingNames() {
return holdings.stream()
.map(holding -> holding.getName().toLowerCase())
.collect(Collectors.toList());
}
/**
* Zwraca nazwy wszystkich holdingów sklejone w jeden string i posortowane.
* String ma postać: (Coca-Cola, Nestle, Pepsico)
*/
String getHoldingNamesAsString() {
return holdings.stream()
.map(Holding::getName)
.sorted()
.collect(Collectors.joining(", ", "(", ")"));
}
/**
* Zwraca liczbę firm we wszystkich holdingach.
*/
long getCompaniesAmount() {
return holdings.stream()
.mapToInt(holding -> holding.getCompanies().size())
.sum();
}
/**
* Zwraca liczbę wszystkich pracowników we wszystkich firmach.
*/
long getAllUserAmount() {
return holdings.stream()
.flatMap(holding -> holding.getCompanies().stream())
.mapToLong(company -> company.getUsers().size())
.sum();
}
/**
* Zwraca listę wszystkich nazw firm w formie listy. Tworzenie strumienia firm umieść w osobnej metodzie którą
* później będziesz wykorzystywać.
*/
List<String> getAllCompaniesNames() {
return getCompanyStream()
.map(Company::getName)
.collect(Collectors.toList());
}
/**
* Zwraca listę wszystkich firm jako listę, której implementacja to LinkedList. Obiektów nie przepisujemy
* po zakończeniu działania strumienia.
*/
LinkedList<String> getAllCompaniesNamesAsLinkedList() {
return getCompanyStream()
.map(Company::getName)
.collect(Collectors.toCollection(LinkedList::new));
}
/**
* Zwraca listę firm jako String gdzie poszczególne firmy są oddzielone od siebie znakiem "+"
*/
String getAllCompaniesNamesAsString() {
return getCompanyStream()
.map(Company::getName)
.collect(Collectors.joining("+"));
}
/**
* Zwraca listę firm jako string gdzie poszczególne firmy są oddzielone od siebie znakiem "+".
* Używamy collect i StringBuilder.
* <p>
* UWAGA: Zadanie z gwiazdką. Nie używamy zmiennych.
*/
String getAllCompaniesNamesAsStringUsingStringBuilder() {
AtomicBoolean first = new AtomicBoolean(false);
return getCompanyStream()
.map(Company::getName)
.collect(Collector.of(StringBuilder::new,
(stringBuilder, s) -> {
if (first.getAndSet(true)) stringBuilder.append("+");
stringBuilder.append(s);
},
StringBuilder::append,
StringBuilder::toString));
}
/**
* Zwraca liczbę wszystkich rachunków, użytkowników we wszystkich firmach.
*/
long getAllUserAccountsAmount() {
return getCompanyStream()
.flatMap(company -> company.getUsers().stream())
.mapToInt(user -> user.getAccounts().size())
.sum();
}
/**
* Zwraca listę wszystkich walut w jakich są rachunki jako string, w którym wartości
* występują bez powtórzeń i są posortowane.
*/
String getAllCurrencies() {
final List<String> currencies = getAllCurrenciesToListAsString();
return currencies
.stream()
.distinct()
.sorted()
.collect(Collectors.joining(", "));
}
/**
* Metoda zwraca analogiczne dane jak getAllCurrencies, jednak na utworzonym zbiorze nie uruchamiaj metody
* stream, tylko skorzystaj z Stream.generate. Wspólny kod wynieś do osobnej metody.
*
* @see #getAllCurrencies()
*/
String getAllCurrenciesUsingGenerate() {
final List<String> currencies = getAllCurrenciesToListAsString();
return Stream.generate(currencies.iterator()::next)
.limit(currencies.size())
.distinct()
.sorted()
.collect(Collectors.joining(", "));
}
private List<String> getAllCurrenciesToListAsString() {
return getCompanyStream()
.flatMap(company -> company.getUsers().stream())
.flatMap(user -> user.getAccounts().stream())
.map(Account::getCurrency)
.map(c -> Objects.toString(c, null))
.collect(Collectors.toList());
}
/**
* Zwraca liczbę kobiet we wszystkich firmach. Powtarzający się fragment kodu tworzący strumień użytkowników umieść
* w osobnej metodzie. Predicate określający czy mamy do czynienia z kobietą niech będzie polem statycznym w klasie.
*/
long getWomanAmount() {
return getUserStream()
.filter(isWoman)
.count();
}
/**
* Przelicza kwotę na rachunku na złotówki za pomocą kursu określonego w enum Currency.
*/
BigDecimal getAccountAmountInPLN(final Account account) {
return account
.getAmount()
.multiply(BigDecimal.valueOf(account.getCurrency().rate))
.round(new MathContext(4, RoundingMode.HALF_UP));
}
/**
* Przelicza kwotę na podanych rachunkach na złotówki za pomocą kursu określonego w enum Currency i sumuje ją.
*/
BigDecimal getTotalCashInPLN(final List<Account> accounts) {
return accounts
.stream()
.map(account -> account.getAmount().multiply(BigDecimal.valueOf(account.getCurrency().rate)))
.reduce(BigDecimal.valueOf(0), BigDecimal::add);
}
/**
* Zwraca imiona użytkowników w formie zbioru, którzy spełniają podany warunek.
*/
Set<String> getUsersForPredicate(final Predicate<User> userPredicate) {
return getUserStream()
.filter(userPredicate)
.map(User::getFirstName)
.collect(Collectors.toSet());
}
/**
* Metoda filtruje użytkowników starszych niż podany jako parametr wiek, wyświetla ich na konsoli, odrzuca mężczyzn
* i zwraca ich imiona w formie listy.
*/
List<String> getOldWoman(final int age) {
return getUserStream()
.filter(user -> user.getAge() > age)
.peek(System.out::println)
.filter(isMan)
.map(User::getFirstName)
.collect(Collectors.toList());
}
/**
* Dla każdej firmy uruchamia przekazaną metodę.
*/
void executeForEachCompany(final Consumer<Company> consumer) {
getCompanyStream().forEach(consumer);
}
/**
* Wyszukuje najbogatsza kobietę i zwraca ją. Metoda musi uzwględniać to że rachunki są w różnych walutach.
*/
//pomoc w rozwiązaniu problemu w zadaniu: https://stackoverflow.com/a/55052733/9360524
Optional<User> getRichestWoman() {
return getUserStream()
.filter(user -> user.getSex().equals(Sex.WOMAN))
.max(Comparator.comparing(this::getUserAmountInPLN));
}
private BigDecimal getUserAmountInPLN(final User user) {
return user.getAccounts()
.stream()
.map(this::getAccountAmountInPLN)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* Zwraca nazwy pierwszych N firm. Kolejność nie ma znaczenia.
*/
Set<String> getFirstNCompany(final int n) {
return getCompanyStream()
.limit(n)
.map(Company::getName)
.collect(Collectors.toSet());
}
/**
* Metoda zwraca jaki rodzaj rachunku jest najpopularniejszy. Stwórz pomocniczą metodę getAccountStream.
* Jeżeli nie udało się znaleźć najpopularniejszego rachunku metoda ma wyrzucić wyjątek IllegalStateException.
* Pierwsza instrukcja metody to return.
*/
AccountType getMostPopularAccountType() {
return getAccoutStream()
.map(Account::getType)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue))
.map(Map.Entry::getKey)
.orElseThrow(IllegalStateException::new);
}
/**
* Zwraca pierwszego z brzegu użytkownika dla podanego warunku. W przypadku kiedy nie znajdzie użytkownika wyrzuca
* wyjątek IllegalArgumentException.
*/
User getUser(final Predicate<User> predicate) {
return getUserStream()
.filter(predicate)
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
/**
* Zwraca mapę firm, gdzie kluczem jest jej nazwa a wartością lista pracowników.
*/
Map<String, List<User>> getUserPerCompany() {
return getCompanyStream()
.collect(toMap(Company::getName, Company::getUsers));
}
/**
* Zwraca mapę firm, gdzie kluczem jest jej nazwa a wartością lista pracowników przechowywanych jako String
* składający się z imienia i nazwiska. Podpowiedź: Możesz skorzystać z metody entrySet.
*/
Map<String, List<String>> getUserPerCompanyAsString() {
BiFunction<String, String, String> joinNameAndLastName = (x, y) -> x + " " + y;
return getCompanyStream().collect(Collectors.toMap(
Company::getName,
c -> c.getUsers()
.stream()
.map(u -> joinNameAndLastName.apply(u.getFirstName(), u.getLastName()))
.collect(Collectors.toList())
));
}
/**
* Zwraca mapę firm, gdzie kluczem jest jej nazwa a wartością lista pracowników przechowywanych jako obiekty
* typu T, tworzonych za pomocą przekazanej funkcji.
*/
//pomoc w rozwiązaniu problemu w zadaniu: https://stackoverflow.com/a/54969615/9360524
<T> Map<String, List<T>> getUserPerCompany(final Function<User, T> converter) {
return getCompanyStream()
.collect(Collectors.toMap(
Company::getName,
c -> c.getUsers()
.stream()
.map(converter)
.collect(Collectors.toList())
));
}
/**
* Zwraca mapę gdzie kluczem jest flaga mówiąca o tym czy mamy do czynienia z mężczyzną, czy z kobietą.
* Osoby "innej" płci mają zostać zignorowane. Wartością jest natomiast zbiór nazwisk tych osób.
*/
Map<Boolean, Set<String>> getUserBySex() {
Predicate<User> isManOrWoman = m -> m.getSex() == Sex.MAN || m.getSex() == Sex.WOMAN;
return getUserStream()
.filter(isManOrWoman)
.collect(partitioningBy(isMan, mapping(User::getLastName, toSet())));
}
/**
* Zwraca mapę rachunków, gdzie kluczem jest numer rachunku, a wartością ten rachunek.
*/
Map<String, Account> createAccountsMap() {
return getAccoutStream().collect(Collectors.toMap(Account::getNumber, account -> account));
}
/**
* Zwraca listę wszystkich imion w postaci Stringa, gdzie imiona oddzielone są spacją i nie zawierają powtórzeń.
*/
String getUserNames() {
return getUserStream()
.map(User::getFirstName)
.distinct()
.sorted()
.collect(Collectors.joining(" "));
}
/**
* Zwraca zbiór wszystkich użytkowników. Jeżeli jest ich więcej niż 10 to obcina ich ilość do 10.
*/
Set<User> getUsers() {
return getUserStream()
.limit(10)
.collect(Collectors.toSet());
}
/**
* Zapisuje listę numerów rachunków w pliku na dysku, gdzie w każda linijka wygląda następująco:
* NUMER_RACHUNKU|KWOTA|WALUTA
* <p>
* Skorzystaj z strumieni i try-resources.
*/
void saveAccountsInFile(final String fileName) {
try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
Files.write(Paths.get(String.valueOf(lines)), (Iterable<String>) getAccoutStream()
.map(account -> account.getNumber() + "|" + account.getAmount() + "|" + account.getCurrency())
::iterator);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Zwraca użytkownika, który spełnia podany warunek.
*/
Optional<User> findUser(final Predicate<User> userPredicate) {
return getUserStream()
.filter(userPredicate)
.findAny();
}
/**
* Dla podanego użytkownika zwraca informacje o tym ile ma lat w formie:
* IMIE NAZWISKO ma lat X. Jeżeli użytkownik nie istnieje to zwraca text: Brak użytkownika.
* <p>
* Uwaga: W prawdziwym kodzie nie przekazuj Optionali jako parametrów.
*/
String getAdultantStatus(final Optional<User> user) {
return user.flatMap(u -> getUserStream().filter(u2 -> Objects.equals(u2, u)).findFirst())
.map(u -> format("%s %s ma lat %d", u.getFirstName(), u.getLastName(), u.getAge()))
.orElse("Brak użytkownika");
}
/**
* Metoda wypisuje na ekranie wszystkich użytkowników (imię, nazwisko) posortowanych od z do a.
* Zosia Psikuta, Zenon Kucowski, Zenek Jawowy ... Alfred Pasibrzuch, Adam Wojcik
*/
void showAllUser() {
getUserStream()
.sorted(Comparator.comparing(User::getFirstName).reversed())
.forEach(System.out::println);
}
/**
* Zwraca mapę, gdzie kluczem jest typ rachunku a wartością kwota wszystkich środków na rachunkach tego typu
* przeliczona na złotówki.
*/
//TODO: fix
// java.lang.AssertionError:
// Expected :87461.4992
// Actual :87461.3999
Map<AccountType, BigDecimal> getMoneyOnAccounts() {
return getAccoutStream()
.collect(Collectors.toMap(Account::getType, account -> account.getAmount()
.multiply(BigDecimal.valueOf(account.getCurrency().rate))
.round(new MathContext(6, RoundingMode.DOWN)), BigDecimal::add));
}
/**
* Zwraca sumę kwadratów wieków wszystkich użytkowników.
*/
int getAgeSquaresSum() {
return getUserStream()
.mapToInt(User::getAge)
.map(p -> (int) Math.pow(p, 2)).sum();
}
/**
* Metoda zwraca N losowych użytkowników (liczba jest stała). Skorzystaj z metody generate. Użytkownicy nie mogą się
* powtarzać, wszystkie zmienną muszą być final. Jeżeli podano liczbę większą niż liczba użytkowników należy
* wyrzucić wyjątek (bez zmiany sygnatury metody).
*/
List<User> getRandomUsers(final int n) {
final UserMockGenerator userMockGenerator = new UserMockGenerator();
return Optional.of(userMockGenerator.generate().stream()
.collect(Collectors.collectingAndThen(Collectors.toList(), collected -> {
Collections.shuffle(collected);
return collected.stream();
}))
.limit(n)
.distinct()
.collect(Collectors.toList()))
.orElseThrow(ArrayIndexOutOfBoundsException::new);
}
/**
* Zwraca strumień wszystkich firm.
*/
private Stream<Company> getCompanyStream() {
return holdings.stream()
.flatMap(holding -> holding.getCompanies().stream());
}
/**
* Zwraca zbiór walut w jakich są rachunki.
*/
private Set<Currency> getCurenciesSet() {
return getAccoutStream()
.map(Account::getCurrency)
.collect(Collectors.toSet());
}
/**
* Tworzy strumień rachunków.
*/
private Stream<Account> getAccoutStream() {
return getUserStream()
.flatMap(user -> user.getAccounts().stream());
}
/**
* Tworzy strumień użytkowników.
*/
private Stream<User> getUserStream() {
return getCompanyStream()
.flatMap(company -> company.getUsers().stream());
}
/**
* 38.
* Stwórz mapę gdzie kluczem jest typ rachunku a wartością mapa mężczyzn posiadających ten rachunek, gdzie kluczem
* jest obiekt User a wartością suma pieniędzy na rachunku danego typu przeliczona na złotkówki.
*/
//TODO: zamiast Map<Stream<AccountType>, Map<User, BigDecimal>> metoda ma zwracać
// Map<AccountType>, Map<User, BigDecimal>>, zweryfikować działania metody
Map<Stream<AccountType>, Map<User, BigDecimal>> getMapWithAccountTypeKeyAndSumMoneyForManInPLN() {
return getCompanyStream()
.collect(Collectors.toMap(
company -> company.getUsers()
.stream()
.flatMap(user -> user.getAccounts()
.stream()
.map(Account::getType)),
this::manWithSumMoneyOnAccounts
));
}
private Map<User, BigDecimal> manWithSumMoneyOnAccounts(final Company company) {
return company
.getUsers()
.stream()
.filter(isMan)
.collect(Collectors.toMap(
Function.identity(),
this::getSumUserAmountInPLN
));
}
private BigDecimal getSumUserAmountInPLN(final User user) {
return user.getAccounts()
.stream()
.map(this::getAccountAmountInPLN)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* 39. Policz ile pieniędzy w złotówkach jest na kontach osób które nie są ani kobietą ani mężczyzną.
*/
BigDecimal getSumMoneyOnAccountsForPeopleOtherInPLN() {
return getUserStream()
.filter(user -> user.getSex().equals(Sex.OTHER))
.map(this::getUserAmountInPLN)
.reduce(BigDecimal.ZERO, BigDecimal::add)
.round(MathContext.DECIMAL32);
}
/**
* 40. Wymyśl treść polecenia i je zaimplementuj.
* Policz ile osób pełnoletnich posiada rachunek oraz ile osób niepełnoletnich posiada rachunek. Zwróć mapę
* przyjmując klucz True dla osób pełnoletnich i klucz False dla osób niepełnoletnich. Osoba pełnoletnia to osoba
* która ma więcej lub równo 18 lat
*/
Map<Boolean, Long> divideIntoAdultsAndNonAdults() {
Predicate<User> ofAge = u -> u.getAge() >= 18;
return getUserStream()
.collect(Collectors.partitioningBy(ofAge, Collectors.counting()));
}
}
| //pomoc w rozwiązaniu problemu w zadaniu: https://stackoverflow.com/a/54969615/9360524 | package pl.klolo.workshops.logic;
import pl.klolo.workshops.domain.*;
import pl.klolo.workshops.domain.Currency;
import pl.klolo.workshops.mock.HoldingMockGenerator;
import pl.klolo.workshops.mock.UserMockGenerator;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.String.format;
import static java.util.stream.Collectors.*;
import static java.util.stream.Collectors.toSet;
class WorkShop {
/**
* Lista holdingów wczytana z mocka.
*/
private final List<Holding> holdings;
private final Predicate<User> isWoman = user -> user.getSex().equals(Sex.WOMAN);
private Predicate<User> isMan = m -> m.getSex() == Sex.MAN;
WorkShop() {
final HoldingMockGenerator holdingMockGenerator = new HoldingMockGenerator();
holdings = holdingMockGenerator.generate();
}
/**
* Metoda zwraca liczbę holdingów w których jest przynajmniej jedna firma.
*/
long getHoldingsWhereAreCompanies() {
return holdings.stream()
.filter(holding -> holding.getCompanies().size() > 0)
.count();
}
/**
* Zwraca nazwy wszystkich holdingów pisane z małej litery w formie listy.
*/
List<String> getHoldingNames() {
return holdings.stream()
.map(holding -> holding.getName().toLowerCase())
.collect(Collectors.toList());
}
/**
* Zwraca nazwy wszystkich holdingów sklejone w jeden string i posortowane.
* String ma postać: (Coca-Cola, Nestle, Pepsico)
*/
String getHoldingNamesAsString() {
return holdings.stream()
.map(Holding::getName)
.sorted()
.collect(Collectors.joining(", ", "(", ")"));
}
/**
* Zwraca liczbę firm we wszystkich holdingach.
*/
long getCompaniesAmount() {
return holdings.stream()
.mapToInt(holding -> holding.getCompanies().size())
.sum();
}
/**
* Zwraca liczbę wszystkich pracowników we wszystkich firmach.
*/
long getAllUserAmount() {
return holdings.stream()
.flatMap(holding -> holding.getCompanies().stream())
.mapToLong(company -> company.getUsers().size())
.sum();
}
/**
* Zwraca listę wszystkich nazw firm w formie listy. Tworzenie strumienia firm umieść w osobnej metodzie którą
* później będziesz wykorzystywać.
*/
List<String> getAllCompaniesNames() {
return getCompanyStream()
.map(Company::getName)
.collect(Collectors.toList());
}
/**
* Zwraca listę wszystkich firm jako listę, której implementacja to LinkedList. Obiektów nie przepisujemy
* po zakończeniu działania strumienia.
*/
LinkedList<String> getAllCompaniesNamesAsLinkedList() {
return getCompanyStream()
.map(Company::getName)
.collect(Collectors.toCollection(LinkedList::new));
}
/**
* Zwraca listę firm jako String gdzie poszczególne firmy są oddzielone od siebie znakiem "+"
*/
String getAllCompaniesNamesAsString() {
return getCompanyStream()
.map(Company::getName)
.collect(Collectors.joining("+"));
}
/**
* Zwraca listę firm jako string gdzie poszczególne firmy są oddzielone od siebie znakiem "+".
* Używamy collect i StringBuilder.
* <p>
* UWAGA: Zadanie z gwiazdką. Nie używamy zmiennych.
*/
String getAllCompaniesNamesAsStringUsingStringBuilder() {
AtomicBoolean first = new AtomicBoolean(false);
return getCompanyStream()
.map(Company::getName)
.collect(Collector.of(StringBuilder::new,
(stringBuilder, s) -> {
if (first.getAndSet(true)) stringBuilder.append("+");
stringBuilder.append(s);
},
StringBuilder::append,
StringBuilder::toString));
}
/**
* Zwraca liczbę wszystkich rachunków, użytkowników we wszystkich firmach.
*/
long getAllUserAccountsAmount() {
return getCompanyStream()
.flatMap(company -> company.getUsers().stream())
.mapToInt(user -> user.getAccounts().size())
.sum();
}
/**
* Zwraca listę wszystkich walut w jakich są rachunki jako string, w którym wartości
* występują bez powtórzeń i są posortowane.
*/
String getAllCurrencies() {
final List<String> currencies = getAllCurrenciesToListAsString();
return currencies
.stream()
.distinct()
.sorted()
.collect(Collectors.joining(", "));
}
/**
* Metoda zwraca analogiczne dane jak getAllCurrencies, jednak na utworzonym zbiorze nie uruchamiaj metody
* stream, tylko skorzystaj z Stream.generate. Wspólny kod wynieś do osobnej metody.
*
* @see #getAllCurrencies()
*/
String getAllCurrenciesUsingGenerate() {
final List<String> currencies = getAllCurrenciesToListAsString();
return Stream.generate(currencies.iterator()::next)
.limit(currencies.size())
.distinct()
.sorted()
.collect(Collectors.joining(", "));
}
private List<String> getAllCurrenciesToListAsString() {
return getCompanyStream()
.flatMap(company -> company.getUsers().stream())
.flatMap(user -> user.getAccounts().stream())
.map(Account::getCurrency)
.map(c -> Objects.toString(c, null))
.collect(Collectors.toList());
}
/**
* Zwraca liczbę kobiet we wszystkich firmach. Powtarzający się fragment kodu tworzący strumień użytkowników umieść
* w osobnej metodzie. Predicate określający czy mamy do czynienia z kobietą niech będzie polem statycznym w klasie.
*/
long getWomanAmount() {
return getUserStream()
.filter(isWoman)
.count();
}
/**
* Przelicza kwotę na rachunku na złotówki za pomocą kursu określonego w enum Currency.
*/
BigDecimal getAccountAmountInPLN(final Account account) {
return account
.getAmount()
.multiply(BigDecimal.valueOf(account.getCurrency().rate))
.round(new MathContext(4, RoundingMode.HALF_UP));
}
/**
* Przelicza kwotę na podanych rachunkach na złotówki za pomocą kursu określonego w enum Currency i sumuje ją.
*/
BigDecimal getTotalCashInPLN(final List<Account> accounts) {
return accounts
.stream()
.map(account -> account.getAmount().multiply(BigDecimal.valueOf(account.getCurrency().rate)))
.reduce(BigDecimal.valueOf(0), BigDecimal::add);
}
/**
* Zwraca imiona użytkowników w formie zbioru, którzy spełniają podany warunek.
*/
Set<String> getUsersForPredicate(final Predicate<User> userPredicate) {
return getUserStream()
.filter(userPredicate)
.map(User::getFirstName)
.collect(Collectors.toSet());
}
/**
* Metoda filtruje użytkowników starszych niż podany jako parametr wiek, wyświetla ich na konsoli, odrzuca mężczyzn
* i zwraca ich imiona w formie listy.
*/
List<String> getOldWoman(final int age) {
return getUserStream()
.filter(user -> user.getAge() > age)
.peek(System.out::println)
.filter(isMan)
.map(User::getFirstName)
.collect(Collectors.toList());
}
/**
* Dla każdej firmy uruchamia przekazaną metodę.
*/
void executeForEachCompany(final Consumer<Company> consumer) {
getCompanyStream().forEach(consumer);
}
/**
* Wyszukuje najbogatsza kobietę i zwraca ją. Metoda musi uzwględniać to że rachunki są w różnych walutach.
*/
//pomoc w rozwiązaniu problemu w zadaniu: https://stackoverflow.com/a/55052733/9360524
Optional<User> getRichestWoman() {
return getUserStream()
.filter(user -> user.getSex().equals(Sex.WOMAN))
.max(Comparator.comparing(this::getUserAmountInPLN));
}
private BigDecimal getUserAmountInPLN(final User user) {
return user.getAccounts()
.stream()
.map(this::getAccountAmountInPLN)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* Zwraca nazwy pierwszych N firm. Kolejność nie ma znaczenia.
*/
Set<String> getFirstNCompany(final int n) {
return getCompanyStream()
.limit(n)
.map(Company::getName)
.collect(Collectors.toSet());
}
/**
* Metoda zwraca jaki rodzaj rachunku jest najpopularniejszy. Stwórz pomocniczą metodę getAccountStream.
* Jeżeli nie udało się znaleźć najpopularniejszego rachunku metoda ma wyrzucić wyjątek IllegalStateException.
* Pierwsza instrukcja metody to return.
*/
AccountType getMostPopularAccountType() {
return getAccoutStream()
.map(Account::getType)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparing(Map.Entry::getValue))
.map(Map.Entry::getKey)
.orElseThrow(IllegalStateException::new);
}
/**
* Zwraca pierwszego z brzegu użytkownika dla podanego warunku. W przypadku kiedy nie znajdzie użytkownika wyrzuca
* wyjątek IllegalArgumentException.
*/
User getUser(final Predicate<User> predicate) {
return getUserStream()
.filter(predicate)
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
/**
* Zwraca mapę firm, gdzie kluczem jest jej nazwa a wartością lista pracowników.
*/
Map<String, List<User>> getUserPerCompany() {
return getCompanyStream()
.collect(toMap(Company::getName, Company::getUsers));
}
/**
* Zwraca mapę firm, gdzie kluczem jest jej nazwa a wartością lista pracowników przechowywanych jako String
* składający się z imienia i nazwiska. Podpowiedź: Możesz skorzystać z metody entrySet.
*/
Map<String, List<String>> getUserPerCompanyAsString() {
BiFunction<String, String, String> joinNameAndLastName = (x, y) -> x + " " + y;
return getCompanyStream().collect(Collectors.toMap(
Company::getName,
c -> c.getUsers()
.stream()
.map(u -> joinNameAndLastName.apply(u.getFirstName(), u.getLastName()))
.collect(Collectors.toList())
));
}
/**
* Zwraca mapę firm, gdzie kluczem jest jej nazwa a wartością lista pracowników przechowywanych jako obiekty
* typu T, tworzonych za pomocą przekazanej funkcji.
*/
//pomoc w <SUF>
<T> Map<String, List<T>> getUserPerCompany(final Function<User, T> converter) {
return getCompanyStream()
.collect(Collectors.toMap(
Company::getName,
c -> c.getUsers()
.stream()
.map(converter)
.collect(Collectors.toList())
));
}
/**
* Zwraca mapę gdzie kluczem jest flaga mówiąca o tym czy mamy do czynienia z mężczyzną, czy z kobietą.
* Osoby "innej" płci mają zostać zignorowane. Wartością jest natomiast zbiór nazwisk tych osób.
*/
Map<Boolean, Set<String>> getUserBySex() {
Predicate<User> isManOrWoman = m -> m.getSex() == Sex.MAN || m.getSex() == Sex.WOMAN;
return getUserStream()
.filter(isManOrWoman)
.collect(partitioningBy(isMan, mapping(User::getLastName, toSet())));
}
/**
* Zwraca mapę rachunków, gdzie kluczem jest numer rachunku, a wartością ten rachunek.
*/
Map<String, Account> createAccountsMap() {
return getAccoutStream().collect(Collectors.toMap(Account::getNumber, account -> account));
}
/**
* Zwraca listę wszystkich imion w postaci Stringa, gdzie imiona oddzielone są spacją i nie zawierają powtórzeń.
*/
String getUserNames() {
return getUserStream()
.map(User::getFirstName)
.distinct()
.sorted()
.collect(Collectors.joining(" "));
}
/**
* Zwraca zbiór wszystkich użytkowników. Jeżeli jest ich więcej niż 10 to obcina ich ilość do 10.
*/
Set<User> getUsers() {
return getUserStream()
.limit(10)
.collect(Collectors.toSet());
}
/**
* Zapisuje listę numerów rachunków w pliku na dysku, gdzie w każda linijka wygląda następująco:
* NUMER_RACHUNKU|KWOTA|WALUTA
* <p>
* Skorzystaj z strumieni i try-resources.
*/
void saveAccountsInFile(final String fileName) {
try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
Files.write(Paths.get(String.valueOf(lines)), (Iterable<String>) getAccoutStream()
.map(account -> account.getNumber() + "|" + account.getAmount() + "|" + account.getCurrency())
::iterator);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Zwraca użytkownika, który spełnia podany warunek.
*/
Optional<User> findUser(final Predicate<User> userPredicate) {
return getUserStream()
.filter(userPredicate)
.findAny();
}
/**
* Dla podanego użytkownika zwraca informacje o tym ile ma lat w formie:
* IMIE NAZWISKO ma lat X. Jeżeli użytkownik nie istnieje to zwraca text: Brak użytkownika.
* <p>
* Uwaga: W prawdziwym kodzie nie przekazuj Optionali jako parametrów.
*/
String getAdultantStatus(final Optional<User> user) {
return user.flatMap(u -> getUserStream().filter(u2 -> Objects.equals(u2, u)).findFirst())
.map(u -> format("%s %s ma lat %d", u.getFirstName(), u.getLastName(), u.getAge()))
.orElse("Brak użytkownika");
}
/**
* Metoda wypisuje na ekranie wszystkich użytkowników (imię, nazwisko) posortowanych od z do a.
* Zosia Psikuta, Zenon Kucowski, Zenek Jawowy ... Alfred Pasibrzuch, Adam Wojcik
*/
void showAllUser() {
getUserStream()
.sorted(Comparator.comparing(User::getFirstName).reversed())
.forEach(System.out::println);
}
/**
* Zwraca mapę, gdzie kluczem jest typ rachunku a wartością kwota wszystkich środków na rachunkach tego typu
* przeliczona na złotówki.
*/
//TODO: fix
// java.lang.AssertionError:
// Expected :87461.4992
// Actual :87461.3999
Map<AccountType, BigDecimal> getMoneyOnAccounts() {
return getAccoutStream()
.collect(Collectors.toMap(Account::getType, account -> account.getAmount()
.multiply(BigDecimal.valueOf(account.getCurrency().rate))
.round(new MathContext(6, RoundingMode.DOWN)), BigDecimal::add));
}
/**
* Zwraca sumę kwadratów wieków wszystkich użytkowników.
*/
int getAgeSquaresSum() {
return getUserStream()
.mapToInt(User::getAge)
.map(p -> (int) Math.pow(p, 2)).sum();
}
/**
* Metoda zwraca N losowych użytkowników (liczba jest stała). Skorzystaj z metody generate. Użytkownicy nie mogą się
* powtarzać, wszystkie zmienną muszą być final. Jeżeli podano liczbę większą niż liczba użytkowników należy
* wyrzucić wyjątek (bez zmiany sygnatury metody).
*/
List<User> getRandomUsers(final int n) {
final UserMockGenerator userMockGenerator = new UserMockGenerator();
return Optional.of(userMockGenerator.generate().stream()
.collect(Collectors.collectingAndThen(Collectors.toList(), collected -> {
Collections.shuffle(collected);
return collected.stream();
}))
.limit(n)
.distinct()
.collect(Collectors.toList()))
.orElseThrow(ArrayIndexOutOfBoundsException::new);
}
/**
* Zwraca strumień wszystkich firm.
*/
private Stream<Company> getCompanyStream() {
return holdings.stream()
.flatMap(holding -> holding.getCompanies().stream());
}
/**
* Zwraca zbiór walut w jakich są rachunki.
*/
private Set<Currency> getCurenciesSet() {
return getAccoutStream()
.map(Account::getCurrency)
.collect(Collectors.toSet());
}
/**
* Tworzy strumień rachunków.
*/
private Stream<Account> getAccoutStream() {
return getUserStream()
.flatMap(user -> user.getAccounts().stream());
}
/**
* Tworzy strumień użytkowników.
*/
private Stream<User> getUserStream() {
return getCompanyStream()
.flatMap(company -> company.getUsers().stream());
}
/**
* 38.
* Stwórz mapę gdzie kluczem jest typ rachunku a wartością mapa mężczyzn posiadających ten rachunek, gdzie kluczem
* jest obiekt User a wartością suma pieniędzy na rachunku danego typu przeliczona na złotkówki.
*/
//TODO: zamiast Map<Stream<AccountType>, Map<User, BigDecimal>> metoda ma zwracać
// Map<AccountType>, Map<User, BigDecimal>>, zweryfikować działania metody
Map<Stream<AccountType>, Map<User, BigDecimal>> getMapWithAccountTypeKeyAndSumMoneyForManInPLN() {
return getCompanyStream()
.collect(Collectors.toMap(
company -> company.getUsers()
.stream()
.flatMap(user -> user.getAccounts()
.stream()
.map(Account::getType)),
this::manWithSumMoneyOnAccounts
));
}
private Map<User, BigDecimal> manWithSumMoneyOnAccounts(final Company company) {
return company
.getUsers()
.stream()
.filter(isMan)
.collect(Collectors.toMap(
Function.identity(),
this::getSumUserAmountInPLN
));
}
private BigDecimal getSumUserAmountInPLN(final User user) {
return user.getAccounts()
.stream()
.map(this::getAccountAmountInPLN)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* 39. Policz ile pieniędzy w złotówkach jest na kontach osób które nie są ani kobietą ani mężczyzną.
*/
BigDecimal getSumMoneyOnAccountsForPeopleOtherInPLN() {
return getUserStream()
.filter(user -> user.getSex().equals(Sex.OTHER))
.map(this::getUserAmountInPLN)
.reduce(BigDecimal.ZERO, BigDecimal::add)
.round(MathContext.DECIMAL32);
}
/**
* 40. Wymyśl treść polecenia i je zaimplementuj.
* Policz ile osób pełnoletnich posiada rachunek oraz ile osób niepełnoletnich posiada rachunek. Zwróć mapę
* przyjmując klucz True dla osób pełnoletnich i klucz False dla osób niepełnoletnich. Osoba pełnoletnia to osoba
* która ma więcej lub równo 18 lat
*/
Map<Boolean, Long> divideIntoAdultsAndNonAdults() {
Predicate<User> ofAge = u -> u.getAge() >= 18;
return getUserStream()
.collect(Collectors.partitioningBy(ofAge, Collectors.counting()));
}
}
| f |
10094_1 | kon-mat/SAN | 623 | Semestr 5/Programowanie współbieżne/Tworzenie watkow/src/main/java/Fifth/CorrectConsumerProducer.java | package Fifth;
import java.time.Duration;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class CorrectConsumerProducer {
private static final Random generator = new Random();
private static final Queue<String> queue = new LinkedList<>();
public static void main(String[] args) {
int itemCount = 5;
Thread producer = new Thread(() -> {
for (int i = 0; i < itemCount; i++) {
try {
Thread.sleep(Duration.ofSeconds(generator.nextInt(5)).toMillis());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (queue) {
queue.add("Item no. " + i);
queue.notify(); //dodajemy powiadomienie informując w ten sposób konsumentów o nowym elemencie.
}
}
});
Thread consumer = new Thread(() -> {
int itemsLeft = itemCount;
while (itemsLeft > 0) {
String item;
synchronized (queue) {
//Specyfikacja języka Java pozwala na fałszywe wybudzenia (ang. spurious wake-ups). Są to wybudzenia, które mogą wystąpić nawet gdy nie było odpowiadającego im powiadomienia – wywołania metody notify. Dlatego właśnie sprawdzenie warunku (queue.isEmpty()) musi być wykonane w pętli.
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e2) {
throw new RuntimeException(e2);
}
}
item = queue.poll();
}
itemsLeft--;
System.out.println("Consumer got item: " + item);
}
});
consumer.start();
producer.start();
}
}
| //Specyfikacja języka Java pozwala na fałszywe wybudzenia (ang. spurious wake-ups). Są to wybudzenia, które mogą wystąpić nawet gdy nie było odpowiadającego im powiadomienia – wywołania metody notify. Dlatego właśnie sprawdzenie warunku (queue.isEmpty()) musi być wykonane w pętli. | package Fifth;
import java.time.Duration;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class CorrectConsumerProducer {
private static final Random generator = new Random();
private static final Queue<String> queue = new LinkedList<>();
public static void main(String[] args) {
int itemCount = 5;
Thread producer = new Thread(() -> {
for (int i = 0; i < itemCount; i++) {
try {
Thread.sleep(Duration.ofSeconds(generator.nextInt(5)).toMillis());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (queue) {
queue.add("Item no. " + i);
queue.notify(); //dodajemy powiadomienie informując w ten sposób konsumentów o nowym elemencie.
}
}
});
Thread consumer = new Thread(() -> {
int itemsLeft = itemCount;
while (itemsLeft > 0) {
String item;
synchronized (queue) {
//Specyfikacja języka <SUF>
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e2) {
throw new RuntimeException(e2);
}
}
item = queue.poll();
}
itemsLeft--;
System.out.println("Consumer got item: " + item);
}
});
consumer.start();
producer.start();
}
}
| f |
3876_0 | kottajl/oolab | 454 | src/main/java/agh/ics/oop/Grass.java | package agh.ics.oop;
import java.util.Objects;
public class Grass {
/**
* W mojej opinii dodawanie tu klasy abstrakcyjnej AbstractWorldMapElement jest bez sensu, bo klasy
* Animal oraz Grass mają stosunkowo mało cech wspólnych - praktycznie tylko coś takiego jak "pozycja",
* lecz musiałbym pozmieniać nazwy w kodzie, a uważam, że trawa ma mieć "pozycję", a zwierzę ma mieć
* aktualną "lokalizację". Ponadto nazw metod też bym nie mógł zmienić, gdyż w sporej części dostałem
* w poleceniu jasny opis tych nazw dla konkretnych metod.
*
* Analogicznie z interfejsem IMapElement - oprócz tego "getPosition" (gdzie chcę zachować indywidualne
* nazewnictwo) wszystko jest praktycznie inne. Dla samego toString nie ma raczej sensu.
*/
private final Vector2d position;
public Grass (Vector2d position) {
this.position= position;
}
public Vector2d getPosition () {
return position;
}
public String toString () {
return "*";
}
@Override
public boolean equals (Object other) {
if (this == other)
return true;
if (!(other instanceof Grass))
return false;
Grass that = (Grass) other;
return this.position.equals(that.position);
}
@Override
public int hashCode() {
return Objects.hash(position);
}
}
| /**
* W mojej opinii dodawanie tu klasy abstrakcyjnej AbstractWorldMapElement jest bez sensu, bo klasy
* Animal oraz Grass mają stosunkowo mało cech wspólnych - praktycznie tylko coś takiego jak "pozycja",
* lecz musiałbym pozmieniać nazwy w kodzie, a uważam, że trawa ma mieć "pozycję", a zwierzę ma mieć
* aktualną "lokalizację". Ponadto nazw metod też bym nie mógł zmienić, gdyż w sporej części dostałem
* w poleceniu jasny opis tych nazw dla konkretnych metod.
*
* Analogicznie z interfejsem IMapElement - oprócz tego "getPosition" (gdzie chcę zachować indywidualne
* nazewnictwo) wszystko jest praktycznie inne. Dla samego toString nie ma raczej sensu.
*/ | package agh.ics.oop;
import java.util.Objects;
public class Grass {
/**
* W mojej opinii <SUF>*/
private final Vector2d position;
public Grass (Vector2d position) {
this.position= position;
}
public Vector2d getPosition () {
return position;
}
public String toString () {
return "*";
}
@Override
public boolean equals (Object other) {
if (this == other)
return true;
if (!(other instanceof Grass))
return false;
Grass that = (Grass) other;
return this.position.equals(that.position);
}
@Override
public int hashCode() {
return Objects.hash(position);
}
}
| f |
9124_0 | kozuchowski/RoutTracker | 421 | src/main/java/com/example/routtracker/controller/TripsController.java | package com.example.routtracker.controller;
import com.example.routtracker.model.Trip;
import com.example.routtracker.repository.TripRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
@RestController()
@RequestMapping("/api")
public class TripsController {
@Autowired
TripRepository repository;
@PostMapping ("/addTrip")
public Trip addTrip (@RequestParam("origin") String origin,
@RequestParam("destination") String destination,
@RequestParam("amount") BigDecimal amount ){
Trip trip = new Trip(origin, destination, amount);
repository.save(trip);
return trip;
}
@GetMapping("/trip")
public Trip getTripById (@RequestParam("id") Long id){
Optional<Trip> trip = repository.findById(id);
if(trip.isPresent()){
return trip.get();
}
//I know, I know - muszę przypomnieć sobie optionale i zmienię to ;)
return null;
}
@GetMapping("/trips")
public List<Trip> getAllTrips (){
List<Trip> trips = repository.findAll();
return trips;
}
@GetMapping("/deleteTrip")
public String deleteTRipById (@RequestParam("id") Long id){
repository.deleteTripById(id);
return "Deleted";
}
}
| //I know, I know - muszę przypomnieć sobie optionale i zmienię to ;) | package com.example.routtracker.controller;
import com.example.routtracker.model.Trip;
import com.example.routtracker.repository.TripRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
@RestController()
@RequestMapping("/api")
public class TripsController {
@Autowired
TripRepository repository;
@PostMapping ("/addTrip")
public Trip addTrip (@RequestParam("origin") String origin,
@RequestParam("destination") String destination,
@RequestParam("amount") BigDecimal amount ){
Trip trip = new Trip(origin, destination, amount);
repository.save(trip);
return trip;
}
@GetMapping("/trip")
public Trip getTripById (@RequestParam("id") Long id){
Optional<Trip> trip = repository.findById(id);
if(trip.isPresent()){
return trip.get();
}
//I know, <SUF>
return null;
}
@GetMapping("/trips")
public List<Trip> getAllTrips (){
List<Trip> trips = repository.findAll();
return trips;
}
@GetMapping("/deleteTrip")
public String deleteTRipById (@RequestParam("id") Long id){
repository.deleteTripById(id);
return "Deleted";
}
}
| f |
9826_0 | kpiotrowski/Drone_control_system_JAVA | 501 | src/dataModels/Dron.java | package dataModels;
import com.sun.istack.internal.NotNull;
import javax.xml.ws.soap.Addressing;
import java.lang.annotation.Target;
import lombok.Getter;
import lombok.Setter;
public class Dron extends DataModel {
public static final int STATUS_WOLNY = 0;
public static final int STATUS_PRZYDZIELONY_DO_ZADANIA = 1;
private static final int STATUS_WYKONUJE_ZADANIE = 2;
private static final int STATUS_WYŁĄCZONY = 3;
@Getter @Setter private Integer id;
@Getter @Setter private String nazwa;
@Getter @Setter private String opis;
@Getter @Setter private Float masa;
@Getter @Setter private Integer ilosc_wirnikow;
@Getter @Setter private Float max_predkosc;
@Getter @Setter private Float max_czas_lotu;
@Getter @Setter private Float poziom_baterii;
@Getter @Setter private Float wspx;
@Getter @Setter private Float wspy;
@Getter @Setter private Float wspz;
@Setter @Getter private Integer stan;
@Getter @Setter private Integer punkt_kontrolny_id;
public String getStanString(){
//Zawsze chciałem to zrobić :)
if(this.stan==null) return "other";
return this.stan==STATUS_WOLNY ? "free" :
(this.stan==STATUS_PRZYDZIELONY_DO_ZADANIA ? "assigned to job" :
(this.stan==STATUS_WYKONUJE_ZADANIE ? "job in progress" :
(this.stan==STATUS_WYŁĄCZONY ? "not available" : "other")));
}
} | //Zawsze chciałem to zrobić :) | package dataModels;
import com.sun.istack.internal.NotNull;
import javax.xml.ws.soap.Addressing;
import java.lang.annotation.Target;
import lombok.Getter;
import lombok.Setter;
public class Dron extends DataModel {
public static final int STATUS_WOLNY = 0;
public static final int STATUS_PRZYDZIELONY_DO_ZADANIA = 1;
private static final int STATUS_WYKONUJE_ZADANIE = 2;
private static final int STATUS_WYŁĄCZONY = 3;
@Getter @Setter private Integer id;
@Getter @Setter private String nazwa;
@Getter @Setter private String opis;
@Getter @Setter private Float masa;
@Getter @Setter private Integer ilosc_wirnikow;
@Getter @Setter private Float max_predkosc;
@Getter @Setter private Float max_czas_lotu;
@Getter @Setter private Float poziom_baterii;
@Getter @Setter private Float wspx;
@Getter @Setter private Float wspy;
@Getter @Setter private Float wspz;
@Setter @Getter private Integer stan;
@Getter @Setter private Integer punkt_kontrolny_id;
public String getStanString(){
//Zawsze chciałem <SUF>
if(this.stan==null) return "other";
return this.stan==STATUS_WOLNY ? "free" :
(this.stan==STATUS_PRZYDZIELONY_DO_ZADANIA ? "assigned to job" :
(this.stan==STATUS_WYKONUJE_ZADANIE ? "job in progress" :
(this.stan==STATUS_WYŁĄCZONY ? "not available" : "other")));
}
} | f |
9891_0 | krystianres2/java-inne | 534 | lesson8/src/lesson8.java | import java.util.Random;
import java.util.Scanner;
public class lesson8 {
public static void main(String[] args){
/* int ile=0, licz, odp;
Scanner scanner=new Scanner(System.in);
Random rnd=new Random();
licz=rnd.nextInt(10);
System.out.println("Zgadnij liczbę od 0 do 9");
do{
ile++;
System.out.println("Podaj liczbę: ");
odp=scanner.nextInt();
if(odp>licz){
System.out.println("Mniejsza ");
}
if(odp<licz){
System.out.println("Większa");
}
}while(odp!=licz);
System.out.println("Zgadłeś za " + ile + " razem");*/
int a,b,wyb=0;
Scanner scanner=new Scanner(System.in);
System.out.println("Podaj liczbe a: ");
a= scanner.nextInt();
System.out.println("Podaj liczbe b: ");
b= scanner.nextInt();
while(wyb!=5) {
System.out.println("1. dodaj");
System.out.println("2. odejmij");
System.out.println("3. pomnóż");
System.out.println("4. podziel");
System.out.println("5. wyjdz");
System.out.println("Co chesz zrobić: ");
wyb= scanner.nextInt();
switch (wyb) {
case 1:
System.out.println(a + b);
break;
case 2:
System.out.println(a - b);
break;
case 3:
System.out.println(a * b);
break;
case 4:
System.out.println(a / b);
break;
default:
System.out.println("nie");
}
}//while
}
}
| /* int ile=0, licz, odp;
Scanner scanner=new Scanner(System.in);
Random rnd=new Random();
licz=rnd.nextInt(10);
System.out.println("Zgadnij liczbę od 0 do 9");
do{
ile++;
System.out.println("Podaj liczbę: ");
odp=scanner.nextInt();
if(odp>licz){
System.out.println("Mniejsza ");
}
if(odp<licz){
System.out.println("Większa");
}
}while(odp!=licz);
System.out.println("Zgadłeś za " + ile + " razem");*/ | import java.util.Random;
import java.util.Scanner;
public class lesson8 {
public static void main(String[] args){
/* int ile=0, licz, <SUF>*/
int a,b,wyb=0;
Scanner scanner=new Scanner(System.in);
System.out.println("Podaj liczbe a: ");
a= scanner.nextInt();
System.out.println("Podaj liczbe b: ");
b= scanner.nextInt();
while(wyb!=5) {
System.out.println("1. dodaj");
System.out.println("2. odejmij");
System.out.println("3. pomnóż");
System.out.println("4. podziel");
System.out.println("5. wyjdz");
System.out.println("Co chesz zrobić: ");
wyb= scanner.nextInt();
switch (wyb) {
case 1:
System.out.println(a + b);
break;
case 2:
System.out.println(a - b);
break;
case 3:
System.out.println(a * b);
break;
case 4:
System.out.println(a / b);
break;
default:
System.out.println("nie");
}
}//while
}
}
| f |
5690_1 | krzJozef/Magnetic | 760 | src/main/java/pl/grzegorz2047/magnetic/Main.java | package pl.grzegorz2047.magnetic;
import javafx.application.Application;
import javafx.stage.Stage;
import pl.grzegorz2047.magnetic.window.SimulationStartWindow;
import static java.lang.Thread.sleep;
/**
* Plik stworzony przez grzegorz2047 27.04.2017.
*/
public class Main extends Application {
/*
Wykonujesz obliczenia dla modelu (50,1, 50000), (50, 2, 50000),(50, 3, 50000),(50, 4, 50000),(50, 5, 50000)
oraz wartości wokół 2.4 czyli np. 2.1, 2.2, 2.3 ,2.4, 2.5
Dla każdego modelu robisz wykres przedstawiający magnetyzację do czasu MCS co dziesięć MCS
Potem z tych wszystkich średnich wyliczonych z modelu oraz ich temperatur robisz wykres pokazujący
jak zachowuje się magnetyzacja dla danych temperatur.
Całość możesz robić na raz używając osobnych wątków po skończeniu przy okazji zapisz magnetyzację do pliku.
Najlepiej w pliku dawaj magnetyzację co linię.
Ewentualnie możesz robić czas MCS : magnetyzacja, żeby widzieć co i jak
Po zapisaniu do plików wartości wrzuconych z wykresów, bierzesz od której linii ma brać wartości linia = DANY MCS
a w linii jest dana magnetyzacja w danym MCS.
Robisz sobie jeszcze jedno okno, gdzie podajesz nazwę pliku, z którego ma brać wartości, podajesz od którego MCSa
ma brać magnetyzacje i jeszcze przycisk, żeby rozpoczył przetwarzanie pliku. Po zakończeniu przetwarzania w labelu
wyświetla się średnia.
Potem tę średnia bierzesz do innego okna, gdzie dodajesz sobie średnia magnetyzacja dla danej temperatury.
Potrzebujesz przycisk dodaj, który dokłada punkt do wykresu, ewentualnie przycisk do pokazywania wykresu i chowania
*/
@Override
public void start(Stage stage) {
SimulationStartWindow simulationStartWindow = new SimulationStartWindow();
simulationStartWindow.show();
}
@Override
public void stop() throws Exception {
}
public static void main(String[] args) {
launch(args);
}
} | /*
Wykonujesz obliczenia dla modelu (50,1, 50000), (50, 2, 50000),(50, 3, 50000),(50, 4, 50000),(50, 5, 50000)
oraz wartości wokół 2.4 czyli np. 2.1, 2.2, 2.3 ,2.4, 2.5
Dla każdego modelu robisz wykres przedstawiający magnetyzację do czasu MCS co dziesięć MCS
Potem z tych wszystkich średnich wyliczonych z modelu oraz ich temperatur robisz wykres pokazujący
jak zachowuje się magnetyzacja dla danych temperatur.
Całość możesz robić na raz używając osobnych wątków po skończeniu przy okazji zapisz magnetyzację do pliku.
Najlepiej w pliku dawaj magnetyzację co linię.
Ewentualnie możesz robić czas MCS : magnetyzacja, żeby widzieć co i jak
Po zapisaniu do plików wartości wrzuconych z wykresów, bierzesz od której linii ma brać wartości linia = DANY MCS
a w linii jest dana magnetyzacja w danym MCS.
Robisz sobie jeszcze jedno okno, gdzie podajesz nazwę pliku, z którego ma brać wartości, podajesz od którego MCSa
ma brać magnetyzacje i jeszcze przycisk, żeby rozpoczył przetwarzanie pliku. Po zakończeniu przetwarzania w labelu
wyświetla się średnia.
Potem tę średnia bierzesz do innego okna, gdzie dodajesz sobie średnia magnetyzacja dla danej temperatury.
Potrzebujesz przycisk dodaj, który dokłada punkt do wykresu, ewentualnie przycisk do pokazywania wykresu i chowania
*/ | package pl.grzegorz2047.magnetic;
import javafx.application.Application;
import javafx.stage.Stage;
import pl.grzegorz2047.magnetic.window.SimulationStartWindow;
import static java.lang.Thread.sleep;
/**
* Plik stworzony przez grzegorz2047 27.04.2017.
*/
public class Main extends Application {
/*
Wykonujesz obliczenia dla <SUF>*/
@Override
public void start(Stage stage) {
SimulationStartWindow simulationStartWindow = new SimulationStartWindow();
simulationStartWindow.show();
}
@Override
public void stop() throws Exception {
}
public static void main(String[] args) {
launch(args);
}
} | f |
6875_10 | krzynio/Liner2 | 3,818 | g419-corpus/src/main/java/g419/corpus/io/writer/ZeroVerbWriter.java | package g419.corpus.io.writer;
import g419.corpus.structure.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Pattern;
//import java.io.BufferedOutputStream;
public class ZeroVerbWriter extends AbstractDocumentWriter{
private static final String AGLT_CLASS = "aglt";
private static final String QUB_CLASS = "qub";
private OutputStream os;
private static List<String> verbPos = Arrays.asList(new String[]{"fin", "praet", "winien", "bedzie", "aglt"});
private static int zeroVerbCount = 0;
private static int verbCount = 0;
private static int undelZeroAglt = 0;
private static boolean delAglt = false;
private static boolean delQub = false;
private static boolean delVerb = false;
private static String docid = "";
public ZeroVerbWriter(OutputStream os){
this.os = os;
}
public ZeroVerbWriter(){
this.os = new ByteArrayOutputStream();
}
// public static String[] convertSentence(Sentence s){
// int index = 0;
// String[] sentenceConll = new String[s.getTokenNumber()];
// TokenAttributeIndex ai = s.getAttributeIndex();
// for(Token t : s.getTokens()){
// sentenceConll[index] = convertToken(t, ai, ++index);
// }
// return sentenceConll;
// }
private void writeSentence(Sentence s) throws IOException{
int index = 0;
TokenAttributeIndex ai = s.getAttributeIndex();
// System.out.println(s.annotationsToString());
LinkedHashSet<Annotation> zeroAnnotations = s.getAnnotations(Arrays.asList(new Pattern[]{
// Pattern.compile("anafora_verb_null.*"),
// Pattern.compile("anafora_wyznacznik")
Pattern.compile("mention")
}));
TreeSet<Integer> zeroTokens = new TreeSet<>();
for(Annotation zeroAnnotation : zeroAnnotations){
boolean onlyVerbs = true;
for(Integer zeroToken: zeroAnnotation.getTokens()){
if(!verbPos.contains(ai.getAttributeValue(s.getTokens().get(zeroToken), "ctag").split(":")[0])){
onlyVerbs = false;
break;
}
}
if(onlyVerbs){
zeroTokens.addAll(zeroAnnotation.getTokens());
}
}
// System.out.println(zeroTokens);
for(Token t : s.getTokens()){
boolean zeroVerb = zeroTokens.contains(s.getTokens().indexOf(t));
boolean zero1 = zeroTokens.contains(s.getTokens().indexOf(t) + 1);
boolean zero2 = zeroTokens.contains(s.getTokens().indexOf(t) + 2);
this.os.write(convertToken(t, ai, ++index, zeroVerb, zero1, zero2, s).getBytes());
//writeToken(t, ai, ++index);
}
};
public static String convertToken(Token t, TokenAttributeIndex ai, int tokenIndex, boolean zeroVerb, boolean zero1, boolean zero2, Sentence sentence){
String orth = t.getOrth();
String base = ai.getAttributeValue(t, "base");
String posext = ai.getAttributeValue(t, "class");
String pos = ai.getAttributeValue(t, "pos");
String ctag = "";
String cpos = null;
String label = "N";
Tag disambTag = t.getTags().get(0);
for(Tag iterTag : t.getTags())
if(iterTag.getDisamb())
disambTag = iterTag;
// for(Tag tag : t.getTags()){
// if(tag.getDisamb() || t.getTags().size() == 1){
Tag tag = disambTag;
int firstSep = Math.max(0, tag.getCtag().indexOf(":"));
if(firstSep > 0) cpos = tag.getCtag().substring(0, firstSep);
ctag = tag.getCtag().substring(tag.getCtag().indexOf(":") + 1).replace(":", "|");
if(ctag.equals(pos) || ctag.equals(posext)) ctag = "_";
if(pos == null && posext == null){
if(cpos != null){
pos = cpos;
posext = cpos;
}
else{
pos = ctag;
posext = ctag;
ctag = "_";
}
}
if(pos.startsWith(AGLT_CLASS) && delAglt){
delAglt = false;
return "";
}
if(pos.startsWith(QUB_CLASS) && delQub){
delQub = false;
return "";
}
if(verbPos.contains(pos) && !pos.equalsIgnoreCase(AGLT_CLASS) && !pos.equalsIgnoreCase(QUB_CLASS) && delVerb){
delVerb = false;
return "";
}
// }
// }
//TODO: ctag dla interp conj, etc.
//TODO: iż -> dlaczego nie ma pos?
if(verbPos.contains(pos) && !pos.equalsIgnoreCase(AGLT_CLASS)){
// 1. verb + aglt
if(tokenIndex < sentence.getTokens().size()){
Token agltCandidate = sentence.getTokens().get(tokenIndex);
if(AGLT_CLASS.equalsIgnoreCase(ai.getAttributeValue(agltCandidate, "ctag").split(":")[0])){
String agltCtag = ai.getAttributeValue(agltCandidate, "ctag");
String person = "ter";
if(agltCtag.startsWith("pri:") || agltCtag.endsWith(":pri") || agltCtag.contains(":pri:")) person = "pri";
if(agltCtag.startsWith("sec:") || agltCtag.endsWith(":sec") || agltCtag.contains(":sec:")) person = "sec";
pos = pos + "|" + person;
orth = orth + ai.getAttributeValue(agltCandidate, "orth");
delAglt = true;
zeroVerb = zeroVerb || zero1;
}
}
// 2. verb + qub + aglt
if(tokenIndex + 1 < sentence.getTokens().size()){
Token qubCandidate = sentence.getTokens().get(tokenIndex);
Token agltCandidate = sentence.getTokens().get(tokenIndex + 1);
if(AGLT_CLASS.equalsIgnoreCase(ai.getAttributeValue(agltCandidate, "ctag").split(":")[0]) && QUB_CLASS.equalsIgnoreCase(ai.getAttributeValue(qubCandidate, "ctag").split(":")[0])){
String person = ai.getAttributeValue(agltCandidate, "person");
pos = pos + "|" + person;
orth = orth + ai.getAttributeValue(qubCandidate, "orth") + ai.getAttributeValue(agltCandidate, "orth");
delAglt = true;
delQub = true;
zeroVerb = zeroVerb || zero2;
}
}
verbCount++;
label = "V";
if(zeroVerb){
label = "Z";
zeroVerbCount ++;
// System.out.println("ZERO");
// System.out.println(zeroVerbCount);
// System.out.println(orth);
}
}
else if (pos.equalsIgnoreCase(AGLT_CLASS)){
// Aglutynant
String prec = "", foll = "";
boolean precQub = false, follVb = false, fem = false, sg = false, pri = false, sec = false, ter = true;
pri = ctag.contains("|pri|") || ctag.startsWith("pri|") || ctag.endsWith("|pri");
sec = ctag.contains("|sec|") || ctag.startsWith("sec|") || ctag.endsWith("|sec");
ter = !pri && !sec;
try{
prec = sentence.getTokens().get(tokenIndex - 2).getOrth();
precQub = QUB_CLASS.equalsIgnoreCase(ai.getAttributeValue(sentence.getTokens().get(tokenIndex - 2), "ctag").split(":")[0]);
}catch(Exception e){}
for(int i = tokenIndex; i < Math.min(i+5, sentence.getTokenNumber()); i++){
Token vst = sentence.getTokens().get(i);
follVb = verbPos.contains(ai.getAttributeValue(vst, "ctag").split(":")[0]);
if(follVb){
fem = ai.getAttributeValue(vst, "ctag").contains(":f:") || ai.getAttributeValue(vst, "ctag").startsWith("f:") || ai.getAttributeValue(vst, "ctag").endsWith(":f");
sg = ai.getAttributeValue(vst, "ctag").contains(":sg:") || ai.getAttributeValue(vst, "ctag").startsWith("sg:") || ai.getAttributeValue(vst, "ctag").endsWith(":sg");
foll = vst.getOrth();
break;
}
}
if(precQub && follVb){
// System.out.println("FIRST RULE: " + prec + " " + orth + " " + foll + " ---> " + foll + prec + orth);
System.out.println(docid + " FIRST RULE ALT: " + prec + " " + orth + " " + foll + " ---> " + prec + " " + foll + (fem||!sg?"":"e") + orth);
orth = foll + (fem||!sg?"":"e") + orth;
delVerb = true;
}
else if (follVb){
System.out.println(docid +" SECOND RULE: " + prec + " " + orth + " " + foll + " ---> " + prec + " " + foll + (fem||!sg?"":"e") + orth);
orth = foll + (fem||!sg?"":"e") + orth;
delVerb = true;
}
else System.out.println(docid + " SHIT: " + prec + " " + orth + " " + foll);
label = "V";
if(zeroVerb) {
label = "Z";
// zeroVerbCount++;
undelZeroAglt++;
}
else{
System.out.println("NONZERO AGLT FIX");
}
}
return String.format("%d\t%s\t%s\t%s\t%s\t%s\n", tokenIndex, orth, base, pos, ctag, label);
// return String.format("%d\t%s\t%s\t%s\t%s\t%s\t_\t_\t_\t_\n", tokenIndex, orth, base, pos, posext, ctag);
};
public String getStreamAsString(){
return this.os.toString();
}
private void writeNewLine() throws IOException{
this.os.write("\n".getBytes());
}
@Override
public void writeDocument(Document document) {
docid = document.getName();
for(Sentence s: document.getSentences()){
try {
writeSentence(s);
writeNewLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
docid = "";
// System.out.println(document.getName());
// System.out.println("VERBS IN TOTAL: "+verbCount);
// System.out.println("ZERO VERBS IN TOTAL: "+ zeroVerbCount);
// System.out.println("ZERO VERBS IN TOTAL (W. AGLT): "+ (zeroVerbCount + undelZeroAglt));
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void close() {
// TODO Auto-generated method stub
}
}
| //TODO: iż -> dlaczego nie ma pos? | package g419.corpus.io.writer;
import g419.corpus.structure.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Pattern;
//import java.io.BufferedOutputStream;
public class ZeroVerbWriter extends AbstractDocumentWriter{
private static final String AGLT_CLASS = "aglt";
private static final String QUB_CLASS = "qub";
private OutputStream os;
private static List<String> verbPos = Arrays.asList(new String[]{"fin", "praet", "winien", "bedzie", "aglt"});
private static int zeroVerbCount = 0;
private static int verbCount = 0;
private static int undelZeroAglt = 0;
private static boolean delAglt = false;
private static boolean delQub = false;
private static boolean delVerb = false;
private static String docid = "";
public ZeroVerbWriter(OutputStream os){
this.os = os;
}
public ZeroVerbWriter(){
this.os = new ByteArrayOutputStream();
}
// public static String[] convertSentence(Sentence s){
// int index = 0;
// String[] sentenceConll = new String[s.getTokenNumber()];
// TokenAttributeIndex ai = s.getAttributeIndex();
// for(Token t : s.getTokens()){
// sentenceConll[index] = convertToken(t, ai, ++index);
// }
// return sentenceConll;
// }
private void writeSentence(Sentence s) throws IOException{
int index = 0;
TokenAttributeIndex ai = s.getAttributeIndex();
// System.out.println(s.annotationsToString());
LinkedHashSet<Annotation> zeroAnnotations = s.getAnnotations(Arrays.asList(new Pattern[]{
// Pattern.compile("anafora_verb_null.*"),
// Pattern.compile("anafora_wyznacznik")
Pattern.compile("mention")
}));
TreeSet<Integer> zeroTokens = new TreeSet<>();
for(Annotation zeroAnnotation : zeroAnnotations){
boolean onlyVerbs = true;
for(Integer zeroToken: zeroAnnotation.getTokens()){
if(!verbPos.contains(ai.getAttributeValue(s.getTokens().get(zeroToken), "ctag").split(":")[0])){
onlyVerbs = false;
break;
}
}
if(onlyVerbs){
zeroTokens.addAll(zeroAnnotation.getTokens());
}
}
// System.out.println(zeroTokens);
for(Token t : s.getTokens()){
boolean zeroVerb = zeroTokens.contains(s.getTokens().indexOf(t));
boolean zero1 = zeroTokens.contains(s.getTokens().indexOf(t) + 1);
boolean zero2 = zeroTokens.contains(s.getTokens().indexOf(t) + 2);
this.os.write(convertToken(t, ai, ++index, zeroVerb, zero1, zero2, s).getBytes());
//writeToken(t, ai, ++index);
}
};
public static String convertToken(Token t, TokenAttributeIndex ai, int tokenIndex, boolean zeroVerb, boolean zero1, boolean zero2, Sentence sentence){
String orth = t.getOrth();
String base = ai.getAttributeValue(t, "base");
String posext = ai.getAttributeValue(t, "class");
String pos = ai.getAttributeValue(t, "pos");
String ctag = "";
String cpos = null;
String label = "N";
Tag disambTag = t.getTags().get(0);
for(Tag iterTag : t.getTags())
if(iterTag.getDisamb())
disambTag = iterTag;
// for(Tag tag : t.getTags()){
// if(tag.getDisamb() || t.getTags().size() == 1){
Tag tag = disambTag;
int firstSep = Math.max(0, tag.getCtag().indexOf(":"));
if(firstSep > 0) cpos = tag.getCtag().substring(0, firstSep);
ctag = tag.getCtag().substring(tag.getCtag().indexOf(":") + 1).replace(":", "|");
if(ctag.equals(pos) || ctag.equals(posext)) ctag = "_";
if(pos == null && posext == null){
if(cpos != null){
pos = cpos;
posext = cpos;
}
else{
pos = ctag;
posext = ctag;
ctag = "_";
}
}
if(pos.startsWith(AGLT_CLASS) && delAglt){
delAglt = false;
return "";
}
if(pos.startsWith(QUB_CLASS) && delQub){
delQub = false;
return "";
}
if(verbPos.contains(pos) && !pos.equalsIgnoreCase(AGLT_CLASS) && !pos.equalsIgnoreCase(QUB_CLASS) && delVerb){
delVerb = false;
return "";
}
// }
// }
//TODO: ctag dla interp conj, etc.
//TODO: iż <SUF>
if(verbPos.contains(pos) && !pos.equalsIgnoreCase(AGLT_CLASS)){
// 1. verb + aglt
if(tokenIndex < sentence.getTokens().size()){
Token agltCandidate = sentence.getTokens().get(tokenIndex);
if(AGLT_CLASS.equalsIgnoreCase(ai.getAttributeValue(agltCandidate, "ctag").split(":")[0])){
String agltCtag = ai.getAttributeValue(agltCandidate, "ctag");
String person = "ter";
if(agltCtag.startsWith("pri:") || agltCtag.endsWith(":pri") || agltCtag.contains(":pri:")) person = "pri";
if(agltCtag.startsWith("sec:") || agltCtag.endsWith(":sec") || agltCtag.contains(":sec:")) person = "sec";
pos = pos + "|" + person;
orth = orth + ai.getAttributeValue(agltCandidate, "orth");
delAglt = true;
zeroVerb = zeroVerb || zero1;
}
}
// 2. verb + qub + aglt
if(tokenIndex + 1 < sentence.getTokens().size()){
Token qubCandidate = sentence.getTokens().get(tokenIndex);
Token agltCandidate = sentence.getTokens().get(tokenIndex + 1);
if(AGLT_CLASS.equalsIgnoreCase(ai.getAttributeValue(agltCandidate, "ctag").split(":")[0]) && QUB_CLASS.equalsIgnoreCase(ai.getAttributeValue(qubCandidate, "ctag").split(":")[0])){
String person = ai.getAttributeValue(agltCandidate, "person");
pos = pos + "|" + person;
orth = orth + ai.getAttributeValue(qubCandidate, "orth") + ai.getAttributeValue(agltCandidate, "orth");
delAglt = true;
delQub = true;
zeroVerb = zeroVerb || zero2;
}
}
verbCount++;
label = "V";
if(zeroVerb){
label = "Z";
zeroVerbCount ++;
// System.out.println("ZERO");
// System.out.println(zeroVerbCount);
// System.out.println(orth);
}
}
else if (pos.equalsIgnoreCase(AGLT_CLASS)){
// Aglutynant
String prec = "", foll = "";
boolean precQub = false, follVb = false, fem = false, sg = false, pri = false, sec = false, ter = true;
pri = ctag.contains("|pri|") || ctag.startsWith("pri|") || ctag.endsWith("|pri");
sec = ctag.contains("|sec|") || ctag.startsWith("sec|") || ctag.endsWith("|sec");
ter = !pri && !sec;
try{
prec = sentence.getTokens().get(tokenIndex - 2).getOrth();
precQub = QUB_CLASS.equalsIgnoreCase(ai.getAttributeValue(sentence.getTokens().get(tokenIndex - 2), "ctag").split(":")[0]);
}catch(Exception e){}
for(int i = tokenIndex; i < Math.min(i+5, sentence.getTokenNumber()); i++){
Token vst = sentence.getTokens().get(i);
follVb = verbPos.contains(ai.getAttributeValue(vst, "ctag").split(":")[0]);
if(follVb){
fem = ai.getAttributeValue(vst, "ctag").contains(":f:") || ai.getAttributeValue(vst, "ctag").startsWith("f:") || ai.getAttributeValue(vst, "ctag").endsWith(":f");
sg = ai.getAttributeValue(vst, "ctag").contains(":sg:") || ai.getAttributeValue(vst, "ctag").startsWith("sg:") || ai.getAttributeValue(vst, "ctag").endsWith(":sg");
foll = vst.getOrth();
break;
}
}
if(precQub && follVb){
// System.out.println("FIRST RULE: " + prec + " " + orth + " " + foll + " ---> " + foll + prec + orth);
System.out.println(docid + " FIRST RULE ALT: " + prec + " " + orth + " " + foll + " ---> " + prec + " " + foll + (fem||!sg?"":"e") + orth);
orth = foll + (fem||!sg?"":"e") + orth;
delVerb = true;
}
else if (follVb){
System.out.println(docid +" SECOND RULE: " + prec + " " + orth + " " + foll + " ---> " + prec + " " + foll + (fem||!sg?"":"e") + orth);
orth = foll + (fem||!sg?"":"e") + orth;
delVerb = true;
}
else System.out.println(docid + " SHIT: " + prec + " " + orth + " " + foll);
label = "V";
if(zeroVerb) {
label = "Z";
// zeroVerbCount++;
undelZeroAglt++;
}
else{
System.out.println("NONZERO AGLT FIX");
}
}
return String.format("%d\t%s\t%s\t%s\t%s\t%s\n", tokenIndex, orth, base, pos, ctag, label);
// return String.format("%d\t%s\t%s\t%s\t%s\t%s\t_\t_\t_\t_\n", tokenIndex, orth, base, pos, posext, ctag);
};
public String getStreamAsString(){
return this.os.toString();
}
private void writeNewLine() throws IOException{
this.os.write("\n".getBytes());
}
@Override
public void writeDocument(Document document) {
docid = document.getName();
for(Sentence s: document.getSentences()){
try {
writeSentence(s);
writeNewLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
docid = "";
// System.out.println(document.getName());
// System.out.println("VERBS IN TOTAL: "+verbCount);
// System.out.println("ZERO VERBS IN TOTAL: "+ zeroVerbCount);
// System.out.println("ZERO VERBS IN TOTAL (W. AGLT): "+ (zeroVerbCount + undelZeroAglt));
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void close() {
// TODO Auto-generated method stub
}
}
| f |
4627_0 | kucharzyk/spring-angular2-starter | 181 | shardis-ui/src/main/java/com/shardis/ui/config/ViewConfigurer.java | package com.shardis.ui.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.concurrent.TimeUnit;
/**
* Created by Tomasz Kucharzyk
*/
@Configuration
public class ViewConfigurer extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod((int) TimeUnit.HOURS.toSeconds(24L));
}
}
| /**
* Created by Tomasz Kucharzyk
*/ | package com.shardis.ui.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.concurrent.TimeUnit;
/**
* Created by Tomasz <SUF>*/
@Configuration
public class ViewConfigurer extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod((int) TimeUnit.HOURS.toSeconds(24L));
}
}
| f |
4660_0 | kucharzyk/vuejs-java-starter | 461 | src/main/java/com/shardis/controllers/rest/SampleRestController.java | package com.shardis.controllers.rest;
import com.google.common.collect.Lists;
import com.shardis.dto.user.UserPost;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.List;
/**
* Created by Tomasz Kucharzyk
*/
@RestController
@RequestMapping("/rest")
public class SampleRestController {
@RequestMapping("/test")
public List<String> test() {
return Lists.newArrayList("Vue.js", "is", "great");
}
@RequestMapping("/fail")
public List<String> fail() {
throw new RuntimeException("method failed");
}
@RequestMapping("/user/{userId}/posts")
public List<UserPost> userPosts(@PathVariable("userId") Long userId) {
List<UserPost> posts = Lists.newArrayList();
for (long i = 1; i <= 8; i++) {
posts.add(new UserPost(i, "Post #" + i + " of user " + userId, "sample content #" + i, LocalDateTime.now()));
}
return posts;
}
@RequestMapping("/user/{userId}/settings")
public List<String> userSettings(@PathVariable("userId") Long userId) throws InterruptedException {
//Don't do that at home
Thread.currentThread().sleep(1000);
List<String> settings = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
settings.add("Setting #" + i+" of user "+userId);
}
return settings;
}
}
| /**
* Created by Tomasz Kucharzyk
*/ | package com.shardis.controllers.rest;
import com.google.common.collect.Lists;
import com.shardis.dto.user.UserPost;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.List;
/**
* Created by Tomasz <SUF>*/
@RestController
@RequestMapping("/rest")
public class SampleRestController {
@RequestMapping("/test")
public List<String> test() {
return Lists.newArrayList("Vue.js", "is", "great");
}
@RequestMapping("/fail")
public List<String> fail() {
throw new RuntimeException("method failed");
}
@RequestMapping("/user/{userId}/posts")
public List<UserPost> userPosts(@PathVariable("userId") Long userId) {
List<UserPost> posts = Lists.newArrayList();
for (long i = 1; i <= 8; i++) {
posts.add(new UserPost(i, "Post #" + i + " of user " + userId, "sample content #" + i, LocalDateTime.now()));
}
return posts;
}
@RequestMapping("/user/{userId}/settings")
public List<String> userSettings(@PathVariable("userId") Long userId) throws InterruptedException {
//Don't do that at home
Thread.currentThread().sleep(1000);
List<String> settings = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
settings.add("Setting #" + i+" of user "+userId);
}
return settings;
}
}
| f |
10323_7 | kuchcik09/Ogzy | 4,332 | RibbonModule/src/org/gui/MainTopComponent.java | package org.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import org.database.models.GrupaCwiczeniowa;
import org.database.models.Termin;
import java.sql.Time;
import java.util.LinkedList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.gui.grupy_cwiczeniowe.GrupaCwiczeniowaTopComponent;
import org.netbeans.api.settings.ConvertAsProperties;
import org.officelaf.listeners.TopComponentsManagerListener;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.Mode;
import org.openide.windows.WindowManager;
/**
* Top component which displays something.
*/
@ConvertAsProperties(
dtd = "-//org.gui//Main//EN",
autostore = false
)
@TopComponent.Description(
preferredID = "MainTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE",
persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "editor", openAtStartup = true)
@ActionID(category = "Window", id = "org.gui.MainTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
displayName = "#CTL_MainAction",
preferredID = "MainTopComponent"
)
@Messages({
"CTL_MainAction=Plan zajęć",
"CTL_MainTopComponent=Plan zajęć",
"HINT_MainTopComponent=To okno ukazuje plan zajęć"
})
public final class MainTopComponent extends TopComponent {
private LinkedList<Termin> allTerms;
private Termin[][] terms = new Termin[7][7];
public Termin getTerms(int r, int c) {
return terms[r][c];
}
public MainTopComponent() {
this.allTerms = new LinkedList<Termin>();
initComponents();
setName(Bundle.CTL_MainTopComponent());
setToolTipText(Bundle.HINT_MainTopComponent());
//putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
this.termsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final MainTopComponent me = this;
ListSelectionListener tableListener = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
TopComponentsManagerListener.MainTopComponentActivated(me);
}
};
this.termsTable.getSelectionModel().addListSelectionListener(tableListener);
this.termsTable.getColumnModel().getSelectionModel().addListSelectionListener(tableListener);
this.termsTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
this.termsTable.getActionMap().put("Enter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
DefaultTableModel model = (DefaultTableModel) termsTable.getModel();
String value = (String) model.getValueAt(termsTable.getSelectedRow(), termsTable.getSelectedColumn());
if (value != null && termsTable.getSelectedColumn() > 0) {
openGroupTopComponent(terms[termsTable.getSelectedRow()][termsTable.getSelectedColumn() - 1]);
}
}
});
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
this.termsTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
this.termsTable.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(2).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(3).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(4).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(5).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(6).setCellRenderer(new CustomRenderer());
}
/**
* 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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
termsTable = new javax.swing.JTable();
setLayout(new java.awt.BorderLayout());
termsTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Czas", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
termsTable.setColumnSelectionAllowed(true);
termsTable.setRowHeight(60);
termsTable.getTableHeader().setReorderingAllowed(false);
termsTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
termsTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(termsTable);
termsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
if (termsTable.getColumnModel().getColumnCount() > 0) {
termsTable.getColumnModel().getColumn(0).setResizable(false);
termsTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title0")); // NOI18N
termsTable.getColumnModel().getColumn(1).setResizable(false);
termsTable.getColumnModel().getColumn(1).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title1")); // NOI18N
termsTable.getColumnModel().getColumn(2).setResizable(false);
termsTable.getColumnModel().getColumn(2).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title2")); // NOI18N
termsTable.getColumnModel().getColumn(3).setResizable(false);
termsTable.getColumnModel().getColumn(3).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title3")); // NOI18N
termsTable.getColumnModel().getColumn(4).setResizable(false);
termsTable.getColumnModel().getColumn(4).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title4")); // NOI18N
termsTable.getColumnModel().getColumn(5).setResizable(false);
termsTable.getColumnModel().getColumn(5).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title5")); // NOI18N
termsTable.getColumnModel().getColumn(6).setResizable(false);
termsTable.getColumnModel().getColumn(6).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title6")); // NOI18N
termsTable.getColumnModel().getColumn(7).setResizable(false);
termsTable.getColumnModel().getColumn(7).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title7")); // NOI18N
}
add(jScrollPane1, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void openGroupTopComponent(Termin term) {
List<GrupaCwiczeniowa> groups = GrupaCwiczeniowa.getAll();
GrupaCwiczeniowa grupa = null;
String grupa_name = term.getGrupa().getNazwa();
String przedmiot_name = term.getGrupa().getPrzedmiot().getNazwa();
for (int i = 0; i < groups.size(); i++) {
if (groups.get(i).getNazwa().equals(grupa_name) && groups.get(i).getPrzedmiot().getNazwa().equals(przedmiot_name)) {
grupa = groups.get(i);
break;
}
}
//GrupaCwiczeniowaTopComponent top = (GrupaCwiczeniowaTopComponent) WindowManager.getDefault().findTopComponent("GrupaCwiczeniowaTopComponent");
Mode mode = WindowManager.getDefault().findMode("editor");
for (TopComponent tc : WindowManager.getDefault().getOpenedTopComponents(mode)) {
if (tc instanceof GrupaCwiczeniowaTopComponent) {
if (((GrupaCwiczeniowaTopComponent) tc).getGrupa().getId() == grupa.getId()) {
if (!tc.isOpened()) {
tc.open();
}
tc.requestActive();
return;
}
}
}
GrupaCwiczeniowaTopComponent top = new GrupaCwiczeniowaTopComponent();
top.setGroup(grupa);
top.open();
top.requestActive();
}
private void termsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_termsTableMouseClicked
DefaultTableModel model = (DefaultTableModel) this.termsTable.getModel();
String value = (String) model.getValueAt(this.termsTable.getSelectedRow(), this.termsTable.getSelectedColumn());
if (value != null && this.termsTable.getSelectedColumn() > 0 && evt.getClickCount() == 2) {
openGroupTopComponent(terms[termsTable.getSelectedRow()][termsTable.getSelectedColumn() - 1]);
}
}//GEN-LAST:event_termsTableMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable termsTable;
// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
allTerms = Termin.getAllTermsForYearAndSemester(); //pobieram wszystkie terminy
DefaultTableModel model = (DefaultTableModel) this.termsTable.getModel(); //pobieram model tabeli
while (model.getRowCount() > 0) {
model.removeRow(0); //czyszcze całą tabele
}
int startScaleTime = 6; //od jakiej godziny zaczynam liczyć
//tu jest 6-ta bo w pętli będę dodwać po 2 godziny
Time tempToTable = new Time(startScaleTime, 0, 0); //ustalam startowy czas
/*
Pętla idzie 6-króków to daje od 8 do 20 składając w każdym kroku stringa do wyświetlania i dodając
puste narazie wartości null do tabeli ustawając czas o 2godziny wiecej
czyli poprostu inicjalizuje się tu pusta tabela
*/
for (int i = 0; i <= 6; i++) {
String temp = tempToTable.toString().substring(0, tempToTable.toString().length() - 3) + " - ";
tempToTable.setTime(tempToTable.getTime() + 7200000); // 7200000 milisec = 1h
model.addRow(new Object[]{temp + tempToTable.toString().substring(0, tempToTable.toString().length() - 3), null, null, null, null, null, null, null});
}
//teraz przechodząc po terminach dodaję odpowiednio grupy
for (int i = 0; i < allTerms.size(); i++) {
Termin term = allTerms.get(i);
int rowIndex = (Integer.parseInt(term.getGodzina_start().substring(0, 2)) / 2) - 3;
int columnIndex = term.getDzien_tygodnia().ordinal() + 1;
terms[rowIndex][columnIndex - 1] = term;
model.setValueAt("<html><div style=\"margin:5px;\"><b>" + term.getGrupa().getNazwa() + "</b><br>" + term.getGrupa().getPrzedmiot().getNazwa() + "</div></html>", rowIndex, columnIndex);
}
termsTable.setModel(model);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
termsTable.setDefaultRenderer(String.class, centerRenderer);
}
@Override
public void componentClosed() {
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
// TODO store your settings
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
}
public DefaultTableModel getTableModel() {
return (DefaultTableModel) this.termsTable.getModel();
}
public JTable getTable() {
return this.termsTable;
}
class CustomRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (terms[row][column - 1] != null) {
if (!isSelected) {
cellComponent.setBackground(Color.decode(terms[row][column - 1].getGrupa().getColor()));
}
} else {
cellComponent.setBackground(null);
}
return cellComponent;
}
}
}
| //pobieram wszystkie terminy
| package org.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import org.database.models.GrupaCwiczeniowa;
import org.database.models.Termin;
import java.sql.Time;
import java.util.LinkedList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.gui.grupy_cwiczeniowe.GrupaCwiczeniowaTopComponent;
import org.netbeans.api.settings.ConvertAsProperties;
import org.officelaf.listeners.TopComponentsManagerListener;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.Mode;
import org.openide.windows.WindowManager;
/**
* Top component which displays something.
*/
@ConvertAsProperties(
dtd = "-//org.gui//Main//EN",
autostore = false
)
@TopComponent.Description(
preferredID = "MainTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE",
persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "editor", openAtStartup = true)
@ActionID(category = "Window", id = "org.gui.MainTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
displayName = "#CTL_MainAction",
preferredID = "MainTopComponent"
)
@Messages({
"CTL_MainAction=Plan zajęć",
"CTL_MainTopComponent=Plan zajęć",
"HINT_MainTopComponent=To okno ukazuje plan zajęć"
})
public final class MainTopComponent extends TopComponent {
private LinkedList<Termin> allTerms;
private Termin[][] terms = new Termin[7][7];
public Termin getTerms(int r, int c) {
return terms[r][c];
}
public MainTopComponent() {
this.allTerms = new LinkedList<Termin>();
initComponents();
setName(Bundle.CTL_MainTopComponent());
setToolTipText(Bundle.HINT_MainTopComponent());
//putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
this.termsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final MainTopComponent me = this;
ListSelectionListener tableListener = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
TopComponentsManagerListener.MainTopComponentActivated(me);
}
};
this.termsTable.getSelectionModel().addListSelectionListener(tableListener);
this.termsTable.getColumnModel().getSelectionModel().addListSelectionListener(tableListener);
this.termsTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
this.termsTable.getActionMap().put("Enter", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
DefaultTableModel model = (DefaultTableModel) termsTable.getModel();
String value = (String) model.getValueAt(termsTable.getSelectedRow(), termsTable.getSelectedColumn());
if (value != null && termsTable.getSelectedColumn() > 0) {
openGroupTopComponent(terms[termsTable.getSelectedRow()][termsTable.getSelectedColumn() - 1]);
}
}
});
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
this.termsTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
this.termsTable.getColumnModel().getColumn(1).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(2).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(3).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(4).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(5).setCellRenderer(new CustomRenderer());
this.termsTable.getColumnModel().getColumn(6).setCellRenderer(new CustomRenderer());
}
/**
* 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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
termsTable = new javax.swing.JTable();
setLayout(new java.awt.BorderLayout());
termsTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Czas", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
termsTable.setColumnSelectionAllowed(true);
termsTable.setRowHeight(60);
termsTable.getTableHeader().setReorderingAllowed(false);
termsTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
termsTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(termsTable);
termsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
if (termsTable.getColumnModel().getColumnCount() > 0) {
termsTable.getColumnModel().getColumn(0).setResizable(false);
termsTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title0")); // NOI18N
termsTable.getColumnModel().getColumn(1).setResizable(false);
termsTable.getColumnModel().getColumn(1).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title1")); // NOI18N
termsTable.getColumnModel().getColumn(2).setResizable(false);
termsTable.getColumnModel().getColumn(2).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title2")); // NOI18N
termsTable.getColumnModel().getColumn(3).setResizable(false);
termsTable.getColumnModel().getColumn(3).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title3")); // NOI18N
termsTable.getColumnModel().getColumn(4).setResizable(false);
termsTable.getColumnModel().getColumn(4).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title4")); // NOI18N
termsTable.getColumnModel().getColumn(5).setResizable(false);
termsTable.getColumnModel().getColumn(5).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title5")); // NOI18N
termsTable.getColumnModel().getColumn(6).setResizable(false);
termsTable.getColumnModel().getColumn(6).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title6")); // NOI18N
termsTable.getColumnModel().getColumn(7).setResizable(false);
termsTable.getColumnModel().getColumn(7).setHeaderValue(org.openide.util.NbBundle.getMessage(MainTopComponent.class, "MainTopComponent.termsTable.columnModel.title7")); // NOI18N
}
add(jScrollPane1, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void openGroupTopComponent(Termin term) {
List<GrupaCwiczeniowa> groups = GrupaCwiczeniowa.getAll();
GrupaCwiczeniowa grupa = null;
String grupa_name = term.getGrupa().getNazwa();
String przedmiot_name = term.getGrupa().getPrzedmiot().getNazwa();
for (int i = 0; i < groups.size(); i++) {
if (groups.get(i).getNazwa().equals(grupa_name) && groups.get(i).getPrzedmiot().getNazwa().equals(przedmiot_name)) {
grupa = groups.get(i);
break;
}
}
//GrupaCwiczeniowaTopComponent top = (GrupaCwiczeniowaTopComponent) WindowManager.getDefault().findTopComponent("GrupaCwiczeniowaTopComponent");
Mode mode = WindowManager.getDefault().findMode("editor");
for (TopComponent tc : WindowManager.getDefault().getOpenedTopComponents(mode)) {
if (tc instanceof GrupaCwiczeniowaTopComponent) {
if (((GrupaCwiczeniowaTopComponent) tc).getGrupa().getId() == grupa.getId()) {
if (!tc.isOpened()) {
tc.open();
}
tc.requestActive();
return;
}
}
}
GrupaCwiczeniowaTopComponent top = new GrupaCwiczeniowaTopComponent();
top.setGroup(grupa);
top.open();
top.requestActive();
}
private void termsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_termsTableMouseClicked
DefaultTableModel model = (DefaultTableModel) this.termsTable.getModel();
String value = (String) model.getValueAt(this.termsTable.getSelectedRow(), this.termsTable.getSelectedColumn());
if (value != null && this.termsTable.getSelectedColumn() > 0 && evt.getClickCount() == 2) {
openGroupTopComponent(terms[termsTable.getSelectedRow()][termsTable.getSelectedColumn() - 1]);
}
}//GEN-LAST:event_termsTableMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable termsTable;
// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
allTerms = Termin.getAllTermsForYearAndSemester(); //pobieram wszystkie <SUF>
DefaultTableModel model = (DefaultTableModel) this.termsTable.getModel(); //pobieram model tabeli
while (model.getRowCount() > 0) {
model.removeRow(0); //czyszcze całą tabele
}
int startScaleTime = 6; //od jakiej godziny zaczynam liczyć
//tu jest 6-ta bo w pętli będę dodwać po 2 godziny
Time tempToTable = new Time(startScaleTime, 0, 0); //ustalam startowy czas
/*
Pętla idzie 6-króków to daje od 8 do 20 składając w każdym kroku stringa do wyświetlania i dodając
puste narazie wartości null do tabeli ustawając czas o 2godziny wiecej
czyli poprostu inicjalizuje się tu pusta tabela
*/
for (int i = 0; i <= 6; i++) {
String temp = tempToTable.toString().substring(0, tempToTable.toString().length() - 3) + " - ";
tempToTable.setTime(tempToTable.getTime() + 7200000); // 7200000 milisec = 1h
model.addRow(new Object[]{temp + tempToTable.toString().substring(0, tempToTable.toString().length() - 3), null, null, null, null, null, null, null});
}
//teraz przechodząc po terminach dodaję odpowiednio grupy
for (int i = 0; i < allTerms.size(); i++) {
Termin term = allTerms.get(i);
int rowIndex = (Integer.parseInt(term.getGodzina_start().substring(0, 2)) / 2) - 3;
int columnIndex = term.getDzien_tygodnia().ordinal() + 1;
terms[rowIndex][columnIndex - 1] = term;
model.setValueAt("<html><div style=\"margin:5px;\"><b>" + term.getGrupa().getNazwa() + "</b><br>" + term.getGrupa().getPrzedmiot().getNazwa() + "</div></html>", rowIndex, columnIndex);
}
termsTable.setModel(model);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
termsTable.setDefaultRenderer(String.class, centerRenderer);
}
@Override
public void componentClosed() {
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
// TODO store your settings
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
}
public DefaultTableModel getTableModel() {
return (DefaultTableModel) this.termsTable.getModel();
}
public JTable getTable() {
return this.termsTable;
}
class CustomRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (terms[row][column - 1] != null) {
if (!isSelected) {
cellComponent.setBackground(Color.decode(terms[row][column - 1].getGrupa().getColor()));
}
} else {
cellComponent.setBackground(null);
}
return cellComponent;
}
}
}
| t |
9049_1 | kxonixnio/PJATK_UTP | 2,004 | UTP5/src/zad1/Main.java | /**
*
* @author Tomczyk Mikołaj S22472
*
*/
package zad1;
public class Main {
public static void main(String[] args) {
CustomersPurchaseSortFind cpsf = new CustomersPurchaseSortFind();
String fname = System.getProperty("user.home") + "/customers.txt";
cpsf.readFile(fname);
cpsf.showSortedBy("Nazwiska");
cpsf.showSortedBy("Koszty");
String[] custSearch = { "c00001", "c00002" };
for (String id : custSearch) {
cpsf.showPurchaseFor(id);
}
}
}
/*
W pliku customers.txt umieszczonym w katalogu {user.home} znajdują się dane o zakupach klientów w postaci:
id_klienta; nazwisko i imię; nazwa_towaru;cena;zakupiona_ilość
Identyfikator klienta ma postać
cNNNNN
gdzie N cyfra ze zbioru [0...9]
np.
c00001;Kowalski Jan;bułka;2;100
Wczytać dane z pliku i wypisać na konsoli w kolejnych wierszach:
poprzedzone napisem "Nazwiska" dane posortowane wg nazwisk w porządku rosnącym (porządek rekordów z tymi samymi nazwiskami jest określany przez identyfikatory klientów - rosnąco),
poprzedzone napisem "Koszty" dane posortowane wg kosztów zakupów w porządku malejącym (porządek rekordów z tymi samymi kosztami jest określany przez identyfikatory klientów - rosnąco) z dodatkowym dopiskiem na końcu w nawiasach: koszty: kosztZakupu (np. (koszt: 200.0)),
poprzedzone napisem "Klient c00001" dane o wszystkich zakupach klienta o identyfikatorze "c00001" (w odrębnych wierszach)
poprzedzone napisem "Klient c00002" - w odrębnych wierszach -dane o wszystkich zakupach klienta o identyfikatorze "c00002" (w odrebnych wierszach) (a więc uwaga: w pliku muszą być klienci o identyfikatorach c00001 i c00002)
Np. dla pliku w postaci:
c00004;Nowak Anna;banany;4.0;50.0
c00003;Kowalski Jan;mleko;4.0;5.0
c00001;Kowalski Jan;mleko;4.0;10.0
c00001;Kowalski Jan;mleko;5.0;2.0
c00002;Malina Jan;mleko;4.0;2.0
c00002;Malina Jan;chleb;3.0;5.0
c00001;Kowalski Jan;bulka;2.0;100.0
Nazwiska
c00001;Kowalski Jan;mleko;4.0;10.0
c00001;Kowalski Jan;mleko;5.0;2.0
c00001;Kowalski Jan;bulka;2.0;100.0
c00003;Kowalski Jan;mleko;4.0;5.0
c00002;Malina Jan;mleko;4.0;2.0
c00002;Malina Jan;chleb;3.0;5.0
c00004;Nowak Anna;banany;4.0;50.0
Koszty
c00001;Kowalski Jan;bulka;2.0;100.0 (koszt: 200.0)
c00004;Nowak Anna;banany;4.0;50.0 (koszt: 200.0)
c00001;Kowalski Jan;mleko;4.0;10.0 (koszt: 40.0)
c00003;Kowalski Jan;mleko;4.0;5.0 (koszt: 20.0)
c00002;Malina Jan;chleb;3.0;5.0 (koszt: 15.0)
c00001;Kowalski Jan;mleko;5.0;2.0 (koszt: 10.0)
c00002;Malina Jan;mleko;4.0;2.0 (koszt: 8.0)
Klient c00001
c00001;Kowalski Jan;mleko;4.0;10.0
c00001;Kowalski Jan;mleko;5.0;2.0
c00001;Kowalski Jan;bulka;2.0;100.0
Klient c00002
c00002;Malina Jan;mleko;4.0;2.0
c00002;Malina Jan;chleb;3.0;5.0
Uwaga: programy nie dające pokazanej formy wydruku otrzymują 0 punktów.
Niezbędne jest stworzenie klasy, opisującej zakupy klientów (Purchase) i operowanie na jej obiektach. Nie przyjmuję rozwiązań działających na "surowych" Stringach.
Aplikacja powinna zawierać klasy Purchase, CustomersPurchaseSortFind oraz Main.
Ta ostatnia ma obowiązakową postać (nie wolno jej zmienić):
public class Main {
public static void main(String[] args) {
CustomersPurchaseSortFind cpsf = new CustomersPurchaseSortFind();
String fname = System.getProperty("user.home") + "/customers.txt";
cpsf.readFile(fname);
cpsf.showSortedBy("Nazwiska");
cpsf.showSortedBy("Koszty");
String[] custSearch = { "c00001", "c00002" };
for (String id : custSearch) {
cpsf.showPurchaseFor(id);
}
}
}
Generator projektów utworzy wymagane klasy.
Wykonanie programu rozpoczyna się od metody main(...) w klasie Main.
Uwaga: nazwa pliku jest obowiązkowe. Niespełnienie tego warunku skutkuje brakiem punktów.
Utworzona przez generator projektów klasa Main zawiera fragment pomocny dla uzyskania wymaganej nazwy pliku.
Uwaga: aby dowiedzieć się który katalog jest {user.home} i umieścić w nim plik testowy można z poziomu Javy użyć:
System.getProperty("user.home");
Np. jeśli identyfikatorem użytkownika jest Janek, to w Windows 7 katalog {user.home} to C:\Users\Janek.
Należy samodzielnie utworzyć testowy plikii umieścić je w katalogu {user.home}.
*/ | /*
W pliku customers.txt umieszczonym w katalogu {user.home} znajdują się dane o zakupach klientów w postaci:
id_klienta; nazwisko i imię; nazwa_towaru;cena;zakupiona_ilość
Identyfikator klienta ma postać
cNNNNN
gdzie N cyfra ze zbioru [0...9]
np.
c00001;Kowalski Jan;bułka;2;100
Wczytać dane z pliku i wypisać na konsoli w kolejnych wierszach:
poprzedzone napisem "Nazwiska" dane posortowane wg nazwisk w porządku rosnącym (porządek rekordów z tymi samymi nazwiskami jest określany przez identyfikatory klientów - rosnąco),
poprzedzone napisem "Koszty" dane posortowane wg kosztów zakupów w porządku malejącym (porządek rekordów z tymi samymi kosztami jest określany przez identyfikatory klientów - rosnąco) z dodatkowym dopiskiem na końcu w nawiasach: koszty: kosztZakupu (np. (koszt: 200.0)),
poprzedzone napisem "Klient c00001" dane o wszystkich zakupach klienta o identyfikatorze "c00001" (w odrębnych wierszach)
poprzedzone napisem "Klient c00002" - w odrębnych wierszach -dane o wszystkich zakupach klienta o identyfikatorze "c00002" (w odrebnych wierszach) (a więc uwaga: w pliku muszą być klienci o identyfikatorach c00001 i c00002)
Np. dla pliku w postaci:
c00004;Nowak Anna;banany;4.0;50.0
c00003;Kowalski Jan;mleko;4.0;5.0
c00001;Kowalski Jan;mleko;4.0;10.0
c00001;Kowalski Jan;mleko;5.0;2.0
c00002;Malina Jan;mleko;4.0;2.0
c00002;Malina Jan;chleb;3.0;5.0
c00001;Kowalski Jan;bulka;2.0;100.0
Nazwiska
c00001;Kowalski Jan;mleko;4.0;10.0
c00001;Kowalski Jan;mleko;5.0;2.0
c00001;Kowalski Jan;bulka;2.0;100.0
c00003;Kowalski Jan;mleko;4.0;5.0
c00002;Malina Jan;mleko;4.0;2.0
c00002;Malina Jan;chleb;3.0;5.0
c00004;Nowak Anna;banany;4.0;50.0
Koszty
c00001;Kowalski Jan;bulka;2.0;100.0 (koszt: 200.0)
c00004;Nowak Anna;banany;4.0;50.0 (koszt: 200.0)
c00001;Kowalski Jan;mleko;4.0;10.0 (koszt: 40.0)
c00003;Kowalski Jan;mleko;4.0;5.0 (koszt: 20.0)
c00002;Malina Jan;chleb;3.0;5.0 (koszt: 15.0)
c00001;Kowalski Jan;mleko;5.0;2.0 (koszt: 10.0)
c00002;Malina Jan;mleko;4.0;2.0 (koszt: 8.0)
Klient c00001
c00001;Kowalski Jan;mleko;4.0;10.0
c00001;Kowalski Jan;mleko;5.0;2.0
c00001;Kowalski Jan;bulka;2.0;100.0
Klient c00002
c00002;Malina Jan;mleko;4.0;2.0
c00002;Malina Jan;chleb;3.0;5.0
Uwaga: programy nie dające pokazanej formy wydruku otrzymują 0 punktów.
Niezbędne jest stworzenie klasy, opisującej zakupy klientów (Purchase) i operowanie na jej obiektach. Nie przyjmuję rozwiązań działających na "surowych" Stringach.
Aplikacja powinna zawierać klasy Purchase, CustomersPurchaseSortFind oraz Main.
Ta ostatnia ma obowiązakową postać (nie wolno jej zmienić):
public class Main {
public static void main(String[] args) {
CustomersPurchaseSortFind cpsf = new CustomersPurchaseSortFind();
String fname = System.getProperty("user.home") + "/customers.txt";
cpsf.readFile(fname);
cpsf.showSortedBy("Nazwiska");
cpsf.showSortedBy("Koszty");
String[] custSearch = { "c00001", "c00002" };
for (String id : custSearch) {
cpsf.showPurchaseFor(id);
}
}
}
Generator projektów utworzy wymagane klasy.
Wykonanie programu rozpoczyna się od metody main(...) w klasie Main.
Uwaga: nazwa pliku jest obowiązkowe. Niespełnienie tego warunku skutkuje brakiem punktów.
Utworzona przez generator projektów klasa Main zawiera fragment pomocny dla uzyskania wymaganej nazwy pliku.
Uwaga: aby dowiedzieć się który katalog jest {user.home} i umieścić w nim plik testowy można z poziomu Javy użyć:
System.getProperty("user.home");
Np. jeśli identyfikatorem użytkownika jest Janek, to w Windows 7 katalog {user.home} to C:\Users\Janek.
Należy samodzielnie utworzyć testowy plikii umieścić je w katalogu {user.home}.
*/ | /**
*
* @author Tomczyk Mikołaj S22472
*
*/
package zad1;
public class Main {
public static void main(String[] args) {
CustomersPurchaseSortFind cpsf = new CustomersPurchaseSortFind();
String fname = System.getProperty("user.home") + "/customers.txt";
cpsf.readFile(fname);
cpsf.showSortedBy("Nazwiska");
cpsf.showSortedBy("Koszty");
String[] custSearch = { "c00001", "c00002" };
for (String id : custSearch) {
cpsf.showPurchaseFor(id);
}
}
}
/*
W pliku customers.txt <SUF>*/ | f |
6065_5 | lburcon/Fly_High | 3,735 | FlyHighConference/app/src/main/java/com/example/yggdralisk/flyhighconference/BackEnd/MainActivity.java | package com.example.yggdralisk.flyhighconference.BackEnd;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.yggdralisk.flyhighconference.Adapters_Managers_Items.DrawerAdapter;
import com.example.yggdralisk.flyhighconference.Adapters_Managers_Items.DrawerItem;
import com.example.yggdralisk.flyhighconference.Fragments.ConferenceFavouriteList;
import com.example.yggdralisk.flyhighconference.Fragments.ConferenceFragment;
import com.example.yggdralisk.flyhighconference.Fragments.ConferenceListFragment;
import com.example.yggdralisk.flyhighconference.Fragments.LoginFragment;
import com.example.yggdralisk.flyhighconference.Fragments.LoginOutFragment;
import com.example.yggdralisk.flyhighconference.Fragments.MapFragment;
import com.example.yggdralisk.flyhighconference.Fragments.OrganisersListFragment;
import com.example.yggdralisk.flyhighconference.Fragments.QuestionFragment;
import com.example.yggdralisk.flyhighconference.Fragments.SpeakerFragment;
import com.example.yggdralisk.flyhighconference.Fragments.SpeakersConferenceListFragment;
import com.example.yggdralisk.flyhighconference.R;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements SpeakerFragment.OnDataPassSpeaker {
@Bind(R.id.main_drawer)
DrawerLayout mDrawerLayout;
@Bind(R.id.left_drawer_list_view)
ListView mDrawerList;
@Bind(R.id.left_drawer_logged_name)
TextView loggedName;
@Bind(R.id.activity_main_toolbar)
Toolbar mToolbar;
private ActionBarDrawerToggle mDrawerToggle;
private String toolbarData;
private String[] navMenuTitles;
boolean ifLast = false;
private List<Integer> navMenuIcons = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
setDrawer();
if (DataGetter.checkUserLogged(getApplicationContext()))
setLoggedNameOnDrawer(DataGetter.getLoggedUserName(getApplicationContext()));
setFragment(savedInstanceState, new ConferenceListFragment(), null);
toolbarOnclick();
}
public void toggleDrawer() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
mDrawerLayout.closeDrawer(GravityCompat.START);
else
mDrawerLayout.openDrawer(GravityCompat.START);
}
public void setDrawer() {
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
TypedArray ids = getResources().obtainTypedArray(R.array.nav_drawer_icons);
for (int i = 0; i < ids.length(); i++)
navMenuIcons.add(ids.getResourceId(i, -1));
changeLoginLogoutDrawer();
ids.recycle();
}
//Jeżeli nie wiesz co wysłać w jako savedInstanceState wyślij null
public void setFragment(Bundle savedInstanceState, Fragment fragmentActivity, Bundle args) {
try {
if (findViewById(R.id.fragment_container_main) != null) {
if (savedInstanceState != null) {
return;
}
if (getSupportFragmentManager().findFragmentById(R.id.fragment_container_main) != null)
if ((getSupportFragmentManager().findFragmentById(R.id.fragment_container_main).getClass() == fragmentActivity.getClass()))
return;
fragmentActivity.setArguments(getIntent().getExtras());
if (args != null) fragmentActivity.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
boolean isLog = (fragmentManager.findFragmentById(R.id.fragment_container_main) instanceof LoginFragment
|| fragmentManager.findFragmentById(R.id.fragment_container_main) instanceof LoginOutFragment);
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_top, R.anim.slide_out_bottom, R.anim.slide_in_bottom, R.anim.slide_out_top);
fragmentTransaction.replace(R.id.fragment_container_main, fragmentActivity);
if (!isLog)
fragmentTransaction.addToBackStack(null);
setupToolbar(fragmentActivity);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
invalidateOptionsMenu();
}
} catch (IllegalStateException ex) {
ex.printStackTrace();
}
}
@Override
public void dataPassSpeaker(String data) {
toolbarData = data;
}
private class DrawerItemClickListener implements android.widget.AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setFragment(null, ((DrawerItem) mDrawerList.getItemAtPosition(position)).getFragment(), null);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
toggleDrawer();
}
}, 350);
}
}
public void setLoggedNameOnDrawer(String name) {
if (name != null) {
if (name.equals(""))
loggedName.setText("");
else
loggedName.setText(getString(R.string.left_drawer_logged_name) + " " + name);
loggedName.invalidate();
}
}
public boolean changeLoginLogoutDrawer() //Returns true if drawer has been changed to zaloguj
{
ArrayList<DrawerItem> drawerElements = new ArrayList<>();
int temp;
boolean ifChanged = false;
if (navMenuTitles.length >= navMenuIcons.size())
temp = navMenuTitles.length - 2;
else
temp = navMenuIcons.size() - 2;
for (int i = 0; i < temp; i++)
drawerElements.add(new DrawerItem(navMenuTitles[i], navMenuIcons.get(i)));
if (DataGetter.checkUserLogged(getApplicationContext())) {
drawerElements.add(new DrawerItem(navMenuTitles[temp + 1], navMenuIcons.get(temp + 1)));
ifChanged = true;
} else {
// temp+1 if so it gets "wyloguj" String and icon
drawerElements.add(new DrawerItem(navMenuTitles[temp], navMenuIcons.get(temp)));
}
// Set the adapter for the list view
mDrawerList.setAdapter(new DrawerAdapter(getApplicationContext(), R.layout.drawer_item, drawerElements));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
return ifChanged;
}
private void toolbarOnclick() {
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setPreviousFragment();
}
});
}
@Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
toggleDrawer();
if (!setPreviousFragment()) {
this.finish();
System.exit(0);
//android.os.Process.killProcess(android.os.Process.myPid()); // mozna tez uzyć tego do killowania
}
}
public boolean setPreviousFragment() {
if (getSupportActionBar() != null) {
if (getSupportFragmentManager().getBackStackEntryCount() > 2) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportFragmentManager().popBackStack();
setupToolbar(true);
ifLast = false;
getSupportFragmentManager().executePendingTransactions();
invalidateOptionsMenu();
} else if (getSupportFragmentManager().getBackStackEntryCount() == 2) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportFragmentManager().popBackStack();
setupToolbar(false);
ifLast = getSupportFragmentManager().getFragments().get(0) instanceof ConferenceListFragment;
getSupportFragmentManager().executePendingTransactions();
invalidateOptionsMenu();
} else if (!ifLast) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
setFragment(null, new ConferenceListFragment(), null);
ifLast = true;
getSupportFragmentManager().executePendingTransactions();
invalidateOptionsMenu();
} else {
android.os.Process.killProcess(android.os.Process.myPid());
}
} else {
getSupportFragmentManager().popBackStack();
}
return getSupportFragmentManager().getBackStackEntryCount() != 0
|| !(getSupportFragmentManager().getFragments().get(0) instanceof LoginFragment)
|| !(getSupportFragmentManager().getFragments().get(0) instanceof LoginOutFragment);
}
private void setupToolbar(boolean count) { //only used when back arrow clicked
if (getSupportActionBar() != null)
if (count) {
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
}
private void setupToolbar(Fragment fragment) {
if (getSupportActionBar() == null) return;
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
if (getSupportActionBar() != null) {
if (fragment instanceof ConferenceFragment ||
fragment instanceof SpeakerFragment || fragment instanceof QuestionFragment ||
fragment instanceof SpeakersConferenceListFragment ||
fragment instanceof OrganisersListFragment || fragment instanceof ConferenceFavouriteList
|| fragment instanceof MapFragment) {
ifLast = false;
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
} else {
ifLast = fragment instanceof ConferenceListFragment;
mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
clearBackStack();
}
}
}
@Override
protected void onPostCreate(final Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if ((getSupportFragmentManager().findFragmentById(R.id.fragment_container_main) instanceof SpeakerFragment) && !toolbarData.equals("")) {
menu.clear();
getMenuInflater().inflate(R.menu.menu_speaker, menu);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_general, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.organisers:
if (!(getSupportFragmentManager().findFragmentById(R.id.fragment_container_main) instanceof OrganisersListFragment))
setFragment(null, new OrganisersListFragment(), null);
return true;
case R.id.favourites:
if (!(getSupportFragmentManager().findFragmentById(R.id.fragment_container_main) instanceof ConferenceFavouriteList) && DataGetter.checkUserLogged(this))
setFragment(null, new ConferenceFavouriteList(), null);
else
Toast.makeText(this, R.string.not_logged_fav, Toast.LENGTH_SHORT).show();
return true;
case R.id.site:
if (toolbarData.equals("")) {
return false;
} else {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(toolbarData));
startActivity(i);
}
}
return super.onOptionsItemSelected(item);
}
private void clearBackStack() {
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0) {
FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
}
| //android.os.Process.killProcess(android.os.Process.myPid()); // mozna tez uzyć tego do killowania | package com.example.yggdralisk.flyhighconference.BackEnd;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.yggdralisk.flyhighconference.Adapters_Managers_Items.DrawerAdapter;
import com.example.yggdralisk.flyhighconference.Adapters_Managers_Items.DrawerItem;
import com.example.yggdralisk.flyhighconference.Fragments.ConferenceFavouriteList;
import com.example.yggdralisk.flyhighconference.Fragments.ConferenceFragment;
import com.example.yggdralisk.flyhighconference.Fragments.ConferenceListFragment;
import com.example.yggdralisk.flyhighconference.Fragments.LoginFragment;
import com.example.yggdralisk.flyhighconference.Fragments.LoginOutFragment;
import com.example.yggdralisk.flyhighconference.Fragments.MapFragment;
import com.example.yggdralisk.flyhighconference.Fragments.OrganisersListFragment;
import com.example.yggdralisk.flyhighconference.Fragments.QuestionFragment;
import com.example.yggdralisk.flyhighconference.Fragments.SpeakerFragment;
import com.example.yggdralisk.flyhighconference.Fragments.SpeakersConferenceListFragment;
import com.example.yggdralisk.flyhighconference.R;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements SpeakerFragment.OnDataPassSpeaker {
@Bind(R.id.main_drawer)
DrawerLayout mDrawerLayout;
@Bind(R.id.left_drawer_list_view)
ListView mDrawerList;
@Bind(R.id.left_drawer_logged_name)
TextView loggedName;
@Bind(R.id.activity_main_toolbar)
Toolbar mToolbar;
private ActionBarDrawerToggle mDrawerToggle;
private String toolbarData;
private String[] navMenuTitles;
boolean ifLast = false;
private List<Integer> navMenuIcons = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
setDrawer();
if (DataGetter.checkUserLogged(getApplicationContext()))
setLoggedNameOnDrawer(DataGetter.getLoggedUserName(getApplicationContext()));
setFragment(savedInstanceState, new ConferenceListFragment(), null);
toolbarOnclick();
}
public void toggleDrawer() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
mDrawerLayout.closeDrawer(GravityCompat.START);
else
mDrawerLayout.openDrawer(GravityCompat.START);
}
public void setDrawer() {
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
TypedArray ids = getResources().obtainTypedArray(R.array.nav_drawer_icons);
for (int i = 0; i < ids.length(); i++)
navMenuIcons.add(ids.getResourceId(i, -1));
changeLoginLogoutDrawer();
ids.recycle();
}
//Jeżeli nie wiesz co wysłać w jako savedInstanceState wyślij null
public void setFragment(Bundle savedInstanceState, Fragment fragmentActivity, Bundle args) {
try {
if (findViewById(R.id.fragment_container_main) != null) {
if (savedInstanceState != null) {
return;
}
if (getSupportFragmentManager().findFragmentById(R.id.fragment_container_main) != null)
if ((getSupportFragmentManager().findFragmentById(R.id.fragment_container_main).getClass() == fragmentActivity.getClass()))
return;
fragmentActivity.setArguments(getIntent().getExtras());
if (args != null) fragmentActivity.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
boolean isLog = (fragmentManager.findFragmentById(R.id.fragment_container_main) instanceof LoginFragment
|| fragmentManager.findFragmentById(R.id.fragment_container_main) instanceof LoginOutFragment);
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_top, R.anim.slide_out_bottom, R.anim.slide_in_bottom, R.anim.slide_out_top);
fragmentTransaction.replace(R.id.fragment_container_main, fragmentActivity);
if (!isLog)
fragmentTransaction.addToBackStack(null);
setupToolbar(fragmentActivity);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
invalidateOptionsMenu();
}
} catch (IllegalStateException ex) {
ex.printStackTrace();
}
}
@Override
public void dataPassSpeaker(String data) {
toolbarData = data;
}
private class DrawerItemClickListener implements android.widget.AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setFragment(null, ((DrawerItem) mDrawerList.getItemAtPosition(position)).getFragment(), null);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
toggleDrawer();
}
}, 350);
}
}
public void setLoggedNameOnDrawer(String name) {
if (name != null) {
if (name.equals(""))
loggedName.setText("");
else
loggedName.setText(getString(R.string.left_drawer_logged_name) + " " + name);
loggedName.invalidate();
}
}
public boolean changeLoginLogoutDrawer() //Returns true if drawer has been changed to zaloguj
{
ArrayList<DrawerItem> drawerElements = new ArrayList<>();
int temp;
boolean ifChanged = false;
if (navMenuTitles.length >= navMenuIcons.size())
temp = navMenuTitles.length - 2;
else
temp = navMenuIcons.size() - 2;
for (int i = 0; i < temp; i++)
drawerElements.add(new DrawerItem(navMenuTitles[i], navMenuIcons.get(i)));
if (DataGetter.checkUserLogged(getApplicationContext())) {
drawerElements.add(new DrawerItem(navMenuTitles[temp + 1], navMenuIcons.get(temp + 1)));
ifChanged = true;
} else {
// temp+1 if so it gets "wyloguj" String and icon
drawerElements.add(new DrawerItem(navMenuTitles[temp], navMenuIcons.get(temp)));
}
// Set the adapter for the list view
mDrawerList.setAdapter(new DrawerAdapter(getApplicationContext(), R.layout.drawer_item, drawerElements));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
return ifChanged;
}
private void toolbarOnclick() {
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setPreviousFragment();
}
});
}
@Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START))
toggleDrawer();
if (!setPreviousFragment()) {
this.finish();
System.exit(0);
//android.os.Process.killProcess(android.os.Process.myPid()); // <SUF>
}
}
public boolean setPreviousFragment() {
if (getSupportActionBar() != null) {
if (getSupportFragmentManager().getBackStackEntryCount() > 2) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportFragmentManager().popBackStack();
setupToolbar(true);
ifLast = false;
getSupportFragmentManager().executePendingTransactions();
invalidateOptionsMenu();
} else if (getSupportFragmentManager().getBackStackEntryCount() == 2) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportFragmentManager().popBackStack();
setupToolbar(false);
ifLast = getSupportFragmentManager().getFragments().get(0) instanceof ConferenceListFragment;
getSupportFragmentManager().executePendingTransactions();
invalidateOptionsMenu();
} else if (!ifLast) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
setFragment(null, new ConferenceListFragment(), null);
ifLast = true;
getSupportFragmentManager().executePendingTransactions();
invalidateOptionsMenu();
} else {
android.os.Process.killProcess(android.os.Process.myPid());
}
} else {
getSupportFragmentManager().popBackStack();
}
return getSupportFragmentManager().getBackStackEntryCount() != 0
|| !(getSupportFragmentManager().getFragments().get(0) instanceof LoginFragment)
|| !(getSupportFragmentManager().getFragments().get(0) instanceof LoginOutFragment);
}
private void setupToolbar(boolean count) { //only used when back arrow clicked
if (getSupportActionBar() != null)
if (count) {
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
}
private void setupToolbar(Fragment fragment) {
if (getSupportActionBar() == null) return;
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
if (getSupportActionBar() != null) {
if (fragment instanceof ConferenceFragment ||
fragment instanceof SpeakerFragment || fragment instanceof QuestionFragment ||
fragment instanceof SpeakersConferenceListFragment ||
fragment instanceof OrganisersListFragment || fragment instanceof ConferenceFavouriteList
|| fragment instanceof MapFragment) {
ifLast = false;
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
} else {
ifLast = fragment instanceof ConferenceListFragment;
mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
clearBackStack();
}
}
}
@Override
protected void onPostCreate(final Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if ((getSupportFragmentManager().findFragmentById(R.id.fragment_container_main) instanceof SpeakerFragment) && !toolbarData.equals("")) {
menu.clear();
getMenuInflater().inflate(R.menu.menu_speaker, menu);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_general, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.organisers:
if (!(getSupportFragmentManager().findFragmentById(R.id.fragment_container_main) instanceof OrganisersListFragment))
setFragment(null, new OrganisersListFragment(), null);
return true;
case R.id.favourites:
if (!(getSupportFragmentManager().findFragmentById(R.id.fragment_container_main) instanceof ConferenceFavouriteList) && DataGetter.checkUserLogged(this))
setFragment(null, new ConferenceFavouriteList(), null);
else
Toast.makeText(this, R.string.not_logged_fav, Toast.LENGTH_SHORT).show();
return true;
case R.id.site:
if (toolbarData.equals("")) {
return false;
} else {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(toolbarData));
startActivity(i);
}
}
return super.onOptionsItemSelected(item);
}
private void clearBackStack() {
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0) {
FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
}
| f |
5704_1 | lethiandev/clockwork-2d | 1,072 | src/vault/clockwork/editor/props/PlankProp.java | /*
* The MIT License
*
* Copyright 2015 Konrad Nowakowski https://github.com/konrad92.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package vault.clockwork.editor.props;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import vault.clockwork.actors.PlankActor;
import vault.clockwork.editor.PropActor;
import vault.clockwork.editor.PropSerialized;
/**
* General plank editor prop.
* @author Agnieszka Makowska https://github.com/Migemiley
*/
public class PlankProp extends PropSerialized {
/**
* Szerokosc i wysokosc planka.
* Dla konstruktora {@link PlankActor#PlankActor(int, float, float)}, gdzie
* x/y to odpowiednio width/height.
*/
public float width = 50, height = 256;
/**
* Obrot aktora.
*/
public float angle = 0;
/**
* Szybkosc obrotu aktora.
*/
public float rotate_speed = 0;
/**
* Wysokosc poruszania sie deski.
*/
public float move_height = 200;
/**
* Kierunek poruszania sie deski.
*/
public float move_direction_x = 0, move_direction_y = 1;
/**
* Ctor.
*/
public PlankProp() {
this.layer = 2;
}
/**
* @param gizmo
*/
@Override
public void draw(ShapeRenderer gizmo) {
Matrix4 transform = new Matrix4();
transform.translate(position.x, position.y, 0);
transform.rotate(0, 0, 1, angle);
gizmo.setTransformMatrix(transform);
gizmo.rect(-width, -height, width*2, height*2);
gizmo.setTransformMatrix(new Matrix4());
gizmo.setColor(Color.CYAN);
gizmo.line(position, position.cpy().add(
new Vector2(move_direction_x, move_direction_y).nor().scl(64.f)
));
gizmo.setColor(Color.YELLOW);
}
/**
* PlankActor class.
* @return
*/
@Override
public Class<? extends PropActor> getActorClass() {
return PlankActor.class;
}
}
| /**
* General plank editor prop.
* @author Agnieszka Makowska https://github.com/Migemiley
*/ | /*
* The MIT License
*
* Copyright 2015 Konrad Nowakowski https://github.com/konrad92.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package vault.clockwork.editor.props;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import vault.clockwork.actors.PlankActor;
import vault.clockwork.editor.PropActor;
import vault.clockwork.editor.PropSerialized;
/**
* General plank editor <SUF>*/
public class PlankProp extends PropSerialized {
/**
* Szerokosc i wysokosc planka.
* Dla konstruktora {@link PlankActor#PlankActor(int, float, float)}, gdzie
* x/y to odpowiednio width/height.
*/
public float width = 50, height = 256;
/**
* Obrot aktora.
*/
public float angle = 0;
/**
* Szybkosc obrotu aktora.
*/
public float rotate_speed = 0;
/**
* Wysokosc poruszania sie deski.
*/
public float move_height = 200;
/**
* Kierunek poruszania sie deski.
*/
public float move_direction_x = 0, move_direction_y = 1;
/**
* Ctor.
*/
public PlankProp() {
this.layer = 2;
}
/**
* @param gizmo
*/
@Override
public void draw(ShapeRenderer gizmo) {
Matrix4 transform = new Matrix4();
transform.translate(position.x, position.y, 0);
transform.rotate(0, 0, 1, angle);
gizmo.setTransformMatrix(transform);
gizmo.rect(-width, -height, width*2, height*2);
gizmo.setTransformMatrix(new Matrix4());
gizmo.setColor(Color.CYAN);
gizmo.line(position, position.cpy().add(
new Vector2(move_direction_x, move_direction_y).nor().scl(64.f)
));
gizmo.setColor(Color.YELLOW);
}
/**
* PlankActor class.
* @return
*/
@Override
public Class<? extends PropActor> getActorClass() {
return PlankActor.class;
}
}
| f |
5001_1 | logger421/PRiR | 152 | exc/ex3/src/Binder.java |
/**
* Interfejs rejestracji usługi RMI.
*/
public interface Binder {
/**
* Rejestruje w rmiregistry pod podaną nazwą serwer usługi. Usługa rmiregistry
* będzie uruchomiona pod adresem localhost:1099. <b>Metoda nie może
* samodzielnie uruchamiać rmiregistry!</b>
*
* @param serviceName oczekiwana nazwa usługi w rmiregistry
*/
public void bind(String serviceName);
} | /**
* Rejestruje w rmiregistry pod podaną nazwą serwer usługi. Usługa rmiregistry
* będzie uruchomiona pod adresem localhost:1099. <b>Metoda nie może
* samodzielnie uruchamiać rmiregistry!</b>
*
* @param serviceName oczekiwana nazwa usługi w rmiregistry
*/ |
/**
* Interfejs rejestracji usługi RMI.
*/
public interface Binder {
/**
* Rejestruje w rmiregistry <SUF>*/
public void bind(String serviceName);
} | f |
2809_1 | loomchild/maligna | 1,106 | maligna-ui/src/main/java/net/loomchild/maligna/ui/console/command/ModelCommand.java | package net.loomchild.maligna.ui.console.command;
import java.util.ArrayList;
import java.util.List;
import net.loomchild.maligna.coretypes.Alignment;
import net.loomchild.maligna.model.translation.TranslationModelUtil;
import net.loomchild.maligna.model.vocabulary.Vocabulary;
import net.loomchild.maligna.model.vocabulary.VocabularyUtil;
import net.loomchild.maligna.parser.AlParser;
import net.loomchild.maligna.parser.Parser;
import net.loomchild.maligna.ui.console.command.exception.MissingParameterException;
import net.loomchild.maligna.filter.modifier.modify.split.SplitAlgorithm;
import net.loomchild.maligna.ui.console.command.exception.UnknownParameterException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
public class ModelCommand extends AbstractCommand {
protected void initOptions(Options options) {
options.addOption("c", "class", true, "Modeller class. Valid values are: length, language-translation.");
options.addOption("i", "iterations", true, "Translation model train iteration count. Optional for language-translation modeller, default " + TranslationModelUtil.DEFAULT_TRAIN_ITERATION_COUNT + ".");
}
public void run(CommandLine commandLine) {
String cls = commandLine.getOptionValue('c');
if (cls == null) {
throw new MissingParameterException("class");
} else if (cls.equals("language-translation")) {
//int iterations = createInt(commandLine, "iterations",
// TranslationModelUtil.DEFAULT_TRAIN_ITERATION_COUNT);
//Prosty algorytm tokenizujący dlatego że wejście powinno być już
//stokenizowane - tokeny rozdzielone spacją.
//TODO: Czy dobrze? nie może być tokenów ze spacją w środku.
SplitAlgorithm splitAlgorithm =
VocabularyUtil.DEFAULT_TOKENIZE_ALGORITHM;
Vocabulary sourceVocabulary = new Vocabulary();
Vocabulary targetVocabulary = new Vocabulary();
Parser parser = new AlParser(getIn());
List<Alignment> alignmentList = parser.parse();
List<List<Integer>> sourceWidList = new ArrayList<List<Integer>>();
List<List<Integer>> targetWidList = new ArrayList<List<Integer>>();
for (Alignment alignment : alignmentList) {
sourceWidList.add(tokenizePutGet(
alignment.getSourceSegmentList(),
sourceVocabulary, splitAlgorithm));
targetWidList.add(tokenizePutGet(
alignment.getTargetSegmentList(),
targetVocabulary, splitAlgorithm));
}
//LanguageModel sourceLanguageModel =
// LanguageModelUtil.train(sourceWidList);
//LanguageModel targetLanguageModel =
// LanguageModelUtil.train(targetWidList);
//TranslationModel translationModel =
// TranslationModelUtil.train(iterations, sourceWidList, targetWidList);
} else {
throw new UnknownParameterException("class");
}
}
private List<Integer> tokenizePutGet(List<String> segmentList,
Vocabulary vocabulary, SplitAlgorithm splitAlgorithm) {
List<String> wordList = splitAlgorithm.modify(segmentList);
vocabulary.putWordList(wordList);
List<Integer> widList = vocabulary.getWidList(wordList);
return widList;
}
}
| //Prosty algorytm tokenizujący dlatego że wejście powinno być już | package net.loomchild.maligna.ui.console.command;
import java.util.ArrayList;
import java.util.List;
import net.loomchild.maligna.coretypes.Alignment;
import net.loomchild.maligna.model.translation.TranslationModelUtil;
import net.loomchild.maligna.model.vocabulary.Vocabulary;
import net.loomchild.maligna.model.vocabulary.VocabularyUtil;
import net.loomchild.maligna.parser.AlParser;
import net.loomchild.maligna.parser.Parser;
import net.loomchild.maligna.ui.console.command.exception.MissingParameterException;
import net.loomchild.maligna.filter.modifier.modify.split.SplitAlgorithm;
import net.loomchild.maligna.ui.console.command.exception.UnknownParameterException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
public class ModelCommand extends AbstractCommand {
protected void initOptions(Options options) {
options.addOption("c", "class", true, "Modeller class. Valid values are: length, language-translation.");
options.addOption("i", "iterations", true, "Translation model train iteration count. Optional for language-translation modeller, default " + TranslationModelUtil.DEFAULT_TRAIN_ITERATION_COUNT + ".");
}
public void run(CommandLine commandLine) {
String cls = commandLine.getOptionValue('c');
if (cls == null) {
throw new MissingParameterException("class");
} else if (cls.equals("language-translation")) {
//int iterations = createInt(commandLine, "iterations",
// TranslationModelUtil.DEFAULT_TRAIN_ITERATION_COUNT);
//Prosty algorytm <SUF>
//stokenizowane - tokeny rozdzielone spacją.
//TODO: Czy dobrze? nie może być tokenów ze spacją w środku.
SplitAlgorithm splitAlgorithm =
VocabularyUtil.DEFAULT_TOKENIZE_ALGORITHM;
Vocabulary sourceVocabulary = new Vocabulary();
Vocabulary targetVocabulary = new Vocabulary();
Parser parser = new AlParser(getIn());
List<Alignment> alignmentList = parser.parse();
List<List<Integer>> sourceWidList = new ArrayList<List<Integer>>();
List<List<Integer>> targetWidList = new ArrayList<List<Integer>>();
for (Alignment alignment : alignmentList) {
sourceWidList.add(tokenizePutGet(
alignment.getSourceSegmentList(),
sourceVocabulary, splitAlgorithm));
targetWidList.add(tokenizePutGet(
alignment.getTargetSegmentList(),
targetVocabulary, splitAlgorithm));
}
//LanguageModel sourceLanguageModel =
// LanguageModelUtil.train(sourceWidList);
//LanguageModel targetLanguageModel =
// LanguageModelUtil.train(targetWidList);
//TranslationModel translationModel =
// TranslationModelUtil.train(iterations, sourceWidList, targetWidList);
} else {
throw new UnknownParameterException("class");
}
}
private List<Integer> tokenizePutGet(List<String> segmentList,
Vocabulary vocabulary, SplitAlgorithm splitAlgorithm) {
List<String> wordList = splitAlgorithm.modify(segmentList);
vocabulary.putWordList(wordList);
List<Integer> widList = vocabulary.getWidList(wordList);
return widList;
}
}
| f |
9860_2 | luczak20p/2023-24-studying | 469 | FiguryGUI/src/myclass/gui/App.java | package myclass.gui;
import myclass.Figura;
import java.io.*;
import java.util.ArrayList;
import java.util.Objects;
public class App {
public static void main(String[] args) {
//OknoAWTExtends okno = new OknoAWTExtends("testing awt");
ArrayList <Figura> bazaFigur;//tutaj bedziemy przechowywac liste figur
bazaFigur = new ArrayList<Figura>();
//przyklad uzycia serializacji do zapisu listy figur
// Figura tmp = new Figura("Magiczny","Kwadrat",45.00);
// bazaFigur.add(tmp);
//zapis arraylisty do pliku
// try {
// ObjectOutputStream ouS = new ObjectOutputStream(new FileOutputStream("test.bin"));
// ouS.writeObject(bazaFigur);
// ouS.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// try {
// ObjectInputStream inS = new ObjectInputStream(new FileInputStream("test.bin"));
// ArrayList <Figura> bazaFigur2 = (ArrayList<Figura>) inS.readObject();
// System.out.println(bazaFigur2.get(0).getNazwa());
//
//
// } catch (IOException e) {
// throw new RuntimeException(e);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
/// zrobić zapisywanie do pliku, czytanie z pliku i czytanie danych wybranego z listy elementu
Start oknoStart = new Start("Figury", bazaFigur);
}
}
| //przyklad uzycia serializacji do zapisu listy figur
| package myclass.gui;
import myclass.Figura;
import java.io.*;
import java.util.ArrayList;
import java.util.Objects;
public class App {
public static void main(String[] args) {
//OknoAWTExtends okno = new OknoAWTExtends("testing awt");
ArrayList <Figura> bazaFigur;//tutaj bedziemy przechowywac liste figur
bazaFigur = new ArrayList<Figura>();
//przyklad uzycia <SUF>
// Figura tmp = new Figura("Magiczny","Kwadrat",45.00);
// bazaFigur.add(tmp);
//zapis arraylisty do pliku
// try {
// ObjectOutputStream ouS = new ObjectOutputStream(new FileOutputStream("test.bin"));
// ouS.writeObject(bazaFigur);
// ouS.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// try {
// ObjectInputStream inS = new ObjectInputStream(new FileInputStream("test.bin"));
// ArrayList <Figura> bazaFigur2 = (ArrayList<Figura>) inS.readObject();
// System.out.println(bazaFigur2.get(0).getNazwa());
//
//
// } catch (IOException e) {
// throw new RuntimeException(e);
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
/// zrobić zapisywanie do pliku, czytanie z pliku i czytanie danych wybranego z listy elementu
Start oknoStart = new Start("Figury", bazaFigur);
}
}
| f |
3741_1 | ludzienamoscie/ORM | 637 | src/main/java/model/Show.java | package model;
import com.sun.istack.NotNull;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import net.bytebuddy.asm.Advice;
import org.bson.codecs.pojo.annotations.BsonCreator;
import org.bson.codecs.pojo.annotations.BsonProperty;
import repositories.UniqueIdMgd;
import java.time.LocalDateTime;
import java.util.UUID;
@Getter
@Setter
public class Show extends AbstractEntity{
@BsonCreator
public Show(@BsonProperty("id") UniqueIdMgd entityId,
@BsonProperty("show_id") Long show_id,
@BsonProperty("room") Room room,
@BsonProperty("beginTime") LocalDateTime beginTime,
@BsonProperty("endTime") LocalDateTime endTime,
@BsonProperty("showType") ShowType showType) {
super(entityId);
this.show_id = show_id;
this.room = room;
this.beginTime = beginTime;
this.endTime = endTime;
this.showType = showType;
this.availableSeats = room.getCapacity();
}
public Show(
Long show_id,
Room room,
LocalDateTime beginTime,
LocalDateTime endTime,
ShowType showType
){
super(new UniqueIdMgd());
this.show_id = show_id;
this.room = room;
this.beginTime = beginTime;
this.endTime = endTime;
this.showType = showType;
}
// Nie wem jak to przerobic
public enum ShowType {
show2D,
show3D
}
@GeneratedValue(strategy = GenerationType.IDENTITY)
@BsonProperty("show_id")
private Long show_id;
@BsonProperty("room")
private Room room;
@BsonProperty("beginTime")
private LocalDateTime beginTime;
@BsonProperty("endTime")
private LocalDateTime endTime;
@BsonProperty("showType")
private ShowType showType;
// nie wiem jak to przerobic jak nie jest w konstruktorze
private Integer availableSeats;
public void decreaseSeats(){
availableSeats--;
}
@Override
public void close() throws Exception {
}
} | // nie wiem jak to przerobic jak nie jest w konstruktorze | package model;
import com.sun.istack.NotNull;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import net.bytebuddy.asm.Advice;
import org.bson.codecs.pojo.annotations.BsonCreator;
import org.bson.codecs.pojo.annotations.BsonProperty;
import repositories.UniqueIdMgd;
import java.time.LocalDateTime;
import java.util.UUID;
@Getter
@Setter
public class Show extends AbstractEntity{
@BsonCreator
public Show(@BsonProperty("id") UniqueIdMgd entityId,
@BsonProperty("show_id") Long show_id,
@BsonProperty("room") Room room,
@BsonProperty("beginTime") LocalDateTime beginTime,
@BsonProperty("endTime") LocalDateTime endTime,
@BsonProperty("showType") ShowType showType) {
super(entityId);
this.show_id = show_id;
this.room = room;
this.beginTime = beginTime;
this.endTime = endTime;
this.showType = showType;
this.availableSeats = room.getCapacity();
}
public Show(
Long show_id,
Room room,
LocalDateTime beginTime,
LocalDateTime endTime,
ShowType showType
){
super(new UniqueIdMgd());
this.show_id = show_id;
this.room = room;
this.beginTime = beginTime;
this.endTime = endTime;
this.showType = showType;
}
// Nie wem jak to przerobic
public enum ShowType {
show2D,
show3D
}
@GeneratedValue(strategy = GenerationType.IDENTITY)
@BsonProperty("show_id")
private Long show_id;
@BsonProperty("room")
private Room room;
@BsonProperty("beginTime")
private LocalDateTime beginTime;
@BsonProperty("endTime")
private LocalDateTime endTime;
@BsonProperty("showType")
private ShowType showType;
// nie wiem <SUF>
private Integer availableSeats;
public void decreaseSeats(){
availableSeats--;
}
@Override
public void close() throws Exception {
}
} | f |
5207_8 | lumgwun/Dating-And-Chat-App | 4,697 | app/src/main/java/com/lahoriagency/cikolive/Fragments/TestFragment.java | package com.lahoriagency.cikolive.Fragments;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.kofigyan.stateprogressbar.StateProgressBar;
import com.lahoriagency.cikolive.Classes.AppChat;
import com.lahoriagency.cikolive.Classes.AppE;
import com.lahoriagency.cikolive.Classes.BaseAsyncTask22;
import com.lahoriagency.cikolive.Classes.MyPreferences;
import com.lahoriagency.cikolive.Classes.PersonalityTrait;
import com.lahoriagency.cikolive.Classes.TestRequest;
import com.lahoriagency.cikolive.Interfaces.ServerMethodsConsts;
import com.lahoriagency.cikolive.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class TestFragment extends Fragment {
private ScrollView scrollView;
private SeekBar SliderQ1;
private SeekBar SliderQ2;
private SeekBar SliderQ3;
private SeekBar SliderQ4;
private SeekBar SliderQ5;
private SeekBar SliderQ6;
private SeekBar[] sliders;
private StateProgressBar pageProgressBar;
private TextView[] textViews;
private PersonalityTrait[] personalityTraits;
String[] allQuestions;
private ArrayList<Integer> shuffledQuestionIndexes;
private int numberOfScreens;
private int actualScreen;
private int numberOfQuestionsPerPage;
private float range;
private MyPreferences myPreferences;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
myPreferences = AppE.getPreferences();
range = 120;
actualScreen = 0;
numberOfScreens = 4;
numberOfQuestionsPerPage = 6;
allQuestions = new String[numberOfScreens * numberOfQuestionsPerPage];
shuffledQuestionIndexes = new ArrayList<>();
for (int i = 0; i < allQuestions.length; i++)
shuffledQuestionIndexes.add(i + 1);
Collections.shuffle(shuffledQuestionIndexes);
scrollView = (ScrollView) view.findViewById(R.id.test_container_scrollView);
SliderQ1 = (SeekBar) view.findViewById(R.id.sliderQ1);
SliderQ2 = (SeekBar) view.findViewById(R.id.sliderQ2);
SliderQ3 = (SeekBar) view.findViewById(R.id.sliderQ3);
SliderQ4 = (SeekBar) view.findViewById(R.id.sliderQ4);
SliderQ5 = (SeekBar) view.findViewById(R.id.sliderQ5);
SliderQ6 = (SeekBar) view.findViewById(R.id.sliderQ6);
sliders = new SeekBar[]{SliderQ1, SliderQ2, SliderQ3, SliderQ4, SliderQ5, SliderQ6};
for (SeekBar s : sliders) {
s.setOnSeekBarChangeListener(seekBarChangeListener);
s.setProgress(51);
s.setProgress(50);
}
TextView textQ1 = (TextView) view.findViewById(R.id.TextQ1);
TextView textQ2 = (TextView) view.findViewById(R.id.TextQ2);
TextView textQ3 = (TextView) view.findViewById(R.id.TextQ3);
TextView textQ4 = (TextView) view.findViewById(R.id.TextQ4);
TextView textQ5 = (TextView) view.findViewById(R.id.TextQ5);
TextView textQ6 = (TextView) view.findViewById(R.id.TextQ6);
textViews = new TextView[]{textQ1, textQ2, textQ3, textQ4, textQ5, textQ6};
Button nextQuestions = (Button) view.findViewById(R.id.nextQuestions);
nextQuestions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawQuestions();
}
});
pageProgressBar = (StateProgressBar) view.findViewById(R.id.pageProgressBar);
String[] questionsJ = new String[4];
// Tworzę listę zadań do wykonania i trzymam się jej
questionsJ[0] = "I create to-do list and stick to it";
// Skupiam się na jednej rzeczy do wykonania na raz
questionsJ[1] = "I focus on one thing at a time";
// Moja praca jest metodyczna i zorganizowana
questionsJ[2] = "My work is methodical and organized";
// Nie lubię niespodziewanych wydarzeń
questionsJ[3] = "I don't like unexpected events";
int[] numbers = new int[]{1, 2, 3, 4};
System.arraycopy(questionsJ, 0, allQuestions, 0, questionsJ.length);
PersonalityTrait JTrait = new PersonalityTrait("J", questionsJ, numbers);
String[] questionsP = new String[2];
// Jestem najbardziej efektywny, kiedy wykonuję swoje zadania na ostatnią chwilę
questionsP[0] = "I am most effective when I complete my tasks at the last minute";
// Często podejmuję decyzje impulsywnie
questionsP[1] = "I often make decisions impulsively";
numbers = new int[]{5, 6};
System.arraycopy(questionsP, 0, allQuestions, 4, questionsP.length);
PersonalityTrait PTrait = new PersonalityTrait("P", questionsP, numbers);
String[] questionsN = new String[3];
// Żyję bardziej w swojej głowie, niż w świecie rzeczywistym
questionsN[0] = "I live more in my head than in the real world";
// Fantazjowanie często sprawia mi większą przyjemność niż realne doznania
questionsN[1] = "Fantasizing often give more joy than real sensations";
// Wolę wymyślać nowe sposoby na rozwiązanie problemu, niż korzystać ze sprawdzonych
questionsN[2] = "I prefer to invent new ways to solve problems, than using a proven ones";
numbers = new int[]{7, 8, 9};
System.arraycopy(questionsN, 0, allQuestions, 6, questionsN.length);
PersonalityTrait NTrait = new PersonalityTrait("N", questionsN, numbers);
NTrait.setScore(40);
String[] questionsS = new String[3];
// Stąpam twardo po ziemi
questionsS[0] = "I keep my feet firmly on the ground";
// Wolę skupić się na rzeczywistości, niż oddawać fantazjom
questionsS[1] = "I prefer to focus on reality than indulge in fantasies";
// Aktywność fizyczna sprawia mi większą przyjemność niż umysłowa
questionsS[2] = "Psychical activity is more enjoyable than mental one";
numbers = new int[]{10, 11, 12};
System.arraycopy(questionsS, 0, allQuestions, 9, questionsS.length);
PersonalityTrait STrait = new PersonalityTrait("S", questionsS, numbers);
STrait.setScore(60);
String[] questionsE = {
// Mówienie o moich problemach nie jest dla mnie trudne
"It is not difficult for me to talk about my problems",
// Lubię być w centrum uwagi
"I like being the center of attention",
// Łatwo nawiązuję nowe znajomości
"I easily make new friendships",
// Często rozpoczynam rozmowę
"I start conversations often"};
numbers = new int[]{13, 14, 15, 16};
System.arraycopy(questionsE, 0, allQuestions, 12, questionsE.length);
PersonalityTrait ETrait = new PersonalityTrait("E", questionsE, numbers);
String[] questionsI = new String[2];
// Chętnie chodzę na samotne spacery z dala od zgiełku i hałasu
questionsI[0] = "I like to go for lonely walks away from the hustle and bustle";
// Wolę przysłuchiwać się dyskusji niż w niej uczestniczyć
questionsI[1] = "I prefer to listen to the discussion than to participate in it";
numbers = new int[]{17, 18};
System.arraycopy(questionsI, 0, allQuestions, 16, questionsI.length);
PersonalityTrait ITrait = new PersonalityTrait("I", questionsI, numbers);
String[] questionsF = new String[3];
// Unikam kłótni, nawet jeśli wiem, że mam rację
questionsF[0] = "I avoid arguing, even if I know I'm right";
// Subiektywne odczucia mają duży wpływ na moje decyzje
questionsF[1] = "Subjective feelings have a big influence on my decisions";
// Wyrażanie swoich uczuć nie sprawia mi problemu
questionsF[2] = "I have no problem expressing my feelings";
numbers = new int[]{19, 20, 21};
System.arraycopy(questionsF, 0, allQuestions, 18, questionsF.length);
PersonalityTrait FTrait = new PersonalityTrait("F", questionsF, numbers);
String[] questionsT = new String[3];
// Wolę być postrzegany jako ktoś niemiły, niż nielogiczny
questionsT[0] = "I'd rather be seen as rude than illogical";
// Uważam, że logiczne rozwiązania są zawsze najlepsze
questionsT[1] = "I believe logical solutions are always the best";
// Jestem bezpośredni, nawet jeśli mogę tym kogoś zranić"
questionsT[2] = "I am straightforward, even if it can hurt somebody";
numbers = new int[]{22, 23, 24};
System.arraycopy(questionsT, 0, allQuestions, 21, questionsT.length);
PersonalityTrait TTrait = new PersonalityTrait("T", questionsT, numbers);
personalityTraits = new PersonalityTrait[]{ETrait, ITrait, NTrait, STrait, TTrait, JTrait, FTrait, PTrait};
drawQuestions();
return view;
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
double barProgress = seekBar.getProgress();
float max = (float) seekBar.getMax();
float h = 15 + (float) ((max / range) * barProgress);
float s = 100;
float v = 90;
String hexColor = hsvToRgb(h, s, v);
//String hexColor = String.format("#%06X", (0xFFFFFF & color));
seekBar.getProgressDrawable().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
public void saveAnswers() {
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
for (PersonalityTrait temp : personalityTraits) {
if (temp.containsNumber(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i))) {
temp.saveScore(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i), Math.round(sliders[i].getProgress()));
break;
}
}
}
}
public void drawQuestions() {
if (actualScreen < numberOfScreens) {
if (actualScreen > 0)
saveAnswers();
actualScreen++;
switch (actualScreen) {
case 2:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO);
break;
case 3:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.THREE);
break;
case 4:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.FOUR);
break;
default:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.ONE);
}
SliderQ1.setProgress(50);
SliderQ2.setProgress(50);
SliderQ3.setProgress(50);
SliderQ4.setProgress(50);
SliderQ5.setProgress(50);
SliderQ6.setProgress(50);
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
textViews[i].setText(allQuestions[shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i) - 1]);
}
scrollView.scrollTo(0, 0);
} else {
saveAnswers();
HashMap<String, String> answers = new HashMap<>();
for (PersonalityTrait tr : personalityTraits) {
for (int i = 0; i < tr.getNumbersOfQuestions().length; i++) {
answers.put("q" + tr.getNumbersOfQuestions()[i], String.valueOf(tr.getAnswerPoints()[i]));
}
}
TestRequest testRequest = new TestRequest(myPreferences.getUserId(), 24, answers);
BaseAsyncTask22<TestRequest> sendResults = new BaseAsyncTask22<>(ServerMethodsConsts.TEST, testRequest);
sendResults.setHttpMethod("POST");
sendResults.execute();
showResults();
}
}
private void showResults() {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_content, new TestResultsFragment());
ft.commit();
}
public static String hsvToRgb(float H, float S, float V) {
float R, G, B;
H /= 360f;
S /= 100f;
V /= 100f;
if (S == 0) {
R = V * 255;
G = V * 255;
B = V * 255;
} else {
float var_h = H * 6;
if (var_h == 6)
var_h = 0; // H must be < 1
int var_i = (int) Math.floor((double) var_h); // Or ... var_i =
// floor( var_h )
float var_1 = V * (1 - S);
float var_2 = V * (1 - S * (var_h - var_i));
float var_3 = V * (1 - S * (1 - (var_h - var_i)));
float var_r;
float var_g;
float var_b;
if (var_i == 0) {
var_r = V;
var_g = var_3;
var_b = var_1;
} else if (var_i == 1) {
var_r = var_2;
var_g = V;
var_b = var_1;
} else if (var_i == 2) {
var_r = var_1;
var_g = V;
var_b = var_3;
} else if (var_i == 3) {
var_r = var_1;
var_g = var_2;
var_b = V;
} else if (var_i == 4) {
var_r = var_3;
var_g = var_1;
var_b = V;
} else {
var_r = V;
var_g = var_1;
var_b = var_2;
}
R = var_r * 255;
G = var_g * 255;
B = var_b * 255;
}
String rs = Integer.toHexString((int) (R));
String gs = Integer.toHexString((int) (G));
String bs = Integer.toHexString((int) (B));
if (rs.length() == 1)
rs = "0" + rs;
if (gs.length() == 1)
gs = "0" + gs;
if (bs.length() == 1)
bs = "0" + bs;
return "#" + rs + gs + bs;
}
}
| // Wolę wymyślać nowe sposoby na rozwiązanie problemu, niż korzystać ze sprawdzonych | package com.lahoriagency.cikolive.Fragments;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.kofigyan.stateprogressbar.StateProgressBar;
import com.lahoriagency.cikolive.Classes.AppChat;
import com.lahoriagency.cikolive.Classes.AppE;
import com.lahoriagency.cikolive.Classes.BaseAsyncTask22;
import com.lahoriagency.cikolive.Classes.MyPreferences;
import com.lahoriagency.cikolive.Classes.PersonalityTrait;
import com.lahoriagency.cikolive.Classes.TestRequest;
import com.lahoriagency.cikolive.Interfaces.ServerMethodsConsts;
import com.lahoriagency.cikolive.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class TestFragment extends Fragment {
private ScrollView scrollView;
private SeekBar SliderQ1;
private SeekBar SliderQ2;
private SeekBar SliderQ3;
private SeekBar SliderQ4;
private SeekBar SliderQ5;
private SeekBar SliderQ6;
private SeekBar[] sliders;
private StateProgressBar pageProgressBar;
private TextView[] textViews;
private PersonalityTrait[] personalityTraits;
String[] allQuestions;
private ArrayList<Integer> shuffledQuestionIndexes;
private int numberOfScreens;
private int actualScreen;
private int numberOfQuestionsPerPage;
private float range;
private MyPreferences myPreferences;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
myPreferences = AppE.getPreferences();
range = 120;
actualScreen = 0;
numberOfScreens = 4;
numberOfQuestionsPerPage = 6;
allQuestions = new String[numberOfScreens * numberOfQuestionsPerPage];
shuffledQuestionIndexes = new ArrayList<>();
for (int i = 0; i < allQuestions.length; i++)
shuffledQuestionIndexes.add(i + 1);
Collections.shuffle(shuffledQuestionIndexes);
scrollView = (ScrollView) view.findViewById(R.id.test_container_scrollView);
SliderQ1 = (SeekBar) view.findViewById(R.id.sliderQ1);
SliderQ2 = (SeekBar) view.findViewById(R.id.sliderQ2);
SliderQ3 = (SeekBar) view.findViewById(R.id.sliderQ3);
SliderQ4 = (SeekBar) view.findViewById(R.id.sliderQ4);
SliderQ5 = (SeekBar) view.findViewById(R.id.sliderQ5);
SliderQ6 = (SeekBar) view.findViewById(R.id.sliderQ6);
sliders = new SeekBar[]{SliderQ1, SliderQ2, SliderQ3, SliderQ4, SliderQ5, SliderQ6};
for (SeekBar s : sliders) {
s.setOnSeekBarChangeListener(seekBarChangeListener);
s.setProgress(51);
s.setProgress(50);
}
TextView textQ1 = (TextView) view.findViewById(R.id.TextQ1);
TextView textQ2 = (TextView) view.findViewById(R.id.TextQ2);
TextView textQ3 = (TextView) view.findViewById(R.id.TextQ3);
TextView textQ4 = (TextView) view.findViewById(R.id.TextQ4);
TextView textQ5 = (TextView) view.findViewById(R.id.TextQ5);
TextView textQ6 = (TextView) view.findViewById(R.id.TextQ6);
textViews = new TextView[]{textQ1, textQ2, textQ3, textQ4, textQ5, textQ6};
Button nextQuestions = (Button) view.findViewById(R.id.nextQuestions);
nextQuestions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawQuestions();
}
});
pageProgressBar = (StateProgressBar) view.findViewById(R.id.pageProgressBar);
String[] questionsJ = new String[4];
// Tworzę listę zadań do wykonania i trzymam się jej
questionsJ[0] = "I create to-do list and stick to it";
// Skupiam się na jednej rzeczy do wykonania na raz
questionsJ[1] = "I focus on one thing at a time";
// Moja praca jest metodyczna i zorganizowana
questionsJ[2] = "My work is methodical and organized";
// Nie lubię niespodziewanych wydarzeń
questionsJ[3] = "I don't like unexpected events";
int[] numbers = new int[]{1, 2, 3, 4};
System.arraycopy(questionsJ, 0, allQuestions, 0, questionsJ.length);
PersonalityTrait JTrait = new PersonalityTrait("J", questionsJ, numbers);
String[] questionsP = new String[2];
// Jestem najbardziej efektywny, kiedy wykonuję swoje zadania na ostatnią chwilę
questionsP[0] = "I am most effective when I complete my tasks at the last minute";
// Często podejmuję decyzje impulsywnie
questionsP[1] = "I often make decisions impulsively";
numbers = new int[]{5, 6};
System.arraycopy(questionsP, 0, allQuestions, 4, questionsP.length);
PersonalityTrait PTrait = new PersonalityTrait("P", questionsP, numbers);
String[] questionsN = new String[3];
// Żyję bardziej w swojej głowie, niż w świecie rzeczywistym
questionsN[0] = "I live more in my head than in the real world";
// Fantazjowanie często sprawia mi większą przyjemność niż realne doznania
questionsN[1] = "Fantasizing often give more joy than real sensations";
// Wolę wymyślać <SUF>
questionsN[2] = "I prefer to invent new ways to solve problems, than using a proven ones";
numbers = new int[]{7, 8, 9};
System.arraycopy(questionsN, 0, allQuestions, 6, questionsN.length);
PersonalityTrait NTrait = new PersonalityTrait("N", questionsN, numbers);
NTrait.setScore(40);
String[] questionsS = new String[3];
// Stąpam twardo po ziemi
questionsS[0] = "I keep my feet firmly on the ground";
// Wolę skupić się na rzeczywistości, niż oddawać fantazjom
questionsS[1] = "I prefer to focus on reality than indulge in fantasies";
// Aktywność fizyczna sprawia mi większą przyjemność niż umysłowa
questionsS[2] = "Psychical activity is more enjoyable than mental one";
numbers = new int[]{10, 11, 12};
System.arraycopy(questionsS, 0, allQuestions, 9, questionsS.length);
PersonalityTrait STrait = new PersonalityTrait("S", questionsS, numbers);
STrait.setScore(60);
String[] questionsE = {
// Mówienie o moich problemach nie jest dla mnie trudne
"It is not difficult for me to talk about my problems",
// Lubię być w centrum uwagi
"I like being the center of attention",
// Łatwo nawiązuję nowe znajomości
"I easily make new friendships",
// Często rozpoczynam rozmowę
"I start conversations often"};
numbers = new int[]{13, 14, 15, 16};
System.arraycopy(questionsE, 0, allQuestions, 12, questionsE.length);
PersonalityTrait ETrait = new PersonalityTrait("E", questionsE, numbers);
String[] questionsI = new String[2];
// Chętnie chodzę na samotne spacery z dala od zgiełku i hałasu
questionsI[0] = "I like to go for lonely walks away from the hustle and bustle";
// Wolę przysłuchiwać się dyskusji niż w niej uczestniczyć
questionsI[1] = "I prefer to listen to the discussion than to participate in it";
numbers = new int[]{17, 18};
System.arraycopy(questionsI, 0, allQuestions, 16, questionsI.length);
PersonalityTrait ITrait = new PersonalityTrait("I", questionsI, numbers);
String[] questionsF = new String[3];
// Unikam kłótni, nawet jeśli wiem, że mam rację
questionsF[0] = "I avoid arguing, even if I know I'm right";
// Subiektywne odczucia mają duży wpływ na moje decyzje
questionsF[1] = "Subjective feelings have a big influence on my decisions";
// Wyrażanie swoich uczuć nie sprawia mi problemu
questionsF[2] = "I have no problem expressing my feelings";
numbers = new int[]{19, 20, 21};
System.arraycopy(questionsF, 0, allQuestions, 18, questionsF.length);
PersonalityTrait FTrait = new PersonalityTrait("F", questionsF, numbers);
String[] questionsT = new String[3];
// Wolę być postrzegany jako ktoś niemiły, niż nielogiczny
questionsT[0] = "I'd rather be seen as rude than illogical";
// Uważam, że logiczne rozwiązania są zawsze najlepsze
questionsT[1] = "I believe logical solutions are always the best";
// Jestem bezpośredni, nawet jeśli mogę tym kogoś zranić"
questionsT[2] = "I am straightforward, even if it can hurt somebody";
numbers = new int[]{22, 23, 24};
System.arraycopy(questionsT, 0, allQuestions, 21, questionsT.length);
PersonalityTrait TTrait = new PersonalityTrait("T", questionsT, numbers);
personalityTraits = new PersonalityTrait[]{ETrait, ITrait, NTrait, STrait, TTrait, JTrait, FTrait, PTrait};
drawQuestions();
return view;
}
private SeekBar.OnSeekBarChangeListener seekBarChangeListener
= new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
double barProgress = seekBar.getProgress();
float max = (float) seekBar.getMax();
float h = 15 + (float) ((max / range) * barProgress);
float s = 100;
float v = 90;
String hexColor = hsvToRgb(h, s, v);
//String hexColor = String.format("#%06X", (0xFFFFFF & color));
seekBar.getProgressDrawable().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(Color.parseColor(hexColor), PorterDuff.Mode.SRC_IN);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
public void saveAnswers() {
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
for (PersonalityTrait temp : personalityTraits) {
if (temp.containsNumber(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i))) {
temp.saveScore(shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i), Math.round(sliders[i].getProgress()));
break;
}
}
}
}
public void drawQuestions() {
if (actualScreen < numberOfScreens) {
if (actualScreen > 0)
saveAnswers();
actualScreen++;
switch (actualScreen) {
case 2:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO);
break;
case 3:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.THREE);
break;
case 4:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.FOUR);
break;
default:
pageProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.ONE);
}
SliderQ1.setProgress(50);
SliderQ2.setProgress(50);
SliderQ3.setProgress(50);
SliderQ4.setProgress(50);
SliderQ5.setProgress(50);
SliderQ6.setProgress(50);
for (int i = 0; i < numberOfQuestionsPerPage; i++) {
textViews[i].setText(allQuestions[shuffledQuestionIndexes.get(numberOfQuestionsPerPage * (actualScreen - 1) + i) - 1]);
}
scrollView.scrollTo(0, 0);
} else {
saveAnswers();
HashMap<String, String> answers = new HashMap<>();
for (PersonalityTrait tr : personalityTraits) {
for (int i = 0; i < tr.getNumbersOfQuestions().length; i++) {
answers.put("q" + tr.getNumbersOfQuestions()[i], String.valueOf(tr.getAnswerPoints()[i]));
}
}
TestRequest testRequest = new TestRequest(myPreferences.getUserId(), 24, answers);
BaseAsyncTask22<TestRequest> sendResults = new BaseAsyncTask22<>(ServerMethodsConsts.TEST, testRequest);
sendResults.setHttpMethod("POST");
sendResults.execute();
showResults();
}
}
private void showResults() {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_content, new TestResultsFragment());
ft.commit();
}
public static String hsvToRgb(float H, float S, float V) {
float R, G, B;
H /= 360f;
S /= 100f;
V /= 100f;
if (S == 0) {
R = V * 255;
G = V * 255;
B = V * 255;
} else {
float var_h = H * 6;
if (var_h == 6)
var_h = 0; // H must be < 1
int var_i = (int) Math.floor((double) var_h); // Or ... var_i =
// floor( var_h )
float var_1 = V * (1 - S);
float var_2 = V * (1 - S * (var_h - var_i));
float var_3 = V * (1 - S * (1 - (var_h - var_i)));
float var_r;
float var_g;
float var_b;
if (var_i == 0) {
var_r = V;
var_g = var_3;
var_b = var_1;
} else if (var_i == 1) {
var_r = var_2;
var_g = V;
var_b = var_1;
} else if (var_i == 2) {
var_r = var_1;
var_g = V;
var_b = var_3;
} else if (var_i == 3) {
var_r = var_1;
var_g = var_2;
var_b = V;
} else if (var_i == 4) {
var_r = var_3;
var_g = var_1;
var_b = V;
} else {
var_r = V;
var_g = var_1;
var_b = var_2;
}
R = var_r * 255;
G = var_g * 255;
B = var_b * 255;
}
String rs = Integer.toHexString((int) (R));
String gs = Integer.toHexString((int) (G));
String bs = Integer.toHexString((int) (B));
if (rs.length() == 1)
rs = "0" + rs;
if (gs.length() == 1)
gs = "0" + gs;
if (bs.length() == 1)
bs = "0" + bs;
return "#" + rs + gs + bs;
}
}
| f |
10330_2 | lutencjusz/TestJava | 2,419 | src/main/java/ZipArchive.java | import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.Getter;
import lombok.Setter;
import org.fusesource.jansi.Ansi;
import java.io.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipArchive {
static List<String> excludedPathAndFiles;
static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
static DateTimeFormatter showDateTime = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
static LocalDateTime today = LocalDateTime.now();
private static final File MAIN_PATH = new File("C:\\Data\\Java");
private static final String PREFIX_ZIPPED_FILES = "C:\\Users\\micha\\Dropbox\\backup aplikacji\\";
private static final Set<String> pathSet = new HashSet<>();
private static final int MAX_QUEUE = 5;
private static final int WEEKS_NUMBER = 2;
private static final String END_FILE = "end";
public static void main(String[] args) {
excludedPathAndFiles = loadExcludes("C:\\Data\\Java\\TestJava\\excludes.json");
BlockingQueue<String> queue = new ArrayBlockingQueue<>(MAX_QUEUE);
new Thread(new ZipArchive.SearcherFiles(MAIN_PATH, queue)).start();
for (int i = 0; i < MAX_QUEUE; i++) {
new Thread(new SearcherMatchingModifiedDateInFiles(queue)).start();
}
}
private static List<String> loadExcludes(String filePath) {
try {
FileReader reader = new FileReader(filePath);
List<String> excludes = new Gson().fromJson(reader, new TypeToken<ArrayList<String>>() {
}.getType());
reader.close();
return excludes;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static void saveExcludes(List<String> excludes) {
excludes.add("modules");
excludes.add("target");
excludes.add(".idea");
excludes.add("node_modules");
excludes.add("TestJava");
Gson gson = new Gson();
String json = gson.toJson(excludedPathAndFiles);
try {
FileWriter writer = new FileWriter("excludes.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static class SearcherFiles implements Runnable {
File searchingPath;
BlockingQueue<String> queue;
public SearcherFiles(File searchingPath, BlockingQueue<String> queue) {
this.searchingPath = searchingPath;
this.queue = queue;
}
@Override
public void run() {
try {
searcherPath(searchingPath, "");
queue.put(END_FILE);
} catch (InterruptedException e) {
System.out.println("Błąd przeszukiwacza ścieżek: " + e.getMessage());
}
}
public void searcherPath(File path, String mainPath) throws InterruptedException {
String filePath;
File[] paths = path.listFiles();
if (paths != null && paths.length > 0) {
for (File file : paths) {
filePath = mainPath.isEmpty() ? file.getPath() : mainPath;
if (file.isDirectory()) {
// System.out.println("Przeszukuję katalog: " + file.getPath());
searcherPath(file, filePath);
} else {
boolean isPathFound = false;
for (String ex : excludedPathAndFiles) {
if (file.getPath().contains(ex)) {
isPathFound = true;
break;
}
}
if (!isPathFound && isFileModifyDateBetweenDates(file.getPath(), today.minusDays(WEEKS_NUMBER), today)) {
// System.out.println("Zmodyfikowany plik: '" + file.getPath() + "'");
if (!pathSet.contains(filePath)) {
System.out.println(Ansi.ansi().fg(Ansi.Color.YELLOW).a("Zmodyfikowany plik '" + file.getPath() + "' "
+ LocalDateTime.ofInstant(new Date(file.lastModified()).toInstant(), ZoneId.systemDefault()).format(showDateTime)
+ ", więc będę kompresował '" + filePath + "'...").reset());
pathSet.add(filePath);
queue.put(filePath);
}
return;
}
}
}
}
}
}
static class SearcherMatchingModifiedDateInFiles implements Runnable {
BlockingQueue<String> queue;
public SearcherMatchingModifiedDateInFiles(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
boolean isSearchingFinished = false;
while (!isSearchingFinished) {
String searchingFile = queue.take();
// System.out.println("Pobieram z kolejki plik: " + searchingFile.getName());
if (searchingFile.equals(END_FILE)) {
isSearchingFinished = true;
queue.put(END_FILE);
} else {
System.out.println("Kompresuje '" + searchingFile + "'...");
compressToZipDirectory zip = new compressToZipDirectory(searchingFile);
System.out.println(Ansi.ansi().fg(Ansi.Color.GREEN).a("Zakończyłem kompresję '" + searchingFile + "', rozmiar przed kompresją: "
+ zip.getFileSpace() / 1000 + " KB ,rozmiar po kompresji: "
+ zip.getFileZipSpace() / 1000 + " KB").reset());
}
}
} catch (Exception e) {
System.out.println("Błąd przeszukiwania pliku: " + e.getMessage());
}
}
}
public static boolean isFileModifyDateBetweenDates(String filePath, LocalDateTime beginDate, LocalDateTime endDate) {
LocalDateTime lastModifyDate = LocalDateTime.ofInstant(new Date(new File(filePath).lastModified()).toInstant(), ZoneId.systemDefault());
return (beginDate.isBefore(lastModifyDate) && endDate.isAfter(lastModifyDate));
}
@Getter
@Setter
static class compressToZipDirectory {
ZipOutputStream zos;
File srcDir;
FileOutputStream fos;
Long fileSpace;
Long fileZipSpace;
public compressToZipDirectory(String dir) {
if (dir.isBlank()) System.out.println("Brak katalogów do kompresji");
try {
this.fileSpace = 0L;
this.fileZipSpace = 0L;
this.srcDir = new File(dir);
this.fos = new FileOutputStream(PREFIX_ZIPPED_FILES + srcDir.getName() + "_" + today.format(dateTimeFormatter) + ".zip");
this.zos = new ZipOutputStream(new BufferedOutputStream(fos));
addDirectory(srcDir, srcDir);
this.zos.close();
this.fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void addDirectory(File baseDir, File dir) throws IOException {
File[] files = dir.listFiles();
assert files != null;
for (File file : files) {
if (file.isDirectory()) {
addDirectory(baseDir, file);
continue;
}
String name = file.getCanonicalPath().substring(baseDir.getCanonicalPath().length() + 1);
boolean isPathFound = false;
for (String ex : excludedPathAndFiles) {
if (name.contains(ex)) {
isPathFound = true;
// System.out.println("wykluczam: " + file.getCanonicalPath());
break;
}
}
if (isPathFound) continue;
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(name);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[4096];
int length;
// System.out.print(file.getPath() + " ");
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
fileSpace += length;
// System.out.print(".");
}
zos.closeEntry();
fileZipSpace += zipEntry.getCompressedSize();
fis.close();
}
}
}
}
| // System.out.println("Pobieram z kolejki plik: " + searchingFile.getName()); | import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.Getter;
import lombok.Setter;
import org.fusesource.jansi.Ansi;
import java.io.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipArchive {
static List<String> excludedPathAndFiles;
static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
static DateTimeFormatter showDateTime = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
static LocalDateTime today = LocalDateTime.now();
private static final File MAIN_PATH = new File("C:\\Data\\Java");
private static final String PREFIX_ZIPPED_FILES = "C:\\Users\\micha\\Dropbox\\backup aplikacji\\";
private static final Set<String> pathSet = new HashSet<>();
private static final int MAX_QUEUE = 5;
private static final int WEEKS_NUMBER = 2;
private static final String END_FILE = "end";
public static void main(String[] args) {
excludedPathAndFiles = loadExcludes("C:\\Data\\Java\\TestJava\\excludes.json");
BlockingQueue<String> queue = new ArrayBlockingQueue<>(MAX_QUEUE);
new Thread(new ZipArchive.SearcherFiles(MAIN_PATH, queue)).start();
for (int i = 0; i < MAX_QUEUE; i++) {
new Thread(new SearcherMatchingModifiedDateInFiles(queue)).start();
}
}
private static List<String> loadExcludes(String filePath) {
try {
FileReader reader = new FileReader(filePath);
List<String> excludes = new Gson().fromJson(reader, new TypeToken<ArrayList<String>>() {
}.getType());
reader.close();
return excludes;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static void saveExcludes(List<String> excludes) {
excludes.add("modules");
excludes.add("target");
excludes.add(".idea");
excludes.add("node_modules");
excludes.add("TestJava");
Gson gson = new Gson();
String json = gson.toJson(excludedPathAndFiles);
try {
FileWriter writer = new FileWriter("excludes.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static class SearcherFiles implements Runnable {
File searchingPath;
BlockingQueue<String> queue;
public SearcherFiles(File searchingPath, BlockingQueue<String> queue) {
this.searchingPath = searchingPath;
this.queue = queue;
}
@Override
public void run() {
try {
searcherPath(searchingPath, "");
queue.put(END_FILE);
} catch (InterruptedException e) {
System.out.println("Błąd przeszukiwacza ścieżek: " + e.getMessage());
}
}
public void searcherPath(File path, String mainPath) throws InterruptedException {
String filePath;
File[] paths = path.listFiles();
if (paths != null && paths.length > 0) {
for (File file : paths) {
filePath = mainPath.isEmpty() ? file.getPath() : mainPath;
if (file.isDirectory()) {
// System.out.println("Przeszukuję katalog: " + file.getPath());
searcherPath(file, filePath);
} else {
boolean isPathFound = false;
for (String ex : excludedPathAndFiles) {
if (file.getPath().contains(ex)) {
isPathFound = true;
break;
}
}
if (!isPathFound && isFileModifyDateBetweenDates(file.getPath(), today.minusDays(WEEKS_NUMBER), today)) {
// System.out.println("Zmodyfikowany plik: '" + file.getPath() + "'");
if (!pathSet.contains(filePath)) {
System.out.println(Ansi.ansi().fg(Ansi.Color.YELLOW).a("Zmodyfikowany plik '" + file.getPath() + "' "
+ LocalDateTime.ofInstant(new Date(file.lastModified()).toInstant(), ZoneId.systemDefault()).format(showDateTime)
+ ", więc będę kompresował '" + filePath + "'...").reset());
pathSet.add(filePath);
queue.put(filePath);
}
return;
}
}
}
}
}
}
static class SearcherMatchingModifiedDateInFiles implements Runnable {
BlockingQueue<String> queue;
public SearcherMatchingModifiedDateInFiles(BlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
boolean isSearchingFinished = false;
while (!isSearchingFinished) {
String searchingFile = queue.take();
// System.out.println("Pobieram z <SUF>
if (searchingFile.equals(END_FILE)) {
isSearchingFinished = true;
queue.put(END_FILE);
} else {
System.out.println("Kompresuje '" + searchingFile + "'...");
compressToZipDirectory zip = new compressToZipDirectory(searchingFile);
System.out.println(Ansi.ansi().fg(Ansi.Color.GREEN).a("Zakończyłem kompresję '" + searchingFile + "', rozmiar przed kompresją: "
+ zip.getFileSpace() / 1000 + " KB ,rozmiar po kompresji: "
+ zip.getFileZipSpace() / 1000 + " KB").reset());
}
}
} catch (Exception e) {
System.out.println("Błąd przeszukiwania pliku: " + e.getMessage());
}
}
}
public static boolean isFileModifyDateBetweenDates(String filePath, LocalDateTime beginDate, LocalDateTime endDate) {
LocalDateTime lastModifyDate = LocalDateTime.ofInstant(new Date(new File(filePath).lastModified()).toInstant(), ZoneId.systemDefault());
return (beginDate.isBefore(lastModifyDate) && endDate.isAfter(lastModifyDate));
}
@Getter
@Setter
static class compressToZipDirectory {
ZipOutputStream zos;
File srcDir;
FileOutputStream fos;
Long fileSpace;
Long fileZipSpace;
public compressToZipDirectory(String dir) {
if (dir.isBlank()) System.out.println("Brak katalogów do kompresji");
try {
this.fileSpace = 0L;
this.fileZipSpace = 0L;
this.srcDir = new File(dir);
this.fos = new FileOutputStream(PREFIX_ZIPPED_FILES + srcDir.getName() + "_" + today.format(dateTimeFormatter) + ".zip");
this.zos = new ZipOutputStream(new BufferedOutputStream(fos));
addDirectory(srcDir, srcDir);
this.zos.close();
this.fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void addDirectory(File baseDir, File dir) throws IOException {
File[] files = dir.listFiles();
assert files != null;
for (File file : files) {
if (file.isDirectory()) {
addDirectory(baseDir, file);
continue;
}
String name = file.getCanonicalPath().substring(baseDir.getCanonicalPath().length() + 1);
boolean isPathFound = false;
for (String ex : excludedPathAndFiles) {
if (name.contains(ex)) {
isPathFound = true;
// System.out.println("wykluczam: " + file.getCanonicalPath());
break;
}
}
if (isPathFound) continue;
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(name);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[4096];
int length;
// System.out.print(file.getPath() + " ");
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
fileSpace += length;
// System.out.print(".");
}
zos.closeEntry();
fileZipSpace += zipEntry.getCompressedSize();
fis.close();
}
}
}
}
| f |
3901_43 | m87/Savanna | 4,447 | sawanna/Hyena.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sawanna;
import java.util.HashMap;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Bartosz Radliński
*/
public class Hyena extends Mammal implements Runnable {
/**
* Grafika
*/
static private String spName = ISettings.HYENA;
/**
* Tempo wzrostu
*/
static private int size_age = 1;
/**
* Tempo starzenia
*/
static private int agingRate = 1;
/**
* Tempo reprodukcji
*/
static private int reproductionRate = 50;
/**
* @return the velocity
*/
public static int getVelocity() {
return velocity;
}
/**
* @param aVelocity the velocity to set
*/
public static void setVelocity(int aVelocity) {
velocity = aVelocity;
}
/**
* Czas odpoczynku
*/
private static int restTime = 20;
/**
* Gdzie malować
*/
static private Board sce;
/**
* @return the restTime
*/
public static int getRestTime() {
return restTime;
}
/**
* @param aRestTime the restTime to set
*/
public static void setRestTime(int aRestTime) {
restTime = aRestTime;
}
/**
* Licznik czasu odpoczynku
*/
private int restTimer = 0;
public static int[] Terrytory = new int[4];
/**
* Tempo jedzenia
*/
private static int eatingRate = 5;
/**
* Tempo picia
*/
private static int drinkingRate = 5;
/**
* Tempo spalania energii
*/
private static int energyRate = 1;
/**
* Prędkość
*/
private static int velocity = 100;
/**
* Licznik urodzenia
*/
private int born = 0;
/**
* Kolekcja punktów drogi do wodopoju
*/
public static HashMap WaterPlaceRoad = new HashMap();
/**
* Iterator
*/
private int WaterPlaceRoadInc;
/**
* Licznik stanu okresu
*/
private int period = 0;
/**
* Inicjalizacja i ustalenie terytorium
*/
Hyena(Board scene) {
super(scene, spName);
this.setHome(ISettings.ELEROCK);
sce = scene;
born = 0;
setType(0);
this.setFoodObject(ISettings.CARRION);
this.setSize(80);
WaterPlaceRoadInc = 0;
Hyena.Terrytory = this.findRestPlace();
this.PatrolRoad.put(0, new Point(this.getX(), this.getY()));
this.setPatrolRoadInc(0);
this.setPatrolRoadis(true);
}
/**
* @return the eatingRate
*/
public static int getEatingRate() {
return eatingRate;
}
/**
* @param aEatingRate the eatingRate to set
*/
public static void setEatingRate(int aEatingRate) {
eatingRate = aEatingRate;
}
/**
* @return the drinkingRate
*/
public static int getDrinkingRate() {
return drinkingRate;
}
/**
* @param aDrinkingRate the drinkingRate to set
*/
public static void setDrinkingRate(int aDrinkingRate) {
drinkingRate = aDrinkingRate;
}
/**
* @return the energyRate
*/
public static int getEnergyRate() {
return energyRate;
}
/**
* @param aEnergyRate the energyRate to set
*/
public static void setEnergyRate(int aEnergyRate) {
energyRate = aEnergyRate;
}
/**
* Konsumpcja pokarmu
*/
public void foodrUse() {
this.setFood(this.getFood() - Hyena.getEnergyRate());
this.setAppetite(this.getAppetite() + Hyena.getEnergyRate());
}
/**
* Picie
*/
public void drink() {
this.setWater(this.getWater() + Hyena.getDrinkingRate());
}
/**
* Zużywanie wody
*/
public void waterUse() {
this.setWater(this.getWater() - Hyena.getEnergyRate());
}
/**
* Jedzenie jeżeli upolowana zwierzyna była mniejsza niż tempo jedzenia to
* zjada, jeżeli większa to je dopóki się nie naje, jeżeli coś zostanie to
* tworzy padlinę o masie równej resztkom.
*/
public void eatHunt() {
if (this.getFood() < ISettings.STOMACH) {
if (this.getFoodHunt() <= Hyena.getEatingRate()) {
this.setFood(this.getFood() + this.getFoodHunt());
this.setFoodHunt(0);
if (this.getFood() > ISettings.HUNGER) {
this.setAnimalState(0);
} else {
this.setAnimalState(4);
}
} else {
this.setFood(this.getFood() + Hyena.getEatingRate());
this.setAppetite(this.getAppetite() - Hyena.getEatingRate());
this.setFoodHunt(this.getFoodHunt() - Hyena.getEatingRate());
if (this.getFood() > ISettings.HUNGER) {
Carrion m = new Carrion(this.scene, this.getFoodHunt());
m.setX(this.getX());
m.setY(this.getY());
Board.setCarrion_fields(this.getPointX(), this.getPointY(), m);
this.setAnimalState(0);
this.setFoodHunt(0);
} else {
Carrion m = new Carrion(this.scene, this.getFoodHunt());
m.setX(this.getX());
m.setY(this.getY());
Board.setCarrion_fields(this.getPointX(), this.getPointY(), m);
this.setFoodHunt(0);
this.setAnimalState(4);
}
}
} else {
this.setFood(ISettings.STOMACH);
this.setAppetite(0);
}
}
/**
* @return the size_age
*/
public static int getSize_age() {
return size_age;
}
/**
* @param aSize_age the size_age to set
*/
public static void setSize_age(int aSize_age) {
size_age = aSize_age;
}
/**
* @return the agingRate
*/
public static int getAgingRate() {
return agingRate;
}
/**
* @param aAgingRate the agingRate to set
*/
public static void setAgingRate(int aAgingRate) {
agingRate = aAgingRate;
}
/**
* @return the reproductionRate
*/
public static int getReproductionRate() {
return reproductionRate;
}
/**
* @param aReproductionRate the reproductionRate to set
*/
public static void setReproductionRate(int aReproductionRate) {
reproductionRate = aReproductionRate;
}
/**
* Sprawdza czy w punkcie znajduje się obiekt który może zjeść
*/
public boolean canHunt(Point f) {
if (Board.getDynamic_fields(f.getPointX(), f.getPointY()).getSpriteName().equals(ISettings.CARRION)) {
return true;
} else {
return false;
}
}
/**
* Reprodkcja - losowanie pozycji nowej hieny na terytorium(Cmentarzysko
* słoni) i tworzenie nowego potomka;
*/
public void reproduct() {
Hyena ant = new Hyena(scene);
Random rand = new Random();
int x, y;
do {
x = (rand.nextInt((Hyena.Terrytory[1] - Hyena.Terrytory[0] + 1)) + Hyena.Terrytory[0]) * ISettings.FIELD_SIZE;
y = (rand.nextInt((Hyena.Terrytory[3] - Hyena.Terrytory[2] + 1)) + Hyena.Terrytory[2]) * ISettings.FIELD_SIZE;
} while ((Board.getStatic_fields(this.calcPoint(x), this.calcPoint(y)).isBlocked()));
this.createAnimal(x, y, ant);
ant.PatrolRoad.put(0, new Point(this.getPointX(), this.getPointY()));
new Thread(ant).start();
}
/**
* Odpoczynek przez określony czas
*/
public void rest() {
if (getRestTimer() >= Hyena.getRestTime()) {
setRestTimer(0);
this.setRestPlace(null);
this.setAnimalState(0);
} else {
setRestTimer(getRestTimer() + 1);
}
}
/**
* Reset licznika okresu
*/
public void resetPeriod() {
this.period = 0;
}
/**
* Wykonywanie akcji okresowych - zwiększenie rozmiaru, wieku . Zwiększenie
* licznika urodzenia(born). Jeżeli born równa się tempo rozrodu -
* powastanie nowej hieny i reset licznika.
*/
public void exPeriod() {
if (this.getPeriod() == ISettings.PERIOD) {
this.resetPeriod();
this.setAge(this.getAge() + Hyena.getAgingRate());
this.setSize(this.getSize() + Hyena.size_age);
setBorn(getBorn() + 1);
} else {
this.setPeriod();
}
if (getBorn() == Hyena.getReproductionRate()) {
this.reproduct();
this.setBorn(0);
}
}
/**
* Cykl życia. Dopóki żyje(stop). Jeżeli hiena jest najedzona i napojona to
* odpoczywa na swoim terytorium co jakiś czas zmieniając pozycję. Jeżeli
* poziom jedzenie < ISettings.HUNGER to żeruje dopóki się nie naje, jeżeli
* poziom wody < ISEttings.THISRST to idzie do wodpoju (pokoleji przechodzi
* elementy kolekcji WaterPlaceRoad) i pije. Następnie wykonanie okresowych
* czynności, zużywanie jedzenia i wody oraz sprawdzenie funkcji życiowych.
* Jedzenie ma większy priotytet niż picie;
*
*
* Cykl powtarza się co czas w milisekundach równy prędkości.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* @Override
*/
public void run() {
while (!isStop()) {
if (Hyena.Terrytory == null) {
this.remove();
}
if (this.isPatrolRoadis()) {
this.checkFood();
switch (getAnimalState()) {
case 0: {
this.setWaterPlaceRoadInc(0);
if (this.getRestPlace() == null) {
Random rand = new Random();
setRestPlace(new Point((rand.nextInt(Hyena.Terrytory[1] - Hyena.Terrytory[0] + 1) + Hyena.Terrytory[0]) * ISettings.FIELD_SIZE,
(rand.nextInt(Hyena.Terrytory[3] - Hyena.Terrytory[2] + 1) + Hyena.Terrytory[2]) * ISettings.FIELD_SIZE));
move(getRestPlace());
} else {
if (!this.isArrive(this.getRestPlace())) {
move(getRestPlace());
} else {
this.setAnimalState(1);
}
}
break;
}
case 1: {
rest();
break;
}
case 2: {
this.checkFood();
if (!Hyena.WaterPlaceRoad.isEmpty()) {
if (this.isArrive(((Point) Hyena.WaterPlaceRoad.get(0)))) {
this.setAnimalState(3);
} else {
this.move((Point) Hyena.WaterPlaceRoad.get(0));
}
}
break;
}
case 3: {
if (getWaterPlaceRoadInc() < Hyena.WaterPlaceRoad.size()) {
this.move((Point) Hyena.WaterPlaceRoad.get(getWaterPlaceRoadInc()));
if (this.isArrive(((Point) Hyena.WaterPlaceRoad.get(getWaterPlaceRoadInc())))) {
setWaterPlaceRoadInc(getWaterPlaceRoadInc() + 1);
}
} else {
if (this.getWater() < ISettings.BLADDER) {
this.drink();
} else {
this.setAnimalState(0);
}
}
break;
}
case 4: {
if (this.getFoodHunt() != 0) {
this.eatHunt();
} else {
patrol();
}
break;
}
}
if (this.getWater() < ISettings.THIRST && this.getFood() > ISettings.HUNGER && this.getAnimalState() == 1) {
this.setAnimalState(2);
}
this.waterUse();
this.foodrUse();
this.exPeriod();
if (!checkLife()) {
this.remove();
}
}
try {
Thread.sleep(Hyena.getVelocity());
} catch (InterruptedException ex) {
Logger.getLogger(Hyena.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* @return the period
*/
public int getPeriod() {
return period;
}
/**
* @param period the period to set
*/
public void setPeriod() {
this.period++;
}
/**
* @return the restTimer
*/
public int getRestTimer() {
return restTimer;
}
/**
* @param restTimer the restTimer to set
*/
public void setRestTimer(int restTimer) {
this.restTimer = restTimer;
}
/**
* @return the WaterPlaceRoadInc
*/
public int getWaterPlaceRoadInc() {
return WaterPlaceRoadInc;
}
/**
* @param WaterPlaceRoadInc the WaterPlaceRoadInc to set
*/
public void setWaterPlaceRoadInc(int WaterPlaceRoadInc) {
this.WaterPlaceRoadInc = WaterPlaceRoadInc;
}
/**
* @return the born
*/
public int getBorn() {
return born;
}
/**
* @param born the born to set
*/
public void setBorn(int born) {
this.born = born;
}
}
| /**
* Cykl życia. Dopóki żyje(stop). Jeżeli hiena jest najedzona i napojona to
* odpoczywa na swoim terytorium co jakiś czas zmieniając pozycję. Jeżeli
* poziom jedzenie < ISettings.HUNGER to żeruje dopóki się nie naje, jeżeli
* poziom wody < ISEttings.THISRST to idzie do wodpoju (pokoleji przechodzi
* elementy kolekcji WaterPlaceRoad) i pije. Następnie wykonanie okresowych
* czynności, zużywanie jedzenia i wody oraz sprawdzenie funkcji życiowych.
* Jedzenie ma większy priotytet niż picie;
*
*
* Cykl powtarza się co czas w milisekundach równy prędkości.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* @Override
*/ | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sawanna;
import java.util.HashMap;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Bartosz Radliński
*/
public class Hyena extends Mammal implements Runnable {
/**
* Grafika
*/
static private String spName = ISettings.HYENA;
/**
* Tempo wzrostu
*/
static private int size_age = 1;
/**
* Tempo starzenia
*/
static private int agingRate = 1;
/**
* Tempo reprodukcji
*/
static private int reproductionRate = 50;
/**
* @return the velocity
*/
public static int getVelocity() {
return velocity;
}
/**
* @param aVelocity the velocity to set
*/
public static void setVelocity(int aVelocity) {
velocity = aVelocity;
}
/**
* Czas odpoczynku
*/
private static int restTime = 20;
/**
* Gdzie malować
*/
static private Board sce;
/**
* @return the restTime
*/
public static int getRestTime() {
return restTime;
}
/**
* @param aRestTime the restTime to set
*/
public static void setRestTime(int aRestTime) {
restTime = aRestTime;
}
/**
* Licznik czasu odpoczynku
*/
private int restTimer = 0;
public static int[] Terrytory = new int[4];
/**
* Tempo jedzenia
*/
private static int eatingRate = 5;
/**
* Tempo picia
*/
private static int drinkingRate = 5;
/**
* Tempo spalania energii
*/
private static int energyRate = 1;
/**
* Prędkość
*/
private static int velocity = 100;
/**
* Licznik urodzenia
*/
private int born = 0;
/**
* Kolekcja punktów drogi do wodopoju
*/
public static HashMap WaterPlaceRoad = new HashMap();
/**
* Iterator
*/
private int WaterPlaceRoadInc;
/**
* Licznik stanu okresu
*/
private int period = 0;
/**
* Inicjalizacja i ustalenie terytorium
*/
Hyena(Board scene) {
super(scene, spName);
this.setHome(ISettings.ELEROCK);
sce = scene;
born = 0;
setType(0);
this.setFoodObject(ISettings.CARRION);
this.setSize(80);
WaterPlaceRoadInc = 0;
Hyena.Terrytory = this.findRestPlace();
this.PatrolRoad.put(0, new Point(this.getX(), this.getY()));
this.setPatrolRoadInc(0);
this.setPatrolRoadis(true);
}
/**
* @return the eatingRate
*/
public static int getEatingRate() {
return eatingRate;
}
/**
* @param aEatingRate the eatingRate to set
*/
public static void setEatingRate(int aEatingRate) {
eatingRate = aEatingRate;
}
/**
* @return the drinkingRate
*/
public static int getDrinkingRate() {
return drinkingRate;
}
/**
* @param aDrinkingRate the drinkingRate to set
*/
public static void setDrinkingRate(int aDrinkingRate) {
drinkingRate = aDrinkingRate;
}
/**
* @return the energyRate
*/
public static int getEnergyRate() {
return energyRate;
}
/**
* @param aEnergyRate the energyRate to set
*/
public static void setEnergyRate(int aEnergyRate) {
energyRate = aEnergyRate;
}
/**
* Konsumpcja pokarmu
*/
public void foodrUse() {
this.setFood(this.getFood() - Hyena.getEnergyRate());
this.setAppetite(this.getAppetite() + Hyena.getEnergyRate());
}
/**
* Picie
*/
public void drink() {
this.setWater(this.getWater() + Hyena.getDrinkingRate());
}
/**
* Zużywanie wody
*/
public void waterUse() {
this.setWater(this.getWater() - Hyena.getEnergyRate());
}
/**
* Jedzenie jeżeli upolowana zwierzyna była mniejsza niż tempo jedzenia to
* zjada, jeżeli większa to je dopóki się nie naje, jeżeli coś zostanie to
* tworzy padlinę o masie równej resztkom.
*/
public void eatHunt() {
if (this.getFood() < ISettings.STOMACH) {
if (this.getFoodHunt() <= Hyena.getEatingRate()) {
this.setFood(this.getFood() + this.getFoodHunt());
this.setFoodHunt(0);
if (this.getFood() > ISettings.HUNGER) {
this.setAnimalState(0);
} else {
this.setAnimalState(4);
}
} else {
this.setFood(this.getFood() + Hyena.getEatingRate());
this.setAppetite(this.getAppetite() - Hyena.getEatingRate());
this.setFoodHunt(this.getFoodHunt() - Hyena.getEatingRate());
if (this.getFood() > ISettings.HUNGER) {
Carrion m = new Carrion(this.scene, this.getFoodHunt());
m.setX(this.getX());
m.setY(this.getY());
Board.setCarrion_fields(this.getPointX(), this.getPointY(), m);
this.setAnimalState(0);
this.setFoodHunt(0);
} else {
Carrion m = new Carrion(this.scene, this.getFoodHunt());
m.setX(this.getX());
m.setY(this.getY());
Board.setCarrion_fields(this.getPointX(), this.getPointY(), m);
this.setFoodHunt(0);
this.setAnimalState(4);
}
}
} else {
this.setFood(ISettings.STOMACH);
this.setAppetite(0);
}
}
/**
* @return the size_age
*/
public static int getSize_age() {
return size_age;
}
/**
* @param aSize_age the size_age to set
*/
public static void setSize_age(int aSize_age) {
size_age = aSize_age;
}
/**
* @return the agingRate
*/
public static int getAgingRate() {
return agingRate;
}
/**
* @param aAgingRate the agingRate to set
*/
public static void setAgingRate(int aAgingRate) {
agingRate = aAgingRate;
}
/**
* @return the reproductionRate
*/
public static int getReproductionRate() {
return reproductionRate;
}
/**
* @param aReproductionRate the reproductionRate to set
*/
public static void setReproductionRate(int aReproductionRate) {
reproductionRate = aReproductionRate;
}
/**
* Sprawdza czy w punkcie znajduje się obiekt który może zjeść
*/
public boolean canHunt(Point f) {
if (Board.getDynamic_fields(f.getPointX(), f.getPointY()).getSpriteName().equals(ISettings.CARRION)) {
return true;
} else {
return false;
}
}
/**
* Reprodkcja - losowanie pozycji nowej hieny na terytorium(Cmentarzysko
* słoni) i tworzenie nowego potomka;
*/
public void reproduct() {
Hyena ant = new Hyena(scene);
Random rand = new Random();
int x, y;
do {
x = (rand.nextInt((Hyena.Terrytory[1] - Hyena.Terrytory[0] + 1)) + Hyena.Terrytory[0]) * ISettings.FIELD_SIZE;
y = (rand.nextInt((Hyena.Terrytory[3] - Hyena.Terrytory[2] + 1)) + Hyena.Terrytory[2]) * ISettings.FIELD_SIZE;
} while ((Board.getStatic_fields(this.calcPoint(x), this.calcPoint(y)).isBlocked()));
this.createAnimal(x, y, ant);
ant.PatrolRoad.put(0, new Point(this.getPointX(), this.getPointY()));
new Thread(ant).start();
}
/**
* Odpoczynek przez określony czas
*/
public void rest() {
if (getRestTimer() >= Hyena.getRestTime()) {
setRestTimer(0);
this.setRestPlace(null);
this.setAnimalState(0);
} else {
setRestTimer(getRestTimer() + 1);
}
}
/**
* Reset licznika okresu
*/
public void resetPeriod() {
this.period = 0;
}
/**
* Wykonywanie akcji okresowych - zwiększenie rozmiaru, wieku . Zwiększenie
* licznika urodzenia(born). Jeżeli born równa się tempo rozrodu -
* powastanie nowej hieny i reset licznika.
*/
public void exPeriod() {
if (this.getPeriod() == ISettings.PERIOD) {
this.resetPeriod();
this.setAge(this.getAge() + Hyena.getAgingRate());
this.setSize(this.getSize() + Hyena.size_age);
setBorn(getBorn() + 1);
} else {
this.setPeriod();
}
if (getBorn() == Hyena.getReproductionRate()) {
this.reproduct();
this.setBorn(0);
}
}
/**
* Cykl życia. Dopóki <SUF>*/
public void run() {
while (!isStop()) {
if (Hyena.Terrytory == null) {
this.remove();
}
if (this.isPatrolRoadis()) {
this.checkFood();
switch (getAnimalState()) {
case 0: {
this.setWaterPlaceRoadInc(0);
if (this.getRestPlace() == null) {
Random rand = new Random();
setRestPlace(new Point((rand.nextInt(Hyena.Terrytory[1] - Hyena.Terrytory[0] + 1) + Hyena.Terrytory[0]) * ISettings.FIELD_SIZE,
(rand.nextInt(Hyena.Terrytory[3] - Hyena.Terrytory[2] + 1) + Hyena.Terrytory[2]) * ISettings.FIELD_SIZE));
move(getRestPlace());
} else {
if (!this.isArrive(this.getRestPlace())) {
move(getRestPlace());
} else {
this.setAnimalState(1);
}
}
break;
}
case 1: {
rest();
break;
}
case 2: {
this.checkFood();
if (!Hyena.WaterPlaceRoad.isEmpty()) {
if (this.isArrive(((Point) Hyena.WaterPlaceRoad.get(0)))) {
this.setAnimalState(3);
} else {
this.move((Point) Hyena.WaterPlaceRoad.get(0));
}
}
break;
}
case 3: {
if (getWaterPlaceRoadInc() < Hyena.WaterPlaceRoad.size()) {
this.move((Point) Hyena.WaterPlaceRoad.get(getWaterPlaceRoadInc()));
if (this.isArrive(((Point) Hyena.WaterPlaceRoad.get(getWaterPlaceRoadInc())))) {
setWaterPlaceRoadInc(getWaterPlaceRoadInc() + 1);
}
} else {
if (this.getWater() < ISettings.BLADDER) {
this.drink();
} else {
this.setAnimalState(0);
}
}
break;
}
case 4: {
if (this.getFoodHunt() != 0) {
this.eatHunt();
} else {
patrol();
}
break;
}
}
if (this.getWater() < ISettings.THIRST && this.getFood() > ISettings.HUNGER && this.getAnimalState() == 1) {
this.setAnimalState(2);
}
this.waterUse();
this.foodrUse();
this.exPeriod();
if (!checkLife()) {
this.remove();
}
}
try {
Thread.sleep(Hyena.getVelocity());
} catch (InterruptedException ex) {
Logger.getLogger(Hyena.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* @return the period
*/
public int getPeriod() {
return period;
}
/**
* @param period the period to set
*/
public void setPeriod() {
this.period++;
}
/**
* @return the restTimer
*/
public int getRestTimer() {
return restTimer;
}
/**
* @param restTimer the restTimer to set
*/
public void setRestTimer(int restTimer) {
this.restTimer = restTimer;
}
/**
* @return the WaterPlaceRoadInc
*/
public int getWaterPlaceRoadInc() {
return WaterPlaceRoadInc;
}
/**
* @param WaterPlaceRoadInc the WaterPlaceRoadInc to set
*/
public void setWaterPlaceRoadInc(int WaterPlaceRoadInc) {
this.WaterPlaceRoadInc = WaterPlaceRoadInc;
}
/**
* @return the born
*/
public int getBorn() {
return born;
}
/**
* @param born the born to set
*/
public void setBorn(int born) {
this.born = born;
}
}
| f |
9136_1 | maciejgawlowski/Spring-Boot-JPA | 151 | springboot-jpa/src/main/java/pl/gawlowski/maciej/service/CourseRepository.java | package pl.gawlowski.maciej.service;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import pl.gawlowski.maciej.domain.Course;
public interface CourseRepository extends CrudRepository<Course, String> { //String to typ primary key (id)
//Spring Data JPA sam implementuje tą metodę! nie muszę jej sam pisać, tylko deklarować ją w interfejsie!!!
public List<Course> findByTopicId(String topicId);
}
| //Spring Data JPA sam implementuje tą metodę! nie muszę jej sam pisać, tylko deklarować ją w interfejsie!!!
| package pl.gawlowski.maciej.service;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import pl.gawlowski.maciej.domain.Course;
public interface CourseRepository extends CrudRepository<Course, String> { //String to typ primary key (id)
//Spring Data <SUF>
public List<Course> findByTopicId(String topicId);
}
| f |
3802_0 | magda2357/Codility | 522 | src/main/java/org/example/OddOccurrencesInArray.java | package org.example;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class OddOccurrencesInArray {
public static int solution1(int[] tab) {
Arrays.sort(tab);
int result;
int i = 0;
while (true) {
if (tab[tab.length - 1] == tab[i]) {
result = tab[i];
break;
} else if (tab[i] == tab[i + 1]) {
i += 2;
} else {
result = tab[i];
break;
}
}
return result;
}
/*pierwsze rozwiązanie przeszło 100% efektywności,
* wcześniej zaczyanłam od stremów, ale wiem, że są wolniejsze,
* ale tiem w nano seconds wychodził krótszy - nie rozumiem tego*/
public static int solution2(int[] tab) {
List<Integer> list = Arrays.stream(tab).boxed().collect(Collectors.toList());
return list.stream()
.filter(a -> Collections.frequency(list, a) == 1)
.collect(Collectors.toList()).get(0);
}
public static void main(String[] args) {
int[] a = new int[]{1, 2, 1, 4, 2, 0, 4, 0, 7};
long startTime = System.nanoTime();
System.out.println("Solution1: " + solution1(a));
long endTime = System.nanoTime();
System.out.println(endTime - startTime);
long startTime2 = System.nanoTime();
System.out.println("Solution2: " + solution2(a));
long endTime2 = System.nanoTime();
System.out.println(endTime2 - startTime2);
}
}
| /*pierwsze rozwiązanie przeszło 100% efektywności,
* wcześniej zaczyanłam od stremów, ale wiem, że są wolniejsze,
* ale tiem w nano seconds wychodził krótszy - nie rozumiem tego*/ | package org.example;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class OddOccurrencesInArray {
public static int solution1(int[] tab) {
Arrays.sort(tab);
int result;
int i = 0;
while (true) {
if (tab[tab.length - 1] == tab[i]) {
result = tab[i];
break;
} else if (tab[i] == tab[i + 1]) {
i += 2;
} else {
result = tab[i];
break;
}
}
return result;
}
/*pierwsze rozwiązanie przeszło <SUF>*/
public static int solution2(int[] tab) {
List<Integer> list = Arrays.stream(tab).boxed().collect(Collectors.toList());
return list.stream()
.filter(a -> Collections.frequency(list, a) == 1)
.collect(Collectors.toList()).get(0);
}
public static void main(String[] args) {
int[] a = new int[]{1, 2, 1, 4, 2, 0, 4, 0, 7};
long startTime = System.nanoTime();
System.out.println("Solution1: " + solution1(a));
long endTime = System.nanoTime();
System.out.println(endTime - startTime);
long startTime2 = System.nanoTime();
System.out.println("Solution2: " + solution2(a));
long endTime2 = System.nanoTime();
System.out.println(endTime2 - startTime2);
}
}
| f |
6264_0 | marcin-chwedczuk/polish-holidays | 2,621 | src/main/java/pl/marcinchwedczuk/polishholidays/PolishHolidaysLibrary.java | package pl.marcinchwedczuk.polishholidays;
import static pl.marcinchwedczuk.polishholidays.EffectiveTimespan.fromYearOnward;
import static pl.marcinchwedczuk.polishholidays.HolidayType.*;
import static pl.marcinchwedczuk.polishholidays.HolidayDateAlgorithms.*;
import java.util.Arrays;
import java.util.List;
class PolishHolidaysLibrary {
private final HolidayDefinition newYear =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(1, 1))
.withEnglishName("New Year's Day")
.withPolishName("Nowy Rok")
.withHolidayType(OTHER)
.markAsPublicHoliday()
.build();
/*
* Wiki: https://pl.wikipedia.org/wiki/Objawienie_Pa%C5%84skie W powojennej Polsce było dniem wolnym
* od pracy do 16 listopada 1960. Zostało zniesione ustawą Sejmu PRL[4]. We wrześniu 2010 rozpoczęto
* prace legislacyjne nad ponownym przywróceniem dnia wolnego. Odpowiednią ustawę uchwalił Sejm RP
* przy okazji zmiany Kodeksu pracy[5]. Ustawa została podpisana[6] przez prezydenta Bronisława
* Komorowskiego 19 listopada 2010 i ogłoszona w Dzienniku Ustaw 26 listopada 2010[7]. 6 stycznia
* 2011 był pierwszym od 1960 dniem Objawienia Pańskiego wolnym od pracy.
*/
private final HolidayDefinition epiphany =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(1, 6))
.withEnglishName("Epiphany")
.withPolishName("Święto Trzech Króli")
.withHolidayType(RELIGIOUS)
.addOverride(HolidayDefinitionOverride.newBuilder()
.withEffectiveTimespan(fromYearOnward(2011))
.withOverride(definition -> definition.markAsPublicHoliday())
.build())
.build();
private final HolidayDefinition valentinesDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(2, 14))
.withEnglishName("Valentine's Day")
.withPolishName("Walentynki")
.withHolidayType(OTHER)
.build();
private final HolidayDefinition goodFriday =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(-2))
.withEnglishName("Good Friday")
.withPolishName("Wielki Piątek")
.withHolidayType(RELIGIOUS)
.build();
private final HolidayDefinition holySaturday =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(-1))
.withEnglishName("Holy Saturday")
.withPolishName("Wielka Sobota")
.withHolidayType(RELIGIOUS)
.build();
// TODO: Rule valid from-to, overrides holiday attributes
private final HolidayDefinition easter =
HolidayDefinition.newBuilder()
.withDate(new EasterDateHolidayDateAlgorithm())
.withEnglishName("Easter")
.withPolishName("Wielkanoc")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition easterMonday =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(1))
.withEnglishName("Easter Monday")
.withPolishName("Poniedziałek Wielkanocny")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition labourDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(5, 1))
.withEnglishName("Labour Day")
.withPolishName("Święto Pracy")
.withHolidayType(OTHER)
.markAsPublicHoliday()
.build();
private final HolidayDefinition flagDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(5, 2))
.withEnglishName("Polish National Flag Day")
.withPolishName("Dzień Flagi Rzeczypospolitej Polskiej")
.withHolidayType(NATIONAL)
.build();
private final HolidayDefinition constitutionDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(5, 3))
.withEnglishName("Constitution Day")
.withPolishName("Święto Konstytucji Trzeciego Maja")
.withHolidayType(NATIONAL)
.markAsPublicHoliday()
.build();
private final HolidayDefinition whiteSunday =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(49))
.withEnglishName("White Sunday")
.withPolishName("Zielone Świątki")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition mothersDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(5, 26))
.withEnglishName("Mother's Day")
.withPolishName("Dzień Matki")
.withHolidayType(UNOFFICIAL)
.build();
private final HolidayDefinition childrensDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(6, 1))
.withEnglishName("Children's Day")
.withPolishName("Dzień Dziecka")
.withHolidayType(UNOFFICIAL)
.build();
private final HolidayDefinition corpusChristi =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(60))
.withEnglishName("Feast of Corpus Christi")
.withPolishName("Boże Ciało")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition fathersDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(6, 23))
.withEnglishName("Father's Day")
.withPolishName("Dzień Ojca")
.withHolidayType(UNOFFICIAL)
.build();
private final HolidayDefinition assumptionOfMary =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(8, 15))
.withEnglishName("Assumption of Mary")
.withPolishName("Wniebowzięcie Najświętszej Maryi Panny")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition allSaintsDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(11, 1))
.withEnglishName("All Saints' Day")
.withPolishName("Wszystkich Świętych")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition independenceDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(11, 11))
.withEnglishName("National Independence Day")
.withPolishName("Dzień Niepodległości")
.withHolidayType(NATIONAL)
.markAsPublicHoliday()
.build();
private final HolidayDefinition christmasEve =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(12, 24))
.withEnglishName("Christmas Eve")
.withPolishName("Wigilia Bożego Narodzenia")
.withHolidayType(RELIGIOUS)
.build();
private final HolidayDefinition christmas =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(12, 25))
.withEnglishName("Christmas")
.withPolishName("Boże Narodzenie")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition christmasSecondDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(12, 26))
.withEnglishName("Christmas")
.withPolishName("Boże Narodzenie")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition newYearsEve =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(12, 31))
.withEnglishName("New Year's Eve")
.withPolishName("Sylwester")
.withHolidayType(UNOFFICIAL)
.build();
public List<HolidayDefinition> holidaysDefinitions() {
return Arrays.asList(
newYear,
epiphany,
valentinesDay,
goodFriday,
holySaturday,
easter,
easterMonday,
labourDay,
flagDay,
constitutionDay,
whiteSunday,
mothersDay,
childrensDay,
corpusChristi,
fathersDay,
assumptionOfMary,
allSaintsDay,
independenceDay,
christmasEve,
christmas,
christmasSecondDay,
newYearsEve);
}
public int validSinceYearIncluding() {
return 2000;
}
}
| /*
* Wiki: https://pl.wikipedia.org/wiki/Objawienie_Pa%C5%84skie W powojennej Polsce było dniem wolnym
* od pracy do 16 listopada 1960. Zostało zniesione ustawą Sejmu PRL[4]. We wrześniu 2010 rozpoczęto
* prace legislacyjne nad ponownym przywróceniem dnia wolnego. Odpowiednią ustawę uchwalił Sejm RP
* przy okazji zmiany Kodeksu pracy[5]. Ustawa została podpisana[6] przez prezydenta Bronisława
* Komorowskiego 19 listopada 2010 i ogłoszona w Dzienniku Ustaw 26 listopada 2010[7]. 6 stycznia
* 2011 był pierwszym od 1960 dniem Objawienia Pańskiego wolnym od pracy.
*/ | package pl.marcinchwedczuk.polishholidays;
import static pl.marcinchwedczuk.polishholidays.EffectiveTimespan.fromYearOnward;
import static pl.marcinchwedczuk.polishholidays.HolidayType.*;
import static pl.marcinchwedczuk.polishholidays.HolidayDateAlgorithms.*;
import java.util.Arrays;
import java.util.List;
class PolishHolidaysLibrary {
private final HolidayDefinition newYear =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(1, 1))
.withEnglishName("New Year's Day")
.withPolishName("Nowy Rok")
.withHolidayType(OTHER)
.markAsPublicHoliday()
.build();
/*
* Wiki: https://pl.wikipedia.org/wiki/Objawienie_Pa%C5%84skie W <SUF>*/
private final HolidayDefinition epiphany =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(1, 6))
.withEnglishName("Epiphany")
.withPolishName("Święto Trzech Króli")
.withHolidayType(RELIGIOUS)
.addOverride(HolidayDefinitionOverride.newBuilder()
.withEffectiveTimespan(fromYearOnward(2011))
.withOverride(definition -> definition.markAsPublicHoliday())
.build())
.build();
private final HolidayDefinition valentinesDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(2, 14))
.withEnglishName("Valentine's Day")
.withPolishName("Walentynki")
.withHolidayType(OTHER)
.build();
private final HolidayDefinition goodFriday =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(-2))
.withEnglishName("Good Friday")
.withPolishName("Wielki Piątek")
.withHolidayType(RELIGIOUS)
.build();
private final HolidayDefinition holySaturday =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(-1))
.withEnglishName("Holy Saturday")
.withPolishName("Wielka Sobota")
.withHolidayType(RELIGIOUS)
.build();
// TODO: Rule valid from-to, overrides holiday attributes
private final HolidayDefinition easter =
HolidayDefinition.newBuilder()
.withDate(new EasterDateHolidayDateAlgorithm())
.withEnglishName("Easter")
.withPolishName("Wielkanoc")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition easterMonday =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(1))
.withEnglishName("Easter Monday")
.withPolishName("Poniedziałek Wielkanocny")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition labourDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(5, 1))
.withEnglishName("Labour Day")
.withPolishName("Święto Pracy")
.withHolidayType(OTHER)
.markAsPublicHoliday()
.build();
private final HolidayDefinition flagDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(5, 2))
.withEnglishName("Polish National Flag Day")
.withPolishName("Dzień Flagi Rzeczypospolitej Polskiej")
.withHolidayType(NATIONAL)
.build();
private final HolidayDefinition constitutionDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(5, 3))
.withEnglishName("Constitution Day")
.withPolishName("Święto Konstytucji Trzeciego Maja")
.withHolidayType(NATIONAL)
.markAsPublicHoliday()
.build();
private final HolidayDefinition whiteSunday =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(49))
.withEnglishName("White Sunday")
.withPolishName("Zielone Świątki")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition mothersDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(5, 26))
.withEnglishName("Mother's Day")
.withPolishName("Dzień Matki")
.withHolidayType(UNOFFICIAL)
.build();
private final HolidayDefinition childrensDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(6, 1))
.withEnglishName("Children's Day")
.withPolishName("Dzień Dziecka")
.withHolidayType(UNOFFICIAL)
.build();
private final HolidayDefinition corpusChristi =
HolidayDefinition.newBuilder()
.withDate(relativeToEaster(60))
.withEnglishName("Feast of Corpus Christi")
.withPolishName("Boże Ciało")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition fathersDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(6, 23))
.withEnglishName("Father's Day")
.withPolishName("Dzień Ojca")
.withHolidayType(UNOFFICIAL)
.build();
private final HolidayDefinition assumptionOfMary =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(8, 15))
.withEnglishName("Assumption of Mary")
.withPolishName("Wniebowzięcie Najświętszej Maryi Panny")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition allSaintsDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(11, 1))
.withEnglishName("All Saints' Day")
.withPolishName("Wszystkich Świętych")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition independenceDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(11, 11))
.withEnglishName("National Independence Day")
.withPolishName("Dzień Niepodległości")
.withHolidayType(NATIONAL)
.markAsPublicHoliday()
.build();
private final HolidayDefinition christmasEve =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(12, 24))
.withEnglishName("Christmas Eve")
.withPolishName("Wigilia Bożego Narodzenia")
.withHolidayType(RELIGIOUS)
.build();
private final HolidayDefinition christmas =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(12, 25))
.withEnglishName("Christmas")
.withPolishName("Boże Narodzenie")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition christmasSecondDay =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(12, 26))
.withEnglishName("Christmas")
.withPolishName("Boże Narodzenie")
.withHolidayType(RELIGIOUS)
.markAsPublicHoliday()
.build();
private final HolidayDefinition newYearsEve =
HolidayDefinition.newBuilder()
.withDate(fixedAtMonthDay(12, 31))
.withEnglishName("New Year's Eve")
.withPolishName("Sylwester")
.withHolidayType(UNOFFICIAL)
.build();
public List<HolidayDefinition> holidaysDefinitions() {
return Arrays.asList(
newYear,
epiphany,
valentinesDay,
goodFriday,
holySaturday,
easter,
easterMonday,
labourDay,
flagDay,
constitutionDay,
whiteSunday,
mothersDay,
childrensDay,
corpusChristi,
fathersDay,
assumptionOfMary,
allSaintsDay,
independenceDay,
christmasEve,
christmas,
christmasSecondDay,
newYearsEve);
}
public int validSinceYearIncluding() {
return 2000;
}
}
| f |
7680_1 | markup54/szkola_3Pgr2 | 511 | src/Klasa.java | import java.util.ArrayList;
public class Klasa {
private ArrayList<Uczen> uczniowie = new ArrayList<>();
private String nazwaKlasy;
private Wychowawca wychowawca;
public Klasa(String nazwaKlasy) {
this.nazwaKlasy = nazwaKlasy;
}
public Klasa(ArrayList<Uczen> uczniowie, String nazwaKlasy) {
this.uczniowie = uczniowie;
this.nazwaKlasy = nazwaKlasy;
}
public Klasa(ArrayList<Uczen> uczniowie, String nazwaKlasy, Wychowawca wychowawca) {
this.uczniowie = uczniowie;
this.nazwaKlasy = nazwaKlasy;
this.wychowawca = wychowawca;
}
public Klasa(String nazwaKlasy, Wychowawca wychowawca) {
this.nazwaKlasy = nazwaKlasy;
this.wychowawca = wychowawca;
}
private boolean czyUczenJestWKlasie(Uczen uczen){
return uczniowie.contains(uczen);
}
/**
* metoda dodaje ucznia do listy uczniów jeżeli jeszcze go nie ma w tej liście
* @param uczen - obiekt dodawny do listy uczniów
* @return brak wartości
*/
//żeby wygenerować z javaDoc html wybierz Tools/Generate JavaDoc...
public void dodajUczniaDoKlasy(Uczen uczen){
if(czyUczenJestWKlasie(uczen)){
System.out.println("Nie można dodać ucznia już jest");
}
else{
uczniowie.add(uczen);
}
}
}
| //żeby wygenerować z javaDoc html wybierz Tools/Generate JavaDoc... | import java.util.ArrayList;
public class Klasa {
private ArrayList<Uczen> uczniowie = new ArrayList<>();
private String nazwaKlasy;
private Wychowawca wychowawca;
public Klasa(String nazwaKlasy) {
this.nazwaKlasy = nazwaKlasy;
}
public Klasa(ArrayList<Uczen> uczniowie, String nazwaKlasy) {
this.uczniowie = uczniowie;
this.nazwaKlasy = nazwaKlasy;
}
public Klasa(ArrayList<Uczen> uczniowie, String nazwaKlasy, Wychowawca wychowawca) {
this.uczniowie = uczniowie;
this.nazwaKlasy = nazwaKlasy;
this.wychowawca = wychowawca;
}
public Klasa(String nazwaKlasy, Wychowawca wychowawca) {
this.nazwaKlasy = nazwaKlasy;
this.wychowawca = wychowawca;
}
private boolean czyUczenJestWKlasie(Uczen uczen){
return uczniowie.contains(uczen);
}
/**
* metoda dodaje ucznia do listy uczniów jeżeli jeszcze go nie ma w tej liście
* @param uczen - obiekt dodawny do listy uczniów
* @return brak wartości
*/
//żeby wygenerować <SUF>
public void dodajUczniaDoKlasy(Uczen uczen){
if(czyUczenJestWKlasie(uczen)){
System.out.println("Nie można dodać ucznia już jest");
}
else{
uczniowie.add(uczen);
}
}
}
| f |
4539_1 | martakarolina/wszib-io-2022-a | 497 | trojkaty.java | /**
* To jest program do rozpoznawania trójkąta.
*/
class Trojkaty {
/**
* Główna funkcja programu.
* @param {float} a - Długość pierwszego boku.
* @param {float} b - Długość drugiego boku.
* @param {float} c - Długość trzeciego boku.
*/
public static void jakiTrojkat(float a, float b, float c){
if (a == b && b == c) {
System.out.println("Trójkąt poprawiony równoboczny");
}
if (a == b || b == c || a == c) {
System.out.println("Trójkąt równoramienny");
}
// TODO: tutaj trzeba bedzie dopisac inne przypadki
}
/** Wyświetla ekran pomocy */
public static void pomoc(){
System.out.println("Acme INC. (C) 2022");
System.out.println("Program do rozpoznawania rodzaju trójkąta");
System.out.println("Uruchom z trzema argumentami liczbowymi - długość boków trójkąta");
}
/** Glowna funkcja */
public static void main(String... args) {
if (args.length != 3) {
pomoc();
System.exit(1);
}
float a = Float.valueOf(args[0]);
float b = Float.valueOf(args[1]);
float c = Float.valueOf(args[2]);
if (a < 0 || b < 0 || c < 0) {
System.out.println("Długości boków trójkąta muszą być nieujemne!");
System.exit(2);
}
jakiTrojkat(a, b, c);
}
}
| /**
* Główna funkcja programu.
* @param {float} a - Długość pierwszego boku.
* @param {float} b - Długość drugiego boku.
* @param {float} c - Długość trzeciego boku.
*/ | /**
* To jest program do rozpoznawania trójkąta.
*/
class Trojkaty {
/**
* Główna funkcja programu. <SUF>*/
public static void jakiTrojkat(float a, float b, float c){
if (a == b && b == c) {
System.out.println("Trójkąt poprawiony równoboczny");
}
if (a == b || b == c || a == c) {
System.out.println("Trójkąt równoramienny");
}
// TODO: tutaj trzeba bedzie dopisac inne przypadki
}
/** Wyświetla ekran pomocy */
public static void pomoc(){
System.out.println("Acme INC. (C) 2022");
System.out.println("Program do rozpoznawania rodzaju trójkąta");
System.out.println("Uruchom z trzema argumentami liczbowymi - długość boków trójkąta");
}
/** Glowna funkcja */
public static void main(String... args) {
if (args.length != 3) {
pomoc();
System.exit(1);
}
float a = Float.valueOf(args[0]);
float b = Float.valueOf(args[1]);
float c = Float.valueOf(args[2]);
if (a < 0 || b < 0 || c < 0) {
System.out.println("Długości boków trójkąta muszą być nieujemne!");
System.exit(2);
}
jakiTrojkat(a, b, c);
}
}
| t |
6062_22 | marudergit1991/WielowatkowoscSeba | 1,571 | src/consumer/producer/Main.java | package consumer.producer;
import java.time.Duration;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class Main {
private static final Random generator = new Random();
private static final Queue<String> queue = new LinkedList<>();
public static void main(String[] args) {
int itemCount = 5;
// Thread producer = new Thread(() -> {
// // produkujemy zadana liczbe elementow:
// for (int i = 0; i < itemCount; i++) {
// try {
// //metoda sleep sluzy do uspienia wątku, przekazany parametro mowi o min czasie
// //przez ktory dany watek bedzie uspiony - nie bedzie zajmowal czasu procesora
// //czyli symulacja zwiazana z produkcja elementow
// Thread.sleep(Duration.ofSeconds(generator.nextInt(5)).toMillis());
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
// synchronized (queue) {
// queue.offer("Item no " + i);
// }
// }
// });
//
// // watek konsumujacy
// Thread consumer = new Thread(() -> {
// int itemsLeft = itemCount;
// int licznik = 0;
// // wykonuje sie dopoki zadana liczba elementow nie bedzie odebrana z kolejki
// while (itemsLeft > 0) {
// String item;
// licznik++;
// //uzywamy bloku synchronized w który sprawdza czy elementy są w kolejce i do ewentualnego ich pobrania.
// synchronized (queue) {
// if (queue.isEmpty()) {
// continue;
// }
// item = queue.poll();
// }
// itemsLeft--;
// System.out.println("Consumer got item: " + item);
// System.out.println(licznik);
// }
// });
//
// consumer.start();
// producer.start();
/*
* Program działa. Ma jednak pewien subtelny błąd. Zwróć uwagę na wątek
* konsumenta. Wątek ten działa bez przerwy. Bez przerwy zajmuje czas
* procesora. Co więcej, przez większość swojego czasu kręci się wewnątrz pętli
* sprawdzając czy kolejka jest pusta. Jako drobne ćwiczenie dla Ciebie
* zostawiam dodanie licznika iteracji – ile razy pętla wykonała się w Twoim
* przypadku?
*
* Jednym ze sposobów może być usypianie wątku konsumenta używając metody
* Thread.sleep(), którą już znasz. To także byłoby marnowanie zasobów – skąd
* możesz wiedzieć jak długo zajmie produkowanie kolejnego elementu?
*
* Wiesz już, że każdy obiekt powiązany jest z monitorem używamy w trakcie
* synchronizacji. Podobnie wygląda sprawa w przypadku mechanizmu powiadomień.
* Każdy obiekt w języku Java posiada zbiór powiadamianych wątków (ang. waiting
* set).
*
* Wewnątrz tego zbioru znajdują się wątki, które czekają na powiadomienie
* dotyczące danego obiektu. Jedynym sposobem, żeby modyfikować zawartość tego
* zbioru jest używanie metod dostępnych w klasie Object:
*
* Object.wait() – dodanie aktualnego wątku do zbioru powiadamianych wątków,
* Object.notify() – powiadomienie i wybudzenie jednego z oczekujących wątków,
* Object.notifyAll() – powiadomienie i wybudzenie wszystkich oczekujących wątków.
*/
Thread producer = new Thread(() -> {
// produkujemy zadana liczbe elementow:
for (int i = 0; i < itemCount; i++) {
try {
//metoda sleep sluzy do uspienia wątku, przekazany parametro mowi o min czasie
//przez ktory dany watek bedzie uspiony - nie bedzie zajmowal czasu procesora
//czyli symulacja zwiazana z produkcja elementow
Thread.sleep(Duration.ofSeconds(generator.nextInt(5)).toMillis());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (queue) {
queue.offer("Item no " + i);
queue.notify();
}
}
});
// watek konsumujacy
Thread consumer = new Thread(() -> {
int itemsLeft = itemCount;
int licznik = 0;
// wykonuje sie dopoki zadana liczba elementow nie bedzie odebrana z kolejki
while (itemsLeft > 0) {
String item;
licznik++;
//uzywamy bloku synchronized w który sprawdza czy elementy są w kolejce i do ewentualnego ich pobrania.
synchronized (queue) {
if (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
item = queue.poll();
}
itemsLeft--;
System.out.println("Consumer got item: " + item);
System.out.println(licznik);
}
});
consumer.start();
producer.start();
}
}
| //metoda sleep sluzy do uspienia wątku, przekazany parametro mowi o min czasie | package consumer.producer;
import java.time.Duration;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class Main {
private static final Random generator = new Random();
private static final Queue<String> queue = new LinkedList<>();
public static void main(String[] args) {
int itemCount = 5;
// Thread producer = new Thread(() -> {
// // produkujemy zadana liczbe elementow:
// for (int i = 0; i < itemCount; i++) {
// try {
// //metoda sleep sluzy do uspienia wątku, przekazany parametro mowi o min czasie
// //przez ktory dany watek bedzie uspiony - nie bedzie zajmowal czasu procesora
// //czyli symulacja zwiazana z produkcja elementow
// Thread.sleep(Duration.ofSeconds(generator.nextInt(5)).toMillis());
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
// synchronized (queue) {
// queue.offer("Item no " + i);
// }
// }
// });
//
// // watek konsumujacy
// Thread consumer = new Thread(() -> {
// int itemsLeft = itemCount;
// int licznik = 0;
// // wykonuje sie dopoki zadana liczba elementow nie bedzie odebrana z kolejki
// while (itemsLeft > 0) {
// String item;
// licznik++;
// //uzywamy bloku synchronized w który sprawdza czy elementy są w kolejce i do ewentualnego ich pobrania.
// synchronized (queue) {
// if (queue.isEmpty()) {
// continue;
// }
// item = queue.poll();
// }
// itemsLeft--;
// System.out.println("Consumer got item: " + item);
// System.out.println(licznik);
// }
// });
//
// consumer.start();
// producer.start();
/*
* Program działa. Ma jednak pewien subtelny błąd. Zwróć uwagę na wątek
* konsumenta. Wątek ten działa bez przerwy. Bez przerwy zajmuje czas
* procesora. Co więcej, przez większość swojego czasu kręci się wewnątrz pętli
* sprawdzając czy kolejka jest pusta. Jako drobne ćwiczenie dla Ciebie
* zostawiam dodanie licznika iteracji – ile razy pętla wykonała się w Twoim
* przypadku?
*
* Jednym ze sposobów może być usypianie wątku konsumenta używając metody
* Thread.sleep(), którą już znasz. To także byłoby marnowanie zasobów – skąd
* możesz wiedzieć jak długo zajmie produkowanie kolejnego elementu?
*
* Wiesz już, że każdy obiekt powiązany jest z monitorem używamy w trakcie
* synchronizacji. Podobnie wygląda sprawa w przypadku mechanizmu powiadomień.
* Każdy obiekt w języku Java posiada zbiór powiadamianych wątków (ang. waiting
* set).
*
* Wewnątrz tego zbioru znajdują się wątki, które czekają na powiadomienie
* dotyczące danego obiektu. Jedynym sposobem, żeby modyfikować zawartość tego
* zbioru jest używanie metod dostępnych w klasie Object:
*
* Object.wait() – dodanie aktualnego wątku do zbioru powiadamianych wątków,
* Object.notify() – powiadomienie i wybudzenie jednego z oczekujących wątków,
* Object.notifyAll() – powiadomienie i wybudzenie wszystkich oczekujących wątków.
*/
Thread producer = new Thread(() -> {
// produkujemy zadana liczbe elementow:
for (int i = 0; i < itemCount; i++) {
try {
//metoda sleep <SUF>
//przez ktory dany watek bedzie uspiony - nie bedzie zajmowal czasu procesora
//czyli symulacja zwiazana z produkcja elementow
Thread.sleep(Duration.ofSeconds(generator.nextInt(5)).toMillis());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (queue) {
queue.offer("Item no " + i);
queue.notify();
}
}
});
// watek konsumujacy
Thread consumer = new Thread(() -> {
int itemsLeft = itemCount;
int licznik = 0;
// wykonuje sie dopoki zadana liczba elementow nie bedzie odebrana z kolejki
while (itemsLeft > 0) {
String item;
licznik++;
//uzywamy bloku synchronized w który sprawdza czy elementy są w kolejce i do ewentualnego ich pobrania.
synchronized (queue) {
if (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
item = queue.poll();
}
itemsLeft--;
System.out.println("Consumer got item: " + item);
System.out.println(licznik);
}
});
consumer.start();
producer.start();
}
}
| t |
3507_0 | matiutd888/set-cover | 1,630 | src/cover/Bufor.java | package cover;
import cover.sets.*;
import cover.solvers.CoverSolver;
import cover.solvers.ExactSolver;
import cover.solvers.GreedySolver;
import cover.solvers.NaiveSolver;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Wczytuje i interpretuje dane oraz wyświetla odpowiednie dla danych wartości.
*
* @author Mateusz Nowakowski
*/
public class Bufor {
/**
* Lista zbiorów, które pojawiły się na wejściu.
* Zbiory te będą wykorzystywane do znajdowania pokrycia zapytań.
*/
private final ArrayList<Set> listOfSets;
private static final int NAIVE_ID = 3;
private static final int GREEDY_ID = 2;
private static final int EXACT_ID = 1;
private static final int SINGLETON_ARGUMENTS_COUNT = 1;
private static final int INFINITE_ARTHMETIC_ARGUMENTS_COUNT = 2;
private static final int FINITE_ARTHMETIC_ARGUMENTS_COUNT = 3;
public Bufor() {
listOfSets = new ArrayList<>();
}
/**
* Główna metoda wczytująca.
* Wczytuje i interpretuje dane ze standardowego wejścia.
*/
public void read() {
Scanner s = new Scanner(System.in);
while (s.hasNextInt()) {
int number = s.nextInt();
if (number > 0) {
readSet(number, s);
} else if (number < 0) {
readQuery(number, s);
} else {
listOfSets.add(new EmptySet());
}
}
s.close();
}
private CoverSolver getSolverByType(int type) {
switch (type) {
case NAIVE_ID:
return new NaiveSolver();
case GREEDY_ID:
return new GreedySolver();
case EXACT_ID:
return new ExactSolver();
}
throw new IllegalArgumentException("Incorrect solver type " + type);
}
/**
* Wczytuje zapytanie i wyświetla rozwiązanie.
* Czyta składniki pewnego zbioru, aż nie wczyta zera.
* Zakłada, że pierwsza liczba opisująca zapytanie jest już
* wczytana i jest nią {@code number}.
* Zakłada, że skaner {@code s} jest ustawiony na wczytanie pierwszej liczby która wystąpiła
* na wejściu po {@code number}.
* Wyświetla rozwiązanie zapytania.
*
* @param number liczba ujemna, pierwszy element zapytania
* @param s skaner skanujący wejście
*/
private void readQuery(int number, Scanner s) {
int n = s.nextInt();
Query query = new Query(-number);
Solution solution = getSolverByType(n).solve(listOfSets, query);
System.out.println(solution);
}
/**
* Wczytuje zbiór.
* Czyta składniki pewnego zbioru, aż nie wczyta zera.
* Zakłada, że pierwsza liczba opisująca pierwszy składnik zbioru jest już
* wczytana i jest nią {@code number}.
* Zakłada, że skaner {@code s} jest ustawiony na wczytanie pierwszej liczby która wystąpiła
* na wejściu po {@code number}.
* Tworzy zbiór zgodny z wczytanym opisem i dodaje go do globalnej listy zbiorów.
*
* @param number liczba dodatnia
* @param s skaner skanujący wejście
*/
private void readSet(int number, Scanner s) {
int[] setKeyNumbers = new int[3];
setKeyNumbers[0] = number;
int i = 1;
SetUnion set = new SetUnion();
boolean isZeroReached = false;
while (!isZeroReached && s.hasNextInt()) {
int n = s.nextInt();
if (n > 0) {
Set aS = setFromArray(setKeyNumbers, i);
set.addSet(aS);
setKeyNumbers[0] = n;
i = 1;
} else if (n < 0) {
setKeyNumbers[i] = n;
i++;
} else {
Set aS = setFromArray(setKeyNumbers, i);
set.addSet(aS);
isZeroReached = true;
}
}
listOfSets.add(set);
}
/**
* Tworzy i zwraca zbiór opisany jako składnik.
* Tworzy prosty zbiór opisany w gramatyce jako składnik
* (singleton, nieskończony ciąg arytmetyczny, skończony ciąg arytmetyczny)
* na wejściu opisany pierwszymi {@code argCount} liczbami w tablicy {@code arr}.
*
* @param arr tablica liczb opisujących składnik
* @param argCount ilość liczb opisujących składnik
* @return Obiekt reprezentujący składnik
* ({@link Singleton}, {@link InfiniteArthmeticSet} lub {@link ArthmeticSet})
*/
private Set setFromArray(int[] arr, int argCount) {
switch (argCount) {
case SINGLETON_ARGUMENTS_COUNT:
return new Singleton(arr[0]);
case INFINITE_ARTHMETIC_ARGUMENTS_COUNT:
return new InfiniteArthmeticSet(arr[0], -arr[1]);
case FINITE_ARTHMETIC_ARGUMENTS_COUNT:
return new ArthmeticSet(arr[0], -arr[1], -arr[2]);
default:
return null;
}
}
}
| /**
* Wczytuje i interpretuje dane oraz wyświetla odpowiednie dla danych wartości.
*
* @author Mateusz Nowakowski
*/ | package cover;
import cover.sets.*;
import cover.solvers.CoverSolver;
import cover.solvers.ExactSolver;
import cover.solvers.GreedySolver;
import cover.solvers.NaiveSolver;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Wczytuje i interpretuje <SUF>*/
public class Bufor {
/**
* Lista zbiorów, które pojawiły się na wejściu.
* Zbiory te będą wykorzystywane do znajdowania pokrycia zapytań.
*/
private final ArrayList<Set> listOfSets;
private static final int NAIVE_ID = 3;
private static final int GREEDY_ID = 2;
private static final int EXACT_ID = 1;
private static final int SINGLETON_ARGUMENTS_COUNT = 1;
private static final int INFINITE_ARTHMETIC_ARGUMENTS_COUNT = 2;
private static final int FINITE_ARTHMETIC_ARGUMENTS_COUNT = 3;
public Bufor() {
listOfSets = new ArrayList<>();
}
/**
* Główna metoda wczytująca.
* Wczytuje i interpretuje dane ze standardowego wejścia.
*/
public void read() {
Scanner s = new Scanner(System.in);
while (s.hasNextInt()) {
int number = s.nextInt();
if (number > 0) {
readSet(number, s);
} else if (number < 0) {
readQuery(number, s);
} else {
listOfSets.add(new EmptySet());
}
}
s.close();
}
private CoverSolver getSolverByType(int type) {
switch (type) {
case NAIVE_ID:
return new NaiveSolver();
case GREEDY_ID:
return new GreedySolver();
case EXACT_ID:
return new ExactSolver();
}
throw new IllegalArgumentException("Incorrect solver type " + type);
}
/**
* Wczytuje zapytanie i wyświetla rozwiązanie.
* Czyta składniki pewnego zbioru, aż nie wczyta zera.
* Zakłada, że pierwsza liczba opisująca zapytanie jest już
* wczytana i jest nią {@code number}.
* Zakłada, że skaner {@code s} jest ustawiony na wczytanie pierwszej liczby która wystąpiła
* na wejściu po {@code number}.
* Wyświetla rozwiązanie zapytania.
*
* @param number liczba ujemna, pierwszy element zapytania
* @param s skaner skanujący wejście
*/
private void readQuery(int number, Scanner s) {
int n = s.nextInt();
Query query = new Query(-number);
Solution solution = getSolverByType(n).solve(listOfSets, query);
System.out.println(solution);
}
/**
* Wczytuje zbiór.
* Czyta składniki pewnego zbioru, aż nie wczyta zera.
* Zakłada, że pierwsza liczba opisująca pierwszy składnik zbioru jest już
* wczytana i jest nią {@code number}.
* Zakłada, że skaner {@code s} jest ustawiony na wczytanie pierwszej liczby która wystąpiła
* na wejściu po {@code number}.
* Tworzy zbiór zgodny z wczytanym opisem i dodaje go do globalnej listy zbiorów.
*
* @param number liczba dodatnia
* @param s skaner skanujący wejście
*/
private void readSet(int number, Scanner s) {
int[] setKeyNumbers = new int[3];
setKeyNumbers[0] = number;
int i = 1;
SetUnion set = new SetUnion();
boolean isZeroReached = false;
while (!isZeroReached && s.hasNextInt()) {
int n = s.nextInt();
if (n > 0) {
Set aS = setFromArray(setKeyNumbers, i);
set.addSet(aS);
setKeyNumbers[0] = n;
i = 1;
} else if (n < 0) {
setKeyNumbers[i] = n;
i++;
} else {
Set aS = setFromArray(setKeyNumbers, i);
set.addSet(aS);
isZeroReached = true;
}
}
listOfSets.add(set);
}
/**
* Tworzy i zwraca zbiór opisany jako składnik.
* Tworzy prosty zbiór opisany w gramatyce jako składnik
* (singleton, nieskończony ciąg arytmetyczny, skończony ciąg arytmetyczny)
* na wejściu opisany pierwszymi {@code argCount} liczbami w tablicy {@code arr}.
*
* @param arr tablica liczb opisujących składnik
* @param argCount ilość liczb opisujących składnik
* @return Obiekt reprezentujący składnik
* ({@link Singleton}, {@link InfiniteArthmeticSet} lub {@link ArthmeticSet})
*/
private Set setFromArray(int[] arr, int argCount) {
switch (argCount) {
case SINGLETON_ARGUMENTS_COUNT:
return new Singleton(arr[0]);
case INFINITE_ARTHMETIC_ARGUMENTS_COUNT:
return new InfiniteArthmeticSet(arr[0], -arr[1]);
case FINITE_ARTHMETIC_ARGUMENTS_COUNT:
return new ArthmeticSet(arr[0], -arr[1], -arr[2]);
default:
return null;
}
}
}
| t |
6866_3 | mawarop/github-api-consumer | 544 | src/main/java/com/gmail/oprawam/githubapiconsumer/service/GithubRepoServiceImpl.java | package com.gmail.oprawam.githubapiconsumer.service;
import com.gmail.oprawam.githubapiconsumer.dto.githubdto.GithubRepo;
import com.gmail.oprawam.githubapiconsumer.exception.NotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
@RequiredArgsConstructor
public class GithubRepoServiceImpl implements GithubRepoService {
// private final WebClient webClient = WebClient.create("https://api.github.com");
private final WebClient.Builder webClientBuilder;
public Flux<GithubRepo> fetchGithubRepos(String username) {
return webClientBuilder.build().get().uri("/users/{username}/repos", username)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(HttpStatus.NOT_FOUND::equals, e ->
Mono.error(new NotFoundException("Repo not found")))
// .onStatus(HttpStatusCode::is4xxClientError, e -> {
// if (e.statusCode().equals(HttpStatus.NOT_FOUND)) {
// // todo rzucac mono.error i sprawdzic dlaczego przy mono.error inaczej obsluguje niz przy rzucaniu
//// throw new NotFoundException("Repo not found");
// return Mono.error(new NotFoundException("Repo not found"));
//
// } else {
//// throw new GeneralResponseException("Error occurred. Status " + e.statusCode());
// return Mono.error(new GeneralResponseException("Error occurred. Status " + e.statusCode()));
//
// }
// })
.bodyToFlux(new ParameterizedTypeReference<GithubRepo>() {
});
}
}
| // // todo rzucac mono.error i sprawdzic dlaczego przy mono.error inaczej obsluguje niz przy rzucaniu | package com.gmail.oprawam.githubapiconsumer.service;
import com.gmail.oprawam.githubapiconsumer.dto.githubdto.GithubRepo;
import com.gmail.oprawam.githubapiconsumer.exception.NotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
@RequiredArgsConstructor
public class GithubRepoServiceImpl implements GithubRepoService {
// private final WebClient webClient = WebClient.create("https://api.github.com");
private final WebClient.Builder webClientBuilder;
public Flux<GithubRepo> fetchGithubRepos(String username) {
return webClientBuilder.build().get().uri("/users/{username}/repos", username)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(HttpStatus.NOT_FOUND::equals, e ->
Mono.error(new NotFoundException("Repo not found")))
// .onStatus(HttpStatusCode::is4xxClientError, e -> {
// if (e.statusCode().equals(HttpStatus.NOT_FOUND)) {
// // todo rzucac <SUF>
//// throw new NotFoundException("Repo not found");
// return Mono.error(new NotFoundException("Repo not found"));
//
// } else {
//// throw new GeneralResponseException("Error occurred. Status " + e.statusCode());
// return Mono.error(new GeneralResponseException("Error occurred. Status " + e.statusCode()));
//
// }
// })
.bodyToFlux(new ParameterizedTypeReference<GithubRepo>() {
});
}
}
| f |
6309_0 | mberlins/Mylanguage | 3,846 | src/parser/ASTnode.java | package parser;
import Interpreter.Interpreter;
import Interpreter.InterpreterException;
import standard.Token;
import java.util.ArrayList;
import java.util.HashMap;
public class ASTnode
{
public static class Program implements AST
{
private HashMap<String, AST> functions = new HashMap<>();
public HashMap<String, AST> getFunctions() {
return functions;
}
public void addFunction(String name, AST function) {
functions.put(name, function);
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class FunctionDef implements AST
{
Token name;
AST paramList;
AST functionBody;
public FunctionDef(Token name, AST paramList, AST functionBody)
{
this.name = name;
this.paramList = paramList;
this.functionBody = functionBody;
}
public Token getName() {
return name;
}
public AST getParamList() {
return paramList;
}
public AST getFunctionBody() {
return functionBody;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class ParamList implements AST
{
ArrayList<AST> names;
ParamList(ArrayList<AST> names)
{
this.names = names;
}
public ArrayList<AST> getNames() {
return names;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
}
public static class FunctionBody implements AST
{
ArrayList<AST> statements;
FunctionBody(ArrayList<AST> statements)
{
this.statements = statements;
}
public ArrayList<AST> getStatements() {
return statements;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class Variable implements AST
{
Token name;
AST value; //todo był token
Variable(Token name)
{
this.name = name;
}
public Token getName() {
return name;
}
public AST getValue() {
return value;
}
public void setValue(AST value) {
this.value = value;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class FunctionCall implements AST
{
Token name;
ArrayList<AST> arguments;
public FunctionCall(Token name, ArrayList<AST> arguments)
{
this.name = name;
this.arguments = arguments;
}
public Token getName() {
return name;
}
public ArrayList<AST> getArguments() {
return arguments;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class Assignment implements AST
{
AST variable;
AST assignmentValue;
Assignment(AST var, AST addExp)
{
this.variable = var;
this.assignmentValue = addExp;
}
public AST getVariable() {
return variable;
}
public AST getAssignmentValue() {
return assignmentValue;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class VarDeclaration implements AST
{
AST name; //todo byl token
AST assignmentValue;
VarDeclaration(AST name, AST addExp)
{
this.name = name;
this.assignmentValue = addExp;
}
public AST getName() {
return name;
}
public AST getAssignmentValue() {
return assignmentValue;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class IfStatement implements AST
{
AST condition, ifBody, elseBody;
IfStatement(AST condition, AST ifBody, AST elseBody)
{
this.condition = condition;
this.ifBody = ifBody;
this.elseBody = elseBody;
}
public AST getCondition() {
return condition;
}
public AST getIfBody() {
return ifBody;
}
public AST getElseBody() {
return elseBody;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class WhileStatement implements AST
{
AST condition, whileBody;
WhileStatement(AST condition, AST whileBody)
{
this.condition = condition;
this.whileBody = whileBody;
}
public AST getCondition() {
return condition;
}
public AST getWhileBody() {
return whileBody;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class ReturnStatement implements AST
{
AST retValue;
ReturnStatement(AST retValue)
{
this.retValue = retValue;
}
public AST getRetValue() {
return retValue;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class PrintCall implements AST
{
AST printCall;
PrintCall(AST printCall)
{
this.printCall = printCall;
}
public AST getPrintCall() {
return printCall;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class BinOperator implements AST{
public AST right, left;
public Token operation;
public BinOperator(AST left, Token operation, AST right)
{
this.right = right;
this.left = left;
this.operation = operation;
}
public AST getRight() {
return right;
}
public AST getLeft() {
return left;
}
public Token getOperation() {
return operation;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class BinLogicOperator implements AST
{
public AST right, left;
public Token operation;
public BinLogicOperator(AST left, Token operation, AST right)
{
this.right = right;
this.left = left;
this.operation = operation;
}
public AST getRight() {
return right;
}
public AST getLeft() {
return left;
}
public Token getOperation() {
return operation;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class UnOperator implements AST
{
Token token;
AST expression;
public UnOperator(Token token, AST expression)
{
this.token = token ;
this.expression = expression;
}
public String getType(){
return token.getValue();
}
public AST getExpression(){
return expression;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
}
public static class IntNum implements AST
{
Integer value;
int line;
public IntNum(Token token)
{
this.value = token.getIntValue();
this.line = token.getY_coor();
}
public Integer getValue() {
return value;
}
public int getLine() {
return line;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
@Override
public String toString()
{
return "" + value;
}
}
public static class DoubleNum implements AST
{
Double value;
int line;
public DoubleNum(Token token)
{
this.value = token.getDoubleValue();
this.line = token.getY_coor();
}
public Double getValue() {
return value;
}
public int getLine() {
return line;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
@Override
public String toString()
{
return "" + value;
}
}
public static class StringVar implements AST
{
Token value;
public StringVar(Token token)
{
this.value = token;
}
public Token getValue() {
return value;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
@Override
public String toString()
{
return "" + value.getValue();
}
}
public static class Unit implements AST
{
Token name;
Token number;
Token parentName;
Unit(Token name, Token number, Token parent)
{
this.name = name;
this.number = number;
this.parentName = parent;
}
public Token getName() {
return name;
}
public Token getNumber() {
return number;
}
public Token getParentName() {
return parentName;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class UnitResult implements AST
{
Token name;
Double number;
Double multiplicity;
Token parentName;
public UnitResult(Token number, Token name)
{
this.name = name;
if (number.getIntValue() == Integer.MIN_VALUE)
this.number = number.getDoubleValue();
else
this.number = (double)number.getIntValue();
}
public UnitResult(Token number, Token name, Double multiplicity, Token parentName)
{
this.name = name;
this.multiplicity = multiplicity;
this.parentName = parentName;
if (number.getIntValue() == Integer.MIN_VALUE)
this.number = number.getDoubleValue();
else
this.number = (double)number.getIntValue();
}
public Token getName() {
return name;
}
public Double getNumber() {
return number;
}
public Double getMultiplicity() {
return multiplicity;
}
public void setMultiplicity(Double multiplicity) {
this.multiplicity = multiplicity;
}
public Token getParentName() {
return parentName;
}
public void setParentName(Token parentName) {
this.parentName = parentName;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
public boolean equals(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) == (unitResult.getMultiplicity() * unitResult.getNumber());
}
public boolean isBigger(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) > (unitResult.getMultiplicity() * unitResult.getNumber());
}
public boolean isSmaller(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) < (unitResult.getMultiplicity() * unitResult.getNumber());
}
public boolean isBiggerEqual(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) >= (unitResult.getMultiplicity() * unitResult.getNumber());
}
public boolean isSmallerEqual(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) <= (unitResult.getMultiplicity() * unitResult.getNumber());
}
@Override
public String toString()
{
return "" + number + " " + name.getValue();
}
}
public static class BaseUnit implements AST
{
Token name;
Token unitField;
public BaseUnit(Token name, Token unitField)
{
this.name = name;
this.unitField = unitField;
}
public Token getName() {
return name;
}
public Token getUnitField() {
return unitField;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
}
| //todo był token | package parser;
import Interpreter.Interpreter;
import Interpreter.InterpreterException;
import standard.Token;
import java.util.ArrayList;
import java.util.HashMap;
public class ASTnode
{
public static class Program implements AST
{
private HashMap<String, AST> functions = new HashMap<>();
public HashMap<String, AST> getFunctions() {
return functions;
}
public void addFunction(String name, AST function) {
functions.put(name, function);
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class FunctionDef implements AST
{
Token name;
AST paramList;
AST functionBody;
public FunctionDef(Token name, AST paramList, AST functionBody)
{
this.name = name;
this.paramList = paramList;
this.functionBody = functionBody;
}
public Token getName() {
return name;
}
public AST getParamList() {
return paramList;
}
public AST getFunctionBody() {
return functionBody;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class ParamList implements AST
{
ArrayList<AST> names;
ParamList(ArrayList<AST> names)
{
this.names = names;
}
public ArrayList<AST> getNames() {
return names;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
}
public static class FunctionBody implements AST
{
ArrayList<AST> statements;
FunctionBody(ArrayList<AST> statements)
{
this.statements = statements;
}
public ArrayList<AST> getStatements() {
return statements;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class Variable implements AST
{
Token name;
AST value; //todo był <SUF>
Variable(Token name)
{
this.name = name;
}
public Token getName() {
return name;
}
public AST getValue() {
return value;
}
public void setValue(AST value) {
this.value = value;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class FunctionCall implements AST
{
Token name;
ArrayList<AST> arguments;
public FunctionCall(Token name, ArrayList<AST> arguments)
{
this.name = name;
this.arguments = arguments;
}
public Token getName() {
return name;
}
public ArrayList<AST> getArguments() {
return arguments;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class Assignment implements AST
{
AST variable;
AST assignmentValue;
Assignment(AST var, AST addExp)
{
this.variable = var;
this.assignmentValue = addExp;
}
public AST getVariable() {
return variable;
}
public AST getAssignmentValue() {
return assignmentValue;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class VarDeclaration implements AST
{
AST name; //todo byl token
AST assignmentValue;
VarDeclaration(AST name, AST addExp)
{
this.name = name;
this.assignmentValue = addExp;
}
public AST getName() {
return name;
}
public AST getAssignmentValue() {
return assignmentValue;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class IfStatement implements AST
{
AST condition, ifBody, elseBody;
IfStatement(AST condition, AST ifBody, AST elseBody)
{
this.condition = condition;
this.ifBody = ifBody;
this.elseBody = elseBody;
}
public AST getCondition() {
return condition;
}
public AST getIfBody() {
return ifBody;
}
public AST getElseBody() {
return elseBody;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class WhileStatement implements AST
{
AST condition, whileBody;
WhileStatement(AST condition, AST whileBody)
{
this.condition = condition;
this.whileBody = whileBody;
}
public AST getCondition() {
return condition;
}
public AST getWhileBody() {
return whileBody;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class ReturnStatement implements AST
{
AST retValue;
ReturnStatement(AST retValue)
{
this.retValue = retValue;
}
public AST getRetValue() {
return retValue;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class PrintCall implements AST
{
AST printCall;
PrintCall(AST printCall)
{
this.printCall = printCall;
}
public AST getPrintCall() {
return printCall;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class BinOperator implements AST{
public AST right, left;
public Token operation;
public BinOperator(AST left, Token operation, AST right)
{
this.right = right;
this.left = left;
this.operation = operation;
}
public AST getRight() {
return right;
}
public AST getLeft() {
return left;
}
public Token getOperation() {
return operation;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class BinLogicOperator implements AST
{
public AST right, left;
public Token operation;
public BinLogicOperator(AST left, Token operation, AST right)
{
this.right = right;
this.left = left;
this.operation = operation;
}
public AST getRight() {
return right;
}
public AST getLeft() {
return left;
}
public Token getOperation() {
return operation;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class UnOperator implements AST
{
Token token;
AST expression;
public UnOperator(Token token, AST expression)
{
this.token = token ;
this.expression = expression;
}
public String getType(){
return token.getValue();
}
public AST getExpression(){
return expression;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
}
public static class IntNum implements AST
{
Integer value;
int line;
public IntNum(Token token)
{
this.value = token.getIntValue();
this.line = token.getY_coor();
}
public Integer getValue() {
return value;
}
public int getLine() {
return line;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
@Override
public String toString()
{
return "" + value;
}
}
public static class DoubleNum implements AST
{
Double value;
int line;
public DoubleNum(Token token)
{
this.value = token.getDoubleValue();
this.line = token.getY_coor();
}
public Double getValue() {
return value;
}
public int getLine() {
return line;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
@Override
public String toString()
{
return "" + value;
}
}
public static class StringVar implements AST
{
Token value;
public StringVar(Token token)
{
this.value = token;
}
public Token getValue() {
return value;
}
public void accept(Interpreter visitor)
{
visitor.visit(this);
}
@Override
public String toString()
{
return "" + value.getValue();
}
}
public static class Unit implements AST
{
Token name;
Token number;
Token parentName;
Unit(Token name, Token number, Token parent)
{
this.name = name;
this.number = number;
this.parentName = parent;
}
public Token getName() {
return name;
}
public Token getNumber() {
return number;
}
public Token getParentName() {
return parentName;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
public static class UnitResult implements AST
{
Token name;
Double number;
Double multiplicity;
Token parentName;
public UnitResult(Token number, Token name)
{
this.name = name;
if (number.getIntValue() == Integer.MIN_VALUE)
this.number = number.getDoubleValue();
else
this.number = (double)number.getIntValue();
}
public UnitResult(Token number, Token name, Double multiplicity, Token parentName)
{
this.name = name;
this.multiplicity = multiplicity;
this.parentName = parentName;
if (number.getIntValue() == Integer.MIN_VALUE)
this.number = number.getDoubleValue();
else
this.number = (double)number.getIntValue();
}
public Token getName() {
return name;
}
public Double getNumber() {
return number;
}
public Double getMultiplicity() {
return multiplicity;
}
public void setMultiplicity(Double multiplicity) {
this.multiplicity = multiplicity;
}
public Token getParentName() {
return parentName;
}
public void setParentName(Token parentName) {
this.parentName = parentName;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
public boolean equals(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) == (unitResult.getMultiplicity() * unitResult.getNumber());
}
public boolean isBigger(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) > (unitResult.getMultiplicity() * unitResult.getNumber());
}
public boolean isSmaller(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) < (unitResult.getMultiplicity() * unitResult.getNumber());
}
public boolean isBiggerEqual(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) >= (unitResult.getMultiplicity() * unitResult.getNumber());
}
public boolean isSmallerEqual(UnitResult unitResult) throws InterpreterException
{
String name = this.name.getValue();
String nameBis = unitResult.getName().getValue();
if (!this.parentName.getValue().equals(unitResult.parentName.getValue())) throw new InterpreterException("Impossible to compare units from different dimensions, units: " + name + " and " + nameBis);
return (this.multiplicity * this.number) <= (unitResult.getMultiplicity() * unitResult.getNumber());
}
@Override
public String toString()
{
return "" + number + " " + name.getValue();
}
}
public static class BaseUnit implements AST
{
Token name;
Token unitField;
public BaseUnit(Token name, Token unitField)
{
this.name = name;
this.unitField = unitField;
}
public Token getName() {
return name;
}
public Token getUnitField() {
return unitField;
}
public void accept(Interpreter visitor) throws InterpreterException {
visitor.visit(this);
}
}
}
| f |
7042_2 | mblaszczykowski/concurrent-java-simulation | 494 | src/Client.java | import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class Client extends Thread {
int id;
int iterations;
static List<Semaphore> clientsSemaphores = new ArrayList<>();
Client(String name, int id, int iterations) {
super(name);
this.id = id;
this.iterations = iterations;
}
// Client is a producer of devices to repair
public void run(){
// for each client we are creating a semaphore to check whether the device will be returned
clientsSemaphores.add(new Semaphore(0));
for(int i = 0; i < iterations; i++){
// production
Device device = new Device(id, i);
System.out.println(getName() + " delivers for repairing: " + device);
try{
//producent podnosi semafor wolne, aby sprawdzić, czy w buforze jest jeszcze miejsce na kolejny element, jesli nie ma to czeka az sie pojawi
// acquiring semaphore
ClientsOrderWorkerBuffer.available.tryAcquire(200, TimeUnit.MILLISECONDS);
}catch(InterruptedException e){}
// critical section
ClientsOrderWorkerBuffer.orderBuffor = device;
// notyfing consumer (order takich worker) that there is new device waiting
ClientsOrderWorkerBuffer.taken.release();
}
// waiting for the return of all devices
for(int i = 0; i < iterations; i++){
try {
Client.clientsSemaphores.get(id).acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + " got his repaired device nr: " + i + " back");
}
}
} | //producent podnosi semafor wolne, aby sprawdzić, czy w buforze jest jeszcze miejsce na kolejny element, jesli nie ma to czeka az sie pojawi | import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class Client extends Thread {
int id;
int iterations;
static List<Semaphore> clientsSemaphores = new ArrayList<>();
Client(String name, int id, int iterations) {
super(name);
this.id = id;
this.iterations = iterations;
}
// Client is a producer of devices to repair
public void run(){
// for each client we are creating a semaphore to check whether the device will be returned
clientsSemaphores.add(new Semaphore(0));
for(int i = 0; i < iterations; i++){
// production
Device device = new Device(id, i);
System.out.println(getName() + " delivers for repairing: " + device);
try{
//producent podnosi <SUF>
// acquiring semaphore
ClientsOrderWorkerBuffer.available.tryAcquire(200, TimeUnit.MILLISECONDS);
}catch(InterruptedException e){}
// critical section
ClientsOrderWorkerBuffer.orderBuffor = device;
// notyfing consumer (order takich worker) that there is new device waiting
ClientsOrderWorkerBuffer.taken.release();
}
// waiting for the return of all devices
for(int i = 0; i < iterations; i++){
try {
Client.clientsSemaphores.get(id).acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + " got his repaired device nr: " + i + " back");
}
}
} | t |
5206_2 | mbrunka/zwinne-project | 2,193 | project-rest-api/src/main/java/com/project/controller/projekt/ProjectTeacherRestController.java | package com.project.controller.projekt;
import com.project.auth.AuthenticationService;
import com.project.controller.projekt.requests.CreateProjectRequest;
import com.project.controller.projekt.requests.CreateStatusRequest;
import com.project.controller.projekt.requests.UpdateStatusRequest;
import com.project.model.Projekt;
import com.project.model.Status;
import com.project.model.User;
import com.project.model.Zadanie;
import com.project.repository.ProjektRepository;
import com.project.service.ProjektService;
import com.project.service.StatusService;
import com.project.service.ZadanieService;
import jakarta.transaction.Transactional;
import jakarta.validation.Valid;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@RestController
@CrossOrigin
@PreAuthorize("hasAnyRole('NAUCZYCIEL', 'ADMIN')")
@RequestMapping("/api/v1/projekty/teacher")
public class ProjectTeacherRestController {
@Autowired
private ProjektService projektService;
@Autowired
private StatusService statusService;
@Autowired
private ProjektRepository projektRepository;
@Autowired
private ZadanieService zadanieService;
@PostMapping("/create")
@Transactional
ResponseEntity<Void> createProjekt(@RequestBody CreateProjectRequest request, @AuthenticationPrincipal User currentUser) {
var projekt = Projekt.builder()
.nazwa(request.getNazwa())
.opis(request.getOpis())
.teacher(currentUser.getTeacher())
.build();
// Save the updated Projekt object to the database
Projekt createdProjekt = projektService.setProjekt(projekt);
// Add default statusy
Status status1 = Status.builder()
.nazwa("Do zrobienia")
.kolor("#FF0000")
.waga(50)
.projekt(createdProjekt)
.build();
Status status2 = Status.builder()
.nazwa("W trakcie")
.kolor("#FFFF00")
.waga(100)
.projekt(createdProjekt)
.build();
Status status3 = Status.builder()
.nazwa("Zrobione")
.kolor("#00FF00")
.waga(150)
.projekt(createdProjekt)
.build();
statusService.setStatus(status1);
statusService.setStatus(status2);
statusService.setStatus(status3);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{projektId}").buildAndExpand(createdProjekt.getProjektId()).toUri();
return ResponseEntity.created(location).build();
}
@PatchMapping("/{projektId}")
public ResponseEntity<Void> updateProjekt(@RequestBody CreateProjectRequest request,
@PathVariable Long projektId,
@AuthenticationPrincipal User currentUser) {
Optional<Projekt> projekt = projektService.getProjekt(projektId);
if (projekt.isEmpty()) {
return ResponseEntity.notFound().build();
}
if (!projekt.get().getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
}
projekt.get().setNazwa(request.getNazwa());
projekt.get().setOpis(request.getOpis());
projektRepository.save(projekt.get());
return ResponseEntity.ok().build();
}
@DeleteMapping("/{projektId}")
public ResponseEntity<Void> deleteProjekt(@PathVariable Long projektId,
@AuthenticationPrincipal User currentUser) {
return projektService.getProjekt(projektId).map(p -> {
if (!p.getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
}
Projekt projekt = projektService.getProjekt(projektId).orElseThrow();
Set<Status> statusy = projekt.getStatusy();
for (Status status : statusy) {
Set<Zadanie> zadania = status.getZadania();
for (Zadanie zadanie : zadania) {
zadanieService.deleteZadanie(zadanie.getZadanieId());
}
statusService.deleteStatus(status.getStatusId());
}
projektService.deleteProjekt(projektId);
return new ResponseEntity<Void>(HttpStatus.OK);
}).orElseGet(() -> ResponseEntity.notFound().build());
}
@GetMapping("/{projektId}/code")
public ResponseEntity<String> getJoinCode(@PathVariable Long projektId,
@AuthenticationPrincipal User currentUser) {
return projektService.getProjekt(projektId).map(p -> {
if (!p.getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
}
return new ResponseEntity<String>(p.getJoinCode(), HttpStatus.OK);
}).orElseGet(() -> ResponseEntity.notFound().build());
}
@PostMapping("/status")
public ResponseEntity<Status> createStatus(@RequestBody CreateStatusRequest request,
@AuthenticationPrincipal User currentUser) {
Optional<Projekt> projekt = projektService.getProjekt(request.getProjektId());
if (projekt.isEmpty()) {
return ResponseEntity.notFound().build();
}
Status status = Status.builder()
.nazwa(request.getNazwa())
.kolor(request.getKolor())
.waga(request.getWaga())
.projekt(projekt.get())
.build();
Status createdStatus = statusService.setStatus(status);
return ResponseEntity.ok(createdStatus);
}
@PatchMapping("/status")
public ResponseEntity<?> updateStatus(@RequestBody UpdateStatusRequest request,
@AuthenticationPrincipal User currentUser) {
Optional<Status> status = statusService.getStatus(request.getStatusId());
if (status.isEmpty()) {
return ResponseEntity.notFound().build();
}
if (!status.get().getProjekt().getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
}
status.get().setNazwa(request.getNazwa());
status.get().setKolor(request.getKolor());
status.get().setWaga(request.getWaga());
return ResponseEntity.ok(statusService.setStatus(status.get()));
}
//chyba git: dalej mogę usunąc tylko takie bez statusu => TODO nie usuwa, gdy np. do statusu są przypisane jakieś zadanie (trzeba dodać cascade w jakiś sposób)
@DeleteMapping("/status/{statusId}")
public ResponseEntity<Void> deleteStatus(@PathVariable Long statusId,
@AuthenticationPrincipal User currentUser) {
Optional<Status> status = statusService.getStatus(statusId);
if (status.isEmpty()) {
return ResponseEntity.notFound().build();
}
if (!status.get().getProjekt().getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
}
if (!status.get().getZadania().isEmpty()) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
statusService.deleteStatus(statusId);
return ResponseEntity.ok().build();
}
}
| //chyba git: dalej mogę usunąc tylko takie bez statusu => TODO nie usuwa, gdy np. do statusu są przypisane jakieś zadanie (trzeba dodać cascade w jakiś sposób) | package com.project.controller.projekt;
import com.project.auth.AuthenticationService;
import com.project.controller.projekt.requests.CreateProjectRequest;
import com.project.controller.projekt.requests.CreateStatusRequest;
import com.project.controller.projekt.requests.UpdateStatusRequest;
import com.project.model.Projekt;
import com.project.model.Status;
import com.project.model.User;
import com.project.model.Zadanie;
import com.project.repository.ProjektRepository;
import com.project.service.ProjektService;
import com.project.service.StatusService;
import com.project.service.ZadanieService;
import jakarta.transaction.Transactional;
import jakarta.validation.Valid;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@RestController
@CrossOrigin
@PreAuthorize("hasAnyRole('NAUCZYCIEL', 'ADMIN')")
@RequestMapping("/api/v1/projekty/teacher")
public class ProjectTeacherRestController {
@Autowired
private ProjektService projektService;
@Autowired
private StatusService statusService;
@Autowired
private ProjektRepository projektRepository;
@Autowired
private ZadanieService zadanieService;
@PostMapping("/create")
@Transactional
ResponseEntity<Void> createProjekt(@RequestBody CreateProjectRequest request, @AuthenticationPrincipal User currentUser) {
var projekt = Projekt.builder()
.nazwa(request.getNazwa())
.opis(request.getOpis())
.teacher(currentUser.getTeacher())
.build();
// Save the updated Projekt object to the database
Projekt createdProjekt = projektService.setProjekt(projekt);
// Add default statusy
Status status1 = Status.builder()
.nazwa("Do zrobienia")
.kolor("#FF0000")
.waga(50)
.projekt(createdProjekt)
.build();
Status status2 = Status.builder()
.nazwa("W trakcie")
.kolor("#FFFF00")
.waga(100)
.projekt(createdProjekt)
.build();
Status status3 = Status.builder()
.nazwa("Zrobione")
.kolor("#00FF00")
.waga(150)
.projekt(createdProjekt)
.build();
statusService.setStatus(status1);
statusService.setStatus(status2);
statusService.setStatus(status3);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{projektId}").buildAndExpand(createdProjekt.getProjektId()).toUri();
return ResponseEntity.created(location).build();
}
@PatchMapping("/{projektId}")
public ResponseEntity<Void> updateProjekt(@RequestBody CreateProjectRequest request,
@PathVariable Long projektId,
@AuthenticationPrincipal User currentUser) {
Optional<Projekt> projekt = projektService.getProjekt(projektId);
if (projekt.isEmpty()) {
return ResponseEntity.notFound().build();
}
if (!projekt.get().getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
}
projekt.get().setNazwa(request.getNazwa());
projekt.get().setOpis(request.getOpis());
projektRepository.save(projekt.get());
return ResponseEntity.ok().build();
}
@DeleteMapping("/{projektId}")
public ResponseEntity<Void> deleteProjekt(@PathVariable Long projektId,
@AuthenticationPrincipal User currentUser) {
return projektService.getProjekt(projektId).map(p -> {
if (!p.getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
}
Projekt projekt = projektService.getProjekt(projektId).orElseThrow();
Set<Status> statusy = projekt.getStatusy();
for (Status status : statusy) {
Set<Zadanie> zadania = status.getZadania();
for (Zadanie zadanie : zadania) {
zadanieService.deleteZadanie(zadanie.getZadanieId());
}
statusService.deleteStatus(status.getStatusId());
}
projektService.deleteProjekt(projektId);
return new ResponseEntity<Void>(HttpStatus.OK);
}).orElseGet(() -> ResponseEntity.notFound().build());
}
@GetMapping("/{projektId}/code")
public ResponseEntity<String> getJoinCode(@PathVariable Long projektId,
@AuthenticationPrincipal User currentUser) {
return projektService.getProjekt(projektId).map(p -> {
if (!p.getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
}
return new ResponseEntity<String>(p.getJoinCode(), HttpStatus.OK);
}).orElseGet(() -> ResponseEntity.notFound().build());
}
@PostMapping("/status")
public ResponseEntity<Status> createStatus(@RequestBody CreateStatusRequest request,
@AuthenticationPrincipal User currentUser) {
Optional<Projekt> projekt = projektService.getProjekt(request.getProjektId());
if (projekt.isEmpty()) {
return ResponseEntity.notFound().build();
}
Status status = Status.builder()
.nazwa(request.getNazwa())
.kolor(request.getKolor())
.waga(request.getWaga())
.projekt(projekt.get())
.build();
Status createdStatus = statusService.setStatus(status);
return ResponseEntity.ok(createdStatus);
}
@PatchMapping("/status")
public ResponseEntity<?> updateStatus(@RequestBody UpdateStatusRequest request,
@AuthenticationPrincipal User currentUser) {
Optional<Status> status = statusService.getStatus(request.getStatusId());
if (status.isEmpty()) {
return ResponseEntity.notFound().build();
}
if (!status.get().getProjekt().getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
}
status.get().setNazwa(request.getNazwa());
status.get().setKolor(request.getKolor());
status.get().setWaga(request.getWaga());
return ResponseEntity.ok(statusService.setStatus(status.get()));
}
//chyba git: <SUF>
@DeleteMapping("/status/{statusId}")
public ResponseEntity<Void> deleteStatus(@PathVariable Long statusId,
@AuthenticationPrincipal User currentUser) {
Optional<Status> status = statusService.getStatus(statusId);
if (status.isEmpty()) {
return ResponseEntity.notFound().build();
}
if (!status.get().getProjekt().getTeacher().getTeacherId().equals(currentUser.getTeacher().getTeacherId())) {
return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
}
if (!status.get().getZadania().isEmpty()) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
statusService.deleteStatus(statusId);
return ResponseEntity.ok().build();
}
}
| f |
10340_1 | mcPear/Java_course | 627 | src/main/java/com/example/weather/controller/WeatherController.java | package com.example.weather.controller;
import com.example.weather.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Created by maciej on 14.03.17.
*/
@RestController
@RequestMapping("/api")
public class WeatherController {
@Qualifier(value = "cute")// drugi, lepszy sposób na wskazanie co wstrzyknąć
@Autowired //jak ci się uda znaleźć implementację WeatherService to gra, jak nie to nawet nie startuj aplikacji
private WeatherService weatherService; //nie wskazuję, z której implementacji będę korzystał
//@Qualifier("otherWeatherType")// wykorzystanie nazwy metody z @Bean do sprecyzowania
@Qualifier("xmlBean")
@Autowired
private String myBean;
@Autowired
Collection<WeatherService> weatherServices;
@RequestMapping("/weathers")
public List<String> allWeathers(){
List<String> result = new ArrayList<>();
weatherServices.forEach(x->result.add(x.getWeather()));
result.add(myBean); //dodatek pokazuje, że inne beany też można wstrzykiwać
return result;
}
@RequestMapping("/weather")
public String getWeather(){
return weatherService.getWeather();
}
@RequestMapping("/weathers/{status}")
public List<String> allWeathersStatus(@PathVariable Long status,
HttpServletRequest request,
HttpServletResponse response){
List<String> result = new ArrayList<>();
weatherServices.forEach(x->result.add(x.getWeather()));
result.add(myBean); //dodatek pokazuje, że inne beany też można wstrzykiwać
response.setStatus(401); //warunkowa zmiana zwracanego statusu
return result;
}
}
| // drugi, lepszy sposób na wskazanie co wstrzyknąć | package com.example.weather.controller;
import com.example.weather.service.WeatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Created by maciej on 14.03.17.
*/
@RestController
@RequestMapping("/api")
public class WeatherController {
@Qualifier(value = "cute")// drugi, lepszy <SUF>
@Autowired //jak ci się uda znaleźć implementację WeatherService to gra, jak nie to nawet nie startuj aplikacji
private WeatherService weatherService; //nie wskazuję, z której implementacji będę korzystał
//@Qualifier("otherWeatherType")// wykorzystanie nazwy metody z @Bean do sprecyzowania
@Qualifier("xmlBean")
@Autowired
private String myBean;
@Autowired
Collection<WeatherService> weatherServices;
@RequestMapping("/weathers")
public List<String> allWeathers(){
List<String> result = new ArrayList<>();
weatherServices.forEach(x->result.add(x.getWeather()));
result.add(myBean); //dodatek pokazuje, że inne beany też można wstrzykiwać
return result;
}
@RequestMapping("/weather")
public String getWeather(){
return weatherService.getWeather();
}
@RequestMapping("/weathers/{status}")
public List<String> allWeathersStatus(@PathVariable Long status,
HttpServletRequest request,
HttpServletResponse response){
List<String> result = new ArrayList<>();
weatherServices.forEach(x->result.add(x.getWeather()));
result.add(myBean); //dodatek pokazuje, że inne beany też można wstrzykiwać
response.setStatus(401); //warunkowa zmiana zwracanego statusu
return result;
}
}
| f |
627_12 | mchubby-3rdparty/jdownloader | 2,039 | src/jd/plugins/hoster/PrzeklejOrg.java | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" })
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
if (br.containsHTML("Wygląda na to, że wybrany plik został skasowany") || !this.br.containsHTML("class=\"fileData\"") || this.br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
String filesize = br.getRegex(">Rozmiar[\t\n\r ]*?:</div>[\t\n\r ]*?<div class=\"right\">([^<>\"]*?)<").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
if (filesize != null) {
link.setDownloadSize(SizeFormatter.getSize(filesize));
}
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
final boolean captcha_needed = false;
if (captcha_needed) {
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
} else {
br.postPage("http://przeklej.org/file/captachaValidate", "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
}
final String ad_url = this.br.getRegex("Kliknij <a href=\"(http://[^<>\"]*?)\"").getMatch(0);
if (ad_url != null) {
this.br.getHeaders().put("Referer", ad_url);
this.br.getPage("/file/download/" + downloadkey);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest|Wygląda na to, że wybrany plik został skasowany z naszych serwerów")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | //(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" }) | //jDownloader - Downloadmanager
//Copyright (C) 2010 JD-Team support@jdownloader.org
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
import org.appwork.utils.formatter.SizeFormatter;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "przeklej.org" }, urls = { "http://(www\\.)?przeklej\\.org/file/[A-Za-z0-9]+" }) <SUF>
public class PrzeklejOrg extends PluginForHost {
public PrzeklejOrg(PluginWrapper wrapper) {
super(wrapper);
}
@Override
public String getAGBLink() {
return "http://przeklej.org/regulamin";
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink link) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.setCustomCharset("utf-8");
br.getPage(link.getDownloadURL());
if (br.containsHTML("Wygląda na to, że wybrany plik został skasowany") || !this.br.containsHTML("class=\"fileData\"") || this.br.getHttpConnection().getResponseCode() == 404) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
final String jsredirect = br.getRegex("<script>location\\.href=\"(https?://(www\\.)?przeklej\\.org/file/[^<>\"]*?)\"</script>").getMatch(0);
if (jsredirect != null) {
br.getPage(jsredirect);
}
final String filename = br.getRegex("<title>([^<>\"]*?) \\- Przeklej\\.org</title>").getMatch(0);
String filesize = br.getRegex(">Rozmiar[\t\n\r ]*?:</div>[\t\n\r ]*?<div class=\"right\">([^<>\"]*?)<").getMatch(0);
if (filename == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
link.setName(encodeUnicode(Encoding.htmlDecode(filename.trim())));
if (filesize != null) {
link.setDownloadSize(SizeFormatter.getSize(filesize));
}
return AvailableStatus.TRUE;
}
@Override
public void handleFree(final DownloadLink downloadLink) throws Exception, PluginException {
requestFileInformation(downloadLink);
String dllink = checkDirectLink(downloadLink, "directlink");
if (dllink == null) {
final String fid = new Regex(downloadLink.getDownloadURL(), "([A-Za-z0-9]+)$").getMatch(0);
final String downloadkey = br.getRegex("name=\"downloadKey\" value=\"([^<>\"]*?)\"").getMatch(0);
boolean failed = true;
if (downloadkey == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
br.getHeaders().put("X-Requested-With", "XMLHttpRequest");
final boolean captcha_needed = false;
if (captcha_needed) {
for (int i = 1; i <= 3; i++) {
final String code = this.getCaptchaCode("http://przeklej.org/application/library/token.php?url=" + fid + "_code", downloadLink);
br.postPage("http://przeklej.org/file/captachaValidate", "captacha=" + Encoding.urlEncode(code) + "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
if (br.toString().equals("err")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new PluginException(LinkStatus.ERROR_CAPTCHA);
}
} else {
br.postPage("http://przeklej.org/file/captachaValidate", "&downloadKey=" + downloadkey + "&shortUrl=" + fid + "_code");
}
final String ad_url = this.br.getRegex("Kliknij <a href=\"(http://[^<>\"]*?)\"").getMatch(0);
if (ad_url != null) {
this.br.getHeaders().put("Referer", ad_url);
this.br.getPage("/file/download/" + downloadkey);
}
if (br.containsHTML("Przykro nam, ale wygląda na to, że plik nie jest|Wygląda na to, że wybrany plik został skasowany z naszych serwerów")) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
dllink = br.getRegex("<script>location\\.href=\"(http[^<>\"]*?)\"</script>").getMatch(0);
if (dllink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
}
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, dllink, false, 1);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
downloadLink.setProperty("directlink", dllink);
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
try {
final Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
con.disconnect();
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
return dllink;
}
@Override
public void reset() {
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void resetDownloadlink(final DownloadLink link) {
}
} | f |
3683_1 | mhorod/oop-unit-tests | 364 | satori/E/DominikMatuszekFunctionsTest.java | import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DominikMatuszekFunctionsTest {
@Test
public void constant_function_has_got_exactly_0_arguments(){
String result = "żart_o_gościu_na_żółtym_motorku";
String toAdd = "ten żart jest świetny ale jeśli go zacznę opowiadać w ten sposób to chyba zostanę wyrzucony przez okno";
Function <String, String> testFunction = Functions.constant(result); //funkcja ze Stringa w Stringa, czemu nie?
ArrayList<String> args = new ArrayList<>();
try {
assertEquals(testFunction.compute(args), result);
}
catch(Exception e){
fail(); //proszę tu nie rzucać żadnych exceptionów
}
for(int i=1;i<100;i++){
args.add(toAdd);
try{
testFunction.compute(args);
fail(); //więcej niż zero argumentów jest verboten
}
catch(Exception e){
//tu ma nic nie być
}
}
}
}
| //proszę tu nie rzucać żadnych exceptionów | import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DominikMatuszekFunctionsTest {
@Test
public void constant_function_has_got_exactly_0_arguments(){
String result = "żart_o_gościu_na_żółtym_motorku";
String toAdd = "ten żart jest świetny ale jeśli go zacznę opowiadać w ten sposób to chyba zostanę wyrzucony przez okno";
Function <String, String> testFunction = Functions.constant(result); //funkcja ze Stringa w Stringa, czemu nie?
ArrayList<String> args = new ArrayList<>();
try {
assertEquals(testFunction.compute(args), result);
}
catch(Exception e){
fail(); //proszę tu <SUF>
}
for(int i=1;i<100;i++){
args.add(toAdd);
try{
testFunction.compute(args);
fail(); //więcej niż zero argumentów jest verboten
}
catch(Exception e){
//tu ma nic nie być
}
}
}
}
| f |
8750_13 | michal-bed/el-proyecte-grande-naspolke | 1,012 | src/main/java/com/company/naspolke/webclient/krs/KrsClient.java | package com.company.naspolke.webclient.krs;
import lombok.Data;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
@Data
@Component
public class KrsClient {
private WebClient webClient;
private String KRS_URL = "https://api-krs.ms.gov.pl/api/krs";
public String webClient(String krsNumber){
WebClient webClient = WebClient
.builder()
.baseUrl(KRS_URL)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
WebClient.RequestHeadersSpec<?> requestHeadersSpec = webClient.get().uri("/OdpisAktualny/"+krsNumber+"?rejestr=p&format=json");
String response = null;
try {
response = requestHeadersSpec.retrieve().bodyToMono(String.class).block();
} catch (WebClientResponseException e) {
return String.valueOf(e.getRawStatusCode());
}
return response;
}
}
// mono
// .doOnNext(body-> System.out.println(body))
// .subscribe();
//
// private RestTemplate restTemplate = new RestTemplate();
//
// public ResponseEntity getKrsData(String krsNumber) {
// System.out.println("ok");
// return restTemplate (KRS_URL +
// "{typeOfAllowance}/{krsNumber}?rejestr={typeOfRegister}&format=json",
// CompanyDto.class,
// "OdpisAktualny", krsNumber, "p");
// }
//<html>
//
//<head>
//<title>Przerwa techniczna</title>
//<meta http-equiv=Content-Type content=text/html; charset=utf-8 />
//<meta name=robots content=noindex, nofollow />
//<style type=text/css> body { background: url(http://gov.pl/sprawiedliwosc/Themes/ErrorPages/Images/background.gif)
// repeat-x white; color: #363636; font-size: 11px; font-family: Georgia; Tahoma, Arial; line-height: 16px; margin:
// 0px; padding: 0px; } </style> </head> <body bgcolor=#363636>
//<center>
//
//
//<a href=http://www.gov.pl/sprawiedliwosc border=0>
//<img src=http://ms.gov.pl/sprawiedliwosc/Themes/ErrorPages//Images/logo.png alt=www.gov.pl/sprawiedliwosc border=0>
//</a>
//<BR><BR><BR><BR>
//<font family=Georgia size=6><b></font><font family=Georgia size=6>Przerwa techniczna </b></font>
//<BR><BR><BR><BR><BR>
//
//<font family=Georgia size=4>
//
//
//<BR>
//<BR>Szanowni Państwo,
//<BR>
//<BR>
//<BR>Uprzejmie informujemy, iż od godz. 18:30 do godz. 23:00
//<BR>
//<BR>trwa przerwa techniczna w dostępie do systemu.
//<BR>
//<BR>
//<BR>Za utrudnienia przepraszamy.</BR>
//<BR>
//<BR>
//</font>
//
//
//</center>
//</body>
//</html>
// | //<BR>Uprzejmie informujemy, iż od godz. 18:30 do godz. 23:00 | package com.company.naspolke.webclient.krs;
import lombok.Data;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
@Data
@Component
public class KrsClient {
private WebClient webClient;
private String KRS_URL = "https://api-krs.ms.gov.pl/api/krs";
public String webClient(String krsNumber){
WebClient webClient = WebClient
.builder()
.baseUrl(KRS_URL)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
WebClient.RequestHeadersSpec<?> requestHeadersSpec = webClient.get().uri("/OdpisAktualny/"+krsNumber+"?rejestr=p&format=json");
String response = null;
try {
response = requestHeadersSpec.retrieve().bodyToMono(String.class).block();
} catch (WebClientResponseException e) {
return String.valueOf(e.getRawStatusCode());
}
return response;
}
}
// mono
// .doOnNext(body-> System.out.println(body))
// .subscribe();
//
// private RestTemplate restTemplate = new RestTemplate();
//
// public ResponseEntity getKrsData(String krsNumber) {
// System.out.println("ok");
// return restTemplate (KRS_URL +
// "{typeOfAllowance}/{krsNumber}?rejestr={typeOfRegister}&format=json",
// CompanyDto.class,
// "OdpisAktualny", krsNumber, "p");
// }
//<html>
//
//<head>
//<title>Przerwa techniczna</title>
//<meta http-equiv=Content-Type content=text/html; charset=utf-8 />
//<meta name=robots content=noindex, nofollow />
//<style type=text/css> body { background: url(http://gov.pl/sprawiedliwosc/Themes/ErrorPages/Images/background.gif)
// repeat-x white; color: #363636; font-size: 11px; font-family: Georgia; Tahoma, Arial; line-height: 16px; margin:
// 0px; padding: 0px; } </style> </head> <body bgcolor=#363636>
//<center>
//
//
//<a href=http://www.gov.pl/sprawiedliwosc border=0>
//<img src=http://ms.gov.pl/sprawiedliwosc/Themes/ErrorPages//Images/logo.png alt=www.gov.pl/sprawiedliwosc border=0>
//</a>
//<BR><BR><BR><BR>
//<font family=Georgia size=6><b></font><font family=Georgia size=6>Przerwa techniczna </b></font>
//<BR><BR><BR><BR><BR>
//
//<font family=Georgia size=4>
//
//
//<BR>
//<BR>Szanowni Państwo,
//<BR>
//<BR>
//<BR>Uprzejmie informujemy, <SUF>
//<BR>
//<BR>trwa przerwa techniczna w dostępie do systemu.
//<BR>
//<BR>
//<BR>Za utrudnienia przepraszamy.</BR>
//<BR>
//<BR>
//</font>
//
//
//</center>
//</body>
//</html>
// | f |
6126_1 | mikkoziel/KITron | 488 | src/game/ControlsThread.java | package game;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import static game.Direction.*;
public class ControlsThread extends Thread{
private String hostName = "localhost"; //tu trza bedzie zmienic
private int portNumber = 12345; //tu trza bedzie zmienic
private Socket socket = null;
public void run(Scene scene){
System.out.println("Tutaj bedzie player sobie wiadomosci TCP wysylal jak zmieni kierunek");
try {
socket = new Socket(hostName, portNumber);
scene.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.DOWN) {
sendMessage(DOWN);
} else if (e.getCode() == KeyCode.UP) {
sendMessage(UP);
} else if (e.getCode() == KeyCode.RIGHT) {
sendMessage(RIGHT);
} else if (e.getCode() == KeyCode.LEFT) {
sendMessage(LEFT);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
void sendMessage(Direction moveDirection) { //down/up, mozliwe ze pozycja
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String message = null; //dopisac wiadomosc w formacie jakims tam np,. up/pozycja obecna
//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
| //tu trza bedzie zmienic | package game;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import static game.Direction.*;
public class ControlsThread extends Thread{
private String hostName = "localhost"; //tu trza bedzie zmienic
private int portNumber = 12345; //tu trza <SUF>
private Socket socket = null;
public void run(Scene scene){
System.out.println("Tutaj bedzie player sobie wiadomosci TCP wysylal jak zmieni kierunek");
try {
socket = new Socket(hostName, portNumber);
scene.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.DOWN) {
sendMessage(DOWN);
} else if (e.getCode() == KeyCode.UP) {
sendMessage(UP);
} else if (e.getCode() == KeyCode.RIGHT) {
sendMessage(RIGHT);
} else if (e.getCode() == KeyCode.LEFT) {
sendMessage(LEFT);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
void sendMessage(Direction moveDirection) { //down/up, mozliwe ze pozycja
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String message = null; //dopisac wiadomosc w formacie jakims tam np,. up/pozycja obecna
//BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
| f |
212_12 | mirror/jdownloader | 6,943 | src/jd/plugins/hoster/Xt7Pl.java | // jDownloader - Downloadmanager
// Copyright (C) 2014 JD-Team support@jdownloader.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.appwork.utils.formatter.SizeFormatter;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.plugins.controller.LazyPlugin;
import org.jdownloader.plugins.controller.LazyPlugin.FEATURE;
import org.jdownloader.settings.GraphicalUserInterfaceSettings.SIZEUNIT;
import org.jdownloader.settings.staticreferences.CFG_GUI;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginConfigPanelNG;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "xt7.pl" }, urls = { "" })
public class Xt7Pl extends PluginForHost {
private String MAINPAGE = "https://xt7.pl/";
private static HashMap<Account, HashMap<String, Long>> hostUnavailableMap = new HashMap<Account, HashMap<String, Long>>();
private static Object LOCK = new Object();
public Xt7Pl(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium(MAINPAGE + "login");
}
@Override
public LazyPlugin.FEATURE[] getFeatures() {
return new LazyPlugin.FEATURE[] { LazyPlugin.FEATURE.MULTIHOST };
}
private void login(Account account, boolean force) throws PluginException, IOException {
synchronized (LOCK) {
try {
br.postPage(MAINPAGE + "login", "login=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass()));
if (br.getCookie(MAINPAGE, "autologin") == null) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PREMIUM_ERROR"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
// Save cookies
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
account.setProperty("cookies", cookies);
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
List<String> getSupportedHosts() {
List<String> supportedHosts = new ArrayList<String>();
String hosts;
try {
hosts = br.getPage(MAINPAGE + "jdhostingi.txt");
} catch (IOException e) {
return null;
}
if (hosts != null) {
String hoster[] = new Regex(hosts, "([A-Zaa-z0-9]+\\.[A-Zaa-z0-9]+)").getColumn(0);
for (String host : hoster) {
if (hosts == null || host.length() == 0) {
continue;
}
supportedHosts.add(host.trim());
}
return supportedHosts;
} else {
return null;
}
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
String validUntil = null;
final AccountInfo ai = new AccountInfo();
br.setConnectTimeout(60 * 1000);
br.setReadTimeout(60 * 1000);
login(account, true);
if (!br.getURL().contains("mojekonto")) {
br.getPage("/mojekonto");
}
if (br.containsHTML("Brak ważnego dostępu Premium")) {
ai.setExpired(true);
// ai.setStatus("Account expired");
ai.setStatus(getPhrase("EXPIRED"));
ai.setProperty("premium", "FALSE");
return ai;
} else if (br.containsHTML(">Brak ważnego dostępu Premium<")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("UNSUPPORTED_PREMIUM"), PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
validUntil = br.getRegex("<div class=\"textPremium\">Dostęp Premium ważny do <b>(.*?)</b><br />").getMatch(0);
if (validUntil == null) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PLUGIN_BROKEN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
validUntil = validUntil.replace(" / ", " ");
ai.setProperty("premium", "TRUE");
}
long expireTime = TimeFormatter.getMilliSeconds(validUntil, "dd.MM.yyyy HH:mm", Locale.ENGLISH);
ai.setValidUntil(expireTime);
account.setValid(true);
String otherHostersLimitLeft = // br.getRegex(" Pozostały limit na serwisy dodatkowe: <b>([^<>\"\\']+)</b></div>").getMatch(0);
br.getRegex("Pozostały Limit Premium do wykorzystania: <b>([^<>\"\\']+)</b></div>").getMatch(0);
if (otherHostersLimitLeft == null) {
otherHostersLimitLeft = br.getRegex("Pozostały limit na serwisy dodatkowe: <b>([^<>\"\\']+)</b></div>").getMatch(0);
}
ai.setProperty("TRAFFIC_LEFT", otherHostersLimitLeft == null ? getPhrase("UNKNOWN") : SizeFormatter.getSize(otherHostersLimitLeft));
String unlimited = br.getRegex("<br />(.*): <b>Bez limitu</b> \\|").getMatch(0);
if (unlimited != null) {
ai.setProperty("UNLIMITED", unlimited);
}
ai.setStatus("Premium" + " (" + getPhrase("TRAFFIC_LEFT") + ": " + (otherHostersLimitLeft == null ? getPhrase("UNKNOWN") : otherHostersLimitLeft) + (unlimited == null ? "" : ", " + unlimited + ": " + getPhrase("UNLIMITED")) + ")");
if (otherHostersLimitLeft != null) {
ai.setTrafficLeft(SizeFormatter.getSize(otherHostersLimitLeft));
}
List<String> supportedHostsList = getSupportedHosts();
ai.setMultiHostSupport(this, supportedHostsList);
return ai;
}
@Override
public String getAGBLink() {
return MAINPAGE + "regulamin";
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 0;
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception, PluginException {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
}
private void showMessage(DownloadLink link, String message) {
link.getLinkStatus().setStatusText(message);
}
/** no override to keep plugin compatible to old stable */
public void handleMultiHost(final DownloadLink link, final Account account) throws Exception {
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
if (unavailableMap != null) {
Long lastUnavailable = unavailableMap.get(link.getHost());
if (lastUnavailable != null && System.currentTimeMillis() < lastUnavailable) {
final long wait = lastUnavailable - System.currentTimeMillis();
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("HOSTER_UNAVAILABLE") + " " + this.getHost(), wait);
} else if (lastUnavailable != null) {
unavailableMap.remove(link.getHost());
if (unavailableMap.size() == 0) {
hostUnavailableMap.remove(account);
}
}
}
}
final String downloadUrl = link.getPluginPatternMatcher();
boolean resume = true;
showMessage(link, "Phase 1/3: Login");
login(account, false);
br.setConnectTimeout(90 * 1000);
br.setReadTimeout(90 * 1000);
dl = null;
// each time new download link is generated
// (so even after user interrupted download) - transfer
// is reduced, so:
// first check if the property generatedLink was previously generated
// if so, then try to use it, generated link store in link properties
// for future usage (broken download etc)
String generatedLink = checkDirectLink(link, "generatedLinkXt7");
if (generatedLink == null) {
/* generate new downloadlink */
String url = Encoding.urlEncode(downloadUrl);
String postData = "step=1" + "&content=" + url;
showMessage(link, "Phase 2/3: Generating Link");
br.postPage(MAINPAGE + "mojekonto/sciagaj", postData);
if (br.containsHTML("Wymagane dodatkowe [0-9.]+ MB limitu")) {
logger.severe("Xt7.pl(Error): " + br.getRegex("(Wymagane dodatkowe [0-9.]+ MB limitu)"));
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("DOWNLOAD_LIMIT"), 1 * 60 * 1000l);
}
postData = "step=2" + "&0=on";
br.postPage(MAINPAGE + "mojekonto/sciagaj", postData);
// New Regex, but not tested if it works for all files (not video)
// String generatedLink =
// br.getRegex("<div class=\"download\">(<a target=\"_blank\" href=\"mojekonto/ogladaj/[0-9A-Za-z]*?\">Oglądaj online</a> /
// )*?<a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(1);
// Old Regex
generatedLink = br.getRegex("<div class=\"download\"><a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(0);
if (generatedLink == null) {
// New Regex (works with video files)
generatedLink = br.getRegex("<div class=\"download\">(<a target=\"_blank\" href=\"mojekonto/ogladaj/[0-9A-Za-z]*?\">Oglądaj[ online]*?</a> / )<a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(1);
}
if (generatedLink == null) {
logger.severe("Xt7.pl(Error): " + generatedLink);
//
// after x retries we disable this host and retry with normal plugin
// but because traffic limit is decreased even if there's a problem
// with download (seems like bug) - we limit retries to 2
//
if (link.getLinkStatus().getRetryCount() >= 2) {
try {
// disable hoster for 30min
tempUnavailableHoster(account, link, 30 * 60 * 1000l);
} catch (Exception e) {
}
/* reset retrycounter */
link.getLinkStatus().setRetryCount(0);
final String inactiveLink = br.getRegex("textarea id=\"listInactive\" class=\"small\" readonly>(.*?)[ \t\n\r]+</textarea>").getMatch(0);
if (downloadUrl.compareTo(inactiveLink) != 0) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("LINK_INACTIVE"), 30 * 1000l);
}
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE);
}
String msg = "(" + link.getLinkStatus().getRetryCount() + 1 + "/" + 2 + ")";
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("RETRY") + msg, 20 * 1000l);
}
link.setProperty("generatedLinkXt7", generatedLink);
}
// wait, workaround
sleep(1 * 1000l, link);
int chunks = 0;
// generated fileshark.pl link allows only 1 chunk
// because download doesn't support more chunks and
// and resume (header response has no: "Content-Range" info)
final String url = link.getPluginPatternMatcher();
final String oneChunkHostersPattern = ".*fileshark\\.pl.*";
if (url.matches(oneChunkHostersPattern) || downloadUrl.matches(oneChunkHostersPattern)) {
chunks = 1;
resume = false;
}
dl = jd.plugins.BrowserAdapter.openDownload(br, link, generatedLink, resume, chunks);
if (dl.getConnection().getContentType().equalsIgnoreCase("text/html")) // unknown
// error
{
br.followConnection();
if (br.containsHTML("<div id=\"message\">Ważność linka wygasła.</div>")) {
// previously generated link expired,
// clear the property and restart the download
// and generate new link
sleep(10 * 1000l, link, getPhrase("LINK_EXPIRED"));
logger.info("Xt7.pl: previously generated link expired - removing it and restarting download process.");
link.setProperty("generatedLinkXt7", null);
throw new PluginException(LinkStatus.ERROR_RETRY);
}
if (br.getBaseURL().contains("notransfer")) {
/* No traffic left */
account.getAccountInfo().setTrafficLeft(0);
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("NO_TRAFFIC"), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE);
}
if (br.getBaseURL().contains("serviceunavailable")) {
tempUnavailableHoster(account, link, 60 * 60 * 1000l);
}
if (br.getBaseURL().contains("connecterror")) {
tempUnavailableHoster(account, link, 60 * 60 * 1000l);
}
if (br.getBaseURL().contains("invaliduserpass")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PREMIUM_ERROR"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ((br.getBaseURL().contains("notfound")) || (br.containsHTML("404 Not Found"))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
if (br.containsHTML("Wymagane dodatkowe [0-9.]+ MB limitu")) {
logger.severe("Xt7.pl(Error): " + br.getRegex("(Wymagane dodatkowe [0-9.]+ MB limitu)"));
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("DOWNLOAD_LIMIT"), 1 * 60 * 1000l);
}
}
if (dl.getConnection().getResponseCode() == 404) {
/* file offline */
dl.getConnection().disconnect();
tempUnavailableHoster(account, link, 20 * 60 * 1000l);
}
showMessage(link, "Phase 3/3: Begin download");
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
URLConnectionAdapter con = null;
try {
final Browser br2 = br.cloneBrowser();
con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
// try redirected link
boolean resetGeneratedLink = true;
String redirectConnection = br2.getRedirectLocation();
if (redirectConnection != null) {
if (redirectConnection.contains("xt7.pl")) {
con = br2.openGetConnection(redirectConnection);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
resetGeneratedLink = true;
} else {
resetGeneratedLink = false;
}
} else { // turbobit link is already redirected link
resetGeneratedLink = false;
}
}
if (resetGeneratedLink) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
} finally {
try {
con.disconnect();
} catch (final Throwable e) {
}
}
}
return dllink;
}
@Override
public AvailableStatus requestFileInformation(DownloadLink link) throws Exception {
return AvailableStatus.UNCHECKABLE;
}
private void tempUnavailableHoster(Account account, DownloadLink downloadLink, long timeout) throws PluginException {
if (downloadLink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, getPhrase("UNKNOWN_ERROR"));
}
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
if (unavailableMap == null) {
unavailableMap = new HashMap<String, Long>();
hostUnavailableMap.put(account, unavailableMap);
}
/* wait to retry this host */
unavailableMap.put(downloadLink.getHost(), (System.currentTimeMillis() + timeout));
}
throw new PluginException(LinkStatus.ERROR_RETRY);
}
@Override
public boolean canHandle(DownloadLink downloadLink, Account account) throws Exception {
return true;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
link.setProperty("generatedLinkXt7", null);
}
@Override
public void extendAccountSettingsPanel(Account acc, PluginConfigPanelNG panel) {
AccountInfo ai = acc.getAccountInfo();
if (ai == null) {
return;
}
if (!"FALSE".equals(ai.getProperty("premium"))) {
long otherHostersLimit = Long.parseLong(ai.getProperty("TRAFFIC_LEFT").toString(), 10);
String unlimited = (String) (ai.getProperty("UNLIMITED"));
panel.addStringPair(_GUI.T.lit_traffic_left(), SIZEUNIT.formatValue((SIZEUNIT) CFG_GUI.MAX_SIZE_UNIT.getValue(), otherHostersLimit) + (unlimited == null ? "" : "\n" + unlimited + ": " + getPhrase("UNLIMITED")));
}
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("PREMIUM_ERROR", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("UNSUPPORTED_PREMIUM", "\r\nUnsupported account type!\r\nIf you think this message is incorrect or it makes sense to add support for this account type\r\ncontact us via our support forum.");
put("PLUGIN_BROKEN", "\r\nPlugin broken, please contact the JDownloader Support!");
put("TRAFFIC_LEFT", "Traffic left");
put("HOSTER_UNAVAILABLE", "Host is temporarily unavailable via");
put("DOWNLOAD_LIMIT", "Download limit exceeded!");
put("RETRY", "Retry in few secs");
put("LINK_INACTIVE", "Xt7 reports the link is as inactive!");
put("LINK_EXPIRED", "Previously generated Link expired!");
put("NO_TRAFFIC", "No traffic left");
put("UNKNOWN_ERROR", "Unable to handle this errorcode!");
put("ACCOUNT_TYPE", "Account type");
put("UNKNOWN", "Unknown");
put("UNLIMITED", "Unlimited");
put("FREE", "free");
put("EXPIRED", "Account expired/free");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("PREMIUM_ERROR", "\r\nNieprawidłowy użytkownik/hasło!\r\nUpewnij się, że wprowadziłeś poprawnie użytkownika i hasło. Podpowiedzi:\r\n1. Jeśli w twoim haśle znajdują się znaki specjalne - usuń je/popraw i wprowadź ponownie hasło!\r\n2. Wprowadzając nazwę użytkownika i hasło - nie używaj operacji Kopiuj i Wklej.");
put("UNSUPPORTED_PREMIUM", "\r\nNieobsługiwany typ konta!\r\nJesli uważasz, że informacja ta jest niepoprawna i chcesz aby dodac obsługę tego typu konta\r\nskontaktuj się z nami poprzez forum wsparcia.");
put("PLUGIN_BROKEN", "\r\nProblem z wtyczką, skontaktuj się z zespołem wsparcia JDownloader!");
put("TRAFFIC_LEFT", "Pozostały transfer");
put("HOSTER_UNAVAILABLE", "Serwis jest niedostępny przez");
put("DOWNLOAD_LIMIT", "Przekroczono dostępny limit transferu!");
put("RETRY", "Ponawianie za kilka sekund");
put("LINK_INACTIVE", "Xt7 raportuje link jako nieaktywny!");
put("LINK_EXPIRED", "Poprzednio wygenerowany link wygasł!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("UNKNOWN_ERROR", "Nieobsługiwany kod błędu!");
put("ACCOUNT_TYPE", "Typ konta");
put("UNKNOWN", "Nieznany");
put("UNLIMITED", "Bez limitu");
put("FREE", "darmowe");
put("EXPIRED", "Konto wygasło/darmowe");
}
};
/**
* Returns a Polish/English translation of a phrase. We don't use the JDownloader translation framework since we need only Polish and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
String language = System.getProperty("user.language");
if ("pl".equals(language) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | // br.getRegex(" Pozostały limit na serwisy dodatkowe: <b>([^<>\"\\']+)</b></div>").getMatch(0);
| // jDownloader - Downloadmanager
// Copyright (C) 2014 JD-Team support@jdownloader.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.appwork.utils.formatter.SizeFormatter;
import org.appwork.utils.formatter.TimeFormatter;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.plugins.controller.LazyPlugin;
import org.jdownloader.plugins.controller.LazyPlugin.FEATURE;
import org.jdownloader.settings.GraphicalUserInterfaceSettings.SIZEUNIT;
import org.jdownloader.settings.staticreferences.CFG_GUI;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.Cookie;
import jd.http.Cookies;
import jd.http.URLConnectionAdapter;
import jd.nutils.encoding.Encoding;
import jd.parser.Regex;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginConfigPanelNG;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "xt7.pl" }, urls = { "" })
public class Xt7Pl extends PluginForHost {
private String MAINPAGE = "https://xt7.pl/";
private static HashMap<Account, HashMap<String, Long>> hostUnavailableMap = new HashMap<Account, HashMap<String, Long>>();
private static Object LOCK = new Object();
public Xt7Pl(PluginWrapper wrapper) {
super(wrapper);
this.enablePremium(MAINPAGE + "login");
}
@Override
public LazyPlugin.FEATURE[] getFeatures() {
return new LazyPlugin.FEATURE[] { LazyPlugin.FEATURE.MULTIHOST };
}
private void login(Account account, boolean force) throws PluginException, IOException {
synchronized (LOCK) {
try {
br.postPage(MAINPAGE + "login", "login=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass()));
if (br.getCookie(MAINPAGE, "autologin") == null) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PREMIUM_ERROR"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
// Save cookies
final HashMap<String, String> cookies = new HashMap<String, String>();
final Cookies add = this.br.getCookies(MAINPAGE);
for (final Cookie c : add.getCookies()) {
cookies.put(c.getKey(), c.getValue());
}
account.setProperty("name", Encoding.urlEncode(account.getUser()));
account.setProperty("pass", Encoding.urlEncode(account.getPass()));
account.setProperty("cookies", cookies);
} catch (final PluginException e) {
account.setProperty("cookies", Property.NULL);
throw e;
}
}
}
List<String> getSupportedHosts() {
List<String> supportedHosts = new ArrayList<String>();
String hosts;
try {
hosts = br.getPage(MAINPAGE + "jdhostingi.txt");
} catch (IOException e) {
return null;
}
if (hosts != null) {
String hoster[] = new Regex(hosts, "([A-Zaa-z0-9]+\\.[A-Zaa-z0-9]+)").getColumn(0);
for (String host : hoster) {
if (hosts == null || host.length() == 0) {
continue;
}
supportedHosts.add(host.trim());
}
return supportedHosts;
} else {
return null;
}
}
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
String validUntil = null;
final AccountInfo ai = new AccountInfo();
br.setConnectTimeout(60 * 1000);
br.setReadTimeout(60 * 1000);
login(account, true);
if (!br.getURL().contains("mojekonto")) {
br.getPage("/mojekonto");
}
if (br.containsHTML("Brak ważnego dostępu Premium")) {
ai.setExpired(true);
// ai.setStatus("Account expired");
ai.setStatus(getPhrase("EXPIRED"));
ai.setProperty("premium", "FALSE");
return ai;
} else if (br.containsHTML(">Brak ważnego dostępu Premium<")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("UNSUPPORTED_PREMIUM"), PluginException.VALUE_ID_PREMIUM_DISABLE);
} else {
validUntil = br.getRegex("<div class=\"textPremium\">Dostęp Premium ważny do <b>(.*?)</b><br />").getMatch(0);
if (validUntil == null) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PLUGIN_BROKEN"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
validUntil = validUntil.replace(" / ", " ");
ai.setProperty("premium", "TRUE");
}
long expireTime = TimeFormatter.getMilliSeconds(validUntil, "dd.MM.yyyy HH:mm", Locale.ENGLISH);
ai.setValidUntil(expireTime);
account.setValid(true);
String otherHostersLimitLeft = // br.getRegex(" Pozostały <SUF>
br.getRegex("Pozostały Limit Premium do wykorzystania: <b>([^<>\"\\']+)</b></div>").getMatch(0);
if (otherHostersLimitLeft == null) {
otherHostersLimitLeft = br.getRegex("Pozostały limit na serwisy dodatkowe: <b>([^<>\"\\']+)</b></div>").getMatch(0);
}
ai.setProperty("TRAFFIC_LEFT", otherHostersLimitLeft == null ? getPhrase("UNKNOWN") : SizeFormatter.getSize(otherHostersLimitLeft));
String unlimited = br.getRegex("<br />(.*): <b>Bez limitu</b> \\|").getMatch(0);
if (unlimited != null) {
ai.setProperty("UNLIMITED", unlimited);
}
ai.setStatus("Premium" + " (" + getPhrase("TRAFFIC_LEFT") + ": " + (otherHostersLimitLeft == null ? getPhrase("UNKNOWN") : otherHostersLimitLeft) + (unlimited == null ? "" : ", " + unlimited + ": " + getPhrase("UNLIMITED")) + ")");
if (otherHostersLimitLeft != null) {
ai.setTrafficLeft(SizeFormatter.getSize(otherHostersLimitLeft));
}
List<String> supportedHostsList = getSupportedHosts();
ai.setMultiHostSupport(this, supportedHostsList);
return ai;
}
@Override
public String getAGBLink() {
return MAINPAGE + "regulamin";
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return 0;
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception, PluginException {
throw new PluginException(LinkStatus.ERROR_PREMIUM, PluginException.VALUE_ID_PREMIUM_ONLY);
}
private void showMessage(DownloadLink link, String message) {
link.getLinkStatus().setStatusText(message);
}
/** no override to keep plugin compatible to old stable */
public void handleMultiHost(final DownloadLink link, final Account account) throws Exception {
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
if (unavailableMap != null) {
Long lastUnavailable = unavailableMap.get(link.getHost());
if (lastUnavailable != null && System.currentTimeMillis() < lastUnavailable) {
final long wait = lastUnavailable - System.currentTimeMillis();
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("HOSTER_UNAVAILABLE") + " " + this.getHost(), wait);
} else if (lastUnavailable != null) {
unavailableMap.remove(link.getHost());
if (unavailableMap.size() == 0) {
hostUnavailableMap.remove(account);
}
}
}
}
final String downloadUrl = link.getPluginPatternMatcher();
boolean resume = true;
showMessage(link, "Phase 1/3: Login");
login(account, false);
br.setConnectTimeout(90 * 1000);
br.setReadTimeout(90 * 1000);
dl = null;
// each time new download link is generated
// (so even after user interrupted download) - transfer
// is reduced, so:
// first check if the property generatedLink was previously generated
// if so, then try to use it, generated link store in link properties
// for future usage (broken download etc)
String generatedLink = checkDirectLink(link, "generatedLinkXt7");
if (generatedLink == null) {
/* generate new downloadlink */
String url = Encoding.urlEncode(downloadUrl);
String postData = "step=1" + "&content=" + url;
showMessage(link, "Phase 2/3: Generating Link");
br.postPage(MAINPAGE + "mojekonto/sciagaj", postData);
if (br.containsHTML("Wymagane dodatkowe [0-9.]+ MB limitu")) {
logger.severe("Xt7.pl(Error): " + br.getRegex("(Wymagane dodatkowe [0-9.]+ MB limitu)"));
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("DOWNLOAD_LIMIT"), 1 * 60 * 1000l);
}
postData = "step=2" + "&0=on";
br.postPage(MAINPAGE + "mojekonto/sciagaj", postData);
// New Regex, but not tested if it works for all files (not video)
// String generatedLink =
// br.getRegex("<div class=\"download\">(<a target=\"_blank\" href=\"mojekonto/ogladaj/[0-9A-Za-z]*?\">Oglądaj online</a> /
// )*?<a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(1);
// Old Regex
generatedLink = br.getRegex("<div class=\"download\"><a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(0);
if (generatedLink == null) {
// New Regex (works with video files)
generatedLink = br.getRegex("<div class=\"download\">(<a target=\"_blank\" href=\"mojekonto/ogladaj/[0-9A-Za-z]*?\">Oglądaj[ online]*?</a> / )<a href=\"([^\"<>]+)\" target=\"_blank\">Pobierz</a>").getMatch(1);
}
if (generatedLink == null) {
logger.severe("Xt7.pl(Error): " + generatedLink);
//
// after x retries we disable this host and retry with normal plugin
// but because traffic limit is decreased even if there's a problem
// with download (seems like bug) - we limit retries to 2
//
if (link.getLinkStatus().getRetryCount() >= 2) {
try {
// disable hoster for 30min
tempUnavailableHoster(account, link, 30 * 60 * 1000l);
} catch (Exception e) {
}
/* reset retrycounter */
link.getLinkStatus().setRetryCount(0);
final String inactiveLink = br.getRegex("textarea id=\"listInactive\" class=\"small\" readonly>(.*?)[ \t\n\r]+</textarea>").getMatch(0);
if (downloadUrl.compareTo(inactiveLink) != 0) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("LINK_INACTIVE"), 30 * 1000l);
}
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE);
}
String msg = "(" + link.getLinkStatus().getRetryCount() + 1 + "/" + 2 + ")";
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("RETRY") + msg, 20 * 1000l);
}
link.setProperty("generatedLinkXt7", generatedLink);
}
// wait, workaround
sleep(1 * 1000l, link);
int chunks = 0;
// generated fileshark.pl link allows only 1 chunk
// because download doesn't support more chunks and
// and resume (header response has no: "Content-Range" info)
final String url = link.getPluginPatternMatcher();
final String oneChunkHostersPattern = ".*fileshark\\.pl.*";
if (url.matches(oneChunkHostersPattern) || downloadUrl.matches(oneChunkHostersPattern)) {
chunks = 1;
resume = false;
}
dl = jd.plugins.BrowserAdapter.openDownload(br, link, generatedLink, resume, chunks);
if (dl.getConnection().getContentType().equalsIgnoreCase("text/html")) // unknown
// error
{
br.followConnection();
if (br.containsHTML("<div id=\"message\">Ważność linka wygasła.</div>")) {
// previously generated link expired,
// clear the property and restart the download
// and generate new link
sleep(10 * 1000l, link, getPhrase("LINK_EXPIRED"));
logger.info("Xt7.pl: previously generated link expired - removing it and restarting download process.");
link.setProperty("generatedLinkXt7", null);
throw new PluginException(LinkStatus.ERROR_RETRY);
}
if (br.getBaseURL().contains("notransfer")) {
/* No traffic left */
account.getAccountInfo().setTrafficLeft(0);
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("NO_TRAFFIC"), PluginException.VALUE_ID_PREMIUM_TEMP_DISABLE);
}
if (br.getBaseURL().contains("serviceunavailable")) {
tempUnavailableHoster(account, link, 60 * 60 * 1000l);
}
if (br.getBaseURL().contains("connecterror")) {
tempUnavailableHoster(account, link, 60 * 60 * 1000l);
}
if (br.getBaseURL().contains("invaliduserpass")) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, getPhrase("PREMIUM_ERROR"), PluginException.VALUE_ID_PREMIUM_DISABLE);
}
if ((br.getBaseURL().contains("notfound")) || (br.containsHTML("404 Not Found"))) {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
if (br.containsHTML("Wymagane dodatkowe [0-9.]+ MB limitu")) {
logger.severe("Xt7.pl(Error): " + br.getRegex("(Wymagane dodatkowe [0-9.]+ MB limitu)"));
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, getPhrase("DOWNLOAD_LIMIT"), 1 * 60 * 1000l);
}
}
if (dl.getConnection().getResponseCode() == 404) {
/* file offline */
dl.getConnection().disconnect();
tempUnavailableHoster(account, link, 20 * 60 * 1000l);
}
showMessage(link, "Phase 3/3: Begin download");
dl.startDownload();
}
private String checkDirectLink(final DownloadLink downloadLink, final String property) {
String dllink = downloadLink.getStringProperty(property);
if (dllink != null) {
URLConnectionAdapter con = null;
try {
final Browser br2 = br.cloneBrowser();
con = br2.openGetConnection(dllink);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
// try redirected link
boolean resetGeneratedLink = true;
String redirectConnection = br2.getRedirectLocation();
if (redirectConnection != null) {
if (redirectConnection.contains("xt7.pl")) {
con = br2.openGetConnection(redirectConnection);
if (con.getContentType().contains("html") || con.getLongContentLength() == -1) {
resetGeneratedLink = true;
} else {
resetGeneratedLink = false;
}
} else { // turbobit link is already redirected link
resetGeneratedLink = false;
}
}
if (resetGeneratedLink) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
}
}
} catch (final Exception e) {
downloadLink.setProperty(property, Property.NULL);
dllink = null;
} finally {
try {
con.disconnect();
} catch (final Throwable e) {
}
}
}
return dllink;
}
@Override
public AvailableStatus requestFileInformation(DownloadLink link) throws Exception {
return AvailableStatus.UNCHECKABLE;
}
private void tempUnavailableHoster(Account account, DownloadLink downloadLink, long timeout) throws PluginException {
if (downloadLink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, getPhrase("UNKNOWN_ERROR"));
}
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
if (unavailableMap == null) {
unavailableMap = new HashMap<String, Long>();
hostUnavailableMap.put(account, unavailableMap);
}
/* wait to retry this host */
unavailableMap.put(downloadLink.getHost(), (System.currentTimeMillis() + timeout));
}
throw new PluginException(LinkStatus.ERROR_RETRY);
}
@Override
public boolean canHandle(DownloadLink downloadLink, Account account) throws Exception {
return true;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
link.setProperty("generatedLinkXt7", null);
}
@Override
public void extendAccountSettingsPanel(Account acc, PluginConfigPanelNG panel) {
AccountInfo ai = acc.getAccountInfo();
if (ai == null) {
return;
}
if (!"FALSE".equals(ai.getProperty("premium"))) {
long otherHostersLimit = Long.parseLong(ai.getProperty("TRAFFIC_LEFT").toString(), 10);
String unlimited = (String) (ai.getProperty("UNLIMITED"));
panel.addStringPair(_GUI.T.lit_traffic_left(), SIZEUNIT.formatValue((SIZEUNIT) CFG_GUI.MAX_SIZE_UNIT.getValue(), otherHostersLimit) + (unlimited == null ? "" : "\n" + unlimited + ": " + getPhrase("UNLIMITED")));
}
}
private HashMap<String, String> phrasesEN = new HashMap<String, String>() {
{
put("PREMIUM_ERROR", "\r\nInvalid username/password!\r\nYou're sure that the username and password you entered are correct? Some hints:\r\n1. If your password contains special characters, change it (remove them) and try again!\r\n2. Type in your username/password by hand without copy & paste.");
put("UNSUPPORTED_PREMIUM", "\r\nUnsupported account type!\r\nIf you think this message is incorrect or it makes sense to add support for this account type\r\ncontact us via our support forum.");
put("PLUGIN_BROKEN", "\r\nPlugin broken, please contact the JDownloader Support!");
put("TRAFFIC_LEFT", "Traffic left");
put("HOSTER_UNAVAILABLE", "Host is temporarily unavailable via");
put("DOWNLOAD_LIMIT", "Download limit exceeded!");
put("RETRY", "Retry in few secs");
put("LINK_INACTIVE", "Xt7 reports the link is as inactive!");
put("LINK_EXPIRED", "Previously generated Link expired!");
put("NO_TRAFFIC", "No traffic left");
put("UNKNOWN_ERROR", "Unable to handle this errorcode!");
put("ACCOUNT_TYPE", "Account type");
put("UNKNOWN", "Unknown");
put("UNLIMITED", "Unlimited");
put("FREE", "free");
put("EXPIRED", "Account expired/free");
}
};
private HashMap<String, String> phrasesPL = new HashMap<String, String>() {
{
put("PREMIUM_ERROR", "\r\nNieprawidłowy użytkownik/hasło!\r\nUpewnij się, że wprowadziłeś poprawnie użytkownika i hasło. Podpowiedzi:\r\n1. Jeśli w twoim haśle znajdują się znaki specjalne - usuń je/popraw i wprowadź ponownie hasło!\r\n2. Wprowadzając nazwę użytkownika i hasło - nie używaj operacji Kopiuj i Wklej.");
put("UNSUPPORTED_PREMIUM", "\r\nNieobsługiwany typ konta!\r\nJesli uważasz, że informacja ta jest niepoprawna i chcesz aby dodac obsługę tego typu konta\r\nskontaktuj się z nami poprzez forum wsparcia.");
put("PLUGIN_BROKEN", "\r\nProblem z wtyczką, skontaktuj się z zespołem wsparcia JDownloader!");
put("TRAFFIC_LEFT", "Pozostały transfer");
put("HOSTER_UNAVAILABLE", "Serwis jest niedostępny przez");
put("DOWNLOAD_LIMIT", "Przekroczono dostępny limit transferu!");
put("RETRY", "Ponawianie za kilka sekund");
put("LINK_INACTIVE", "Xt7 raportuje link jako nieaktywny!");
put("LINK_EXPIRED", "Poprzednio wygenerowany link wygasł!");
put("NO_TRAFFIC", "Brak dostępnego transferu");
put("UNKNOWN_ERROR", "Nieobsługiwany kod błędu!");
put("ACCOUNT_TYPE", "Typ konta");
put("UNKNOWN", "Nieznany");
put("UNLIMITED", "Bez limitu");
put("FREE", "darmowe");
put("EXPIRED", "Konto wygasło/darmowe");
}
};
/**
* Returns a Polish/English translation of a phrase. We don't use the JDownloader translation framework since we need only Polish and
* English.
*
* @param key
* @return
*/
private String getPhrase(String key) {
String language = System.getProperty("user.language");
if ("pl".equals(language) && phrasesPL.containsKey(key)) {
return phrasesPL.get(key);
} else if (phrasesEN.containsKey(key)) {
return phrasesEN.get(key);
}
return "Translation not found!";
}
} | f |
616_0 | mloza/iop-project | 471 | src/gui/Testing.java | package gui;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber.Exception;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
class FrameCapturingTask implements Runnable {
Camera cam;
public FrameCapturingTask(Camera cam) {
this.cam = cam;
}
@Override
public void run() {
try {
cam.startCapturing();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Przyjmijmy na razie, że to jest klasa, z której odpalana jest aplikacja.
public class Testing implements FrameObserver{
Camera cam;
CanvasFrame canvasFrame = new CanvasFrame("Some Title");
long currentMilis = 0;
long oldMilis = 0;
public static void main(String args[]) throws Exception {
Testing main = new Testing(new Camera(0));
main.test();
}
public Testing(Camera cam) throws Exception {
this.cam = cam;
this.cam.addListener(this);
canvasFrame.setCanvasSize(400, 400);
}
void test() {
FrameCapturingTask fct = new FrameCapturingTask(cam);
new Thread(fct).start();
}
@Override
public void update(IplImage frame) {
oldMilis = currentMilis;
currentMilis = System.currentTimeMillis();
System.out.println("Got frame! (it takes " + (currentMilis - oldMilis) + ")");
canvasFrame.showImage(frame);
}
}
| // Przyjmijmy na razie, że to jest klasa, z której odpalana jest aplikacja. | package gui;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber.Exception;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
class FrameCapturingTask implements Runnable {
Camera cam;
public FrameCapturingTask(Camera cam) {
this.cam = cam;
}
@Override
public void run() {
try {
cam.startCapturing();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Przyjmijmy na <SUF>
public class Testing implements FrameObserver{
Camera cam;
CanvasFrame canvasFrame = new CanvasFrame("Some Title");
long currentMilis = 0;
long oldMilis = 0;
public static void main(String args[]) throws Exception {
Testing main = new Testing(new Camera(0));
main.test();
}
public Testing(Camera cam) throws Exception {
this.cam = cam;
this.cam.addListener(this);
canvasFrame.setCanvasSize(400, 400);
}
void test() {
FrameCapturingTask fct = new FrameCapturingTask(cam);
new Thread(fct).start();
}
@Override
public void update(IplImage frame) {
oldMilis = currentMilis;
currentMilis = System.currentTimeMillis();
System.out.println("Got frame! (it takes " + (currentMilis - oldMilis) + ")");
canvasFrame.showImage(frame);
}
}
| f |
8146_0 | mlukasik8/isaDemo | 260 | src/main/java/pages/Login.java | package pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Login {
private WebDriver driver;
//4. Nie brakuje tu czegoś?
@FindBy(id = "")
private WebElement loginInput;
//5. I tu też?
@FindBy(id = "")
private WebElement passwordInput;
@FindBy(id = "login-button")
private WebElement loginButton;
public Login(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(this.driver, this);
}
public void loginAs(String username, String password) {
//2. Jak wpisać do inputów wartości?
//loginInput
//passwordInput
//3. A jak zatwierdzic logowanie inaczej niż click()?
//loginButton
}
} | //4. Nie brakuje tu czegoś? | package pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Login {
private WebDriver driver;
//4. Nie <SUF>
@FindBy(id = "")
private WebElement loginInput;
//5. I tu też?
@FindBy(id = "")
private WebElement passwordInput;
@FindBy(id = "login-button")
private WebElement loginButton;
public Login(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(this.driver, this);
}
public void loginAs(String username, String password) {
//2. Jak wpisać do inputów wartości?
//loginInput
//passwordInput
//3. A jak zatwierdzic logowanie inaczej niż click()?
//loginButton
}
} | f |
3877_1 | mpietrewicz/KarolaWorkshop | 293 | src/zad1/BankCustomer.java | package zad1;
/**
* Created by Marek on 2017-03-18.
*/
public class BankCustomer {
// private String name; // do usunięcie - nie wykorzystujesz
public Account konto;
public Person klient;
BankCustomer (Person klient) {
// this.name = klient.name; // trochę to bez sensu po co powielać imie klienta?
this.klient = klient; // lepiej zapisać obiekt klient ;)
this.konto = new Account(); // tworząc klienta zakladamy od razu jemu konto
}
public Account getAccount() {
return konto; // zwracasz coś pustego - coś co zadeklarowałaś ale go nie wypełniłaś
}
@Override
public String toString() {
return "Klient: " + klient.name + " stan konta " + " " + konto.stan() + ".";
} // musisz nadpisać metodę toString żeby wypisywać to co chcesz
}
| // private String name; // do usunięcie - nie wykorzystujesz | package zad1;
/**
* Created by Marek on 2017-03-18.
*/
public class BankCustomer {
// private String <SUF>
public Account konto;
public Person klient;
BankCustomer (Person klient) {
// this.name = klient.name; // trochę to bez sensu po co powielać imie klienta?
this.klient = klient; // lepiej zapisać obiekt klient ;)
this.konto = new Account(); // tworząc klienta zakladamy od razu jemu konto
}
public Account getAccount() {
return konto; // zwracasz coś pustego - coś co zadeklarowałaś ale go nie wypełniłaś
}
@Override
public String toString() {
return "Klient: " + klient.name + " stan konta " + " " + konto.stan() + ".";
} // musisz nadpisać metodę toString żeby wypisywać to co chcesz
}
| f |