file_id
stringlengths 4
9
| content
stringlengths 41
35k
| repo
stringlengths 7
113
| path
stringlengths 5
90
| token_length
int64 15
4.07k
| original_comment
stringlengths 3
9.88k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | excluded
bool 2
classes |
---|---|---|---|---|---|---|---|---|
60_1 | /*Write a program to find the shortest path between vertices using
bellman-ford algorithm.*/
//bellman ford algorithm for shortest distance from a source node to all the remaining nodes
import java.util.*;
public class BellmanFord {
private static int N;
private static int[][] graph;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of Vertices : ");
N = sc.nextInt();
System.out.println("Enter the Weight Matrix of Graph");
graph = new int[N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
graph[i][j] = sc.nextInt();
System.out.print("Enter the Source Vertex : ");
int source = sc.nextInt();
bellmanFord(source - 1);
}
public static void bellmanFord(int src) {
int[] dist = new int[N];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
for (int i = 0; i < N; i++) {
for (int u = 0; u < N; u++) {
for (int v = 0; v < N; v++) {
if (graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
}
for (int u = 0; u < N; u++) {
for (int v = 0; v < N; v++) {
if (graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
System.out.println("Negative weight cycle detected.");
return;
}
}
}
printSolution(dist);
}
public static void printSolution(int[] dist) {
System.out.println("Vertex \t Distance from Source");
for (int i = 0; i < N; i++) {
System.out.println((i + 1) + "\t\t" + dist[i]);
}
}
}
/*output:-
Enter the number of Vertices : 5
Enter the Weight Matrix of Graph
0 6 0 7 0
0 0 5 8 -4
0 0 0 0 0
0 0 -3 0 9
2 0 0 0 0
Enter the Source Vertex : 1
Vertex Distance from Source
1 0
2 6
3 4
4 7
5 2
*/
/*Enter the number of Vertices : 3
Enter the Weight Matrix of Graph
0 10 5
0 0 -8
0 0 0
Enter the Source Vertex : 1
Vertex Distance from Source
1 0
2 10
3 2
*/
/*
Enter the number of Vertices : 3
Enter the Weight Matrix of Graph
0 10 0
0 0 20
0 -30 0
Enter the Source Vertex : 1
Negative weight cycle detected.
*/
| saadhussain01306/computer_net_lab | 3.bellman_ford.java | 777 | //bellman ford algorithm for shortest distance from a source node to all the remaining nodes | line_comment | en | false |
294_12 | package _2017._09._assignments.projectgo.template.v2;
//imports
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
//class defnition f
public class Go extends Application {
// private fields
private BorderPane bp_layout;
private GoCustomControl customControl;
private GoControlPanel controlPanel;
private GoGameLogic gameLogic;
private GoBoard board;
// overridden init method
public void init() {
bp_layout = new BorderPane(); // create layout
board = new GoBoard(); // creates a board
gameLogic = new GoGameLogic(board); // create gameLogic and pass board to gameLogic so gameLogic can call methods from board
customControl = new GoCustomControl(gameLogic); // create customControl and pass gameLogic to customControl so customControl can call methods from gameLogic
controlPanel = new GoControlPanel(gameLogic); // create controlPanel and pass gameLogic to controlPanel so customControl can call methods from gameLogic
bp_layout.setCenter(customControl); // put the customControl in the center of the layout
bp_layout.setLeft(controlPanel); // put the controlPanel in the right of the layout
}
// overridden start method
public void start(Stage primaryStage) {
// set a title, size and the stack pane as the root of the scene graph
primaryStage.setTitle("Go");
primaryStage.setScene(new Scene(bp_layout, 1000, 800));
primaryStage.show();
}
// overridden stop method
public void stop() {
System.out.println("Application closed");
}
// entry point into our program for launching our javafx applicaton
public static void main(String[] args) {
//T1
launch(args);
}
}
| JosephCheevers/GO | Go.java | 469 | // set a title, size and the stack pane as the root of the scene graph | line_comment | en | false |
625_0 | public final class i {
public static boolean a;
public static final int[] b = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, -10, -11, -13, -12, -20, -21, -1, -2, -3, -4, -6, -7, -5, 42, 35 };
private static final int[][] c = { { 0 }, { 1 }, { 2, 10 }, { 3 }, { 4, 12 }, { 5, 14 }, { 6, 13 }, { 7 }, { 8, 11 }, { 9 }, { 10, 20 }, { 11, 21 }, { 12, 19 }, { 13 }, { 15 }, { 16 }, { 10, 20 }, { 11, 21 }, { 12, 19 }, { 13 }, { 15 }, { 16 }, { 14 }, { 17 }, { 18, 14 } };
public static boolean[] d = new boolean[22];
private static int e = 0;
private static int f = 0;
private static int[] g = new int[20];
private static int[] d(int paramInt) {
for (int i = 0; i < b.length; i++)
if (paramInt == b[i])
return c[i];
return null;
}
public static void a(int paramInt) {
int[] arrayOfInt = d(paramInt);
if (arrayOfInt != null)
for (int i = 0; i < arrayOfInt.length; i++) {
int j = arrayOfInt[i];
e(j);
d[j] = true;
}
a = true;
}
private static void e(int paramInt) {
g[(f++)] = paramInt;
if (f >= 20)
f = 0;
if (f == e) {
e += 1;
if (e >= 20)
e = 0;
}
}
public static void b(int paramInt) {
a = false;
int[] arrayOfInt = d(paramInt);
if (arrayOfInt == null)
return;
for (int i = 0; i < arrayOfInt.length; i++) {
int j = arrayOfInt[i];
if (d[j] != false)
d[j] = false;
}
}
public static boolean c(int paramInt) {
return d[paramInt];
}
public static int a() {
if (e == f)
return -66;
int i = g[(e++)];
if (e >= 20)
e = 0;
return i;
}
public static void b() {
int i = 22;
do {
i--;
d[i] = false;
}
while (i > 0);
a = false;
}
}
/* Location: /Users/ilya/4fun/Biplanes/Bluetooth_Biplanes.jar
* Qualified Name: i
* JD-Core Version: 0.6.2
*/ | TheRealPinkie/BT_Biplanes_src | i.java | 786 | /* Location: /Users/ilya/4fun/Biplanes/Bluetooth_Biplanes.jar
* Qualified Name: i
* JD-Core Version: 0.6.2
*/ | block_comment | en | true |
909_0 | import java.util.Scanner;
import java.text.DecimalFormat;
/**
* Calculate Pi
* @date 19 August 2014
* @author Nefari0uss
*
* This program will request the approximate number of calculations to run in calculating π.
* The final result will be displayed on the console. Assumption is that the user inputs an int.
*
*
* Uses the Gottfried Leibniz formula for calculation of π:
*
* 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = π/4
*
* Source: Wikipedia - Leibniz formula for π
**/
public class Pi {
public static void main(String[] args) {
int n = getInput();
double piValue = calculatePi(n);
printResult(piValue);
}
private static double calculatePi(double n) {
double pi = 0;
for (int i = 1; i < n; i++) {
pi += Math.pow(-1,i+1) / (2*i - 1);
}
return 4 * pi;
}
private static int getInput() {
int n = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many calculations should be run for the approximation?");
try {
n = Integer.parseInt(input.nextLine());
} /** Handle input greater than Java's MAX_INT. **/
catch (NumberFormatException e) {
System.out.println("n is too large. Setting n to be the largest possible int value.");
n = Integer.MAX_VALUE;
}
input.close();
return n;
}
private static double calculateError(double piValue) {
return Math.abs(1 - piValue / Math.PI) * 100;
}
private static void printResult(double piValue) {
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("The value of pi is approximately " + piValue + ".");
System.out.println("The calculated value is off by approximately " + df.format(calculateError(piValue)) + "%.");
}
}
| Nefari0uss/calculate-pi | Pi.java | 542 | /**
* Calculate Pi
* @date 19 August 2014
* @author Nefari0uss
*
* This program will request the approximate number of calculations to run in calculating π.
* The final result will be displayed on the console. Assumption is that the user inputs an int.
*
*
* Uses the Gottfried Leibniz formula for calculation of π:
*
* 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = π/4
*
* Source: Wikipedia - Leibniz formula for π
**/ | block_comment | en | false |
953_1 | import java.io.*;
import java_cup.runtime.*;
/**
* Main program to test the parser.
*
* There should be 2 command-line arguments:
* 1. the file to be parsed
* 2. the output file into which the AST built by the parser should be
* unparsed
* The program opens the two files, creates a scanner and a parser, and
* calls the parser. If the parse is successful, the AST is unparsed.
*/
public class P5 {
FileReader inFile;
private PrintWriter outFile;
private static PrintStream outStream = System.err;
public static final int RESULT_CORRECT = 0;
public static final int RESULT_SYNTAX_ERROR = 1;
public static final int RESULT_TYPE_ERROR = 2;
public static final int RESULT_OTHER_ERROR = -1;
/**
* P5 constructor for client programs and testers. Note that
* users MUST invoke {@link setInfile} and {@link setOutfile}
*/
public P5(){
}
/**
* If we are directly invoking P5 from the command line, this
* is the command line to use. It shouldn't be invoked from
* outside the class (hence the private constructor) because
* it
* @param args command line args array for [<infile> <outfile>]
*/
private P5(String[] args){
//Parse arguments
if (args.length < 2) {
String msg = "please supply name of file to be parsed"
+ "and name of file for unparsed version.";
pukeAndDie(msg);
}
try{
setInfile(args[0]);
setOutfile(args[1]);
} catch(BadInfileException e){
pukeAndDie(e.getMessage());
} catch(BadOutfileException e){
pukeAndDie(e.getMessage());
}
}
/**
* Source code file path
* @param filename path to source file
*/
public void setInfile(String filename) throws BadInfileException{
try {
inFile = new FileReader(filename);
} catch (FileNotFoundException ex) {
throw new BadInfileException(ex, filename);
}
}
/**
* Text file output
* @param filename path to destination file
*/
public void setOutfile(String filename) throws BadOutfileException{
try {
outFile = new PrintWriter(filename);
} catch (FileNotFoundException ex) {
throw new BadOutfileException(ex, filename);
}
}
/**
* Perform cleanup at the end of parsing. This should be called
* after both good and bad input so that the files are all in a
* consistent state
*/
public void cleanup(){
if (inFile != null){
try {
inFile.close();
} catch (IOException e) {
//At this point, users already know they screwed
// up. No need to rub it in.
}
}
if (outFile != null){
//If there is any output that needs to be
// written to the stream, force it out.
outFile.flush();
outFile.close();
}
}
/**
* Private error handling method. Convenience method for
* @link pukeAndDie(String, int) with a default error code
* @param error message to print on exit
*/
private void pukeAndDie(String error){
pukeAndDie(error, -1);
}
/**
* Private error handling method. Prints an error message
* @link pukeAndDie(String, int) with a default error code
* @param error message to print on exit
*/
private void pukeAndDie(String error, int retCode){
outStream.println(error);
cleanup();
System.exit(-1);
}
/** the parser will return a Symbol whose value
* field is the translation of the root nonterminal
* (i.e., of the nonterminal "program")
* @return root of the CFG
*/
private Symbol parseCFG(){
try {
parser P = new parser(new Yylex(inFile));
return P.parse();
} catch (Exception e){
return null;
}
}
public int process(){
Symbol cfgRoot = parseCFG();
ProgramNode astRoot = (ProgramNode)cfgRoot.value;
if (ErrMsg.getErr()) {
return P5.RESULT_SYNTAX_ERROR;
}
astRoot.nameAnalysis(); // perform name analysis
if(ErrMsg.getErr()) {
return P5.RESULT_SYNTAX_ERROR;
}
astRoot.typeCheck();
if(ErrMsg.getErr()) {
return P5.RESULT_TYPE_ERROR;
}
astRoot.unparse(outFile, 0);
return P5.RESULT_CORRECT;
}
public void run(){
int resultCode = process();
if (resultCode == RESULT_CORRECT){
cleanup();
return;
}
switch(resultCode){
case RESULT_SYNTAX_ERROR:
pukeAndDie("Syntax error", resultCode);
case RESULT_TYPE_ERROR:
pukeAndDie("Type checking error", resultCode);
default:
pukeAndDie("Type checking error", RESULT_OTHER_ERROR);
}
}
private class BadInfileException extends Exception{
private static final long serialVersionUID = 1L;
private String message;
public BadInfileException(Exception cause, String filename) {
super(cause);
this.message = "Could not open " + filename + " for reading";
}
@Override
public String getMessage(){
return message;
}
}
private class BadOutfileException extends Exception{
private static final long serialVersionUID = 1L;
private String message;
public BadOutfileException(Exception cause, String filename) {
super(cause);
this.message = "Could not open " + filename + " for reading";
}
@Override
public String getMessage(){
return message;
}
}
public static void main(String[] args){
P5 instance = new P5(args);
instance.run();
}
}
| jkoritzinsky/Moo-Type-Analysis | P5.java | 1,503 | /**
* P5 constructor for client programs and testers. Note that
* users MUST invoke {@link setInfile} and {@link setOutfile}
*/ | block_comment | en | true |
1566_0 | //2-Given sides of a triangle, check whether the triangle is equilateral, isosceles or scalene. Find it's area
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
int a, b, c;
double p, area;
Scanner sc = new Scanner(System.in);
System.out.println("Enter sides of triangle : ");
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
if((a < b + c) && (b < a + c) && (c < a + b)){
if((a == b) && (b == c))
System.out.println("Given Trangle is Equilateral");
else if ((a == b) || (b == c) || (c == a))
System.out.println("Given Triangle is Isoscleles");
else
System.out.println("Given Triangle is Scalane");
p=(a+b+c)/2;
area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
System.out.println("Area of triangle is = " + area);
}else{
System.out.println("Cannot form a triangle");
}
}
}
| KadeejaSahlaPV/java | 2.java | 293 | //2-Given sides of a triangle, check whether the triangle is equilateral, isosceles or scalene. Find it's area | line_comment | en | false |
1570_1 | package Myinterface;
//@FunctionalInterface
public class B implements A { // when we are only one method pass inside class then
// interface show. otherwise more than one method it show error
@Override
public void test1() {
System.out.println(50000);
}
@Override
public void test() {
System.out.println(900);
}
public static void main(String[] args) {
B b1 = new B();
b1.test();
b1.test1();
}
}
| Ashutosh-62044/Interface-in-java | B.java | 141 | // when we are only one method pass inside class then
| line_comment | en | true |
1614_4 | package advanced.gestureSound;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import de.sciss.jcollider.Group;
import de.sciss.jcollider.JCollider;
import de.sciss.jcollider.NodeWatcher;
import de.sciss.jcollider.Server;
import de.sciss.jcollider.ServerOptions;
import de.sciss.jcollider.Synth;
import de.sciss.jcollider.SynthDef;
import de.sciss.jcollider.UGenInfo;
public class SC {
public final String fs = File.separator;
public java.util.List defTables;
public Server server = null;
public ServerOptions serveropts = null;
public NodeWatcher nw = null;
public Group grpAll;
public void setupSupercollider() {
try {
System.out.println("Testing server....");
//server = new Server("localhost");
serveropts= new ServerOptions();
setServerOptions(serveropts);
server = new Server("localhost",new InetSocketAddress("127.0.0.1",57110),serveropts);
File f = findFile(JCollider.isWindows ? "scsynth.exe" : "scsynth",
new String[] {
fs + "Applications" + fs + "SuperCollider_f",
fs + "Applications" + fs + "SC3",
fs + "usr" + fs + "local" + fs + "bin",
fs + "usr" + fs + "bin", "C:\\Program Files\\SC3",
"C:\\Program Files (x86)\\SuperCollider" });
if (f != null) {
System.out.println("Trying to start program at: " + f);
Server.setProgram(f.getAbsolutePath());
} else {
System.out.println("CANNOT FIND PROGRAM");
}
try {
server.start();
server.startAliveThread();
initServer();
//while(!server.isRunning()) {}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e1) {
System.out.println("Ughhh server won't start");
}
// if( server.isRunning() ) initServer();
} catch (IOException e1) {
System.out.println("OOPS SOMETHIGN went wrong, server wont start!");
}
sendDefs();
}
public static File findFile(String fileName, String[] folders) {
File f;
for (int i = 0; i < folders.length; i++) {
f = new File(folders[i], fileName);
if (f.exists())
return f;
}
return null;
}
/**
* this is a useful function if you're using jcollider's synthdefs.
* however I have not.
*/
public void sendDefs() {
File dir = new File(System.getProperty("user.dir")+"/data/synthdefs/");
for (File syn : dir.listFiles()) {
try {
//System.out.println("trying to load "+syn+"...");
if (syn.getName().startsWith("."))
{
System.out.println("Ignoring this file ("+syn.getName()+")");
}
else
{
SynthDef.readDefFile(syn)[0].send(server);
}
} catch (IOException e) {
System.out.println(syn+" is an invalid synthdef! trying to continue without it! if you notice funny behavior, chances are its because of this.");
e.printStackTrace();
}
}
}
/**
* passes a whole bunch of options found in the config file to supercollider
* @param s
*/
public void setServerOptions(ServerOptions s)
{
}
/**
* this is a useful function if you're using jcollider's synthdefs.
* however I have not.
*/
public void createDefs() {
try {
// UGenInfo.readDefinitions();
UGenInfo.readBinaryDefinitions();
// defTables = DemoDefs.create();
// defTables[ 1 ].addDefs( collDefs );
// defTables[ 0 ].addDefs( collDefs );
} catch (IOException e1) {
e1.printStackTrace();
// reportError( e1 );
}
}
public void initServer() throws IOException {
// sendDefs();
if (!server.didWeBootTheServer()) {
server.initTree();
server.notify(true);
}
// if( nw != null ) nw.dispose();
nw = NodeWatcher.newFrom(server);
grpAll = Group.basicNew(server);
nw.register(server.getDefaultGroup());
nw.register(grpAll);
server.sendMsg(grpAll.newMsg());
}
public void testSupercollider() {
try {
Synth s = new Synth("stereosine", new String[] {"out", "freq"}, new float[] { 0, 1213f }, grpAll);
Synth a = new Synth("stereosine", new String[] {"out", "freq"}, new float[] { 1, 1213f }, grpAll);
System.out.println("Made synth!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| acm-uiuc/Tacchi | SC.java | 1,358 | /**
* this is a useful function if you're using jcollider's synthdefs.
* however I have not.
*/ | block_comment | en | true |
1946_5 | /******************************************************************************
* Compilation: javac UF.java
* Execution: java UF < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/15uf/tinyUF.txt
* http://algs4.cs.princeton.edu/15uf/mediumUF.txt
* http://algs4.cs.princeton.edu/15uf/largeUF.txt
*
* Weighted quick-union by rank with path compression by halving.
*
* % java UF < tinyUF.txt
* 4 3
* 3 8
* 6 5
* 9 4
* 2 1
* 5 0
* 7 2
* 6 1
* 2 components
*
******************************************************************************/
import edu.princeton.cs.algs4.MinPQ;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class UF {
private int[] parent; // parent[i] = parent of i
private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31)
private int count; // number of components
/**
* Initializes an empty union–find data structure with {@code n} sites
* {@code 0} through {@code n-1}. Each site is initially in its own
* component.
*
* @param n the number of sites
* @throws IllegalArgumentException if {@code n < 0}
*/
public UF(int n) {
if (n < 0) throw new IllegalArgumentException();
count = n;
parent = new int[n];
rank = new byte[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
/**
* Returns the component identifier for the component containing site {@code p}.
*
* @param p the integer representing one site
* @return the component identifier for the component containing site {@code p}
* @throws IndexOutOfBoundsException unless {@code 0 <= p < n}
*/
public int find(int p) {
validate(p);
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
/**
* Returns the number of components.
*
* @return the number of components (between {@code 1} and {@code n})
*/
public int count() {
return count;
}
/**
* Returns true if the the two sites are in the same component.
*
* @param p the integer representing one site
* @param q the integer representing the other site
* @return {@code true} if the two sites {@code p} and {@code q} are in the same component;
* {@code false} otherwise
* @throws IndexOutOfBoundsException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
public boolean connected(int p, int q) {
return find(p) == find(q);
}
/**
* Merges the component containing site {@code p} with the
* the component containing site {@code q}.
*
* @param p the integer representing one site
* @param q the integer representing the other site
* @throws IndexOutOfBoundsException unless
* both {@code 0 <= p < n} and {@code 0 <= q < n}
*/
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make root of smaller rank point to root of larger rank
if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
else {
parent[rootQ] = rootP;
rank[rootP]++;
}
count--;
}
// validate that p is a valid index
private void validate(int p) {
int n = parent.length;
if (p < 0 || p >= n) {
throw new IndexOutOfBoundsException("index " + p + " is not between 0 and " + (n-1));
}
}
/**
* Reads in a an integer {@code n} and a sequence of pairs of integers
* (between {@code 0} and {@code n-1}) from standard input, where each integer
* in the pair represents some site;
* if the sites are in different components, merge the two components
* and print the pair to standard output.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int n = StdIn.readInt();
UF uf = new UF(n);
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (uf.connected(p, q)) continue;
uf.union(p, q);
StdOut.println(p + " " + q);
}
StdOut.println(uf.count() + " components");
}
}
| dud3/princeton-algs4 | UF.java | 1,263 | /**
* Returns the component identifier for the component containing site {@code p}.
*
* @param p the integer representing one site
* @return the component identifier for the component containing site {@code p}
* @throws IndexOutOfBoundsException unless {@code 0 <= p < n}
*/ | block_comment | en | false |
3634_3 | class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBSTWithRange(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
boolean isValidBSTWithRange(TreeNode root, int min, int max){
// 判断root是否为二叉搜索树,并且所有节点需要在min -> max 闭范围
if (root == null) {
return true;
}
if (root.val < min || root.val > max) {
return false;
}
// 如果root恰好为Integer.MIN_VALUE或Integer.MAX_VALUE,那么就需要特殊处理
if (root.val == Integer.MIN_VALUE && root.left != null) {
// 如果root已经为最小值,且还有左树,那一定不满足条件
return false;
}
if (root.val == Integer.MAX_VALUE && root.right != null) {
// 如果root已经为最大值,且还有右树,那一定不满足条件
return false;
}
// 判断左右子树
if(!isValidBSTWithRange(root.left, min, root.val - 1)) {
return false;
}
if(!isValidBSTWithRange(root.right, root.val + 1, max)) {
return false;
}
return true;
}
} | ninehills/leetcode | 98.java | 301 | // 如果root已经为最大值,且还有右树,那一定不满足条件 | line_comment | en | true |
4844_6 | /**
* Provides basic game state handling.
*/
public abstract class Bot extends AbstractSystemInputParser {
protected Game game;
protected AntMap map;
protected int ROWS;
protected int COLS;
/**
* {@inheritDoc}
*/
@Override
public void setup(int loadTime, int turnTime, int rows, int cols, int turns, int viewRadius2, int attackRadius2, int spawnRadius2)
{
Game g = new Game(loadTime, turnTime, rows, cols, turns, viewRadius2, attackRadius2, spawnRadius2);
setGame(g);
ROWS = game.getRows();
COLS = game.getCols();
setMap(new AntMap(g));
}
/**
* Returns game state information.
*
* @return game state information
*/
public Game getGame() {
return game;
}
/**
* Sets game state information.
*
* @param game game state information to be set
*/
protected void setGame(Game game) {
this.game = game;
}
public AntMap getMap() {
return map;
}
protected void setMap(AntMap map) {
this.map = map;
}
/**
* {@inheritDoc}
*/
@Override
public void beforeUpdate() {
map.log("Bot.beforeUpdate");
map.log("Setting start time");
game.setTurnStartTime(System.currentTimeMillis());
map.log("Clearing orders");
game.getOrders().clear();
map.log("Incrementing turn");
game.incrementTurn();
map.log("map.beforeUpdate (called from Bot)");
map.beforeUpdate();
}
/**
* {@inheritDoc}
*/
@Override
public void addWater(int row, int col) {
map.processWater(row, col);
}
/**
* {@inheritDoc}
*/
@Override
public void addAnt(int row, int col, int owner) {
map.processLiveAnt(row, col, owner);
// map.update(owner > 0 ? Ilk.ENEMY_ANT : Ilk.MY_ANT, new Tile(row, col));
}
/**
* {@inheritDoc}
*/
@Override
public void addFood(int row, int col) {
map.processFood(row, col);
}
/**
* {@inheritDoc}
*/
@Override
public void removeAnt(int row, int col, int owner) {
map.processDeadAnt(row, col, owner);
}
/**
* {@inheritDoc}
*/
@Override
public void addHill(int row, int col, int owner) {
map.processHill(row, col, owner);
}
/**
* {@inheritDoc}
*/
@Override
public void afterUpdate() {
map.afterUpdate();
}
}
| goldcaddy77/Ants-AI-Challenge | Bot.java | 665 | /**
* {@inheritDoc}
*/ | block_comment | en | true |
5737_3 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Babies do not produce cookies for their player but instead take away
* cookies from the other player.
* every second.
*
* @author Patrick Hu
* @version November 2022
*/
public class Baby extends Building
{
private boolean isDrinkingMilk; // whether the baby was given a milk bottle
private int drinkingCount, drinkingActs;
private GreenfootImage drinkingSprite;
/**
* @param player The player who has purchased a Baby
*/
public Baby(Player player) {
super(player);
animationSize = 11;
scale = 0.5;
isDrinkingMilk = false;
drinkingCount = 0;
drinkingActs = 90;
}
public void act() {
super.act();
if(drinkingCount == 0 && isDrinkingMilk) {
player.getBuildingRows().get(Baby.class).getBuildings().remove(this);
getWorld().removeObject(this);
} else if (drinkingCount <= drinkingActs && isDrinkingMilk) {
Effect.fade(drinkingSprite, drinkingCount, drinkingActs);
} else {
if (actCount == actMark) {
eat();
actMark = getNextActMark(2, 3);
}
}
if(isDrinkingMilk) {
setImage(drinkingSprite);
drinkingCount --;
}
}
/**
* Eats(removes) 5-10 cookies from the other player.
*/
public void eat() {
int amountToEat;
if (Building.LUCKY) {
amountToEat = 10;
}
else {
amountToEat = getRandomNumberInRange(5, 10);
}
CookieWorld cw = (CookieWorld)getWorld();
Player otherPlayer = cw.getOtherPlayer(player);
otherPlayer.changeCookieCount(-amountToEat);
}
/**
* Changes baby's image to it drinking a bottle of milk. This happens when the
* Milk Bottles powerup is activated.
*/
public void drinkMilk() {
drinkingSprite = new GreenfootImage("powerup-icns/baby-drinking-milk.png");
drinkingSprite.scale(50, 50);
setImage(drinkingSprite);
isDrinkingMilk = true;
drinkingCount = 120;
}
}
| edzhuang/cookie-clicker-simulation | Baby.java | 610 | /**
* @param player The player who has purchased a Baby
*/ | block_comment | en | false |
5838_7 | import java.util.*;
/**
* Implementation of the Farmer Wolf Goat Cabbage problem.
*
* This code was created by Joshua Bates and is his copyright.
*/
public class FWGC implements Problem
{
private boolean[] river=new boolean[4];
private int cost;
/**
* Constructor to create a new FWGC
* Cost is set to 0.
*/
public FWGC()
{
cost=0;
}
//private constructor to create a new state
private FWGC(boolean[] pstate, int oCost)
{
for(int i=0; i< 4; i++)
{
this.river[i]=pstate[i];
}
this.cost=oCost+1;
}
/**
* Checks to see if state is goal state.
* Goal state is everything is across the river.
* @return
*/
@Override
public boolean isGoal()
{
for(int i=0; i<4; i++)
{
if(!river[i])
return false;
}
return true;
}
/**
* Getter method for cost.
* @return
*/
@Override
public int getCost()
{
return cost;
}
//Private method to switch farmer and something else across the river.
private void changeRiver(int i)
{
if(river[0])
{
river[0]=false;
river[i]=false;
}
else
{
river[0]=true;
river[i]=true;
}
}
//Private method to add to array, and change the position
private void newState(ArrayList<FWGC> arr, int position)
{
FWGC state=new FWGC(river, cost);
state.changeRiver(position);
arr.add(state);
}
/**
* Checks valid successors, and returns all possible successors.
* @return
*/
@Override
public ArrayList<FWGC> successors()
{
ArrayList<FWGC> succ=new ArrayList<FWGC>();
if(!river[0])
{
if(!river[1] && !river[2] && !river[3])//everything on bank
{
newState(succ, 2);
}
else if(!river[1] && river[2] && !river[3]) //goat across river, others on bank
{
newState(succ, 3);
newState(succ, 1);
}
else if(!river[1] && !river[2] && river[3]) //goat and wolf on bank, cabbage across river
{
newState(succ, 1);
newState(succ, 2);
}
else if(river[1] && !river[2] && !river[3]) //goat and cabbage on bank, wolf across bank.
{
newState(succ, 3);
newState(succ, 2);
}
else if(river[1] && !river[2] && river[3]) //goat on bank, everything else across
{
newState(succ, 2);
}
}
else
{
if((!river[1] && river[2] && !river[3])||(river[1] && !river[2] && river[3]))
{
newState(succ, 0);
}
else if(!river[1] && river[2] && river[3])
{
newState(succ, 2);
newState(succ, 3);
}
else if(river[1] && !river[2] && !river[3])
{
newState(succ, 2);
newState(succ, 3);
}
}
return succ;
}
/**
* Method for printing out the state.
*
* @return
*/
@Override
public String toString()
{
String str="===============\n";
for(int i=0; i< 4; i++)
{
if(river[i]==false)
{
str+=getPerson(i)+" |RIVER| \n";
}
else
{
str+=" |RIVER| "+getPerson(i)+" \n";
}
}
return str;
}
// Private method used in toString to get F, W, G, or C
private String getPerson(int i)
{
String str="";
if(0==i)
{
str= "F";
}
else if(1==i)
{
str= "W";
}
else if(2==i)
{
str= "G";
}
else if(3==i)
{
str= "C";
}
return str;
}
/**
* Gets heuristic value, which this problem will not have, so the value is
* -1
* @return
*/
@Override
public int heuristicValue()
{
return -1;
}
/**
* Setter for cost
* @param value
*/
@Override
public void setCost(int value)
{
cost=value;
}
/**
* Compares two FWGC classes. If they aren't FWGC, it will return false.
*If they aren't the same state, will also return false
*
* @param state
*/
@Override
public boolean compare( Problem state)
{
boolean isSame;
if(state instanceof FWGC)
{
FWGC comp=(FWGC) state;
int i=0;
isSame=true;//state instanceof FWGC;
while(i<4 && isSame)
{
if(comp.river[i]!=this.river[i])
{
isSame=false;
}
i++;
}
}
else
{
isSame=false;
}
return isSame;
}
}
| BatesJosh/Artficial-Intelligence-Problem-Assignment | FWGC.java | 1,392 | /**
* Checks valid successors, and returns all possible successors.
* @return
*/ | block_comment | en | false |
6427_0 | import org.patricbrc.Workspace.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class ex
{
public static void main(String args[])
{
try {
String token = "un=olson|tokenid=2A8BCAFA-ACBA-11E4-A91B-68C642A49C03|expiry=1454623630|client_id=olson|token_type=Bearer|SigningSubject=http://rast.nmpdr.org/goauth/keys/E087E220-F8B1-11E3-9175-BD9D42A49C03|this_is_globus=globus_style_token|sig=03a3cfae05a8dbaaaf57e34eb4800bc8b3c8046beb18620a8d605867490228302651f050578a7dd30181366b1cf7170dedc89a45a6b41a3ce6ebd96069834be090281c2bf4f3917a005a63f5ac78799843d33b690cfc76f7d59ef846fe7a23d5d623d830584d23adad60293cb56d250ed8c1c3169e8fdaf89bfc7c3f50bdaf9d";
Workspace w = new Workspace("http://p3.theseed.org/services/Workspace", token);
get_params getpar = new get_params();
getpar.objects = Arrays.asList("/olson/olson/prefs.json");
getpar.metadata_only = 0;
getpar.adminmode = 0;
List<Workspace_tuple_2> getres = w.get(getpar);
System.out.println(getres.get(0).e_2);
Map<String, List<ObjectMeta>> res;
list_params lp = new list_params();
lp.paths = Arrays.asList("/olson/olson");
res = w.ls(lp);
System.out.println(res.entrySet());
get_params gp = new get_params();
gp.objects = Arrays.asList("/olson/olson/Makefile3");
gp.metadata_only = 0;
gp.adminmode = 0;
List<Workspace_tuple_2> r = w.get(gp);
System.out.println(r.get(0).e_2);
} catch (Exception e)
{
System.out.println("Failure: " + e);
}
}
} | BV-BRC/Workspace | ex.java | 706 | //rast.nmpdr.org/goauth/keys/E087E220-F8B1-11E3-9175-BD9D42A49C03|this_is_globus=globus_style_token|sig=03a3cfae05a8dbaaaf57e34eb4800bc8b3c8046beb18620a8d605867490228302651f050578a7dd30181366b1cf7170dedc89a45a6b41a3ce6ebd96069834be090281c2bf4f3917a005a63f5ac78799843d33b690cfc76f7d59ef846fe7a23d5d623d830584d23adad60293cb56d250ed8c1c3169e8fdaf89bfc7c3f50bdaf9d"; | line_comment | en | true |
6881_7 | import java.util.ArrayList;
import java.util.List;
// Basic user interface which defines the basic methods required in the system
public interface User {
String getuserName();
String getPassword();
String getContact();
List<Event> getBookedEvents();
List<Booking> getBookings();
boolean isAdmin();
void displayInfo();
}
// implemented Admin class with admin specific entries and methods.
class Admin implements User {
private String userName;
private String password;
private String contactInfo;
private boolean isAdmin = true;
// constructor
public Admin(String userName, String password, String contactInfo) {
this.userName = userName;
this.password = password;
this.contactInfo = contactInfo;
}
public String getuserName() {
return userName;
}
@Override
public String getPassword() {
return password;
}
public String getContact() {
return contactInfo;
}
@Override
public List<Booking> getBookings() {
return null;
}
@Override
public List<Event> getBookedEvents() {
return null;
}
public boolean isAdmin() {
return isAdmin;
}
// boolean method that returns whether the new event is successfully added into the system or not.
public boolean addNewEvent(String eventName, String eventDate, String eventTime, String eventVenue, int avaliableSeats, String eventOrganizer, Event Events[]) {
Event event = new Event(eventName, eventDate, eventTime, eventVenue, avaliableSeats, eventOrganizer);
boolean creation = false;
for (int i = 0; i < Events.length; i++) {
if (Events[i] == null) {
Events[i] = event;
creation = true;
int eveid = Events[i].getEventId();
System.out.println("Event Registered with ID = " + eveid);
break;
} else {
creation = false;
}
}
return creation;
}
// display method which prints all the essential user information
@Override
public void displayInfo() {
System.out.println("User Name: " + userName);
System.out.println("User Password: " + password);
System.out.println("Contact information: " + contactInfo);
System.out.println("is user admin: " + isAdmin + "\n");
}
}
// implemented NormalUser class with specific entries and methods.
class NormalUser implements User {
private String userName;
private String password;
private String contactInfo;
private boolean isAdmin = false;
private List<Event> bookedEvents;
private List<Booking> bookings;
// constructor
public NormalUser(String userName, String password, String contactInfo) {
this.userName = userName;
this.password = password;
this.contactInfo = contactInfo;
bookedEvents = new ArrayList<>();
bookings = new ArrayList<>();
}
@Override
public String getuserName() {
return userName;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getContact() {
return contactInfo;
}
@Override
public boolean isAdmin() {
return isAdmin;
}
@Override
public List<Booking> getBookings() {
return bookings;
}
@Override
public List<Event> getBookedEvents() {
return bookedEvents;
}
// method which prints all the booking details about the bookings made by the user.
public void getAllBookings() {
for (Booking booking : bookings) {
booking.displayBookingDetails();
}
}
// method which prints all the events the user booked in for.
public void getAllBookedEvent() {
for (Event event : bookedEvents) {
event.displayEventDetails();
}
}
// method to add a specific event object which the user booked for.
public void addBookedEvent(Event event) {
bookedEvents.add(event);
}
// method to add the specific booking object associated with a booking
public void addBooking(Booking booking) {
bookings.add(booking);
}
// display method to print all the essential information about the user.
@Override
public void displayInfo() {
System.out.println("User Name: " + userName);
System.out.println("User Password: " + password);
System.out.println("Contact information: " + contactInfo);
System.out.println("is user admin: " + isAdmin + "\n");
}
} | Jainil2004/LocalEventManagementAndBookingSystem | User.java | 1,039 | // method which prints all the booking details about the bookings made by the user.
| line_comment | en | false |
7028_2 | /*
Copyright (c) 2014, Christoph Stahl
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import lejos.hardware.Button;
import lejos.hardware.lcd.LCD;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import com.kitfox.svg.SVGException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
//import lejos.robotics.RegulatedMotorListener;
/* Notes
* Button.LEDPattern(3); //off 0, static: green 1, red 2, yellow 3, rhythmic: green 7, red 8, yellow 9
* Drawing Rectangle in mm from origin:
*
* upper: 270
* left: -105 right: 125
* bottom: 115
*
* Drawing rectangle size: 155x230
*/
public class TRAC3R
{
private TRAC3RsArm arm;
public TRAC3R()
{
System.out.println("Setting up TRAC3R...");
LCD.clear();
System.out.println("Setting up TRAC3RsArm...");
arm = new TRAC3RsArm();
}
public void start() throws InterruptedException
{
arm.initialize();
arm.calibrateHand();
//arm.testHandPosCodeFreely();
//generate interpolated paths from file
List<Path> paths = null;
try {
paths = SVGHandler.pathsInSVGFile(new URI("file:///tmp/job.svg"));
} catch (SVGException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (paths != null) {
//calculate inverse kinematics and draw as soon as first path is calculated
BlockingQueue<List<double[]>> queue = new ArrayBlockingQueue<List<double[]>>(1);
Thread producer = new Thread(new MovementDataProducer(arm, queue, paths));
Thread consumer = new Thread(new MovementController(arm, queue));
producer.setDaemon(true);
consumer.setDaemon(true);
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("Finished all.");
}
Button.LEDPattern(0);
}
public static void main(String[] args) throws InterruptedException
{
TRAC3R robot = new TRAC3R();
robot.start();
}
}
| stahlfabrik/TRAC3R | TRAC3R.java | 916 | /* Notes
* Button.LEDPattern(3); //off 0, static: green 1, red 2, yellow 3, rhythmic: green 7, red 8, yellow 9
* Drawing Rectangle in mm from origin:
*
* upper: 270
* left: -105 right: 125
* bottom: 115
*
* Drawing rectangle size: 155x230
*/ | block_comment | en | true |
7083_0 | ///usr/bin/env jbang "$0" "$@" ; exit $?
//REPOS mavencentral,jitpack
//DEPS com.github.adriens:excuses-sdk:v0.12
//DEPS info.picocli:picocli:4.5.0
import com.github.adriens.excuses.sdk.Excuses;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import java.util.concurrent.Callable;
@Command(name = "nope", mixinStandardHelpOptions = true, version = "nope 0.1",
description = "nope made with jbang")
class nope implements Callable<Integer> {
//TODO ajouter valeur par défaut
@CommandLine.Option(
names = {"-c", "--category"},
description = "La catégorie d'excuse (boulot,sport,apero)",
required = true)
private String category;
public static void main(String... args) {
int exitCode = new CommandLine(new nope()).execute(args);
System.exit(exitCode);
}
@Override
public Integer call() throws Exception { // your business logic goes here...
Excuses excuses = new Excuses();
System.out.println(excuses.pickRandomly(category));
return 0;
}
}
| adriens/excuses-sdk | nope.java | 322 | ///usr/bin/env jbang "$0" "$@" ; exit $? | line_comment | en | true |
7856_3 | package app;
import java.awt.Desktop;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.StringJoiner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.SwingWorker;
/**
*
* @author Ben Hannel
*/
public class GUI extends javax.swing.JFrame {
private double lat;
private double lon;
private int vid;
private ArrayList<Point2D.Double> points = new ArrayList<>();
private int pointIndex = 0;
private int numPoints = 0;
/** Creates new form GUI */
public GUI() {
initComponents();
}
public void setSpeed(int speed) {
this.speed.setText(speed + " mph");
}
public void setRange(double range) {
this.range.setText(range + " miles");
}
public void setLatLon(double lat, double lon) {
points.add(new Point2D.Double(lat, lon));
if (points.size() > 20)
points.remove(0);
this.lat = lat;
this.lon = lon;
this.coords.setText(lat + ", " + lon);
numPoints++;
numPointsLabel.setText("" + numPoints);
if (numPoints == 1) {
viewLocationActionPerformed(null);
}
}
public void setLastUpdate(Date date) {
lastUpdate.setValue(date);
}
public void setVid(int vid) {
this.vid = vid;
vidLabel.setText("" + vid);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
javax.swing.JPanel jPanel2 = new javax.swing.JPanel();
mapLabel = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
javax.swing.JLabel jLabel1 = new javax.swing.JLabel();
speed = new javax.swing.JLabel();
javax.swing.JLabel jLabel4 = new javax.swing.JLabel();
range = new javax.swing.JLabel();
javax.swing.JLabel jLabel5 = new javax.swing.JLabel();
coords = new javax.swing.JLabel();
javax.swing.JLabel jLabel6 = new javax.swing.JLabel();
lastUpdate = new javax.swing.JFormattedTextField();
javax.swing.JLabel jLabel7 = new javax.swing.JLabel();
vidLabel = new javax.swing.JLabel();
javax.swing.JLabel jLabel8 = new javax.swing.JLabel();
numPointsLabel = new javax.swing.JLabel();
viewLocation = new javax.swing.JButton();
aboutButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(250, 350));
setPreferredSize(new java.awt.Dimension(500, 700));
jPanel2.setMinimumSize(new java.awt.Dimension(200, 200));
jPanel2.setPreferredSize(new java.awt.Dimension(300, 300));
jPanel2.setLayout(new java.awt.BorderLayout());
jPanel2.add(mapLabel, java.awt.BorderLayout.CENTER);
jPanel1.setLayout(new java.awt.GridLayout(0, 2));
jLabel1.setText("Speed");
jPanel1.add(jLabel1);
speed.setText("NA");
jPanel1.add(speed);
jLabel4.setText("Range");
jPanel1.add(jLabel4);
range.setText("NA");
jPanel1.add(range);
jLabel5.setText("Latitude, Longitude");
jPanel1.add(jLabel5);
coords.setText("NA");
jPanel1.add(coords);
jLabel6.setText("Last Update Time");
jPanel1.add(jLabel6);
lastUpdate.setBackground(new java.awt.Color(238, 238, 238));
lastUpdate.setBorder(null);
lastUpdate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getTimeInstance())));
lastUpdate.setFocusable(false);
jPanel1.add(lastUpdate);
jLabel7.setText("Vehicle ID");
jPanel1.add(jLabel7);
vidLabel.setText("NA");
jPanel1.add(vidLabel);
jLabel8.setText("Data Points Recorded");
jPanel1.add(jLabel8);
numPointsLabel.setText("NA");
jPanel1.add(numPointsLabel);
viewLocation.setText("View Location");
viewLocation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewLocationActionPerformed(evt);
}
});
jPanel1.add(viewLocation);
aboutButton.setText("About");
aboutButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutButtonActionPerformed(evt);
}
});
jPanel1.add(aboutButton);
jPanel2.add(jPanel1, java.awt.BorderLayout.PAGE_START);
getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void viewLocationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewLocationActionPerformed
StringJoiner pathStr = new StringJoiner("|");
for (Point2D point : points) {
pathStr.add(point.getX() + "," + point.getY());
}
try {
String urlStr = "http://maps.googleapis.com/maps/api/staticmap?sensor=false"
+ "&size=" + mapLabel.getWidth() + "x" + mapLabel.getHeight()
+ "&markers=" + lat + "," + lon
+ "&path=color:0x0000ff|weight:5" + pathStr.toString();
URL url = new URL(urlStr);
BufferedImage img = ImageIO.read(url);
final ImageIcon icon = new ImageIcon(img);
new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
mapLabel.setIcon(icon);
return null;
}
}.execute();
} catch (IOException ex) {
ex.printStackTrace();
Main.logError(ex, "Static map update failed");
}
}//GEN-LAST:event_viewLocationActionPerformed
private void aboutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutButtonActionPerformed
try {
Desktop.getDesktop().browse(
new URI("http://evtripplanner.com/planner/tracker/tracker_about.php"));
} catch (URISyntaxException | IOException ex) {
ex.printStackTrace();
Main.logError(ex);
}
}//GEN-LAST:event_aboutButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton aboutButton;
private javax.swing.JLabel coords;
private javax.swing.JPanel jPanel1;
private javax.swing.JFormattedTextField lastUpdate;
private javax.swing.JLabel mapLabel;
private javax.swing.JLabel numPointsLabel;
private javax.swing.JLabel range;
private javax.swing.JLabel speed;
private javax.swing.JLabel vidLabel;
private javax.swing.JButton viewLocation;
// End of variables declaration//GEN-END:variables
}
| benhannel/TeslaTracker | GUI.java | 1,784 | // </editor-fold>//GEN-END:initComponents | line_comment | en | true |
7866_0 | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root==null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
TreeNode temp = queue.poll();
if(i==size-1) result.add(temp.val);
if(temp.left!=null) queue.offer(temp.left);
if(temp.right!=null) queue.offer(temp.right);
}
}
return result;
}
} | fztfztfztfzt/leetcode | 199.java | 208 | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/ | block_comment | en | true |
9004_1 | package profile;
import java.net.InetAddress;
import java.net.URI;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import core.data.InterfaceData;
import core.exec.PasswordExec;
import core.iface.IUnit;
import core.model.InterfaceModel;
import core.model.NetworkModel;
import core.model.ServerModel;
import core.profile.AStructuredProfile;
import core.unit.SimpleUnit;
import core.unit.fs.DirUnit;
import core.unit.fs.FileChecksumUnit;
import core.unit.fs.FileDownloadUnit;
import core.unit.pkg.InstalledUnit;
public class Metal extends AStructuredProfile {
private Virtualisation hypervisor;
private HypervisorScripts backups;
private Vector<ServerModel> services;
private ServerModel me;
public Metal(ServerModel me, NetworkModel networkModel) {
super("metal", me, networkModel);
this.me = me;
this.hypervisor = new Virtualisation(me, networkModel);
this.backups = new HypervisorScripts(me, networkModel);
this.services = new Vector<ServerModel>();
}
public Vector<ServerModel> getServices() {
return services;
}
protected Vector<IUnit> getInstalled() {
Vector<IUnit> units = new Vector<IUnit>();
units.addAll(hypervisor.getInstalled());
units.addAll(backups.getInstalled());
units.addElement(new DirUnit("media_dir", "proceed", networkModel.getData().getHypervisorThornsecBase(me.getLabel())));
units.addElement(new InstalledUnit("whois", "proceed", "whois"));
units.addElement(new InstalledUnit("tmux", "proceed", "tmux"));
units.addElement(new InstalledUnit("socat", "proceed", "socat"));
return units;
}
protected Vector<IUnit> getPersistentConfig() {
Vector<IUnit> units = new Vector<IUnit>();
String fuse = "";
fuse += "#user_allow_other";
units.addElement(((ServerModel)me).getConfigsModel().addConfigFile("fuse", "proceed", fuse, "/etc/fuse.conf"));
units.addAll(backups.getPersistentConfig());
return units;
}
public Vector<IUnit> getNetworking() {
Vector<IUnit> units = new Vector<IUnit>();
InterfaceModel im = me.getInterfaceModel();
me.setFirstOctet(10);
me.setSecondOctet(networkModel.getMetalServers().indexOf(me) + 1);
me.setThirdOctet(0);
int i = 0;
//Add this machine's interfaces
for (Map.Entry<String, String> lanIface : networkModel.getData().getLanIfaces(me.getLabel()).entrySet() ) {
if (me.isRouter() || networkModel.getData().getWanIfaces(me.getLabel()).containsKey(lanIface.getKey())) { //Try not to duplicate ifaces if we're a Router/Metal
continue;
}
InetAddress subnet = networkModel.stringToIP(me.getFirstOctet() + "." + me.getSecondOctet() + "." + me.getThirdOctet() + "." + (i * 4));
InetAddress router = networkModel.stringToIP(me.getFirstOctet() + "." + me.getSecondOctet() + "." + me.getThirdOctet() + "." + ((i * 4) + 1));
InetAddress address = networkModel.stringToIP(me.getFirstOctet() + "." + me.getSecondOctet() + "." + me.getThirdOctet() + "." + ((i * 4) + 2));
InetAddress broadcast = networkModel.stringToIP(me.getFirstOctet() + "." + me.getSecondOctet() + "." + me.getThirdOctet() + "." + ((i * 4) + 3));
InetAddress netmask = networkModel.getData().getNetmask();
im.addIface(new InterfaceData(me.getLabel(),
lanIface.getKey(),
lanIface.getValue(),
"static",
null,
subnet,
address,
netmask,
broadcast,
router,
"comment goes here")
);
}
me.addRequiredEgress("gensho.ftp.acc.umu.se");
me.addRequiredEgress("github.com");
return units;
}
protected Vector<IUnit> getLiveConfig() {
Vector<IUnit> units = new Vector<IUnit>();
Vector<String> urls = new Vector<String>();
for (ServerModel service : me.getServices()) {
String newURL = networkModel.getData().getDebianIsoUrl(service.getLabel());
if (urls.contains(newURL)) {
continue;
}
else {
urls.add(newURL);
}
}
for (String url : urls) {
String filename = null;
String cleanedFilename = null;
try {
filename = Paths.get(new URI(url).getPath()).getFileName().toString();
cleanedFilename = filename.replaceAll("[^A-Za-z0-9]", "_");
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "It doesn't appear that " + url + " is a valid link to a Debian ISO.\n\nPlease fix this in your JSON");
System.exit(1);
}
units.addElement(new FileDownloadUnit("debian_netinst_iso_" + cleanedFilename, "metal_genisoimage_installed",
url,
networkModel.getData().getHypervisorThornsecBase(me.getLabel()) + "/" + filename,
"The Debian net install ISO couldn't be downloaded. Please check the URI in your config."));
units.addElement(new FileChecksumUnit("debian_netinst_iso", "debian_netinst_iso_" + cleanedFilename + "_downloaded",
networkModel.getData().getHypervisorThornsecBase(me.getLabel()) + "/" + filename,
networkModel.getData().getDebianIsoSha512(me.getLabel()),
"The sha512 sum of the Debian net install in your config doesn't match what has been downloaded. This could mean your connection is man-in-the-middle'd, or it could just be that the file has been updated on the server. "
+ "Please check http://cdimage.debian.org/debian-cd/current/amd64/iso-cd/SHA512SUMS (64 bit) or http://cdimage.debian.org/debian-cd/current/i386/iso-cd/SHA512SUMS (32 bit) for the correct checksum."));
}
for (ServerModel service : me.getServices()) {
String password = "";
String serviceLabel = service.getLabel();
Boolean expirePasswords = false;
PasswordExec pass = new PasswordExec(serviceLabel, networkModel);
if (pass.init()) {
password = pass.getPassword();
password = Pattern.quote(password); //Turn special characters into literal so they don't get parsed out
password = password.substring(2, password.length()-2).trim(); //Remove '\Q' and '\E' from beginning/end since we're not using this as a regex
password = password.replace("\"", "\\\""); //Also, make sure quote marks are properly escaped!
}
if (pass.isDefaultPassword()) {
expirePasswords = true;
}
units.addElement(new SimpleUnit(serviceLabel + "_password", "proceed",
serviceLabel.toUpperCase() + "_PASSWORD=`printf \"" + password + "\" | mkpasswd -s -m md5`",
"echo $" + serviceLabel.toUpperCase() + "_PASSWORD", "", "fail",
"Couldn't set the passphrase for " + serviceLabel + ". You won't be able to configure this service."));
String bridge = networkModel.getData().getMetalIface(serviceLabel);
if (bridge == null || bridge.equals("")) {
bridge = me.getNetworkData().getLanIfaces(me.getLabel()).getOrDefault(0, "vm" + service.getThirdOctet());
}
units.addAll(hypervisor.buildIso(service.getLabel(), hypervisor.preseed(service.getLabel(), expirePasswords)));
units.addAll(hypervisor.buildServiceVm(service.getLabel(), bridge));
String bootDiskDir = networkModel.getData().getHypervisorThornsecBase(me.getLabel()) + "/disks/boot/" + serviceLabel + "/";
String dataDiskDir = networkModel.getData().getHypervisorThornsecBase(me.getLabel()) + "/disks/data/" + serviceLabel + "/";
units.addElement(new SimpleUnit(serviceLabel + "_boot_disk_formatted", "proceed",
"",
"sudo bash -c 'export LIBGUESTFS_BACKEND_SETTINGS=force_tcg;"
+ "virt-filesystems -a " + bootDiskDir + serviceLabel + "_boot.v*'", "", "fail",
"Boot disk is unformatted (therefore has no OS on it), please configure the service and try mounting again."));
//For now, do this as root. We probably want to move to another user, idk
units.addElement(new SimpleUnit(serviceLabel + "_boot_disk_loopback_mounted", serviceLabel + "_boot_disk_formatted",
"sudo bash -c '"
+ " export LIBGUESTFS_BACKEND_SETTINGS=force_tcg;"
+ " guestmount -a " + bootDiskDir + serviceLabel + "_boot.v*"
+ " -i" //Inspect the disk for the relevant partition
+ " -o direct_io" //All read operations must be done against live, not cache
+ " --ro" //_MOUNT THE DISK READ ONLY_
+ " " + bootDiskDir + "live/"
+"'",
"sudo mount | grep " + bootDiskDir, "", "fail",
"I was unable to loopback mount the boot disk for " + serviceLabel + " in " + getLabel() + "."));
units.addElement(new SimpleUnit(serviceLabel + "_data_disk_formatted", "proceed",
"",
"sudo bash -c 'export LIBGUESTFS_BACKEND_SETTINGS=force_tcg;"
+ "virt-filesystems -a " + dataDiskDir + serviceLabel + "_data.v*'", "", "fail",
"Data disk is unformatted (therefore hasn't been configured), please configure the service and try mounting again."));
units.addElement(new SimpleUnit(serviceLabel + "_data_disk_loopback_mounted", serviceLabel + "_data_disk_formatted",
"sudo bash -c '"
+ " export LIBGUESTFS_BACKEND_SETTINGS=force_tcg;"
+ " guestmount -a " + dataDiskDir + serviceLabel + "_data.v*"
+ " -m /dev/sda1" //Mount the first partition
+ " -o direct_io" //All read operations must be done against live, not cache
+ " --ro" //_MOUNT THE DISK READ ONLY_
+ " " + dataDiskDir + "live/"
+"'",
"sudo mount | grep " + dataDiskDir, "", "fail",
"I was unable to loopback mount the data disk for " + serviceLabel + " in " + getLabel() + ". Backups will not work."));
}
return units;
}
}
| privacyint/ThornSec | src/profile/Metal.java | 2,772 | //Try not to duplicate ifaces if we're a Router/Metal | line_comment | en | true |
9587_0 | package assignment7;
/**
* Project 7 Chat Room
* EE 422C submission by
* Aditya Kharosekar amk3587
* Rahul Jain rj8656
* Fall 2016
* Slip days used - 1 (on this project) (overall - 2)
* This is the second slip day that we have used this semester
*/
import java.util.HashMap;
import java.util.Set;
/**
* This Map is just like a global variable.
* It will store the username-password combinations of all users
*/
public class Map {
public static HashMap<String, String> UsernamePasswordMap = new HashMap<>();
public static HashMap<String, Integer> nameID = new HashMap<>();
static int id = 0;
public static void addOrChange(String username, String password) {
UsernamePasswordMap.put(username, password);
nameID.put(username, id);
id++;
}
public static int size(){
return UsernamePasswordMap.size();
}
public static Set getUsernames(){
return nameID.keySet();
}
public static HashMap<String, Integer> getId(){
return nameID;
}
}
| RahulJain28/Project7 | Map.java | 286 | /**
* Project 7 Chat Room
* EE 422C submission by
* Aditya Kharosekar amk3587
* Rahul Jain rj8656
* Fall 2016
* Slip days used - 1 (on this project) (overall - 2)
* This is the second slip day that we have used this semester
*/ | block_comment | en | true |
9818_3 | package io.Lorenzo;
import java.util.Objects;
/**
* A class to represent a MAC address.
* A MAC address is a 48-bit number, usually represented as a 12-digit hexadecimal number.
* The hexadecimal number is usually split into 6 groups of 2 digits, separated by colons.
* For example, the MAC address 00:0a:95:9d:68:16 is a valid MAC address.
* This class represents a MAC address as a String, and provides methods to convert it to an int, and to compare it to other MAC addresses.
* @see <a href="https://en.wikipedia.org/wiki/MAC_address">MAC address</a>
* @see <a href="https://en.wikipedia.org/wiki/Hexadecimal">Hexadecimal</a>
* @author Lorenzo
* @version 1.0
*/
public class MAC {
/**
* The MAC address, represented as a String.
* The MAC address must be 17 characters long, and must be in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit.
*/
private final String mac;
/**
* The length of a MAC address, in characters.
* A MAC address must be 17 characters long, including the colons.
*/
final int length = 17;
/**
* @param mac The MAC address, represented as a String.
* The MAC address must be 17 characters long, and must be in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit.
* For example, 00:0a:95:9d:68:16 is a valid MAC address.
* The MAC address cannot be null.
* @throws IllegalArgumentException if the MAC address is null, or is not 17 characters long, or is not in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit.
*
*/
public MAC(String mac) {
if(mac == null)
throw new IllegalArgumentException("MAC cannot be null");
if(mac.length() != length)
throw new IllegalArgumentException("MAC must be 17 characters long");
if(!mac.matches("^[A-Fa-f0-9]{2}(:[A-Fa-f0-9]{2}){5}$"))
throw new IllegalArgumentException("MAC must be in the format XX:XX:XX:XX:XX:XX");
this.mac = mac;
}
/**
* @return The MAC address, represented as a String, without colons.
* For example, 00:0a:95:9d:68:16 would be returned as 000a959d6816.
* @see #getMacAsLong()
*
*/
public String getMacNoColons() {
return mac.replaceAll(":", "");
}
/**
* @return The MAC address, represented as an int.
* For example, 00:0a:95:9d:68:16 would be returned as 1077955622.
* @see #getMacNoColons()
*/
public long getMacAsLong() {
return Long.parseLong(getMacNoColons(), 16);
}
/**
* @param mac The MAC address to compare this MAC address to.
* @throws IllegalArgumentException if the MAC address is null.
* @return true if this MAC address is greater than the MAC address passed as a parameter, false otherwise.
*/
public boolean isSmallerThan(MAC mac){
if(mac == null)
throw new IllegalArgumentException("MAC cannot be null");
return getMacAsLong() < mac.getMacAsLong();
}
/**
* @param o The object to compare this MAC address to.
* @return true if the object is a MAC address, and has the same MAC address as this MAC address, false otherwise.
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MAC m)) return false;
return Objects.equals(mac, m.mac);
}
/**
* @return The hash code of this MAC address.
* The hash code is calculated using the MAC address.
*/
@Override
public int hashCode() {
return Objects.hash(mac);
}
/**
* @return The MAC address, represented as a String.
*/
@Override
public String toString() {
return mac;
}
}
| Her0-GitHub/Java | MAC.java | 1,048 | /**
* @param mac The MAC address, represented as a String.
* The MAC address must be 17 characters long, and must be in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit.
* For example, 00:0a:95:9d:68:16 is a valid MAC address.
* The MAC address cannot be null.
* @throws IllegalArgumentException if the MAC address is null, or is not 17 characters long, or is not in the format XX:XX:XX:XX:XX:XX, where X is a hexadecimal digit.
*
*/ | block_comment | en | true |
10415_12 | package billingsystem;
import java.util.ArrayList;
import javafx.scene.control.Label;
/**
*
* @author Jason Li
* @version 1.0
* @since 19.12.2016
*
*
*
* The Class Table.
*/
public class Table extends Label implements java.io.Serializable {
/** The tbl name. */
private String tblName;
/** The people. */
private String people;
/** The orders. */
ArrayList<Order> orders = new ArrayList<Order>();
/** The pos X. */
private double posX;
/** The pos Y. */
private double posY;
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return tblName;
}
/**
* Gets the orders.
*
* @return the orders
*/
public ArrayList<Order> getOrders() {
return orders;
}
/**
* Set new X and Y.
*
* @param x the x-position
* @param y the y-position
*/
public void setXY(double x, double y) {
this.posX = x;
this.posY = y;
}
/**
* Gets the x-position.
*
* @return the x
*/
public double getX() {
return posX;
}
/**
* Gets the y-position.
*
* @return the y
*/
public double getY() {
return posY;
}
/**
* Sets the number of people at the table.
*
* @param people - Number of people
*/
public void setPeople(String people) {
this.people = people;
}
/**
* Gets the number of people at the table.
*
* @return people - Number of people
*/
public String getPeople() {
return people;
}
/**
* Adds the order.
*
* @param order item the order item
*/
public void addOrder(Order orderItem) {
orders.add(orderItem);
}
/**
* Sets the orders.
*
* @param set new orders
*/
public void setOrders(ArrayList<Order> setOrders) {
this.orders = setOrders;
}
/**
* Clear table
*/
public void clear() {
this.people = "";
this.orders.clear();;
}
/**
* Instantiates a new table.
*
* @param tblName the table name
*/
public Table(String tblName) {
this.tblName = tblName;
}
/**
* Instantiates a new table.
*
* @param copyTable - the table to copy
*/
public Table(Table copyTable) {
this.tblName = copyTable.tblName;
this.posX = copyTable.posX;
this.posY = copyTable.posY;
}
}
| kishanrajput23/Java-Projects-Collections | Billing-system/src/billingsystem/Table.java | 732 | /**
* Gets the number of people at the table.
*
* @return people - Number of people
*/ | block_comment | en | false |
10513_0 | /**
* Created by eugenevendensky on 1/17/17.
*/
public class Bank {
private String accountType;
private String accountNumer;
private int balance;
private String accountHoldersName;
private float intRate;
private String status = "Open";
private boolean overDraftProtection = true;
private int transactionCounter;
public int getAccountBalance() {
System.out.println(balance);
return balance;
}
public int creditAccount(int x) {
balance += x;
transactionCounter++;
System.out.println("Your balance is now " + balance);
return balance;
}
public int debitAccount(int x) {
if (status.equalsIgnoreCase("Closed") || status.equalsIgnoreCase("Ofac freeze")) {
System.out.println("The account is unavailable for withdrawal");
return balance;
} else {
if (overDraftProtection) {
if (balance - x <= 0) {
System.out.println("This transaction will result in an overdraft");
return balance;
} else {
int newBalance;
newBalance = balance - x;
balance = newBalance;
System.out.println("Your balance is now " + balance);
transactionCounter++;
return balance;
}
} else {
int newBalance;
newBalance = balance - x;
balance = newBalance;
System.out.println("your balance is now " + balance);
transactionCounter++;
return balance;
}
}
}
public int getTransactions(){
System.out.println("Your account has had " + transactionCounter + " transactions");
return transactionCounter;
}
}
| ggenya132/Access_Control_Lab | Bank.java | 376 | /**
* Created by eugenevendensky on 1/17/17.
*/ | block_comment | en | true |
10518_0 | import java.util.ArrayList;
public class Cube extends Traceable {
/* A Cube is cube centered at the origin, extending from -1 to +1 on
* each axis
*
* Note: there is a bug in local_intersect so it sometimes does not work
* correctly, but this should not give you a problem.
*/
public String toString() {
return "Cube \n"+this.transform;
}
@Override
public ArrayList<Intersection> local_intersect(Ray gray) {
var ray = gray.transform(transform.invert());
double[] rets =
check_axis(ray.origin.t[0], ray.direction.t[0]);
double xtmin = rets[0];
double xtmax = rets[1];
rets = check_axis(ray.origin.t[1], ray.direction.t[1]);
if (rets[0] > xtmin)
xtmin = rets[0];
if (rets[1] < xtmax)
xtmax = rets[1];
rets = check_axis(ray.origin.t[2], ray.direction.t[2]);
if (rets[0] > xtmin)
xtmin = rets[0];
if (rets[1] < xtmax)
xtmax = rets[1];
ArrayList<Intersection> ans = new ArrayList<Intersection>();
if (xtmin >= xtmax || xtmax == Double.POSITIVE_INFINITY)
return ans;
ans.add(new Intersection(this, xtmin));
ans.add(new Intersection(this, xtmax));
return ans;
}
private double[] check_axis(double origin, double direction) {
double tmin_numerator = (-1 - origin);
double tmax_numerator = (1 - origin);
double tmin;
double tmax;
//Had an error where Aux could not be resolved to a variable, so I simply replaced Aux.EPSILON with its value 0.0001
if (Math.abs(direction) >= 0.0001) {
tmin = tmin_numerator / direction;
tmax = tmax_numerator / direction;
}
else {
if (tmin_numerator >= 0)
tmin = Double.POSITIVE_INFINITY;
else if (tmin_numerator <=0)
tmin = Double.NEGATIVE_INFINITY;
else tmin = 0;
if (tmax_numerator >= 0)
tmax = Double.POSITIVE_INFINITY;
else if (tmax_numerator <=0)
tmax = Double.NEGATIVE_INFINITY;
else tmax = 0;
}
if (tmin > tmax) {
double temp = tmin;
tmin = tmax;
tmax = temp;
}
return new double[] {tmin, tmax};
}
@Override
public Vector local_normal_at(Point point, Intersection dontUse) {
double[] point_vals = world_to_object(point).getT();
int pos = 0;
double max = -1;
for (int i = 0; i < point_vals.length - 1; i++) {
if (Math.abs(point_vals[i]) > max) {
max = Math.abs(point_vals[i]);
pos = i;
}
}
if (pos == 0) {
return new Vector(point_vals[0],0,0);
} else if (pos == 1) {
return new Vector(0, point_vals[1], 0);
} else {
return new Vector(0, 0, point_vals[2]);
}
}
public static void main(String[] args) {
}
@Override
public boolean includes(Traceable object) {
return this == object;
}
}
| daviddang415/Ray_Tracer | Cube.java | 964 | /* A Cube is cube centered at the origin, extending from -1 to +1 on
* each axis
*
* Note: there is a bug in local_intersect so it sometimes does not work
* correctly, but this should not give you a problem.
*/ | block_comment | en | false |
11161_0 |
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* This class represents a Graphical User Interface (GUI) for the local movie database.
* Users can view, add, and manage movies in the database through this interface.
* The GUI includes options for sorting and filtering movies by different criteria.
*
* @author Asliddin
* @version 6.0
*/
public class GUI extends JFrame {
private Container container = getContentPane();
private JPanel contentPanel;
private static ArrayList<Movie> allMovies = MovieDatabase.allMovies();
private TreeSet<String> directors = MovieDatabase.directors;
/**
* Constructs a new GUI window for the local movie database.
* Initializes the graphical interface, sets its size and title, and adds various components.
* Users can interact with the GUI to view, sort, and filter movies.
*/
GUI() {
this.setVisible(true);
this.setSize(800, 600);
this.setTitle("Local Movie Database");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(10, 10, 10, 10);
JButton addMovie = new JButton("Add Movie");
addMovie.addActionListener((e) -> {
new AddMovie();
});
/**
* Inner class representing a window for adding a new movie to the database.
* Users can input movie details such as title, director, release year, and runtime.
*/
addMovie.setPreferredSize(new Dimension(200, 75));
addMovie.setPreferredSize(new Dimension(130, 50));
JPanel addPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
addPanel.add(addMovie);
JButton profile = new JButton("Profile");
profile.addActionListener((e) -> {
this.dispose();
new Profile();
});
profile.setPreferredSize(new Dimension(130, 50));
addPanel.add(profile);
String[] str = {"sort by: ", "Title", "Year", "Runtime"};
JComboBox<String> sortBy = new JComboBox<>(str);
sortBy.addActionListener((e)->{
if(sortBy.getSelectedItem().equals("Year")){
Collections.sort(allMovies);
}
else if(sortBy.getSelectedItem().equals("Runtime")){
allMovies.sort((Movie m1, Movie m2)->{
return m2.getRunningTime() - m1.getRunningTime();
});
}
else if(sortBy.getSelectedItem().equals("Title")){
Collections.sort(allMovies, Comparator.comparing(Movie::getTitle));
}
contentPanel.revalidate();
contentPanel.repaint();
this.dispose();
new GUI();
});
Iterator<String> iter = directors.iterator();
String strr[] = new String[directors.size()+2];
strr[0]="Filter By Directors";
strr[1]="All";
int j=2;
while(iter.hasNext()){
strr[j] = iter.next();
j++;
}
JComboBox<String> filter = new JComboBox<>(strr);
filter.addActionListener((e)->{
if(filter.getSelectedItem().equals("All") || filter.getSelectedItem().equals("Filter By Directors")){
allMovies = MovieDatabase.allMovies();
directors = MovieDatabase.directors;
}
else{
allMovies = (ArrayList<Movie>) MovieDatabase.allMovies().stream().filter((ee)->{
return ee.getDirector().equals(filter.getSelectedItem());
}).collect(Collectors.toList());
}
this.dispose();
new GUI();
});
JLabel searchL = new JLabel("search:");
JTextField searchF = new JTextField();
searchF.setPreferredSize(new Dimension(50, 20));
JButton search = new JButton("search");
search.addActionListener(e->{
String txt = searchF.getText();
if(txt.length()==0){
JOptionPane.showMessageDialog(this, "Please fill the blank!");
}else{
Movie movie = MovieDatabase.retrieveMovie(txt);
if(movie==null){
JOptionPane.showMessageDialog(this, "No such movie!");
}else{
String formatted = String.format("Title: %s\n Director: %s\n Year: %d\n Runtime: %d", movie.getTitle(), movie.getDirector(), movie.getReleasedYear(), movie.getRunningTime());
JOptionPane.showMessageDialog(this, formatted);
}
}
});
addPanel.add(sortBy);
addPanel.add(filter);
addPanel.add(searchL);
addPanel.add(searchF);
addPanel.add(search);
container.add(addPanel, BorderLayout.NORTH);
for (int i = 0; i < allMovies.size(); i++) {
String title = allMovies.get(i).getTitle();
String director = allMovies.get(i).getDirector();
int year = allMovies.get(i).getReleasedYear();
int runtime = allMovies.get(i).getRunningTime();
Border insideBorder = BorderFactory.createTitledBorder(title);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(insideBorder);
String movieInfo = String.format(
"<strong>Director:</strong> %s, <br><strong>Year:</strong> %d, <br><strong>Runtime:</strong> %d",
director, year, runtime);
JLabel label = new JLabel(
"<html><div style='text-align: left; padding:10px;'>" + movieInfo + "</div></html>");
panel.add(label, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5));
JButton addToWatchlistButton = new JButton("Add to Watchlist");
addToWatchlistButton.addActionListener((e) -> {
User user = Register.getLoggedIn();
ArrayList<Movie> watchlist = MovieDatabase.getUserDB(user);
boolean exists = watchlist.stream().anyMatch((t)->t.getTitle().equals(title));
if(!exists){
try (FileWriter fw = new FileWriter(String.format("DB/UserDB/DB%s.csv", user.getUsername()), true)) {
String movie = String.format("%s, %s, %d, %d\n", title, director, year, runtime);
fw.append(movie);
} catch (Exception ex) {
ex.printStackTrace();
}
}else{
JOptionPane.showMessageDialog(this, "This movie already exists in your watchlist!");
}
});
buttonPanel.add(addToWatchlistButton);
JButton removeButton = new JButton("Remove");
buttonPanel.add(removeButton);
Movie movie = allMovies.get(i);
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String movieTitle = movie.getTitle();
MovieDatabase.removeMovie(movieTitle);
contentPanel.remove(panel);
contentPanel.revalidate();
contentPanel.repaint();
}
});
panel.add(buttonPanel, BorderLayout.SOUTH);
contentPanel.add(panel, gbc);
gbc.gridy++;
}
JScrollPane scrollPane = new JScrollPane(contentPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
container.add(scrollPane);
}
class AddMovie extends JFrame implements ActionListener {
JButton add = new JButton("add");
JLabel directorLabel = new JLabel("Director : ");
JTextField directorField = new JTextField();
JLabel yearLabel = new JLabel("Release Year: ");
JTextField yearField = new JTextField();
JLabel runtimeLabel = new JLabel("Running time: ");
JTextField runtimeField = new JTextField();
JLabel titleLabel = new JLabel("Title: ");
JTextField titleField = new JTextField();
Container container = getContentPane();
JLabel warning1 = new JLabel("To see the update please click the 'All'");
JLabel warning2 = new JLabel("in filter by director section!!!");
public AddMovie() {
basic();
container.setLayout(null);
setSize();
add.addActionListener(this);
container.add(titleLabel);
container.add(directorLabel);
container.add(yearLabel);
container.add(runtimeLabel);
container.add(titleField);
container.add(directorField);
container.add(yearField);
container.add(runtimeField);
container.add(add);
container.add(warning1);
container.add(warning2);
}
/**
* Performs an action when the add button is clicked in the AddMovie window.
* Validates user input for the new movie and adds it to the database if input is valid.
* Displays error messages for missing or invalid input.
*
* @param e The ActionEvent triggered by clicking the add button.
*/
public void basic() {
this.setVisible(true);
this.setBounds(450, 100, 370, 600);
this.setTitle("Add New Movie");
}
private void setSize() {
titleLabel.setBounds(50, 90, 100, 30);
directorLabel.setBounds(50, 150, 100, 30);
yearLabel.setBounds(50, 220, 150, 30);
runtimeLabel.setBounds(50, 290, 150, 30);
titleField.setBounds(150, 90, 150, 30);
directorField.setBounds(150, 150, 150, 30);
yearField.setBounds(150, 220, 150, 30);
runtimeField.setBounds(150, 290, 150, 30);
add.setBounds(50, 370, 100, 30);
warning1.setFont(new Font("Italic", Font.ITALIC, 15));
warning2.setFont(new Font("Italic", Font.ITALIC, 15));
warning1.setBounds(30, 410, 300, 20);
warning2.setBounds(30, 430, 300, 20);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == add){
if(this.titleField.getText().length()==0 || this.directorField.getText().length()==0 || this.yearField.getText().length()==0 || this.runtimeField.getText().length()==0) {
JOptionPane.showMessageDialog(this, "Please fill all the gaps!");
}
else{
int runtime, year;
try{
runtime = Integer.valueOf(this.runtimeField.getText());
year = Integer.valueOf(this.yearField.getText());
Movie movie = new Movie(this.titleField.getText(), this.directorField.getText(), year, runtime);
MovieDatabase.addMovie(movie);
this.dispose();
}catch(NumberFormatException ee){
JOptionPane.showMessageDialog(this, "Year and runtime should contain only digits!");
}
}
}
}
}
}
| asroilf/MovieDBMS | GUI.java | 2,703 | /**
* This class represents a Graphical User Interface (GUI) for the local movie database.
* Users can view, add, and manage movies in the database through this interface.
* The GUI includes options for sorting and filtering movies by different criteria.
*
* @author Asliddin
* @version 6.0
*/ | block_comment | en | false |
11425_2 | package phoneBook189kk;
/**
*
* @author Kristen Kellerman
* KK: Class Main used for Binary Tree and Hash Table.
*/
public class Main {
/**
* KK: Used in the Binary Tree.
*/
String fullname;
String email;
String pnum;
Main entry;
/**
* KK: Used in the Binary Tree to Find and Delete entries.
* @param fullname concatenated first name and last name.
* @param entry The entry in the Binary Tree Node.
*/
public Main(String fullname, Main entry) {
this.fullname = fullname;
this.entry = entry;
}
/**
* KK: The constructor for the Binary Tree.
* @param fname first name.
* @param lname last name.
* @param email email.
* @param pnum phone number.
*/
Main(String fname, String lname, String email, String pnum) {
this.fullname = (fname + " " + lname).toUpperCase();
this.email = email;
this.pnum = pnum;
}
/**
* KK: Begins the execution of the program.
* @param args
*/
public static void main(String[] args) {
/**
* KK: Begins the Binary Tree test execution.
*/
Tree tree = new Tree();
tree.addEntry("Bob", "Smith", "[email protected]", "555-235-1111");
tree.addEntry("Jane", "Williams", "[email protected]", "555-235-1112");
tree.addEntry("Mohammed", "al-Salam", "[email protected]", "555-235-1113");
tree.addEntry("Pat", "Jones", "[email protected]", "555-235-1114");
tree.addEntry("Billy", "Kidd", "[email protected]", "555-235-1115");
tree.addEntry("H.", "Houdini", "[email protected]", "555-235-1116");
tree.addEntry("Jack", "Jones" , "[email protected]", "555-235-1117");
tree.addEntry("Jill", "Jones", "[email protected]", "555-235-1118");
tree.addEntry("John", "Doe", "[email protected]", "555-235-1119");
tree.addEntry("Jane", "Doe", "[email protected]", "555-235-1120");
tree.findEntry("Pat", "Jones");
tree.findEntry("Billy", "Kidd");
tree.deleteEntry("John", "Doe");
tree.addEntry("Test", "Case", "[email protected]", "555-235-1121");
tree.addEntry("Nadezhda", "Kanachekhovskaya", "[email protected]", "555-235-1122");
tree.addEntry("Jo", "Wu", "[email protected]", "555-235-1123");
tree.addEntry("Millard", "Fillmore", "[email protected]", "555-235-1124");
tree.addEntry("Bob", "vanDyke", "[email protected]", "555-235-1125");
tree.addEntry("Upside", "Down", "[email protected]", "555-235-1126");
tree.findEntry("Jack", "Jones");
tree.findEntry("Nadezhda", "Kanachekhovskaya");
tree.deleteEntry("Jill", "Jones");
tree.deleteEntry("John", "Doe");
tree.findEntry("Jill", "Jones");
tree.findEntry("John", "Doe");
/**
* KK: Begins the Hash Table test execution.
*/
Table hashtable = new Table(13);
hashtable.addEntry("Bob", "Smith", "[email protected]", "555-235-1111");
hashtable.addEntry("Jane", "Williams", "[email protected]", "555-235-1112");
hashtable.addEntry("Mohammed", "al-Salam", "[email protected]", "555-235-1113");
hashtable.addEntry("Pat", "Jones", "[email protected]", "555-235-1114");
hashtable.addEntry("Billy", "Kidd", "[email protected]", "555-235-1115");
hashtable.addEntry("H.", "Houdini", "[email protected]", "555-235-1116");
hashtable.addEntry("Jack", "Jones" , "[email protected]", "555-235-1117");
hashtable.addEntry("Jill", "Jones", "[email protected]", "555-235-1118");
hashtable.addEntry("John", "Doe", "[email protected]", "555-235-1119");
hashtable.addEntry("Jane", "Doe", "[email protected]", "555-235-1120");
hashtable.findEntry("Pat", "Jones");
hashtable.findEntry("Billy", "Kidd");
hashtable.deleteEntry("John", "Doe");
hashtable.addEntry("Test", "Case", "[email protected]", "555-235-1121");
hashtable.addEntry("Nadezhda", "Kanachekhovskaya", "[email protected]", "555-235-1122");
hashtable.addEntry("Jo", "Wu", "[email protected]", "555-235-1123");
hashtable.addEntry("Millard", "Fillmore", "[email protected]", "555-235-1124");
hashtable.addEntry("Bob", "vanDyke", "[email protected]", "555-235-1125");
hashtable.addEntry("Upside", "Down", "[email protected]", "555-235-1126");
hashtable.findEntry("Jack", "Jones");
hashtable.findEntry("Nadezhda", "Kanachekhovskaya");
hashtable.deleteEntry("Jill", "Jones");
hashtable.deleteEntry("John", "Doe");
hashtable.findEntry("Jill", "Jones");
hashtable.findEntry("John", "Doe");
}
}
| DaeData/Java_Data_Structures | Main.java | 1,900 | /**
* KK: Used in the Binary Tree to Find and Delete entries.
* @param fullname concatenated first name and last name.
* @param entry The entry in the Binary Tree Node.
*/ | block_comment | en | true |
11454_1 | package com.selenium.s1;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import io.github.bonigarcia.wdm.WebDriverManager;
public class d41 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
WebDriverManager.chromedriver().setup();
ChromeOptions co=new ChromeOptions();
co.addArguments("--remote-allow-origins=*");
WebDriver driver=new ChromeDriver(co);
driver.get("https://demo.opencart.com/index.php?route=account/register&language=en-gb");
driver.manage().window().maximize();
Thread.sleep(3000);
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,2000)");
WebElement fn=driver.findElement(By.id("input-firstname"));
fn.sendKeys("Maha");
WebElement ln=driver.findElement(By.id("input-lastname"));
ln.sendKeys("jamindar");
WebElement em=driver.findElement(By.id("input-email"));
em.sendKeys("[email protected]");
WebElement pw=driver.findElement(By.id("input-password"));
pw.sendKeys("jamin@03");
WebElement sub=driver.findElement(By.id("input-newsletter-yes"));
sub.click();
}
}
| Naveenm03/selenium1 | d41.java | 414 | //demo.opencart.com/index.php?route=account/register&language=en-gb");
| line_comment | en | true |
12566_1 | //check if a linkedlist is palindrome or not
class LL {
node head;
class node {
int data;
node next;
node(int data) {
this.data = data;
this.next = null;
}
}
/*
* steps:
* 1. find middle of LL
* 2. reverse 2nd half
* 3. check 1st and 2nd half
*/
public void addlast(int data) {
node newnode = new node(data);
if (head == null) {
head = newnode;
}
node curr = head;
while (curr.next != null) {
curr = curr.next;
}
curr.next = newnode;
}
public node reverse(node head) {
node prev = null;
node curr = head;
node next = null;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
public node findmiddle(node head) {
node hare = head;
node turtle = head;
while (hare.next.next != null && hare.next != null) {
hare = hare.next.next;
turtle = turtle.next;
}
return turtle;
}
public boolean isPalindrome(node head) {
if (head == null || head.next == null) {
return true;
}
node middle = findmiddle(head);// end of 1st half
node secondstart = reverse(middle.next);
node firststart = head;
while (secondstart != null) {
if (firststart.data != secondstart.data) {
return false;
}
firststart = firststart.next;
secondstart = secondstart.next;
}
return true;
}
}
class sol{
public static void main(String[] args) {
LL list = new LL();
list.addlast(1);
list.addlast(2);
list.addlast(2);
list.addlast(1);
System.out.println("is palindrome"+list.isPalindrome(list.head));
}
} | GAGANDASH002/Java-DSA | q4.java | 510 | /*
* steps:
* 1. find middle of LL
* 2. reverse 2nd half
* 3. check 1st and 2nd half
*/ | block_comment | en | false |
13150_9 | package LumberYard;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
/**
* LumberYard Log class.
*/
public class Log{
private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss +SSS'ms' '['z']'").withZone(ZoneId.systemDefault());
private static final String DEFAULT_DIR = System.getProperty("user.dir")+System.getProperty("file.separator")+"lumberyard";
/**
* Get the default directory used when creating a log without a specified directory.
*
* @return the string
*/
public static String getDefaultDirectory(){
return DEFAULT_DIR;
}
/**
* Convert a throwable into a structured string.
*
* @param e the throwable
* @return the structured string
*/
public static String parseThrowable(Throwable e) {
StringBuilder sb = new StringBuilder();
sb.append(e.getClass().getName()+(e.getMessage()!=null?": "+e.getMessage():""));
for (StackTraceElement element : e.getStackTrace()) {
sb.append("\n\tat ");
sb.append(element.toString());
}
if(e.getCause()!=null){
sb.append("\nCaused by: ");
sb.append(parseThrowable(e.getCause()));
}
return sb.toString();
}
private static Log defaultLog = null;
/**
* Get the default log.
*
* @return the default log
*/
public static Log getDefault(){
if(defaultLog == null){
defaultLog = new Log(Thread.currentThread().getName());
}
return defaultLog;
}
private String name, dir;
private Path path;
/**
* Flag to mirror new log entries to the System.out console after the log file.
*/
public boolean console = true;
/**
* Instantiates a new unnamed Log in the default directory.
*/
public Log(){
this(null);
}
/**
* Instantiates a new Log with a specified name.
*
* @param name the name
*/
public Log(String name){
this(DEFAULT_DIR, name);
}
/**
* Instantiates a new Log with a specified name in a specified directory.
*
* @param dir the dir
* @param name the name
*/
public Log(String dir, String name){
this.name = name;
this.dir = dir;
timestampName();
generatePath();
}
private void generatePath(){
if(name == null){
timestampName();
}
if(dir == null){
dir = getDefaultDirectory();
}
path = Path.of(getDirectory() + System.getProperty("file.separator") + getName() + ".log");
}
/**
* Get the directory of the log.
*
* @return the directory
*/
public String getDirectory(){
return dir;
}
/**
* Get the name of the log.
*
* @return the name
*/
public String getName(){
return name;
}
/**
* Get the full path of the log.
*
* @return the path
*/
public Path getPath(){
return path;
}
private void timestampName(){
DateTimeFormatter stamp = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").withZone(ZoneId.systemDefault());
name = ((name !=null) ? name + "_" : "") + stamp.format(Instant.now());
}
/**
* Write a categorized message to the log.
*
* @param category the category
* @param message the message
*/
public void write(Category category, String message){
if(category.isEnabled()){
println(category + " | "+ message);
}
}
/**
* Write a throwable to the log.
*
* @param e the throwable
*/
public void write(Throwable e){
if(Category.ERROR.isEnabled()){
println(Category.ERROR +" | "+ parseThrowable(e));
}
}
/**
* Write a blank line to the log.
*/
protected void println(){
try{
Files.write(path, "\n".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch(Exception e){
e.printStackTrace();
}
if(console){
System.out.println();
}
}
/**
* Timestamp and write multiple lines to the log.
*
* @param lines the lines
*/
protected void println(String...lines){
for(String line:lines){
println(line);
}
}
/**
* Timestamp and write a line to the log.
*
* @param line the message
*/
protected void println(String line){
line = TIMESTAMP_FORMATTER.format(Instant.now()) + " | Thread: " +Thread.currentThread().getName()+" | " + line + "\n";
try{
Files.write(path, line.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch(Exception e){
e.printStackTrace();
}
if(console){
System.out.print(line);
}
}
/**
* Make the log the default log.
*/
public void makeDefault(){
defaultLog = this;
}
/**
* Categories of log messages.
*/
public enum Category{
/**
* Info category. Enabled by default.
*/
INFO(),
/**
* Warning category. Enabled by default.
*/
WARNING(),
/**
* Error category. Enabled by default.
*/
ERROR(),
/**
* Debug category. Disabled by default.
*/
DEBUG(false),
/**
* Verbose category. Disabled by default.
*/
VERBOSE(false);
private boolean enabled;
Category(){
this(true);
}
Category(boolean enabled){
this.enabled = enabled;
}
/**
* Enable the category.
*/
public void enable(){
this.enabled = true;
}
/**
* Disable the category.
*/
public void disable(){
this.enabled = false;
}
/**
* Check if the category is enabled.
*
* @return true if the category is enabled.
*/
public boolean isEnabled(){
return enabled;
}
}
}
| YoungGopher/LumberYard | Log.java | 1,600 | /**
* Get the name of the log.
*
* @return the name
*/ | block_comment | en | false |
13299_0 | /*Write a program to input 10 integer elements in an array and sort them in ascending order using the bubble sort technique*/
import java.io.*;
class YT6
{
public static void main(String[] args)throws IOException
{
int a[]= new int[10];
int t=0;
InputStreamReader I = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(I);
System.out.println("Enter the array: ");
for(int i=0; i<10; i++)
{
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("Original Array");
for(int i=0; i<10; i++)
{
System.out.print(a[i]+ " ");
}
for(int i=0; i<9; i++)
{
for(int j=0; j<9-i; j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
System.out.println();
System.out.println("Sorted Array");
for(int i=0; i<10; i++)
{
System.out.print(a[i]+ " ");
}
}
}
| iankitnegi/CodeJava | YT6.java | 316 | /*Write a program to input 10 integer elements in an array and sort them in ascending order using the bubble sort technique*/ | block_comment | en | true |
13354_0 | /*Design and implement a data structure for a compressed string iterator. It should support the following operations: next and hasNext.
The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.
next() - if the original string still has uncompressed characters, return the next letter; Otherwise return a white space.
hasNext() - Judge whether there is any letter needs to be uncompressed.
Note:
Please remember to RESET your class variables declared in StringIterator, as static/class variables are persisted across multiple test cases. Please see here for more details.
Example:
StringIterator iterator = new StringIterator("L1e2t1C1o1d1e1");
iterator.next(); // return 'L'
iterator.next(); // return 'e'
iterator.next(); // return 'e'
iterator.next(); // return 't'
iterator.next(); // return 'C'
iterator.next(); // return 'o'
iterator.next(); // return 'd'
iterator.hasNext(); // return true
iterator.next(); // return 'e'
iterator.hasNext(); // return false
iterator.next(); // return ' '
*/
| wxping715/LeetCode | 604.java | 275 | /*Design and implement a data structure for a compressed string iterator. It should support the following operations: next and hasNext.
The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.
next() - if the original string still has uncompressed characters, return the next letter; Otherwise return a white space.
hasNext() - Judge whether there is any letter needs to be uncompressed.
Note:
Please remember to RESET your class variables declared in StringIterator, as static/class variables are persisted across multiple test cases. Please see here for more details.
Example:
StringIterator iterator = new StringIterator("L1e2t1C1o1d1e1");
iterator.next(); // return 'L'
iterator.next(); // return 'e'
iterator.next(); // return 'e'
iterator.next(); // return 't'
iterator.next(); // return 'C'
iterator.next(); // return 'o'
iterator.next(); // return 'd'
iterator.hasNext(); // return true
iterator.next(); // return 'e'
iterator.hasNext(); // return false
iterator.next(); // return ' '
*/ | block_comment | en | true |
14391_1 | /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
private List<Integer> nodes;
private int counter;
public BSTIterator(TreeNode root) {
this.nodes = new ArrayList();
this.counter = 0;
this.inorderTraverse(root);
}
private void inorderTraverse(TreeNode root){
if(root == null) return;
this.inorderTraverse(root.left);
this.nodes.add(root.val);
this.inorderTraverse(root.right);
}
public int next() {
return this.nodes.get(this.counter++);
}
public boolean hasNext() {
return this.counter < this.nodes.size();
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/ | iamtanbirahmed/100DaysOfLC | 173.java | 320 | /**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/ | block_comment | en | true |
14627_0 | /* Copyright 2010 Brian Mock
*
* This file is part of visint.
*
* visint 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.
*
* visint 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 visint. If not, see <http://www.gnu.org/licenses/>.
*/
import javax.media.opengl.GL;
/**
* This class draws the x, y, and z axes.
* @author Brian Mock
*/
public class Axes {
private Line xAxis;
private Line yAxis;
private Line zAxis;
private float length = 1000;
private float[] xEnd = {length, 0, 0 };
private float[] yEnd = {0, length, 0 };
private float[] zEnd = {0, 0, length};
private float[] origin = {0, 0, 0};
private float[] xColor = Colors.RED;
private float[] yColor = Colors.GREEN;
private float[] zColor = Colors.BLUE;
public
Axes() {
xAxis = new Line(origin, xEnd, xColor);
yAxis = new Line(origin, yEnd, yColor);
zAxis = new Line(origin, zEnd, zColor);
}
public void
draw(GL gl) {
xAxis.draw(gl);
yAxis.draw(gl);
zAxis.draw(gl);
}
}
| wavebeem/visint | Axes.java | 451 | /* Copyright 2010 Brian Mock
*
* This file is part of visint.
*
* visint 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.
*
* visint 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 visint. If not, see <http://www.gnu.org/licenses/>.
*/ | block_comment | en | true |
14639_1 | /* Copyright 2010 Brian Mock
*
* This file is part of visint.
*
* visint 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.
*
* visint 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 visint. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.*;
/**
* This program controls printing debugging output (or not!).
* @author Brian Mock
*/
public class Debug {
public static boolean debug = false;
private static String separator =
"========================================";
public static void error (String s) { if (debug) System.err.println(s); }
public static void println (String s) { if (debug) System.out.println(s); }
public static void print (String s) { if (debug) System.out.print (s); }
public static void printAry(Object[] ary) { println(Arrays.deepToString(ary)); }
public static void printSep() { println(separator); }
}
| wavebeem/visint | Debug.java | 356 | /**
* This program controls printing debugging output (or not!).
* @author Brian Mock
*/ | block_comment | en | false |
15357_1 | import java.text.ParseException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.MaskFormatter;
/**
* Exemplos CPF válidos:
* <p>
* 123.456.789-09 (12345678909)<br>
* 123.123.123-87 (12312312387)<br>
* 111.222.333-96 (11122233396)
*/
public class Cpf {
public static final String MASCARA = "###.###.###-##";
public static final int TAMANHO_APENAS_NUMEROS = 11;
public static boolean validaCpf(String cpf) {
if (cpf == null || cpf.isEmpty())
return false;
Pattern pattern = Pattern
.compile("(\\d)(\\d)(\\d)\\.?(\\d)(\\d)(\\d)\\.?(\\d)(\\d)(\\d)-?(\\d)(\\d)");
Matcher matcher = pattern.matcher(cpf);
if (!matcher.matches())
return false;
int[] digitos = new int[11];
for (int i = 0; i < digitos.length; i++) {
digitos[i] = Integer.parseInt(matcher.group(i + 1));
}
int resul1 = 0;
int resul2 = 0;
for (int i = 0; i < 9; i++)
resul1 = (10 - i) * digitos[i] + resul1;
resul1 = resul1 % 11;
if (resul1 == 0 || resul1 == 1)
resul1 = 0;
else
resul1 = 11 - resul1;
if (resul1 == digitos[9]) {
for (int i = 0; i < 10; i++)
resul2 = (11 - i) * digitos[i] + resul2;
resul2 = resul2 % 11;
if (resul2 == 0 || resul2 == 1)
resul2 = 0;
else
resul2 = 11 - resul2;
if (resul2 == digitos[10])
return true;
}
return false;
}
/**
* @return um CPF aleatório e válido.
* @since Jan 15, 2015
* @author Ulisses
*/
public static String gerarCpf() {
int digito1 = 0, digito2 = 0, resto = 0;
String nDigResult;
String numerosContatenados;
String numeroGerado;
Random numeroAleatorio = new Random();
// números gerados
int n1 = numeroAleatorio.nextInt(10);
int n2 = numeroAleatorio.nextInt(10);
int n3 = numeroAleatorio.nextInt(10);
int n4 = numeroAleatorio.nextInt(10);
int n5 = numeroAleatorio.nextInt(10);
int n6 = numeroAleatorio.nextInt(10);
int n7 = numeroAleatorio.nextInt(10);
int n8 = numeroAleatorio.nextInt(10);
int n9 = numeroAleatorio.nextInt(10);
int soma = n9 * 2 + n8 * 3 + n7 * 4 + n6 * 5 + n5 * 6 + n4 * 7 + n3 * 8
+ n2 * 9 + n1 * 10;
int valor = (soma / 11) * 11;
digito1 = soma - valor;
// Primeiro resto da divisão por 11.
resto = (digito1 % 11);
if (digito1 < 2) {
digito1 = 0;
} else {
digito1 = 11 - resto;
}
int soma2 = digito1 * 2 + n9 * 3 + n8 * 4 + n7 * 5 + n6 * 6 + n5 * 7
+ n4 * 8 + n3 * 9 + n2 * 10 + n1 * 11;
int valor2 = (soma2 / 11) * 11;
digito2 = soma2 - valor2;
// Primeiro resto da divisão por 11.
resto = (digito2 % 11);
if (digito2 < 2) {
digito2 = 0;
} else {
digito2 = 11 - resto;
}
// Concatenando os números
numerosContatenados = String.valueOf(n1) + String.valueOf(n2)
+ String.valueOf(n3) + String.valueOf(n4) + String.valueOf(n5)
+ String.valueOf(n6) + String.valueOf(n7) + String.valueOf(n8)
+ String.valueOf(n9);
// Concatenando o primeiro resto com o segundo.
nDigResult = String.valueOf(digito1) + String.valueOf(digito2);
numeroGerado = numerosContatenados + nDigResult;
return numeroGerado;
}
/**
* @param cpf
* @return o cpf com máscara.
* @since Aug 29, 2013
* @author Ulisses
*/
public static String aplicarMascara(String cpf) {
if (cpf == null)
return null;
MaskFormatter mf;
try {
mf = new MaskFormatter(MASCARA);
mf.setValueContainsLiteralCharacters(false);
return mf.valueToString(cpf);
} catch (ParseException e) {
return cpf;
}
}
/**
* @param cpf
* @return o cpf sem a máscara (apenas números)
* @since Aug 29, 2013
* @author Ulisses
*/
public static String removerMascara(String cpf) {
if (cpf == null)
return null;
return cpf.replaceAll("\\D", "");
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
String cpf = gerarCpf();
boolean valido = validaCpf(cpf);
System.out.println(cpf + " - " + valido);
}
}
}
| ulisseslima/bash-utils | Cpf.java | 1,708 | /**
* @return um CPF aleatório e válido.
* @since Jan 15, 2015
* @author Ulisses
*/ | block_comment | en | true |
16414_1 | import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author 21cse095
*/
public class school {
public static void main(String[] args){
person obj = new student();
System.out.print("STUDENT DETAILS : ");
obj.getdata();
obj.display();
person obj1 = new faculty();
System.out.print("FACULTY DETAILS : ");
obj1.getdata();
obj1.display();
}
}
abstract class person{
abstract void getdata();
abstract void display();
}
class student extends person{
String name;
int aadhar;
int n, total = 0, avg;
void getdata(){
Scanner s = new Scanner(System.in);
System.out.print("Enter Name:");
name = s.next();
System.out.print("Enter aadhar number:");
aadhar = s.nextInt();
System.out.print("Enter no. of subject:");
n = s.nextInt();
int marks[] = new int[n];
System.out.println("Enter marks out of 100:");
for(int i = 0; i < n; i++)
{
marks[i] = s.nextInt();
total = total + marks[i];
}
avg = total / n;
}
void display() {
System.out.println("....DETAILS....");
System.out.println("Name:"+name);
System.out.println("aadharno:"+aadhar);
System.out.println("total:"+total);
System.out.println("average:"+avg);
}
}
class faculty extends person{
String name;
int aadhar;
int id;
String dept;
int Salary;
void getdata() {
Scanner s = new Scanner(System.in);
System.out.print("Enter Name:");
name = s.next();
System.out.print("Enter aadhar number:");
aadhar = s.nextInt();
System.out.print("Enter ID:");
id = s.nextInt();
System.out.print("Enter department:");
dept = s.next();
System.out.print("Enter Salary:");
Salary = s.nextInt();
}
void display() {
System.out.println("....DETAILS....");
System.out.println("Name:"+name);
System.out.println("aadharno:"+aadhar);
System.out.println("id:"+id);
System.out.print("department:"+dept);
System.out.println("salary:"+Salary);
}
} | 21cse095/javacode | ex4/ex.java | 652 | /**
*
* @author 21cse095
*/ | block_comment | en | true |
16462_0 | import java.util.ArrayList;
import java.io.*;
public class Driver {
private static ArrayList<Student> studentList;
private static ArrayList<String> schoolList;
public ArrayList<Student> getStudentList() {
return this.studentList;
}
public void setStudentList(ArrayList<Student> studentList) {
this.studentList = studentList;
}
/*
Reads data from the csv file and creates a Student and stores
it in the list.
*/
public static void csvToList(File csvFile) {
try {
studentList = new ArrayList<Student>();
schoolList = new ArrayList<String>();
String row;
BufferedReader csvReader = new BufferedReader(new FileReader(csvFile));
while ((row = csvReader.readLine()) != null) {
String[] rawStudent = row.split(",");
Student student = new Student(Integer.valueOf(rawStudent[0]), rawStudent[1], rawStudent[2]);
studentList.add(student);
if (!schoolList.contains(rawStudent[2])) {
schoolList.add(rawStudent[2]);
}
}
csvReader.close();
} catch (Exception e) {
System.out.println("Error");
}
}
/*
Creates and write to a .txt file.
Tab delimited.
Does this for one school.
*/
public static void tsvForSchool(String school) {
File tsv = new File("data/" + school + ".txt");
String TAB = "\t";
String EOL = "\n";
try {
FileWriter tsvWriter = new FileWriter(tsv);
for (int i = 0; i < studentList.size(); i++) {
StringBuilder sb = new StringBuilder();
if (studentList.get(i).getSchool().equals(school)) {
sb.append(studentList.get(i).getId());
sb.append(TAB);
sb.append(studentList.get(i).getName());
sb.append(TAB);
sb.append(school + EOL);
tsvWriter.write(sb.toString());
}
}
tsvWriter.close();
} catch (IOException e) {
System.out.println("Error");
}
}
public static void main(String[] args) {
File testFile = new File("testFile.csv");
csvToList(testFile);
for (int i = 0; i < schoolList.size(); i++) {
tsvForSchool(schoolList.get(i));
}
}
} | mattspahr/CSV-to-Tab | Driver.java | 630 | /*
Reads data from the csv file and creates a Student and stores
it in the list.
*/ | block_comment | en | false |
16477_5 | /*
Prompts a frame that asks the user for their personal information and inputs it into a list to be accessed from again
at a later time. Primarily asks for their first and last name, school name, what type of school they are in, and what
quarter or semester they are in currently. Depending on their answers, different choices will show.
@author Nhi Ngo
@version 06/15/2014
*/
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
public class Asking extends Program implements ActionListener{
private JPanel questions;
private JTextPane intro;
private JPanel quarterHS;
private int highS;
private int colle;
private int placeholder;
private JPanel quarterC;
private JPanel overallInfo;
private JPanel userInfo;
private JPanel schoolAsk;
private JPanel empty;
private JPanel overall;
private int quarterNum;
private JPanel info;
private JTextField firstName;
private JTextField lastName;
private JTextField schoolName;
private ArrayList<String> names;
/*Intializes all instance fields*/
public Asking() {
highS = 0;
colle = 0;
placeholder = 0;
questions = new JPanel(new BorderLayout());
overallInfo = new JPanel (new BorderLayout());
userInfo = new JPanel(new GridLayout(1,6));
empty = new JPanel();
schoolAsk = new JPanel (new GridLayout(3,1));
quarterHS = new JPanel(new FlowLayout());
quarterC = new JPanel(new FlowLayout());
overall = new JPanel(new GridLayout(1,1));
info = new JPanel(new BorderLayout());
overall.add(quarterC);
overall.add(quarterHS);
info.add(overall, BorderLayout.NORTH);
overallInfo.add(info, BorderLayout.SOUTH);
names = new ArrayList<String>();
}
/*Adds all components regarding asking the user into the main visual panel for the user to interact and read*/
public JPanel ask() {
questions.add(empty, BorderLayout.CENTER);
intro = introText();
questions.add(intro, BorderLayout.NORTH);
personalInfo();
schoolAsk();
overallInfo.add(userInfo, BorderLayout.NORTH);
overallInfo.add(schoolAsk, BorderLayout.CENTER);
questions.add(overallInfo, BorderLayout.SOUTH);
return questions;
}
/*
*Creates and set a label
*@param name the text that will display on the label
*/
private JLabel label(String name) {
JLabel label = new JLabel(name, JLabel.CENTER);
label.setPreferredSize(new Dimension(80, 15));
return label;
}
/*Creates and set the settings of textfield*/
private JTextField text(){
JTextField text = new JTextField();
text.setPreferredSize(new Dimension(85, 20));
return text;
}
/*Shows the introduction text to the user. Primarily is instructions and information to the user*/
private JTextPane introText() {
JTextPane text = new JTextPane();
text.setEditable(false);
text.setText(" Welcome to Personal Secretary Student Version! Before we start organizing your schedule and\n time, let's set up your profile so you can access it again. All we need is basic information. \n You can edit this information later in the settings option. If you do not wish to answer, feel\n free to leave it blank.");
return text;
}
/*Prompts the user for personal information*/
private void personalInfo() {
JLabel fName = label("First Name");
JLabel lName = label("Last Name");
JLabel sName = label("School Name");
firstName = text();
lastName = text();
schoolName = text();
userInfo.add(fName);
userInfo.add(firstName);
userInfo.add(lName);
userInfo.add(lastName);
userInfo.add(sName);
userInfo.add(schoolName);
}
/*Asks the user about school information and different panels will display according to user's choice*/
private void schoolAsk(){
schoolAsk = new JPanel(new GridLayout(1, 3));
JLabel question = new JLabel ("What school are you in?", JLabel.CENTER);
JRadioButton highSchool = radioButton ("High School");
JRadioButton college = radioButton ("College");
schoolAsk.add(question);
ButtonGroup group = new ButtonGroup();
group.add(highSchool);
group.add(college);
schoolAsk.add(highSchool);
schoolAsk.add(college);
}
/*If the user is in high school, choices of semesters will appear*/
private void highSchool(){
overall.remove(quarterC);
overall.revalidate();
colle += 2;
if (highS == 0) {
JRadioButton firstSem = radioButton("1st Semester");
JRadioButton secondSem = radioButton("2nd Semester");
ButtonGroup group = new ButtonGroup();
group.add(firstSem);
group.add(secondSem);
quarterHS.add(firstSem);
quarterHS.add(secondSem);
}
if(highS == 0 || highS % 2 == 0) {
overall.add(quarterHS);
}
overall.revalidate();
}
/*If user is in college, choices to choose quarters will be visible*/
private void college() {
overall.remove(quarterHS);
overall.revalidate();
highS += 2;
if (colle <= 2) {
JRadioButton fall = radioButton("Fall");
JRadioButton winter = radioButton("Winter");
JRadioButton spring = radioButton("Spring");
JRadioButton summer = radioButton("Summer");
ButtonGroup group = new ButtonGroup();
group.add(fall);
group.add(winter);
group.add(spring);
group.add(summer);
quarterC.add(fall);
quarterC.add(winter);
quarterC.add(spring);
quarterC.add(summer);
}
if(colle == 0 || colle % 2 == 0) {
overall.add(quarterC);
}
overall.revalidate();
}
/*Adds a button of "next" for the user to continue*/
private void next() {
JButton next = button("Continue");
info.add(next, BorderLayout.CENTER);
setNames();
overall.revalidate();
}
/*Add user's info onto arrayList*/
public void setNames() {
names = new ArrayList<String>();
names.add(firstName.getText());
names.add(lastName.getText());
names.add(schoolName.getText());
}
/*
*Creates a radio button
*@param name the text that labels the button
*/
private JRadioButton radioButton(String name){
JRadioButton box = new JRadioButton(name);
box.setSelected(false);
box.addActionListener(this);
return box;
}
/*
*Creates and set the settings for button
*@param name the text that will appear on the button
*/
private JButton button(String name) {
JButton button = new JButton(name);
button.setText(name);
button.setBackground(Color.WHITE);
button.addActionListener(this);
return button;
}
/*Depending on which button user picks, the listener will react differently*/
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("High School")) {
highSchool();
} else if(event.getActionCommand().equals("College")) {
college();
} else if (event.getActionCommand().equals("Continue")){
questions.setVisible(false);
super.classInfo(names, quarterNum);
} else{
if(event.getActionCommand().equals("Fall")){
quarterNum = 1;
placeholder++;
} else if(event.getActionCommand().equals("Winter")){
quarterNum = 2;
placeholder++;
} else if(event.getActionCommand().equals("Spring")) {
quarterNum = 3;
placeholder++;
} else if(event.getActionCommand().equals("Summer")) {
quarterNum = 4;
placeholder++;
} else if(event.getActionCommand().equals("1st Semester")) {
quarterNum = 5;
placeholder++;
} else if(event.getActionCommand().equals("2nd Semester")) {
quarterNum = 6;
placeholder++;
}
if (placeholder == 1) {
next();
}
}
}
} | rooseveltcs/personal-secretary | Asking.java | 1,925 | /*Shows the introduction text to the user. Primarily is instructions and information to the user*/ | block_comment | en | false |
16795_0 | // https://www.hackerrank.com/challenges/java-1d-array-introduction/problem
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] a = new int[n];
for(int j=0;j<n;j++)
{
a[j] = scan.nextInt();
}
scan.close();
// Prints each sequential element in array a
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
| haytastan/Hackerrank_Java | 19.java | 154 | // https://www.hackerrank.com/challenges/java-1d-array-introduction/problem | line_comment | en | true |
16890_0 |
/**
* Klasse Greifarm.
*
* @author [email protected]
*
* @version v4.0 (2018-08-7)
*/
public class Greifarm
{
private ea.edu.Dreieck stativ;
private ea.edu.Kreis drehpunkt;
private ea.edu.Rechteck arm;
private Kugel gegriffeneKugel;
private int winkel;
private java.util.LinkedList<Kugel> kugeln;
private boolean hatKugel;
private Eimer rechts;
private Eimer links;
/**
* Konstruktor der Klasse Greifarm
*/
public Greifarm()
{
this.stativ = new ea.edu.Dreieck( -50,-300 , 50,-300 , 0,-100 );
this.stativ.setzeFarbe( "grau" );
this.stativ.getActor().setLayer( 5 );
this.drehpunkt = new ea.edu.Kreis( 15 );
this.drehpunkt.setzeFarbe( "grau" );
this.drehpunkt.setzeMittelpunkt( 0 , -100 );
this.drehpunkt.getActor().setLayer( 5 );
this.arm = new ea.edu.Rechteck( 300 , 10 );
this.arm.setzeFarbe( "grau" );
this.arm.setzeMittelpunkt( 150 , -100 );
this.gegriffeneKugel = new Kugel( 0, 0 );
this.gegriffeneKugel.setzeSichtbar( false );
this.gegriffeneKugel.macheNeutral();
this.winkel = 0;
this.hatKugel = false;
}
/**
* Dreht den Greifarm um den angegebenen Winkel.
* Gegen den Uhrzeigersinn = positive Winkel ; Mit dem Uhrzeigersinn = negativer Winkel
*
* @param winkel Der Winkel, um den gedreht werden soll
*/
public void drehenUm( int winkel )
{
this.winkel += winkel;
this.winkel %= 360;
this.arm.drehen( (float)Math.toRadians(winkel) ); ////////
this.arm.setzeMittelpunkt( (float)(150*Math.cos(Math.toRadians(this.winkel))) , (float)(150*Math.sin(Math.toRadians(this.winkel))-100) );
if ( this.hatKugel )
{
this.gegriffeneKugel.setzeMittelpunkt( (float)(315*Math.cos(Math.toRadians(this.winkel))) , (float)(315*Math.sin(Math.toRadians(this.winkel))-100) );
}
}
public void greifen()
{
if ( !this.hatKugel )
{
if ( this.arm.schneidet( this.kugeln.peekFirst() ) )
{
this.gegriffeneKugel = this.kugeln.removeFirst();
this.gegriffeneKugel.macheNeutral();
this.gegriffeneKugel.setzeMittelpunkt( (float)(315*Math.cos(Math.toRadians(this.winkel))) , (float)(315*Math.sin(Math.toRadians(this.winkel))-100) );
this.kugeln.addLast( new Kugel( -380 , 380 ) );
}
}
this.hatKugel = true;
}
/**
* Lässt die gegriffene Kugel los.
* Tut nichts, wenn gerade keine Kugel gegriffen wird.
*
*/
public void loslassen()
{
if ( this.hatKugel )
{
this.gegriffeneKugel.macheAktiv();
}
this.hatKugel = false;
}
/**
* Nennt die Farbe der aktuell gegriffenen Kugel.
* Wird gerade keine Kugel gegriffen, so wird "keine Kugel" gemeldet.
*
* @return Die Farbe der aktuell gegriffenen Kugel
*/
public String nenneFarbe()
{
String farbe = "keine Kugel";
if ( this.gegriffeneKugel != null )
{
farbe = this.gegriffeneKugel.nenneFarbe();
}
return farbe;
}
/**
* Nennt den aktuellen Drehwinkel des Greifarms.
*
* @return Der aktuelle Drehwinkel des Greifarms
*/
public int nenneWinkel()
{
return this.winkel;
}
/**
* Mit dieser Methode kann der Greifarm eine Referenz auf die Kugeln erhalten.
*
* @param kugeln Referenz auf die LinkedList von Kugeln der Klasse Greifi
*/
public void nimmReferenzAufKugeln( java.util.LinkedList<Kugel> kugeln )
{
this.kugeln = kugeln;
}
/**
* Mit dier Methode kann der Greifarm eine Referenz auf seine Eimer erhalten.
*
* @param links Referenz auf linken Eimer
* @param rechts Referenz auf rechen Eimer
*/
public void nimmReferenzAufEimer( Eimer links , Eimer rechts )
{
this.links = links;
this.rechts = rechts;
}
/**
* Gibt an, ob der Greifarm gerade eine Kugel hat oder leer ist.
*
* @return 'true' = hat Kugel ; 'false' = ist leer
*/
public boolean hatKugel()
{
return this.hatKugel;
}
// Ticker, der in Greifi angemeldet wurde
public void tick()
{
if ( this.gegriffeneKugel != null )
{
if ( this.gegriffeneKugel.nenneMy() < -250 )
{
if ( this.gegriffeneKugel.nenneMx() > 222 && this.gegriffeneKugel.nenneMx() < 333 )
{
this.gegriffeneKugel.setzeMittelpunkt( 2000 , 2000 );
this.rechts.erhoeheNummer();
}
else if ( this.gegriffeneKugel.nenneMx() < -222 && this.gegriffeneKugel.nenneMx() > -333 )
{
this.gegriffeneKugel.setzeMittelpunkt( 2000 , 2000 );
this.links.erhoeheNummer();
}
}
}
}
}
| engine-alpha/bluej-greifroboter | Greifarm.java | 1,758 | /**
* Klasse Greifarm.
*
* @author [email protected]
*
* @version v4.0 (2018-08-7)
*/ | block_comment | en | true |
16947_10 | import java.util.*;
public class SRT {
private ArrayList<Process> processes;
private ArrayList<Process> queue;
private Process shortest;
private ArrayList<Process> completed;
private static int QUANTA_MAX = 99;
private static int NUMBER_OF_PROCESSES_TO_MAKE = 30;
private int quanta;
private double totalTurnaroundTime;
private double totalWaitTime;
private double totalResponseTime;
private double processesFinished;
private String out;
public static void main(String[] args) {
ArrayList<Process> processes = new ArrayList<Process>();
for (int i = 1; i <= NUMBER_OF_PROCESSES_TO_MAKE; i++) {
Process process = new Process("P" + i, i);
processes.add(process);
}
Process.sortListByArrivalTime(processes);
SRT srt = new SRT(processes);
String table = "";
for (Process process : srt.getProcesses()) {
table += "[Process: " + String.format("%3s", process.getName()) + ", Arrival time: "
+ String.format("%3d", process.getArrivalTime()) + ", Run time: "
+ String.format("%3d", process.getGivenExecutionTime()) + ", Priority: " + process.getPriority()
+ ", End time: " + String.format("%3d", process.getEndTime()) + ", Time started: "
+ String.format("%3d", process.getStartExecutionTime()) + ", Turnaround time: "
+ String.format("%3d", process.calculateTurnaroundTime()) + ", Wait time: "
+ String.format("%3d", process.calculateWaitTime()) + ", Response time: "
+ String.format("%3d", process.calculateResponseTime()) + "]\n";
}
//System.out.println(table);
}
public SRT(ArrayList<Process> processes) {
this.processes = processes;
this.queue = new ArrayList<Process>();
this.shortest = null;
this.completed = new ArrayList<Process>();
run();
}
public ArrayList<Process> getProcesses() {
return this.completed;
}
private void run() {
quanta = 0;
totalTurnaroundTime = 0;
totalWaitTime = 0;
totalResponseTime = 0;
processesFinished = 0;
out = "";
while (quanta < QUANTA_MAX || !queue.isEmpty()) {
// Check the current time quanta, and add processes that arrive at the current time to the queue.
for (Process process : processes) {
if (process.getArrivalTime() <= quanta) {
queue.add(process);
// processes.remove(process);
}
}
processes.removeAll(queue);
// Preemptive code block.
if (!queue.isEmpty()) {
// Get the process in the queue with the lowest remaining execution time.
shortest = queue.get(0);
for (Process process : queue) {
if (process.getExecutionTimeRemaining() < shortest.getExecutionTimeRemaining()) {
shortest = process;
}
}
queue.remove(shortest);
// If the current shortest process has not started yet, start it.
if (shortest.getStartExecutionTime() < 0 && quanta < QUANTA_MAX) {
shortest.setStartExecutionTime(quanta);
}
// If the process has started
if (shortest.getStartExecutionTime() > -1) {
// Represent it in the timeline
out = out+ "[" + shortest.getName() + "]";
// Decrement the execution time remaining
shortest.decrementExecutionTimeRemaining();
// Move the time splice
quanta++;
// If the shortest process is done (execution time remaining == 0)
if (shortest.getExecutionTimeRemaining() <= 0) {
// Set its end time at the current quanta
shortest.setEndTime(quanta);
// Add the finished process to the completed list.
completed.add(shortest);
processesFinished++;
totalTurnaroundTime += shortest.calculateTurnaroundTime();
totalWaitTime += shortest.calculateWaitTime();
totalResponseTime += shortest.calculateResponseTime();
} else {
// The process is not done, add it back into the queue.
queue.add(shortest);
}
}
} else {
out = out+"[*]";
quanta++;
}
}
}
public String getAverages()
{
String averages = "\n" +"Averages turnaround time: " + totalTurnaroundTime / processesFinished +"\n"
+ "Average wait time: " + totalWaitTime / processesFinished +"\n" +
"Average response time: " + totalResponseTime / processesFinished +"\n"
+ "Throughput: " + processesFinished / quanta + " processes completed per quanta." +"\n";
/*System.out.println("\n");
System.out.println("Average turnaround time: " + totalTurnaroundTime / processesFinished);
System.out.println("Average wait time: " + totalWaitTime / processesFinished);
System.out.println("Average response time: " + totalResponseTime / processesFinished);
System.out.println("Throughput: " + processesFinished / quanta + " processes completed per quanta.");
System.out.println();*/
return averages;
}
public String getOut()
{
out = out +"\n";
return out;
}
} | devstudent123/Scheduling-Algorithms | SRT.java | 1,363 | // If the shortest process is done (execution time remaining == 0)
| line_comment | en | false |
17021_0 | /**
*
* I declare that this code was written by me, 21011805.
* I will not copy or allow others to copy my code.
* I understand that copying code is considered as plagiarism.
*
* Student Name: Leticia Linus Jeraled
* Student ID: 21011805
* Class: E63D
* Date created: 2023-Jan-20 12:37:47 pm
*
*/
package FYP;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* @author 21011805
*
*/
@Entity
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotNull
@NotEmpty(message = "Backend: member name cannot be empty")
@Size(min = 3, max = 50, message = "Name length must be between 3 and 50 characters!")
private String name;
@NotNull
@NotEmpty(message = "Backend: member username cannot be empty")
@Size(min = 3, max = 50, message = "Username length must be between 3 and 50 characters!")
private String username;
@NotNull
@NotEmpty(message = "Backend: member password cannot be empty")
@Size(min = 5, max = 100, message = "Password length must be between 5 and 100 characters!")
private String password;
@NotNull
@NotEmpty(message = "Backend: member email cannot be empty")
@Size(min = 5, max = 50, message = "Email length must be between 5 and 50 characters!")
private String email;
private String role;
private int banCount;
private boolean isBanned;
private double totalSpending = 0.0;
@OneToMany(mappedBy = "member")
private List<OrderItem> orderItems;
@OneToMany(mappedBy = "member")
private Set<Item> items;
@OneToMany(mappedBy = "member") // Refers to the "member" property in the Review class
private List<Review> reviews; // This represents the reviews written by the member
private String imgName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public int getBanCount() {
return banCount;
}
public void setBanCount(int banCount) {
this.banCount = banCount;
}
public boolean isBanned() {
return isBanned;
}
public void setBanned(boolean isBanned) {
this.isBanned = isBanned;
}
public double getTotalSpending() {
return totalSpending;
}
public void setTotalSpending(double totalSpending) {
this.totalSpending = totalSpending;
}
public List<OrderItem> getOrderItems() {
return orderItems;
}
public void setOrderItems(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
public Set<Item> getItems() {
return items;
}
public void setItems(Set<Item> items) {
this.items = items;
}
public List<Review> getReviews() {
return reviews;
}
public void setReviews(List<Review> reviews) {
this.reviews = reviews;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
}
| 21011805-LeticiaLinusJeraled/FYP | Member.java | 1,181 | /**
*
* I declare that this code was written by me, 21011805.
* I will not copy or allow others to copy my code.
* I understand that copying code is considered as plagiarism.
*
* Student Name: Leticia Linus Jeraled
* Student ID: 21011805
* Class: E63D
* Date created: 2023-Jan-20 12:37:47 pm
*
*/ | block_comment | en | true |
17979_0 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
/**
*
* @author User
*/
class br {
static String readLine() {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
static void close() {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
}
| l0vnurul/100days | br.java | 149 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/ | block_comment | en | true |
18110_0 | /*Study the Human class carefully.
Correct the class so that only one initialize method initializes all the Human class's instance variables.
Requirements:
The Human class must have 5 variables.
The class must have one initialize method.
The initialize method must have five parameters. */
/*
Initializing objects
*/
public class Human {
String name;
char sex;
int money;
int weight;
double size;
public void initialize(String name, int money, char sex,int weight,double size) {
this.name = name;
this.money = money;
this.sex = sex;
this.weight = weight;
this.size = size;
}
public static void main(String[] args) {
}
}
| samira-nooreen/JavaPracticeProblems | Q40.java | 168 | /*Study the Human class carefully.
Correct the class so that only one initialize method initializes all the Human class's instance variables.
Requirements:
The Human class must have 5 variables.
The class must have one initialize method.
The initialize method must have five parameters. */ | block_comment | en | true |
18261_5 | public class oop {
public static void main(String[] args) {
Pen p1= new Pen();// create a pen obj called p1
p1.size=5;
System.out.println("Pen Size: "+p1.size);
p1.color="Yellow";
System.out.println("Pen Color: "+p1.color);
p1.setColor("Red"); //using setter function instead of direct assignment
System.out.println("New Pen Color after using Setter Function :"+p1.getcolor());
p1.setSize(8);//Using getter functions in place of accessing member variable directly
System.out.println("Updated pen size:"+p1.getsize());
BankAccount myAcc= new BankAccount();
//myAcc is an object of the type "BankAccount" and it has two instance variables
myAcc.usearname="Subhajyoti";
//myAcc.passwors="<PASSWORD>"; Not allowed to access the password directly from
//outside of this object, hence we need a method for setting it
myAcc.setpassword("<PASSWORD>");
}
}
//Getter and Setters
//Get:to return value
//Set:To change or assign or modify values
//this:this keyword is used to refer to current object
class BankAccount{
public String usearname;
private String passwors;
public void setpassword(String pwd){
passwors =pwd ;
}
}
class Pen{
String color;
int size;
String getcolor(){
return this.color;
}
int getsize(){
return this.size;
}
void setColor(String newcolor){
color= newcolor;
}
void setSize(int newsize){
size= newsize;
}
}
// access modifier
// acc mode | with in class| outside package | outside package by sub class | outside package
// private | y | n | n | n
// default | y | y | n | n
// protected | y | y | y | n
// public | y | y | y | y | tanXnyx/java_dsa | oop.java | 511 | //outside of this object, hence we need a method for setting it
| line_comment | en | false |
18527_3 | // Created by Shawn O'Grady on 12/7/17.
// Copyright © 2017 Shawn O'Grady. All rights reserved.
//
/*
This code is a practice Java interview question from testdome.com
https://www.testdome.com/questions/java/two-sum/10284?visibility=1&skillId=4
Problem statement: Write a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null.
+passes 3/4 tests
-code takes too long to answer when array has large # of elements
*/
package TwoSum;
public class TwoSum {
public static int[] findTwoSum(int[] list, int sum) {
int listLength=list.length;
int[] match=new int[2];
for(int i=0; i<listLength; i++){
for(int j=i+1; j<listLength; j++){
if(list[i]+list[j]==sum){
match[0]=i;
match[1]=j;
return match;
}
}
}
return null; //yes this results in an exception, but it's what specification said to do
}
public static void main(String[] args) {
int[] indices = findTwoSum(new int[] { 1, 3, 5, 7, 9 }, 10);
System.out.println(indices[0] + " " + indices[1]);
}
}
| ShawnROGrady/TestdomeJava | TwoSum.java | 386 | /*
This code is a practice Java interview question from testdome.com
https://www.testdome.com/questions/java/two-sum/10284?visibility=1&skillId=4
Problem statement: Write a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null.
+passes 3/4 tests
-code takes too long to answer when array has large # of elements
*/ | block_comment | en | true |
19027_11 | /*
Copyright (C) 2004 Geoffrey Alan Washburn
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.
*/
import java.util.Iterator;
/**
* An abstract class for representing mazes, and the operations a {@link Client}
* in the {@link Maze} may wish to perform..
* @author Geoffrey Washburn <<a href="mailto:[email protected]">[email protected]</a>>
* @version $Id: Maze.java 343 2004-01-24 03:43:45Z geoffw $
*/
public abstract class Maze {
/* Maze Information ****************************************************/
/**
* Obtain a {@link Point} describing the size of the {@link Maze}.
* @return A {@link Point} where the method <code>getX</code> returns the maximum X
* coordintate, and the method <code>getY</code> returns the maximum Y coordinate.
*/
public abstract Point getSize();
/**
* Check whether a {@link Point} is within the bounds of the {@link Maze}.
* @return <code>true</code> if the point lies within the {@link Maze}, <code>false</code> otherwise.
*/
public abstract boolean checkBounds(Point point);
/**
* Obtain the {@link Cell} corresponding to a given {@link Point} in the {@link Maze}.
* @param point Location in the {@link Maze}.
* @return A {@link Cell} describing that location.
*/
public abstract Cell getCell(Point point);
/* Client functionality ************************************************/
/**
* Add a {@link Client} at random location in the {@link Maze}.
* @param client {@link Client} to be added to the {@link Maze}.
*/
public abstract void addClient(Client client);
/**
* Create a new {@link Projectile} from the specified {@link Client}
* @param client {@link Client} that is firing.
* @return <code>false</code> on failure, <code>true</code> on success. */
public abstract boolean clientFire(Client client);
/**
* Remove the specified {@link Client} from the {@link Maze}
* @param client {@link Client} to be removed.
*/
public abstract void removeClient(Client client);
/**
* Find out where a specified {@link Client} is located
* in the {@link Maze}.
* @param client The {@link Client} being located.
* @return A {@link Point} describing the location of the client. */
public abstract Point getClientPoint(Client client);
/**
* Find out the cardinal direction a {@link Client} is facing.
* @param client The {@link Client} being queried.
* @return The orientation of the specific {@link Client} as a {@link Direction}.
*/
public abstract Direction getClientOrientation(Client client);
/**
* Attempt to move a {@link Client} in the {@link Maze} forward.
* @param client {@link Client} to move.
* @return <code>true</code> if successful, <code>false</code> if failure.
*/
public abstract boolean moveClientForward(Client client);
/** Attempt to move a {@link Client} in the {@link Maze} backward.
* @param client {@link Client} to move.
* @return <code>true</code> if successful, false if failure.
*/
public abstract boolean moveClientBackward(Client client);
/**
* Obtain an {@link Iterator} over all {@link Client}s in the {@link Maze}
* @return {@link Iterator} over clients in the {@link Maze}.
*/
public abstract Iterator getClients();
/**
* Add a remote client to the maze in a given location with a given orientation
* @param client Client to be added to the maze
* @param point The point at which the remote client will spawn
* @param dir The starting orientation of the client
*/
public abstract void addRemoteClient(Client client, Point point, Direction dir);
public abstract void addRemoteClientScore(Client client, Point point, Direction dir, int score);
public abstract void missiletick();
/* Maze Listeners ******************************************************/
/**
* Register an object that wishes to be notified when the maze changes
* @param ml An object implementing the {@link MazeListener} interface.
* */
public abstract void addMazeListener(MazeListener ml);
/** Remove an object from the notification queue
* @param ml An object implementing the {@link MazeListener} interface.
*/
public abstract void removeMazeListener(MazeListener ml);
}
| sangaani/Lab2 | Maze.java | 1,225 | /**
* Find out the cardinal direction a {@link Client} is facing.
* @param client The {@link Client} being queried.
* @return The orientation of the specific {@link Client} as a {@link Direction}.
*/ | block_comment | en | false |
19214_6 | class Student {
int coll_id;
String University;
static int University_Code;
// Constructor
public Student() {
coll_id = 56;
University = "OU";
University_Code = 45896;
}
// Here The Static block Execute only once becouse there a class loader and object initialization ,the class load only once so the static block is executed only once but object is initialized multiple times
// Static Block
static {
University_Code = 0100;
System.out.println("Static Block "+University_Code);
}
// Non-Static Method
public void aa1() {
System.out.println(
coll_id + "," + University + "," + University_Code + " Non Static Method"
);
}
// Static Method
public static void bb1(Student s3) {
// The Static Method will not take the non-static Variables it will take only static Varibles
System.out.println(
s3.coll_id +
"," +
s3.University +
"," +
University_Code +
" Static Method"
);
}
}
class Static_Block {
// If we don't keep static keyword in main then we need to use the object of Static BLock to over come this we use static keyword
public static void main(String[] args) {
Student s0=new Student();
s0.aa1();
Student s1 = new Student();
Student s2 = new Student();
s1.coll_id = 99;
s1.University = "Jntu";
Student.University_Code = 123456;
s1.aa1();
s2.aa1();
Student s3 = new Student();
// Here we are giving object itself so the we can run non-static varibles in static method
s3.bb1(s3);
}
}
| NishanthRathod09/JAVA | tut27.java | 429 | // If we don't keep static keyword in main then we need to use the object of Static BLock to over come this we use static keyword | line_comment | en | true |
19263_0 | /*
* Copyright © 2012 Bart Massey and the Fall 2012 Portland State University CS 441/541 class
* [This program is licensed under the "MIT License"]
* Please see the file COPYING in the source
* distribution of this software for license terms.
*/
class Block {
Coord pos; // coordinates of upper-left corner
char color;
Coord[] squares; // array of relative positions
Block(char color, Coord[] squares, int r, int c) {
this.pos = new Coord(r, c);
this.color = color;
this.squares = squares;
}
Block(Block b) {
pos = new Coord(b.pos);
color = b.color;
squares = b.squares;
}
boolean squareAt(Coord pos) {
for (int i = 0; i < squares.length; i++)
if (this.pos.offset(squares[i]).equals(pos))
return true;
return false;
}
boolean squareAt(int r, int c) {
return squareAt(new Coord(r, c));
}
boolean intersects(Block b) {
for (int i = 0; i < squares.length; i++)
if (b.squareAt(pos.offset(squares[i])))
return true;
return false;
}
boolean clipped() {
for (int i = 0; i < squares.length; i++) {
Coord s = pos.offset(squares[i]);
if (s.clipped())
return true;
}
return false;
}
boolean isAt(int r, int c) {
return pos.equals(r, c);
}
public boolean equals(Object o) {
Block b = (Block)o;
return b.color == color && b.pos.equals(pos);
}
public int hashCode() {
return (pos.hashCode() << 8) | color;
}
}
| BartMassey/simplicity-solver | Block.java | 454 | /*
* Copyright © 2012 Bart Massey and the Fall 2012 Portland State University CS 441/541 class
* [This program is licensed under the "MIT License"]
* Please see the file COPYING in the source
* distribution of this software for license terms.
*/ | block_comment | en | true |
19383_0 | /**
* @author Etherstrings
* @create 2022-05-30 19:48 PACKAGE_NAME - the name of the target package where the new class or interface will be created. Algorithm - the name of the current project. null.java - the name of the PHP file that will be created. L944 - the name of the new file which you specify in the New File dialog box during the file creation. ps - the login name of the current user. 2022/5/30 - the current system date. 19:48 - the current system time. 2022 - the current year. 05 - the current month. 30 - the current day of the month. 19 - the current hour. 48 - the current minute. IntelliJ IDEA - the name of the IDE in which the file will be created. 5月 - the first 3 letters of the month name. Example: Jan, Feb, etc. 五月 - full name of a month. Example: January, February, etc
*/
public class L944 {
public int minDeletionSize(String[] strs) {
int index=strs[0].length();
int answer=0;
for(int i=0;i<index;i++){
for(int j=1;j<strs.length;j++){
if(strs[j-1].charAt(i)>strs[j].charAt(i)){
answer++;
break;
}
}
}
return answer;
}
}
| Etherstrings/Algorithm | src/L944.java | 354 | /**
* @author Etherstrings
* @create 2022-05-30 19:48 PACKAGE_NAME - the name of the target package where the new class or interface will be created. Algorithm - the name of the current project. null.java - the name of the PHP file that will be created. L944 - the name of the new file which you specify in the New File dialog box during the file creation. ps - the login name of the current user. 2022/5/30 - the current system date. 19:48 - the current system time. 2022 - the current year. 05 - the current month. 30 - the current day of the month. 19 - the current hour. 48 - the current minute. IntelliJ IDEA - the name of the IDE in which the file will be created. 5月 - the first 3 letters of the month name. Example: Jan, Feb, etc. 五月 - full name of a month. Example: January, February, etc
*/ | block_comment | en | true |
19625_0 | /**
* GeekBrains. Java. Level 1. Lesson 4. Homework
*
* @author Andrey Klopov
* @version dated 19 may 2017
*1. Полностью разобраться с кодом, попробовать переписать с нуля, стараясь не подглядывать в методичку;
*2. Переделать проверку победы, чтобы она не была реализована просто набором условий, например, с использованием циклов.
*3. * Попробовать переписать логику проверки победы, чтобы она работала для поля 5х5 и количества фишек 4. Очень желательно не делать это просто набором условий для каждой из возможных ситуаций;
*4. *** Доработать искусственный интеллект, чтобы он мог блокировать ходы игрока.
*/
import java.util.Random;
import java.util.Scanner;
class DZ4 {
final int SIZE = 5;
final char DOT_X = 'x';
final char DOT_O = 'o';
final char DOT_EMPTY = '.';
char[][] map = new char [SIZE][SIZE];
Scanner sc = new Scanner(System.in);
Random rand = new Random();
public static void main(String[] args) {
new DZ4().go();
}
void go(){
initMap();
while (true){
humanTurn();
printMap();
if(checkWin(DOT_X)){
System.out.println("YOU WON!");
break;
}
if (isMapFull()){
System.out.println("Sorry, DRAW");
break;
}
aiTurn();
printMap();
if(checkWin(DOT_O)){
System.out.println("AI WON");
break;
}
}
System.out.println("GAME OVER.");
}
void printMap() {
for(int y = 0; y < 5; ++y) {
System.out.print((y + 1) + " ");
for(int x = 0; x < 5; ++x) {
System.out.print(map[y][x] + " ");
}
System.out.println();
}
System.out.println();
}
void initMap() {
map = new char[SIZE][SIZE];
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
map[i][j] = DOT_EMPTY;
}
}
}
void humanTurn() {
int x;
int y;
while (true) {
System.out.print("Введи Х_Y: ");
if (sc.hasNextInt()) {
y = sc.nextInt() - 1;
}
else {
System.out.println("Ты ошибся. Повтори:");
continue;
}
if (sc.hasNextInt()) {
x = sc.nextInt() - 1;
}
else {
System.out.println("Ты ошибся. Повтори:");
continue;
}
if (isCellValid(y, x) && isCellEmpty(y, x)) {
map[y][x] = DOT_X;
break;
}
System.out.println("Ты ошибся. Повтори:");
}
}
void aiTurn() {
int y;
int x;
while (true) {
y = rand.nextInt(5);
x = rand.nextInt(5);
if (isCellEmpty(y,x)) {
System.out.println("Ход компьютера X_Y: " + (y + 1) + " " + (x + 1));
map[y][x] = DOT_O;
break;
}
}
}
boolean isCellValid(int y, int x) {
return y >= 0 && y <= 4 && x >= 0 && y <= 4;
}
boolean isCellEmpty(int y, int x) {
return map[y][x] == DOT_EMPTY;
}
boolean isMapFull() {
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 5; x++) {
if(map[y][x] == DOT_EMPTY) {
return false;
}
}
}
return true;
}
boolean checkWin(char symb) {
int strafeX;
int y;
for (strafeX = 0; strafeX < 2; ++strafeX) {
for (y = 0; y < 5; ++y) {
if (map[y][0 + strafeX] == symb && map[y][1 + strafeX] == symb && map[y][2 + strafeX] == symb && map[y][3 + strafeX] == symb) {
return true;
}
}
}
for (strafeX = 0; strafeX < 2; ++strafeX) {
for (y = 0; y < 5; ++y) {
if (map[0 + strafeX][y] == symb && map[1 + strafeX][y] == symb && map[2 + strafeX][y] == symb && map[3 + strafeX][y] == symb) {
return true;
}
}
}
for (strafeX = 0; strafeX < 2; ++strafeX) {
for (y = 0; y < 2; ++y) {
if (map[0 + strafeX][0 + y] == symb && map[1 + strafeX][1 + y] == symb && map[2 + strafeX][2 + y] == symb && map[3 + strafeX][3 + y] == symb) {
return true;
}
if (map[4 - strafeX][0 + y] == symb && map[3 - strafeX][1 + y] == symb && map[2 - strafeX][2 + y] == symb && map[1 - strafeX][3 + y] == symb) {
return true;
}
}
}
return false;
}
} | 13Fox13/Java1 | DZ4.java | 1,581 | /**
* GeekBrains. Java. Level 1. Lesson 4. Homework
*
* @author Andrey Klopov
* @version dated 19 may 2017
*1. Полностью разобраться с кодом, попробовать переписать с нуля, стараясь не подглядывать в методичку;
*2. Переделать проверку победы, чтобы она не была реализована просто набором условий, например, с использованием циклов.
*3. * Попробовать переписать логику проверки победы, чтобы она работала для поля 5х5 и количества фишек 4. Очень желательно не делать это просто набором условий для каждой из возможных ситуаций;
*4. *** Доработать искусственный интеллект, чтобы он мог блокировать ходы игрока.
*/ | block_comment | en | true |
20020_5 | package com.example.myfirstapp;
// What's up JDP? Here is a little work I did on the Event and Date classes. We'll discuss all changes on Sunday?
// I'm going to try to do some more work this weekend, but I will mostly just try to learn how to work with the SDK.
public class Date {
private int numberOfEvents;
Event[] todaysEvents = new Event[50];
//50 events to begin with
public void getListOfEvents(){
// I don't know what we want here
}
public void addEvent(){
todaysEvents[numberOfEvents] = new Event();
numberOfEvents++;
}
public void deleteEvent(int location){
todaysEvents[location] = null;
}
public Event getEvent(int location){
return todaysEvents[location];
}
public void displayListOfEvents(){
for (int i = 0; i < numberOfEvents; i++){
todaysEvents[i].getName();
}
}
// public void displayEvents(){
// Same as displayListOFEvents()?
// }
}
| david10p/JDP | Date.java | 271 | // Same as displayListOFEvents()? | line_comment | en | true |
20060_0 | /*
* Copyright (c) The League of Amazing Programmers 2013-2017
* Level 1
*/
public class Cat {
private String name;
private int lives = 9;
Cat(String name) {
this.name = name;
}
void meow() {
System.out.println("meeeeeooooooooooowwwwwwwww!!");
}
public void printName() {
if (name == null)
System.out.println("i don't know my own name!");
else
System.out.println("my name is " + name);
}
void kill() {
lives--;
if (lives > 0)
System.out.println("nice try, but I still have " + lives + " lives left");
else if (lives < 0)
System.out.println("that's overkill yo!");
else
System.out.println("DEAD CAT :(");
}
public static void main(String[] args) {
/* Do the following things without changing the Cat class */
// 1. Make the Cat meow
Cat Kayla = new Cat("Kayla");
Kayla.meow();
// 2. Get the Cat to print it's name
Kayla.printName();
// 3. Kill the Cat!
for (int i = 1; i < 10; i++) {
Kayla.kill();
}
}
}
| League-Level1-Student/level1-module1-kaylarwright | Cat.java | 371 | /*
* Copyright (c) The League of Amazing Programmers 2013-2017
* Level 1
*/ | block_comment | en | true |
20117_71 | /* */ import javafx.event.ActionEvent;
/* */ import javafx.geometry.Pos;
/* */ import javafx.scene.Node;
/* */ import javafx.scene.Parent;
/* */ import javafx.scene.Scene;
/* */ import javafx.scene.control.Button;
/* */ import javafx.scene.control.Label;
/* */ import javafx.scene.layout.VBox;
/* */ import javafx.stage.Stage;
/* */
/* */ public class score
/* */ {//This class shows the final score, high score, and keeps track of the overall rounds and winning streaks
/* */ public static int p1streak;
/* */ public static int p2streak;
/* */ public static int p1rounds;
/* */ public static int p2rounds;
/* */ public static int temp;
/* */ public static int temp1;
/* 19 */ public static int highscore = 0;
/* 20 */ public static int games = 0;
/* */ public static void update(int w) { //This method updates the score by tracking how many rounds each player has won, and the high score
/* 22 */ games++;
/* 23 */ if (games == 3) {
/* 24 */ if (w == 1) {
/* 25 */ p1streak++;
/* 26 */ temp++;
/* 27 */ if (temp > highscore) {
/* 28 */ highscore = temp;
/* */ }
/* */ }
/* 31 */ if (w == 2) {
/* 32 */ p2streak++;
/* 33 */ temp1++;
/* 34 */ if (temp1 > highscore) {
/* 35 */ highscore = temp1;
/* */ }
/* */ }
/* 38 */ if (p1streak > p2streak) {
/* 39 */ p1rounds++;
/* */ }
/* 41 */ if (p2streak > p1streak) {
/* 42 */ p2rounds++;
/* */ }
/* */
/* 45 */ games = 0;
/* 46 */ p1streak = 0;
/* 47 */ p2streak = 0;
/* */ }
/* 49 */ if (w == 1) {
/* 50 */ p1streak++;
/* 51 */ temp++;
/* 52 */ if (temp > highscore) {
/* 53 */ highscore = temp;
/* */ }
/* 55 */ health.updateHealth(1);
/* */ }
/* 57 */ if (w == 2) {
/* 58 */ p2streak++;
/* 59 */ temp1++;
/* 60 */ if (temp1 > highscore) {
/* 61 */ highscore = temp1;
/* */ }
/* 63 */ health.updateHealth(2);
/* */ }
/* */ }
/* */
/* */
/* */
/* */ public static void showScore() {//This class shows the final window with the overall streaks and how many rounds have been won by each player
/* 70 */ Stage window = new Stage();
/* 71 */ window.setTitle("Score");
/* */
/* 73 */ Label p1score = new Label("Player one's streak: " + p1streak);
/* 74 */ Label p2score = new Label("Player two's streak: " + p2streak);
/* 75 */ Label p1Rounds = new Label("Player one's rounds: " + p1rounds);
/* 76 */ Label p2Rounds = new Label("Player two's rounds: " + p2rounds);
/* */
/* 78 */ Button exit = new Button("Exit");
/* 79 */ exit.setOnAction(e -> window.close());
/* */
/* */
/* */
/* 83 */ VBox layout = new VBox(10.0D);
/* 84 */ layout.getChildren().addAll((Object[])new Node[] { (Node)p1score, (Node)p2score, (Node)p1Rounds, (Node)p2Rounds, (Node)exit });
/* 85 */ layout.setAlignment(Pos.CENTER);
/* 86 */ Scene scene = new Scene((Parent)layout, 300.0D, 300.0D);
/* 87 */ scene.getStylesheets().add("game.css");
/* 88 */ window.setScene(scene);
/* 89 */ window.show();
/* */ }
/* */ public static void showHighScore() {//THis opens a window that shows the highest score, being the largest amount of rounds won
/* 92 */ Stage window = new Stage();
/* 93 */ window.setTitle("High Score");
/* */
/* 95 */ Label p1score = new Label("Highest winning streak: " + highscore);
/* */
/* 97 */ Button exit = new Button("exit");
/* 98 */ exit.setOnAction(e -> window.close());
/* */
/* */
/* */
/* 102 */ VBox layout = new VBox(10.0);
/* 103 */ layout.getChildren().addAll((Object[])new Node[] { (Node)p1score, (Node)exit });
/* 104 */ layout.setAlignment(Pos.CENTER);
/* 105 */ Scene scene = new Scene((Parent)layout, 300.0D, 300.0D);
/* 106 */ scene.getStylesheets().add("game.css");
/* 107 */ window.setScene(scene);
/* 108 */ window.show();
/* */ }
/* */ }
| KavitaDoobay/RockPaperScissors | score.java | 1,498 | //This class shows the final window with the overall streaks and how many rounds have been won by each player | line_comment | en | false |
20619_9 | /**
* Models a simple Car for the game Racer.
*
* @author Joe Finney ([email protected])
*/
public class Car
{
public static String CAR_COLOUR = "#FF0000";
public static String WHEEL_COLOUR = "#404040";
private Rectangle[] parts = new Rectangle[7];
private double xPosition;
private double yPosition;
private GameArena arena;
private double xSpeed;
private double ySpeed;
/**
* Creates a new Car, at the given location.
*
* @param x The x position on the screen of the centre of the car.
* @param y The y position on the screen of the centre of the car.
* @param a The GameArena upon which to draw this car.
*/
public Car(double x, double y, GameArena a)
{
parts[0] = new Rectangle(10, 20, 10, 20, WHEEL_COLOUR);
parts[1] = new Rectangle(10, 80, 10, 20, WHEEL_COLOUR);
parts[2] = new Rectangle(50, 20, 10, 20, WHEEL_COLOUR);
parts[3] = new Rectangle(50, 80, 10, 20, WHEEL_COLOUR);
parts[4] = new Rectangle(30, 50, 40, 70, CAR_COLOUR);
parts[5] = new Rectangle(15, 18, 5, 5, "WHITE");
parts[6] = new Rectangle(45, 18, 5, 5, "WHITE");
arena = a;
this.setXPosition(x);
this.setYPosition(y);
for (int i=0; i < parts.length; i++)
arena.addRectangle(parts[i]);
}
/**
* Changes the position of this car to the given location
*
* @param x The new x positition of this car on the screen.
*/
public void setXPosition(double x)
{
double dx = x - xPosition;
for (int i=0; i < parts.length; i++)
parts[i].setXPosition(parts[i].getXPosition() + dx);
xPosition = x;
}
/**
* Changes the position of this car to the given location
*
* @param y The new y positition of this car on the screen.
*/
public void setYPosition(double y)
{
double dy = y - yPosition;
for (int i=0; i < parts.length; i++)
parts[i].setYPosition(parts[i].getYPosition() + dy);
yPosition = y;
}
/**
* Determines the position of this car on the screen
*
* @return The x position of the centre of this car on the screen.
*/
public double getXPosition()
{
return xPosition;
}
/**
* Determines the position of this car on the screen
*
* @return The y co-ordinate of the centre of this car on the screen.
*/
public double getYPosition()
{
return yPosition;
}
/**
* Sets the speed of this car in the X axis - i.e. the number of pixels it moves in the X axis every time move() is called.
*
* @param s The new speed of this car in the x axis
*/
public void setXSpeed(double s)
{
xSpeed = s;
}
/**
* Sets the speed of this car in the Y axis - i.e. the number of pixels it moves in the Y axis every time move() is called.
*
* @param s The new speed of this car in the y axis
*/
public void setYSpeed(double s)
{
ySpeed = s;
}
/**
* Updates the position of this car by a small amount, depending upon its speed.
* see setXSpeed() and setYSpeed() methods.
*/
public void move()
{
this.setXPosition(xPosition + xSpeed);
this.setYPosition(yPosition + ySpeed);
}
/**
* Determines if this car is touching the given RoadSegment.
*
* @param s The segment of road to test against.
* @return true of this car is touching the given road segment, false otherwise.
*/
public boolean isTouching(RoadSegment s)
{
Rectangle[] roadParts = s.getParts();
for (int i=0; i < parts.length; i++)
for (int j=0; j < roadParts.length; j++)
if(parts[i].isTouching(roadParts[j]))
return true;
return false;
}
}
| finneyj/Racer | Car.java | 1,126 | /**
* Determines if this car is touching the given RoadSegment.
*
* @param s The segment of road to test against.
* @return true of this car is touching the given road segment, false otherwise.
*/ | block_comment | en | false |
20737_2 | package a;
import java.lang.reflect.Method;
import java.util.Arrays;
public final class a {
private final Object object;
private final boolean vGp = false;
public static a cJ(Object obj) {
return new a(obj);
}
private a(Object obj) {
this.object = obj;
}
public final a y(String str, Object... objArr) {
Class[] clsArr = new Class[objArr.length];
for (int i = 0; i < objArr.length; i++) {
Object obj = objArr[i];
clsArr[i] = obj == null ? a.class : obj.getClass();
}
try {
return a(a(str, clsArr), this.object, objArr);
} catch (NoSuchMethodException e) {
Class type = type();
for (Method method : type.getMethods()) {
if (a(method, str, clsArr)) {
break;
}
}
Class cls = type;
loop2:
while (true) {
for (Method method2 : cls.getDeclaredMethods()) {
if (a(method2, str, clsArr)) {
break loop2;
}
}
Class superclass = cls.getSuperclass();
if (superclass == null) {
throw new NoSuchMethodException("No similar method " + str + " with params " + Arrays.toString(clsArr) + " could be found on type " + type() + ".");
}
cls = superclass;
}
return a(method2, this.object, objArr);
} catch (Throwable e2) {
throw new b(e2);
}
}
private Method a(String str, Class<?>[] clsArr) {
Class type = type();
try {
return type.getMethod(str, clsArr);
} catch (NoSuchMethodException e) {
do {
try {
return type.getDeclaredMethod(str, clsArr);
} catch (NoSuchMethodException e2) {
type = type.getSuperclass();
if (type != null) {
throw new NoSuchMethodException();
}
}
} while (type != null);
throw new NoSuchMethodException();
}
}
private static boolean a(Method method, String str, Class<?>[] clsArr) {
if (!method.getName().equals(str)) {
return false;
}
boolean z;
Class[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == clsArr.length) {
int i = 0;
while (i < clsArr.length) {
if (clsArr[i] == a.class || W(parameterTypes[i]).isAssignableFrom(W(clsArr[i]))) {
i++;
}
}
z = true;
return z;
}
z = false;
if (z) {
}
}
public final int hashCode() {
return this.object.hashCode();
}
public final boolean equals(Object obj) {
if (obj instanceof a) {
return this.object.equals(((a) obj).object);
}
return false;
}
public final String toString() {
return this.object.toString();
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static a.a a(java.lang.reflect.Method r3, java.lang.Object r4, java.lang.Object... r5) {
/*
if (r3 == 0) goto L_0x002c;
L_0x0002:
r1 = r3 instanceof java.lang.reflect.Member; Catch:{ Exception -> 0x0045 }
if (r1 == 0) goto L_0x0022;
L_0x0006:
r0 = r3;
r0 = (java.lang.reflect.Member) r0; Catch:{ Exception -> 0x0045 }
r1 = r0;
r2 = r1.getModifiers(); Catch:{ Exception -> 0x0045 }
r2 = java.lang.reflect.Modifier.isPublic(r2); Catch:{ Exception -> 0x0045 }
if (r2 == 0) goto L_0x0022;
L_0x0014:
r1 = r1.getDeclaringClass(); Catch:{ Exception -> 0x0045 }
r1 = r1.getModifiers(); Catch:{ Exception -> 0x0045 }
r1 = java.lang.reflect.Modifier.isPublic(r1); Catch:{ Exception -> 0x0045 }
if (r1 != 0) goto L_0x002c;
L_0x0022:
r1 = r3.isAccessible(); Catch:{ Exception -> 0x0045 }
if (r1 != 0) goto L_0x002c;
L_0x0028:
r1 = 1;
r3.setAccessible(r1); Catch:{ Exception -> 0x0045 }
L_0x002c:
r1 = r3.getReturnType(); Catch:{ Exception -> 0x0045 }
r2 = java.lang.Void.TYPE; Catch:{ Exception -> 0x0045 }
if (r1 != r2) goto L_0x003c;
L_0x0034:
r3.invoke(r4, r5); Catch:{ Exception -> 0x0045 }
r1 = cJ(r4); Catch:{ Exception -> 0x0045 }
L_0x003b:
return r1;
L_0x003c:
r1 = r3.invoke(r4, r5); Catch:{ Exception -> 0x0045 }
r1 = cJ(r1); Catch:{ Exception -> 0x0045 }
goto L_0x003b;
L_0x0045:
r1 = move-exception;
r2 = new a.b;
r2.<init>(r1);
throw r2;
*/
throw new UnsupportedOperationException("Method not decompiled: a.a.a(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]):a.a");
}
private Class<?> type() {
if (this.vGp) {
return (Class) this.object;
}
return this.object.getClass();
}
private static Class<?> W(Class<?> cls) {
if (cls == null) {
return null;
}
if (!cls.isPrimitive()) {
return cls;
}
if (Boolean.TYPE == cls) {
return Boolean.class;
}
if (Integer.TYPE == cls) {
return Integer.class;
}
if (Long.TYPE == cls) {
return Long.class;
}
if (Short.TYPE == cls) {
return Short.class;
}
if (Byte.TYPE == cls) {
return Byte.class;
}
if (Double.TYPE == cls) {
return Double.class;
}
if (Float.TYPE == cls) {
return Float.class;
}
if (Character.TYPE == cls) {
return Character.class;
}
if (Void.TYPE == cls) {
return Void.class;
}
return cls;
}
}
| liujianying/WeChat_java | a/a.java | 1,745 | /*
if (r3 == 0) goto L_0x002c;
L_0x0002:
r1 = r3 instanceof java.lang.reflect.Member; Catch:{ Exception -> 0x0045 }
if (r1 == 0) goto L_0x0022;
L_0x0006:
r0 = r3;
r0 = (java.lang.reflect.Member) r0; Catch:{ Exception -> 0x0045 }
r1 = r0;
r2 = r1.getModifiers(); Catch:{ Exception -> 0x0045 }
r2 = java.lang.reflect.Modifier.isPublic(r2); Catch:{ Exception -> 0x0045 }
if (r2 == 0) goto L_0x0022;
L_0x0014:
r1 = r1.getDeclaringClass(); Catch:{ Exception -> 0x0045 }
r1 = r1.getModifiers(); Catch:{ Exception -> 0x0045 }
r1 = java.lang.reflect.Modifier.isPublic(r1); Catch:{ Exception -> 0x0045 }
if (r1 != 0) goto L_0x002c;
L_0x0022:
r1 = r3.isAccessible(); Catch:{ Exception -> 0x0045 }
if (r1 != 0) goto L_0x002c;
L_0x0028:
r1 = 1;
r3.setAccessible(r1); Catch:{ Exception -> 0x0045 }
L_0x002c:
r1 = r3.getReturnType(); Catch:{ Exception -> 0x0045 }
r2 = java.lang.Void.TYPE; Catch:{ Exception -> 0x0045 }
if (r1 != r2) goto L_0x003c;
L_0x0034:
r3.invoke(r4, r5); Catch:{ Exception -> 0x0045 }
r1 = cJ(r4); Catch:{ Exception -> 0x0045 }
L_0x003b:
return r1;
L_0x003c:
r1 = r3.invoke(r4, r5); Catch:{ Exception -> 0x0045 }
r1 = cJ(r1); Catch:{ Exception -> 0x0045 }
goto L_0x003b;
L_0x0045:
r1 = move-exception;
r2 = new a.b;
r2.<init>(r1);
throw r2;
*/ | block_comment | en | true |
21019_2 | import java.util.*;
public class Hotel {
public static void main(String[] args) {
// ["+1A", "+3E", "-1A", "+4F", "+1A", "-3E"]
String[] books1 = { "+1A", "+3E", "-1A", "+4F", "+1A", "-3E" };
String[] books2 = {"+1A","+3F","+2B"};
String[] books3 = {"+1E", "-1E", "+1E", "-1E", "+1E", "-1E", "+1E", "-1E","+2A", "-2A", "+2A", "-2A", "+2A", "-2A", "+2A",
"-2A","+2B", "-2B", "+2B", "-2B", "+2B", "-2B", "+2B", "-2B"};
System.out.println(solution(books1));
System.out.println(solution(books2));
System.out.println(solution(books3));
}
static class Room implements Comparable<Room>{
public String no;
public int book;
public Room(String no) {
this.no = no;
}
@Override
// The compareTo method is a little bit differet from my orignal solution.
// I use all the time to figure why my code give a null pointer exception.
// Hence, I don't have time to check the result of my compareTo.
// The compareTo method in my solution will give an opposite result of this one.
public int compareTo(Room o) {
if (this.book < o.book) {
return -1;
} else if (this.book > o.book) {
return 1;
} else {
return -this.no.compareTo(o.no);
}
}
}
private static String solution(String[] A) {
Room[] res = new Room[260];
for(int i = 0 ; i < res.length; i++) {
char[] ch = new char[2];
char f = (char)(i/26 + '0');
char n = (char)(i%26 + 'A');
ch[0] = f;
ch[1] = n;
res[i] = new Room(new String(ch));
}
for(String str : A) {
if(str.charAt(0) == '+') {
int floor = str.charAt(1) - '0';
int cell = (str.charAt(2) - 'A');
int id = floor * 26 + cell;
res[id].book += 1; // This line give a nullPointerException
}
}
Arrays.sort(res);
return res[res.length - 1].no;
}
}
| ruoyangqiu/Leetcode | Hotel.java | 701 | // I use all the time to figure why my code give a null pointer exception. | line_comment | en | false |
22170_4 | /**
* King
*
* @author Faiza Salami, 7941056
* <p>
* REMARKS: A king class representing a king piece on a chess board
*/
public class King extends Piece {
public King(char piece) {
super(piece);
}
/**
* checks if the move being made is valid for a player's king
*
* @param move the move that was made
* @param gameBoard the current game board
* @return boolean-returns true if the move is valid and false otherwise
*/
public boolean validMove(Move move, Board gameBoard) {
Piece newPiece = gameBoard.getPiece(move.getNewRow(), move.getNewCol());
boolean output = false;
if ((move.getRow() == move.getNewRow()) && Math.abs(move.getNewCol() - move.getCol()) == 1) {
output = (newPiece == null || newPiece.isAIPiece());
} else if ((move.getCol() == move.getNewCol()) && Math.abs(move.getNewRow() - move.getRow()) == 1) {
output = (newPiece == null || newPiece.isAIPiece());
} else if (Math.abs(move.getNewCol() - move.getCol()) == Math.abs(move.getNewRow() - move.getRow())) {
output = (newPiece == null || newPiece.isAIPiece());
}
if (output) {
gameBoard.getPiece(move.getRow(), move.getCol()).setCaptured(newPiece);
}
return output;
}
/**
* generate a move for the AI king, easy mode. this method just moves the king by one square
*
* @param move the move containing where the king currently is
* @param gameBoard the current game board
* @return boolean-returns the move containing what location the king is moving to or null if there's no available
* space for the king to move to
*/
public Move generateMove(Move move, Board gameBoard) {
int[][] possibleMoves = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int newRow;
int newCol;
Piece newPiece;
for (int i = 0; i < possibleMoves.length; i++) {
newRow = move.getRow() + possibleMoves[i][0];
newCol = move.getCol() + possibleMoves[i][1];
if (newRow >= 0 && newRow < 8 && newCol >= 0 && newCol < 8) {
newPiece = gameBoard.getPiece(newRow, newCol);
if (newPiece == null || newPiece.isPlayerPiece()) {
move.setNewRow(newRow);
move.setNewCol(newCol);
gameBoard.getPiece(move.getRow(), move.getCol()).setCaptured(gameBoard.getPiece(move.getNewRow(), move.getNewCol()));
return move;
}
}
}
return null;
}
/**
* checks if any of the player's piece is in the king's vicinity to be captured
*
* @param move the move containing the king's current location
* @param gameBoard the current game board
* @return Move-the move containing what location the king is moving to or null if the king cant capture any player
*/
public Move capturePlayerPiece(Move move, Board gameBoard) {
int[][] possibleMoves = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {-1, 1}, {-1, -1}, {1, 1}, {1, -1}};
int newRow;
int newCol;
Piece newPiece;
for (int i = 0; i < possibleMoves.length; i++) {
newRow = move.getRow() + possibleMoves[i][0];
newCol = move.getCol() + possibleMoves[i][1];
if (newRow >= 0 && newRow < 8 && newCol >= 0 && newCol < 8) {
newPiece = gameBoard.getPiece(newRow, newCol);
if (newPiece != null && newPiece.isPlayerPiece()) {
move.setNewRow(newRow);
move.setNewCol(newCol);
gameBoard.getPiece(move.getRow(), move.getCol()).setCaptured(gameBoard.getPiece(move.getNewRow(), move.getNewCol()));
return move;
}
}
}
return null;
}
/**
* the name of the piece
*
* @return returns the piece name
*/
public String name() {
return "King";
}
}
| f-osss/chess-game | King.java | 1,077 | /**
* the name of the piece
*
* @return returns the piece name
*/ | block_comment | en | true |
22241_1 | package com.transcendcomputing.cloudanalysis;
import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class Pricing {
private Mongo m = null;
private DB db = null;
public void establishConnection()
{
try {
m = new Mongo( "YOUR IP HERE", 27017);
} catch(Exception e) { System.out.println(e); }
db = m.getDB( "stack_place_development" );
boolean auth = db.authenticate("admin", "YOUR PASSWORD HERE".toCharArray());
//System.out.println(db.getCollectionNames());
DBCollection collection = db.getCollection("clouds");
System.out.println(collection.count());
DBCursor cursor = collection.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
/*
BasicDBObject query = new BasicDBObject();
query.put("i", 71);
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
*/
// db.clouds.find({'cloud_provider': 'OpenStack'}, {'compute_prices':1});
}
}
| jeffrschneider/Vertically-Challenged | Pricing.java | 384 | /*
BasicDBObject query = new BasicDBObject();
query.put("i", 71);
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
*/ | block_comment | en | true |
22320_0 | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Map;
import java.util.regex.Pattern;
public class AEG {
private static final Pattern COMPILE = Pattern.compile("\\R");
public static void main(String[] args) throws IOException {
// Insert name of file containing user answers here.
var inputFile = Path.of("somewhat_right.txt");
if (!Files.exists(inputFile)) throw new NoSuchFileException(inputFile + " does not exist");
var contents = Files.readString(inputFile);
String[] splitter = COMPILE.split(contents, 2);
String name = splitter[0];
splitter[1] = splitter[1].replace(System.lineSeparator(), "");
if (splitter[1].chars().filter(c -> c == ';').count() != 24L) {
System.err.println(inputFile + " must have exactly 24 ';' separating answers");
} else {
Exam e = new Exam(name, LocalDate.now().toString());
e.takeExam(splitter[1].split(";"));
e.gradeExam();
e.writeOut();
e.displayResult(splitter[1].split(";"));
report();
}
}
// private record User(String name, String date, short score) {}
public static void report() throws IOException {
var db = Files.readAllLines(Path.of("db.csv"));
if (db.isEmpty())
System.err.println("Try taking the test, buddy. Nothing to pry open with your wily eyes, eh?");
else {
final var avrgScorPerSubj = new EnumMap<>(Map.of(Subject.Math, 0.0, Subject.Arts, 0.0,
Subject.Geography, 0.0, Subject.History, 0.0, Subject.Science, 0.0));
for (var l : db) {
// Scores in order: Math, Science, History, Geography, Arts (each out of 5)
var tmpStream = Arrays.stream(l.split(",", 3)[2].split(","));
var doubleStream = tmpStream.mapToDouble(Double::parseDouble);
final var userScores = doubleStream.toArray();
avrgScorPerSubj.put(Subject.Math, avrgScorPerSubj.get(Subject.Math) + userScores[0]);
avrgScorPerSubj.put(Subject.Arts, avrgScorPerSubj.get(Subject.Arts) + userScores[4]);
avrgScorPerSubj.put(Subject.Geography, avrgScorPerSubj.get(Subject.Geography) + userScores[3]);
avrgScorPerSubj.put(Subject.History, avrgScorPerSubj.get(Subject.History) + userScores[2]);
avrgScorPerSubj.put(Subject.Science, avrgScorPerSubj.get(Subject.Science) + userScores[1]);
}
for (final var entry : avrgScorPerSubj.entrySet()) {
double avg = entry.getValue() / db.size();
avrgScorPerSubj.put(entry.getKey(), avg);
}
var sb = new StringBuilder("Average score per subject: " + System.lineSeparator());
for (var s : Subject.values())
sb.append("%s: %.1f / 5%n".formatted(s.toString(), avrgScorPerSubj.get(s)));
var f = sb.toString();
var totalAverage = avrgScorPerSubj.values().parallelStream().mapToDouble(n -> n).sum();
System.out.printf("Number of test takers: %d\n".formatted(db.size()) +
f +
"Average overall score: %.1f / 25 (%.1f%%)%n",
totalAverage,
totalAverage * 4.0);
}
}
}
| clin1234/ATG | AEG.java | 958 | // Insert name of file containing user answers here. | line_comment | en | true |
22483_4 | import java.util.*;
/**
* The Sym class defines a symbol-table entry.
* Each Sym contains a type (a Type).
*/
public class Sym {
private Type type;
private int offset = 0;
private boolean global = false;
public Sym(Type type) {
this.type = type;
}
public Type getType() {
return type;
}
public String toString() {
return type.toString();
}
public void setOffset(int offset){
this.offset = offset;
}
public int getOffset(){
return this.offset;
}
public void setGlobal(){
this.global = true;
}
public boolean isGlobal(){
return this.global;
}
}
/**
* The FnSym class is a subclass of the Sym class just for functions.
* The returnType field holds the return type and there are fields to hold
* information about the parameters.
*/
class FnSym extends Sym {
// new fields
private Type returnType;
private int numParams;
private List<Type> paramTypes;
public FnSym(Type type, int numparams) {
super(new FnType());
returnType = type;
numParams = numparams;
}
public void addFormals(List<Type> L) {
paramTypes = L;
}
public Type getReturnType() {
return returnType;
}
public int getNumParams() {
return numParams;
}
public List<Type> getParamTypes() {
return paramTypes;
}
public String toString() {
// make list of formals
String str = "";
boolean notfirst = false;
for (Type type : paramTypes) {
if (notfirst)
str += ",";
else
notfirst = true;
str += type.toString();
}
str += "->" + returnType.toString();
return str;
}
}
/**
* The StructSym class is a subclass of the Sym class just for variables
* declared to be a struct type.
* Each StructSym contains a symbol table to hold information about its
* fields.
*/
class StructSym extends Sym {
// new fields
private IdNode structType; // name of the struct type
public StructSym(IdNode id) {
super(new StructType(id));
structType = id;
}
public IdNode getStructType() {
return structType;
}
}
/**
* The StructDefSym class is a subclass of the Sym class just for the
* definition of a struct type.
* Each StructDefSym contains a symbol table to hold information about its
* fields.
*/
class StructDefSym extends Sym {
// new fields
private SymTable symTab;
public StructDefSym(SymTable table) {
super(new StructDefType());
symTab = table;
}
public SymTable getSymTable() {
return symTab;
}
}
| czliou/p6 | Sym.java | 669 | /**
* The StructSym class is a subclass of the Sym class just for variables
* declared to be a struct type.
* Each StructSym contains a symbol table to hold information about its
* fields.
*/ | block_comment | en | true |
22558_12 | package posix;
/** Read and write memory reachable through a C ptr. Memory access is
bounds checked to keep it within the size of region addressed by
the C ptr. Only classes within the posix package can create CPtr objects,
and the use of this class is completely safe at present. This is
because we know the size of, for instance, shared memory segments or
memory allocated with C malloc. At some future date, we may need the
ability to dereference arbitrary C pointers - those dereferences will
be unsafe.
<p>
We have not yet implemented the floating and 64-bit types for get/set
due to a lack of need.
@author <a href="mailto:[email protected]">Stuart D. Gathman</a>
Copyright (C) 1998 Business Management Systems, Inc. <br>
<p>
This code is distributed under the
<a href="http://www.gnu.org/copyleft/lgpl.html">
GNU Library General Public License </a>
<p>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
<p>
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
Library General Public License for more details.
<p>
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
public class CPtr {
long addr;
int size;
/** A null CPtr value. */
static final long NULL = getNULL();
CPtr() { }
CPtr(long addr,int size) {
this.addr = addr;
this.size = size;
}
private static final long getNULL() {
System.loadLibrary("posix");
return init();
}
private static native long init();
/** Type codes for <code>alignOf()</code> and <code>sizeOf()</code>. */
public static final int
CBYTE_TYPE = 0,
CSHORT_TYPE = 1,
CINT_TYPE = 2,
CLONG_TYPE = 3,
CFLT_TYPE = 4,
CDBL_TYPE = 5,
CPTR_TYPE = 6;
/** Get the alignment of a C type. Can be used to compute C struct
offsets in a mostly system independent manner.
*/
public static native int alignOf(int type);
/** Get the size of a C type. Can be used to compute C struct
offsets in a mostly system independent manner.
*/
public static native int sizeOf(int type);
/** Compute the offsets of a C struct one member at a time. This
is supposed to reflect what a C compiler would do. I can't think
of a better way to track C data structs with code that doesn't get
recompiled. A config file could do it, but would be even
more work. Some C compilers will do surprising things - like
padding structs that contain only 'char' members. They do this to
avoid cache misses at the beginning of the struct - or to make struct
pointers uniform on word addressable machines (e.g. PDP20).
You can work around this for now with the
<code>addMember</code> method - provided you can figure out <u>when</u>
to do so. Please report any problems you encounter - we can add
additional native methods, e.g. 'structAlign' to return minimum
struct alignment.
*/
public static class Struct {
private int offset = 0;
private int align = 0; // maximum alignment in struct
/** Initialize with the offset (within a CPtr) of the C struct.
*/
public Struct(int offset) { this.offset = offset; }
/** Return the offset of the next member. */
public final int offsetOf(int type) {
return offsetOf(type,1);
}
/** Return the offset of the next array member. */
public final int offsetOf(int type,int len) {
return addMember(len * sizeOf(type),alignOf(type) - 1);
}
/** Add a member by size and alignment mask. Return the member
offset.
*/
public final int addMember(int size,int mask) {
int pos = (offset + mask) & ~mask; // align for this member
offset = pos + size;
if (mask > align) align = mask;
return pos;
}
/** Return the offset of a nested struct. The members must have
already been added to the nested struct so that it will have
the proper size and alignment.
*/
public final int offsetOf(Struct s,int cnt) {
return addMember(cnt * s.size(),s.align);
}
/** Return total struct size including padding to reflect
maximum alignment. */
public final int size() {
return (offset + align) & ~align;
}
}
/** Copy bytes out of C memory into a Java byte array. */
public native void copyOut(int off,byte[] ba,int pos,int cnt);
/** Copy a Java byte array into C memory. */
public native void copyIn(int off,byte[] ba,int pos,int cnt);
public native byte getByte(int off);
public native void setByte(int off,byte val);
public native short getShort(int off);
public native void setShort(int off,short val);
public native int getInt(int off);
public native void setInt(int off,int val);
public native short getCShort(int off,int idx);
public native void setCShort(int off,int idx,short val);
public native int getCInt(int off,int idx);
public native void setCInt(int off,int idx,int val);
public short getCShort(int off) { return getCShort(off,0); }
public void setCShort(int off,short val ) { setCShort(off,0,val); }
public int getCInt(int off) { return getCInt(off,0); }
public void setCInt(int off,int val) { setCInt(off,0,val); }
}
| delonnewman/java-posix | CPtr.java | 1,503 | /** Return the offset of a nested struct. The members must have
already been added to the nested struct so that it will have
the proper size and alignment.
*/ | block_comment | en | false |
22922_5 | class Solution {
public String[] reorderLogFiles(String[] logs) {
Comparator<String> myComp = new Comparator<String>() {
@Override
public int compare(String log1, String log2) {
// split each log into two parts: <identifier, content>
String[] split1 = log1.split(" ", 2);
String[] split2 = log2.split(" ", 2);
boolean isDigit1 = Character.isDigit(split1[1].charAt(0));
boolean isDigit2 = Character.isDigit(split2[1].charAt(0));
// case 1). both logs are letter-logs
if (!isDigit1 && !isDigit2) {
// first compare the content
int cmp = split1[1].compareTo(split2[1]);
if (cmp != 0)
return cmp;
// logs of same content, compare the identifiers
return split1[0].compareTo(split2[0]);
}
// case 2). one of logs is digit-log
if (!isDigit1 && isDigit2)
// the letter-log comes before digit-logs
return -1;
else if (isDigit1 && !isDigit2)
return 1;
else
// case 3). both logs are digit-log
return 0;
}
};
Arrays.sort(logs, myComp);
return logs;
}
} | akhilkammila/leetcode-screenshotter | editorial_code/1-999/937. Reorder Data in Log Files/java-0.java | 315 | // the letter-log comes before digit-logs | line_comment | en | true |
23139_4 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.lsu.estimator;
import javax.persistence.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.math.BigDecimal;
/**
*
* @author kwang
*/
@Entity
@Table(name = "FUNDS")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Fund.findAll", query = "SELECT f FROM Fund f"),
@NamedQuery(name = "Fund.findByFundCode", query = "SELECT f FROM Fund f WHERE f.fundCode = :fundCode"),
@NamedQuery(name = "Fund.findByFundDesc", query = "SELECT f FROM Fund f WHERE f.fundDesc = :fundDesc"),
@NamedQuery(name = "Fund.findByReqNoteInd", query = "SELECT f FROM Fund f WHERE f.reqNoteInd = :reqNoteInd"),
@NamedQuery(name = "Fund.findByHasMatching", query = "SELECT f FROM Fund f WHERE f.hasMatching = :hasMatching"),
@NamedQuery(name = "Fund.findByMatchPerc", query = "SELECT f FROM Fund f WHERE f.matchPerc = :matchPerc"),
@NamedQuery(name = "Fund.findByMatchTop", query = "SELECT f FROM Fund f WHERE f.matchTop = :matchTop"),
@NamedQuery(name = "Fund.findByInstCapExcept", query = "SELECT f FROM Fund f WHERE f.instCapExcept = :instCapExcept"),
@NamedQuery(name = "Fund.findByPriority", query = "SELECT f FROM Fund f WHERE f.priority = :priority"),
@NamedQuery(name = "Fund.findByStatus", query = "SELECT f FROM Fund f WHERE f.status = :status order by f.fundDesc"),
@NamedQuery(name = "Fund.findByCreator", query = "SELECT f FROM Fund f WHERE f.creator = :creator"),
@NamedQuery(name = "Fund.findByUpdator", query = "SELECT f FROM Fund f WHERE f.updator = :updator"),
@NamedQuery(name = "Fund.findBySyncor", query = "SELECT f FROM Fund f WHERE f.syncor = :syncor"),
@NamedQuery(name = "Fund.findByEarningsMatch", query = "SELECT f FROM Fund f WHERE f.earningsMatch = :earningsMatch"),
@NamedQuery(name = "Fund.findByFundId", query = "SELECT f FROM Fund f WHERE f.fundId = :fundId")})
public class Fund implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "FUND_ID")
private Integer fundId;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "FUND_CODE")
private String fundCode;
@Size(max = 70)
@Column(name = "FUND_DESC")
private String fundDesc;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 10)
@Column(name = "REQ_NOTE_IND")
private String reqNoteInd;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 3)
@Column(name = "HAS_MATCHING")
private String hasMatching;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "MATCH_PERC")
private BigDecimal matchPerc;
@Column(name = "MATCH_TOP")
private Integer matchTop;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 3)
@Column(name = "INST_CAP_EXCEPT")
private String instCapExcept;
@Basic(optional = false)
@NotNull
@Column(name = "PRIORITY")
private int priority;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 10)
@Column(name = "STATUS")
private String status;
@Basic(optional = false)
@NotNull
@Column(name = "CREATOR")
private Integer creator;
@Column(name = "UPDATOR")
private Integer updator;
@Column(name = "SYNCOR")
private Integer syncor;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 3)
@Column(name = "EARNINGS_MATCH")
private String earningsMatch;
@Column(name = "DOM")
private long dom;
@Column(name = "DOE")
private long doe;
@Size(max = 20)
@Column(name = "DOETZ")
private String doetz;
@Size(max = 20)
@Column(name = "DOMTZ")
private String domtz;
@Column(name = "DOS")
private long dos;
@Size(max = 20)
@Column(name = "DOSTZ")
private String dostz;
@NotNull
@Min(0)
@Max(1)
@Column( name="AUTO_IND")//, columnDefinition="SMALLINT DEFAULT 0", nullable = false) // insertable=false will let JPA totally ignore this field when persisting
private Integer auto_ind = 0;
@NotNull
@Min(-1)
@Max(1)
@Column( name="MAX_IND")//, columnDefinition="SMALLINT DEFAULT 0", nullable = false)
private Integer max_ind = 0;
//JDO allows it in its ORM definition, so JPA needs catch up.
//columnDefinition, you won't get the database default value after an insert in your entity, have to refresh to get value from table
// ensure that default is set for non primitive types (setting null for example). Using @PrePersist and @PreUpdate
//e.g.
/*
@PrePersist
void preInsert() {
createdt = new Date();
}
*/
public Fund() {
}
public Fund(Integer fundId) {
this.fundId = fundId;
}
public Fund(Integer fundId, String fundCode, String reqNoteInd, String hasMatching, String instCapExcept, int priority, String status, Integer creator, String earningsMatch, long doe) {
this.fundId = fundId;
this.fundCode = fundCode;
this.reqNoteInd = reqNoteInd;
this.hasMatching = hasMatching;
this.instCapExcept = instCapExcept;
this.priority = priority;
this.status = status;
this.creator = creator;
this.earningsMatch = earningsMatch;
this.doe = doe;
}
public String getFundCode() {
return fundCode;
}
public void setFundCode(String fundCode) {
this.fundCode = fundCode;
}
public String getFundDesc() {
return fundDesc;
}
public void setFundDesc(String fundDesc) {
this.fundDesc = fundDesc;
}
public String getReqNoteInd() {
return reqNoteInd;
}
public void setReqNoteInd(String reqNoteInd) {
this.reqNoteInd = reqNoteInd;
}
public String getHasMatching() {
return hasMatching;
}
public void setHasMatching(String hasMatching) {
this.hasMatching = hasMatching;
}
public BigDecimal getMatchPerc() {
return matchPerc;
}
public void setMatchPerc(BigDecimal matchPerc) {
this.matchPerc = matchPerc;
}
public Integer getMatchTop() {
return matchTop;
}
public void setMatchTop(Integer matchTop) {
this.matchTop = matchTop;
}
public String getInstCapExcept() {
return instCapExcept;
}
public void setInstCapExcept(String instCapExcept) {
this.instCapExcept = instCapExcept;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getCreator() {
return creator;
}
public void setCreator(Integer creator) {
this.creator = creator;
}
public Integer getUpdator() {
return updator;
}
public void setUpdator(Integer updator) {
this.updator = updator;
}
public Integer getSyncor() {
return syncor;
}
public void setSyncor(Integer syncor) {
this.syncor = syncor;
}
public String getEarningsMatch() {
return earningsMatch;
}
public void setEarningsMatch(String earningsMatch) {
this.earningsMatch = earningsMatch;
}
public Integer getFundId() {
return fundId;
}
public void setFundId(Integer fundId) {
this.fundId = fundId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (fundId != null ? fundId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Fund)) {
return false;
}
Fund other = (Fund) object;
if ((this.fundId == null && other.fundId != null) || (this.fundId != null && !this.fundId.equals(other.fundId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "edu.lsu.estimator.Fund[ fundId=" + fundId + " ]";
}
public long getDom() {
return dom;
}
public void setDom(long dom) {
this.dom = dom;
}
public long getDoe() {
return doe;
}
public void setDoe(long doe) {
this.doe = doe;
}
public String getDoetz() {
return doetz;
}
public void setDoetz(String doetz) {
this.doetz = doetz;
}
public String getDomtz() {
return domtz;
}
public void setDomtz(String domtz) {
this.domtz = domtz;
}
public long getDos() {
return dos;
}
public void setDos(long dos) {
this.dos = dos;
}
public String getDostz() {
return dostz;
}
public void setDostz(String dostz) {
this.dostz = dostz;
}
public Integer getAuto_ind() {
return auto_ind;
}
public void setAuto_ind(Integer auto_ind) {
this.auto_ind = auto_ind;
}
public Integer getMax_ind() {
return max_ind;
}
public void setMax_ind(Integer max_ind) {
this.max_ind = max_ind;
}
}
| SaravanaManikandan92/sara92Coder | Fund.java | 2,670 | //, columnDefinition="SMALLINT DEFAULT 0", nullable = false) | line_comment | en | true |
23254_7 | package com.company;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.math.BigInteger;
import java.net.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
class TelegramBot
{
public String bot_url;
private String api_telegram_org = "https://api.telegram.org/bot";
public TelegramBot(String url)
{
bot_url = url;
}
public String getUpdates()
{
return getHttp(api_telegram_org + bot_url + "/getUpdates");
}
public Boolean writeAllData(String s1)
{
Boolean good = false;
ArrayList<String> res1 = new ArrayList<>();
for (int i = 0; i < s1.length(); i++)
{
if (i < s1.length() - 9)
{
if (s1.substring(i, i + 9).equals("update_id"))
{
if (s1.indexOf("update_id", i + 9) != -1)
{
String cur = s1.substring(i, s1.indexOf("update_id", i + 9));
cur = cur.substring(0, cur.length()-4);
if (!res1.contains(cur))
res1.add(cur);
}
else
{
String cur = s1.substring(i);
res1.add(cur);
}
}
}
}
File f1 = new File("../alldata.txt");
try
{
FileWriter fileWriter = new FileWriter(f1, true);
BufferedWriter bw = new BufferedWriter(fileWriter);
for (int i = 0; i < res1.size(); i++)
{
bw.write(res1.get(i));
bw.newLine();
}
bw.close();
good = true;
}
catch (Exception e){}
return good;
}
public ArrayList<String> findChatID(String s1)
{
ArrayList<String> res1 = new ArrayList<>();
for (int i = 0; i < s1.length(); i++)
{
if (i < s1.length() - 4)
{
String cur = "";
if (s1.substring(i, i + 4).equals("chat"))
{
for (int j = i + 12; j < s1.length(); j++)
{
if (s1.charAt(j) != ',')
cur += s1.charAt(j);
else
{
if (!res1.contains(cur))
res1.add(cur);
i = j;
break;
}
}
}
}
}
return res1;
}
public ArrayList<String> findText(String updates)
{
ArrayList<String> res1 = new ArrayList<>();
for (int i = 0; i < updates.length(); i++)
{
if (i < updates.length() - 4)
{
String cur = "";
if (updates.substring(i, i + 4).equals("text"))
{
for (int j = i + 7; j < updates.length(); j++)
{
if (updates.charAt(j) != '"')
cur += updates.charAt(j);
else
{
res1.add(cur);
i = j;
break;
}
}
}
}
}
return res1;
}
public ArrayList<String> readChatIDsFromFile(File f1)
{
ArrayList<String> res1 = new ArrayList<>();
String sub = "";
try
{
BufferedReader read1 = new BufferedReader(new FileReader(f1));
while ((sub = read1.readLine()) != null)
res1.add(sub);
}
catch (Exception e) {}
return res1;
}
public void writeChatIDsInFile(ArrayList<String> s1)
{
//if you want to save chat ids, then write here a full path for .txt file
//for example :
File f1 = new File("../chatIDs.txt");
ArrayList<String> entries = readChatIDsFromFile(f1);
try
{
FileWriter fileWriter = new FileWriter(f1, true);
BufferedWriter bw = new BufferedWriter(fileWriter);
for (int i = 0; i < s1.size(); i++)
{
if (!entries.contains(s1.get(i)+"&"))
{
bw.write(s1.get(i) + "&");
bw.newLine();
}
}
bw.close();
}
catch (Exception e) {}
}
public String fromUEStoUTF(String ues)
{
String res1 = "";
for (int i = 0; i < ues.length(); i++)
{
if (i < ues.length() - 1)
{
if (ues.substring(i, i + 2).equals("\\u"))
{
char cur = (char) Integer.parseInt(ues.substring(i + 2, i + 6), 16);
i += 5;
res1 += cur;
}
else
res1 += ues.charAt(i);
}
}
return res1;
}
public String getHttp(String http_url)
{
String res1 = "";
try
{
URL bot_url = new URL(http_url);
URLConnection connection = bot_url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
res1 += inputLine;
in.close();
}
catch(Exception e){}
return res1;
}
public void sendText(String chatID, String text)
{
try
{
final HttpClient httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();
HttpRequest request = HttpRequest.newBuilder()
.GET().uri(URI.create(api_telegram_org + bot_url + "/sendMessage?chat_id=" + chatID + "&text=" + text)).build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(api_telegram_org + bot_url + "/sendMessage?chat_id=" + chatID + "&text=" + text);
//System.out.println(response.body());
}
catch(Exception e){}
}
public void sendPhoto(String chatID, String photo_url)
{
try
{
final HttpClient httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();
HttpRequest request = HttpRequest.newBuilder()
.GET().uri(URI.create(api_telegram_org + bot_url + "/sendPhoto?chat_id=" + chatID + "&photo=" + photo_url)).build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
//System.out.println(api_telegram_org + bot_url + "/sendMessage?chat_id=" + chatID + "&text=" + text);
//System.out.println(response.body());
}
catch(Exception e){}
}
public String lastUpdID(String updates)
{
String res1 = "";
int idx = updates.lastIndexOf("update_id");
for (int i = idx + 11; i < updates.length(); i++)
{
if (updates.charAt(i) != ',')
{
res1 += updates.charAt(i);
}
else
break;
}
return res1;
}
public void clearUpdates(String lastUpd)
{
try
{
final HttpClient httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();
HttpRequest request = HttpRequest.newBuilder()
.GET().uri(URI.create("https://api.telegram.org/bot" + bot_url + "/getUpdates?offset=" + (Long.valueOf(lastUpd)+1))).build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
catch(Exception e){}
}
static String fromUTFtoUES(String s1)
{
String res1 = "";
for (int i = 0; i < s1.length(); i++)
{
if ((s1.charAt(i) >= 'a') && (s1.charAt(i) <= 'я') || (s1.charAt(i) >= 'А') && (s1.charAt(i) <= 'Я'))
res1 += s1.charAt(i);
if (s1.charAt(i) == ' ')
res1 += "%20";
if (i < s1.length() - 1 && s1.substring(i, i + 2).equals("\\n"))
{
res1 += "%0A";
i += 1;
}
}
return res1;
}
}
public class Main
{
static String botUrl = "YOUR_TOKEN";
public static void main(String[] args)
{
TelegramBot myBot = new TelegramBot(botUrl);
while (true)
{
try
{
String updates = (myBot.getUpdates());
ArrayList<String> ids = myBot.findChatID(updates);
ArrayList<String> texts = myBot.findText(updates);
System.out.println(updates);
//myBot.clearUpdates(myBot.lastUpdID(updates));
//Thread.sleep(2000);
}
catch (Exception e) {}
}
}
}
| jenyasubbotina/javaTelegramBot | Main.java | 2,229 | //myBot.clearUpdates(myBot.lastUpdID(updates));
| line_comment | en | true |
23612_0 | package a;
import com.tencent.matrix.trace.core.AppMethodBeat;
@l(dWo={1, 1, 13}, dWp={""}, dWq={"Lkotlin/LazyThreadSafetyMode;", "", "(Ljava/lang/String;I)V", "SYNCHRONIZED", "PUBLICATION", "NONE", "kotlin-stdlib"})
public enum k
{
static
{
AppMethodBeat.i(56414);
k localk1 = new k("SYNCHRONIZED", 0);
AUl = localk1;
k localk2 = new k("PUBLICATION", 1);
AUm = localk2;
k localk3 = new k("NONE", 2);
AUn = localk3;
AUo = new k[] { localk1, localk2, localk3 };
AppMethodBeat.o(56414);
}
}
/* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes-dex2jar.jar
* Qualified Name: a.k
* JD-Core Version: 0.6.2
*/ | 0jinxing/wechat-apk-source | a/k.java | 283 | /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes-dex2jar.jar
* Qualified Name: a.k
* JD-Core Version: 0.6.2
*/ | block_comment | en | true |
24100_9 | /**
* @author Alena Fisher
*/
import java.util.ArrayList;
public class Coach {
// Creating instance variables
private String name;
private String title;
private String department;
private String officeLocation;
private String phoneNumber;
private String email;
public Coach(String name, String title, String department, String officeLocation, String phoneNumber, String email) {
/**
* This method receives 'name', 'title', 'department', 'officeLocation', 'phoneNumber', and 'email' as explicit parameters and assigns them to the instance variables
*/
this.name = name;
this.title = title;
this.department = department;
this.officeLocation = officeLocation;
this.phoneNumber = phoneNumber;
this.email = email;
}
public String getCoachName() {
/**
* This method returns the coach's name
*/
return name;
}
public String getOfficeLocation() {
/**
* This method returns the coach's office location
*/
return officeLocation;
}
public String getTitle() {
/**
* This method returns the coach's title
*/
return title;
}
public String getDepartment() {
/**
* This method returns the coach's department
*/
return department;
}
public String getPhoneNumber() {
/**
* This method returns the coach's phone number
*/
return phoneNumber;
}
public String getEmail() {
/**
* This method returns the coach's email address
*/
return email;
}
public void setCoachName(String name) {
/**
* This method receives 'name' as an explicit parameter and assigns it to the instance variable
*/
this.name = name;
}
public void setOfficeLocation(String officeLocation) {
/**
* This method receives 'officeLocation' as an explicit parameter and assigns it to the instance variable
*/
this.officeLocation = officeLocation;
}
public void setTitle(String title) {
/**
* This method receives 'title' as an explicit parameter and assigns it to the instance variable
*/
this.title = title;
}
public void setDepartment(String department) {
/**
* This method receives 'department' as an explicit parameter and assigns it to the instance variable
*/
this.department = department;
}
public void setPhoneNumber(String phoneNumber) {
/**
* This method receives 'phoneNumber' as an explicit parameter and assigns it to the instance variable
*/
this.phoneNumber = phoneNumber;
}
public void setEmail(String email) {
/**
* This method receives 'email' as an explicit parameter and assigns it to the instance variable
*/
this.email = email;
}
}
| AlenaFisher/CS234 | S3/Coach.java | 606 | /**
* This method receives 'name' as an explicit parameter and assigns it to the instance variable
*/ | block_comment | en | false |
24181_0 | package class_files;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class UpdateStaff extends JFrame implements ActionListener{
JTextField tffname,tfaddress,tfemail,tfphone,tfeducation;
JButton update,back;
JLabel lblname, lblsalary, lbldob, labelsid;
String memberName;
UpdateStaff(String memberName){
this.memberName = memberName;
getContentPane().setBackground(Color.WHITE);
setLayout(null);
setTitle("Update Staff details - Library");
JLabel heading=new JLabel("<html><p style='border-bottom: 3px solid rgb(BLACK);'> Update Staff Details </p></html>");
heading.setBounds(230,37,500,50);
heading.setFont(new Font("MONOSPACED",Font.BOLD,30));
heading.setBackground(Color.WHITE);
heading.setForeground(Color.BLACK);
add(heading);
Font font = new Font("Arial", Font.PLAIN, 18);
JLabel labelsname=new JLabel("Name:");
labelsname.setBounds(50,120,180,65);
labelsname.setFont(new Font("Arial",Font.BOLD,18));
add(labelsname);
lblname = new JLabel();
lblname.setBounds(200,140,180,30);
lblname.setFont(font);
add(lblname);
JLabel labelfname=new JLabel("Fathers Name:");
labelfname.setBounds(430,120,180,65);
labelfname.setFont(new Font("Arial",Font.BOLD,18));
add(labelfname);
tffname=new JTextField();
tffname.setBounds(600,140,180,30);
tffname.setFont(font);
add(tffname);
JLabel labelsalary=new JLabel("Salary:");
labelsalary.setBounds(430,170,170,65);
labelsalary.setFont(new Font("Arial",Font.BOLD,18));
add(labelsalary);
lblsalary=new JLabel();
lblsalary.setBounds(600,190,180,30);
lblsalary.setFont(font);
add(lblsalary);
JLabel labeldob=new JLabel("Date of Birth:");
labeldob.setBounds(50,170,170,65);
labeldob.setFont(new Font("Arial",Font.BOLD,18));
add(labeldob);
/*JDateChooser dcdob=new JDateChooser();
dcdob.setBounds(150,190,170,50);
add(dcdob);*/
lbldob=new JLabel();
lbldob.setBounds(200,190,180,30);
lbldob.setFont(font);
add(lbldob);
JLabel labeladdress=new JLabel("Address:");
labeladdress.setBounds(50,220,170,65);
labeladdress.setFont(new Font("Arial",Font.BOLD,18));
add(labeladdress);
tfaddress =new JTextField();
tfaddress.setBounds(200,240,180,30);
tfaddress.setFont(font);
add(tfaddress);
JLabel labelemail=new JLabel("Email Address:");
labelemail.setBounds(430,270,170,65);
labelemail.setFont(new Font("Arial",Font.BOLD,18));
add(labelemail);
tfemail=new JTextField();
tfemail.setBounds(600,290,180,30);
tfemail.setFont(font);
add(tfemail);
JLabel labelphone=new JLabel("Phone number:");
labelphone.setBounds(50,270,180,65);
labelphone.setFont(new Font("Arial",Font.BOLD,18));
add(labelphone);
tfphone=new JTextField();
tfphone.setBounds(200,290,180,30);
tfphone.setFont(font);
add(tfphone);
JLabel labeleducation=new JLabel("Highest education:");
labeleducation.setBounds(430,220,170,65);
labeleducation.setFont(new Font("Arial",Font.BOLD,18));
add(labeleducation);
tfeducation=new JTextField();
tfeducation.setBounds(600,240,180,30);
tfeducation.setBackground(Color.WHITE);
tfeducation.setFont(font);
add(tfeducation);
JLabel labelstaffid=new JLabel("Staff Id:");
labelstaffid.setBounds(50,360,170,50);
labelstaffid.setFont(new Font("Arial",Font.BOLD,20));
add(labelstaffid);
labelsid=new JLabel();
labelsid.setBounds(200,360,170,50);
labelsid.setFont(new Font("Arial",Font.PLAIN,20));
add(labelsid);
try{
Conn c=new Conn();
String query= "select * from staffdetails where memberName= '"+memberName+"'";
ResultSet rs=c.s.executeQuery(query);
while(rs.next()) {
lblname.setText(rs.getString("memberName"));
tffname.setText(rs.getString("fatherName"));
lbldob.setText(rs.getString("dob"));
tfaddress.setText(rs.getString("address"));
lblsalary.setText(rs.getString("salary"));
tfphone.setText(rs.getString("phone"));
tfemail.setText(rs.getString("email"));
tfeducation.setText(rs.getString("education"));
labelsid.setText(rs.getString("staffId"));
}
}
catch(Exception e){
e.printStackTrace();
}
update=new JButton("Update Detail");
update.setBounds(200,460,170,50);
update.setFont(new Font("Arial",Font.PLAIN,18));
update.addActionListener(this);
update.setBackground(Color.BLACK);
update.setForeground(Color.WHITE);
update.setFocusPainted(false);
add(update);
back=new JButton("Back");
back.setBounds(460,460,170,50);
back.setFont(new Font("Arial",Font.PLAIN,18));
back.addActionListener(this);
back.setBackground(Color.BLACK);
back.setFocusPainted(false);
back.setForeground(Color.WHITE);
add(back);
setSize(860,650);
setLocation(300,50);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == update){
String fatherName = tffname.getText();
String address = tfaddress.getText();
String education = tfeducation.getText();
String phone = tfphone.getText();
String email = tfemail.getText();
if(memberName.length() != 0 && fatherName.length() >= 3 && address.length() != 0 && education.length() != 0 && phone.length() >= 10 && email.contains("@") && email.contains("mail.com")){
try{
Conn conn = new Conn();
String query = "update staffdetails set fatherName = '"+fatherName+"' , address = '"+address+"' , education = '"+education+"' , phone = '"+phone+"' , email = '"+email+"' where memberName = '"+memberName+"'";
conn.s.executeUpdate(query);
JOptionPane.showMessageDialog(null, "Member Details Updated Successfully");
setVisible(false);
new StaffDetails();
} catch(Exception e){
e.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(null, "All Details Field are Mandatory");
}
}
else{
setVisible(false);
new StaffDetails();
}
}
public static void main(String args[]){
new UpdateStaff("");
}
}
| Nidhisikarwar/JAVA-PROJECT | UpdateStaff.java | 1,906 | /*JDateChooser dcdob=new JDateChooser();
dcdob.setBounds(150,190,170,50);
add(dcdob);*/ | block_comment | en | true |
24292_0 | /* Trade Fairs are important for companies to present their products and to get in touch with its customers and business parties. One such grandeur Trade Fair Event was organized by the Confederation of National Large Scale Industry.
Number of people who attended the event on the first day was x. But as days progressed, the event gained good response and the number of people who attended the event on the second day was twice the number of people who attended on the first day. Unfortunately due to heavy rains on the third day, the number of people who attended the event was exactly half the number of people who attended on the first day.
Given the total number of people who have attended the event in the first 3 days, find the number of people who have attended the event on day 1, day 2 and day 3.
Input Format:
First line of the input is an integer value that corresponds to the total number of people.
Output Format:
First line of the output should display the number of attendees on day 1.
Second line of the output should display the number of attendees on day 2.
Third line of the output should display the number of attendees on day 3.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and rest corresponds to output.]
Sample Input and Output:
Enter the total number of people
10500
Number of attendees on day 1 : 3000
Number of attendees on day 2 : 6000
Number of attendees on day 3 : 1500*/
//package
import java.util.Scanner;
//main class
class Event2 {
//main method
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the total number of people ");
int total=sc.nextInt();
int day1=(2*total)/7;
int day2=day1*2;
int day3=day1/2;
System.out.println("Number of attendees on day 1:"+day1);
System.out.println("Number of attendees on day 2:"+day2);
System.out.println("Number of attendees on day 3:"+day3);
}
} | Lokesh-Devisetti/Java-Tarabai-batch | Event2.java | 513 | /* Trade Fairs are important for companies to present their products and to get in touch with its customers and business parties. One such grandeur Trade Fair Event was organized by the Confederation of National Large Scale Industry.
Number of people who attended the event on the first day was x. But as days progressed, the event gained good response and the number of people who attended the event on the second day was twice the number of people who attended on the first day. Unfortunately due to heavy rains on the third day, the number of people who attended the event was exactly half the number of people who attended on the first day.
Given the total number of people who have attended the event in the first 3 days, find the number of people who have attended the event on day 1, day 2 and day 3.
Input Format:
First line of the input is an integer value that corresponds to the total number of people.
Output Format:
First line of the output should display the number of attendees on day 1.
Second line of the output should display the number of attendees on day 2.
Third line of the output should display the number of attendees on day 3.
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and rest corresponds to output.]
Sample Input and Output:
Enter the total number of people
10500
Number of attendees on day 1 : 3000
Number of attendees on day 2 : 6000
Number of attendees on day 3 : 1500*/ | block_comment | en | true |
24679_2 | package models;
import play.db.jpa.JPABase;
import play.db.jpa.Model;
import javax.persistence.*;
import java.util.*;
@Entity
@Table(name = "my_recipe")
public class Recipe extends Model {
public String title;
public Date postedAt;
public Date updatedAt;
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL)
public List<Ingredient> ingredients;
@ManyToOne
public User author;
public String source;
public double serves;
public String servesUnit;
// public Blob photo;
// public Blob photoThumb;
@Basic
@Column(name = "steps", columnDefinition = "text")
public String steps;
@Basic
@Column(name = "description", columnDefinition = "text")
public String description;
@ManyToMany(cascade = CascadeType.PERSIST)
public Set<Tag> tags;
public String photoName;
public String photoThumbName;
public Recipe(User author, String title, String description, String steps, String source, double serves, String servesUnit) {
this.ingredients = new ArrayList<Ingredient>();
this.tags = new HashSet<Tag>();
this.author = author;
this.title = title;
this.description = description;
this.steps = steps;
this.source = source;
this.serves = serves;
this.servesUnit = servesUnit;
this.postedAt = new Date();
this.updatedAt = postedAt;
}
public Recipe(User user) {
this.author = user;
this.ingredients = new ArrayList<Ingredient>();
this.tags = new HashSet<Tag>();
this.postedAt = new Date();
this.updatedAt = postedAt;
}
public <T extends JPABase> T save() {
T returned = super.save();
updatedAt = new Date();
return returned;
}
public Ingredient addIngredient(Double amount, String unit, String description) {
Ingredient newIngredient = new Ingredient(this, amount, unit, description).save();
this.ingredients.add(newIngredient);
this.save();
return newIngredient;
}
public Recipe tagItWith(String name) {
if (!tags.contains(Tag.hashName(name))) {
tags.add(Tag.findOrCreateByName(name));
}
return this;
}
/* public static List<Recipe> findTaggedWith(String tag) {
return Recipe.find(
"select DISTINCT(r.id) from Recipe r join r.tags as t where t.nameHash = '?'", tag
).fetch();
}
*/
public static List<Recipe> findTaggedWith(String... tags) {
return Recipe.find(
"select distinct p from Recipe p join p.tags as t where t.nameHash in (:tags) group by p.id, p.author, p.title, p.description, p.steps, p.source, p.postedAt having count(t.id) = :size"
).bind("tags", tags).bind("size", tags.length).fetch();
}
public boolean isFavorite(User user)
{
return user.favorites.contains(this);
}
} | threecee/kokboka | app/models/Recipe.java | 719 | /* public static List<Recipe> findTaggedWith(String tag) {
return Recipe.find(
"select DISTINCT(r.id) from Recipe r join r.tags as t where t.nameHash = '?'", tag
).fetch();
}
*/ | block_comment | en | true |
24771_0 | package finalproject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MyTester {
public static void main(String[] args) throws Exception {
testXml1();
testXml2();
testXml3();
testXml4();
}
private static void testXml1() throws Exception{
System.out.println("----------TESTING test.xml----------");
SearchEngine searchEngine = new SearchEngine("test.xml");
searchEngine.crawlAndIndex("www.cs.mcgill.ca");
searchEngine.assignPageRanks(0.001);
//the following code only works for xml files given by prof
for (String url : searchEngine.internet.getVertices()){
double expectedRank = searchEngine.parser.getPageRank(url);
double actualRank = searchEngine.internet.getPageRank(url);
if (Math.abs(expectedRank-actualRank)>0.001){
System.out.println("Wrong page rank for " + url);
}
}
System.out.println();
}
private static void testXml2() throws Exception{
System.out.println("----------TESTING cs20Links.xml----------");
SearchEngine searchEngine = new SearchEngine("cs20Links.xml");
searchEngine.crawlAndIndex("https://cs.mcgill.ca/");
searchEngine.assignPageRanks(0.001);
System.out.println();
ArrayList<String> results = searchEngine.getResults("engineering");
int count=1;
for (String result : results){
System.out.println(count + ". " + result + " Rank: " + searchEngine.internet.getPageRank(result));
count++;
}
System.out.println();
}
private static void testXml3() throws Exception {
System.out.println("----------TESTING cs60Links.xml----------");
SearchEngine searchEngine = new SearchEngine("cs60Links.xml");
searchEngine.crawlAndIndex("https://cs.mcgill.ca/");
searchEngine.assignPageRanks(0.001);
System.out.println();
ArrayList<String> results = searchEngine.getResults("search");
int count=1;
for (String result : results){
System.out.println(count + ". " + result + " Rank: " + searchEngine.internet.getPageRank(result));
count++;
}
System.out.println();
}
private static void testXml4() throws Exception {
System.out.println("----------TESTING mcgillWiki.xml----------");
SearchEngine searchEngine = new SearchEngine("mcgillWiki.xml");
searchEngine.crawlAndIndex("https://en.wikipedia.org/wiki/McGill_University");
searchEngine.assignPageRanks(0.001);
System.out.println();
ArrayList<String> results = searchEngine.getResults("chemical");
int count=1;
for (String result : results){
System.out.println(count + ". " + result + " Rank: " + searchEngine.internet.getPageRank(result));
count++;
}
System.out.println();
}
}
| charlottevolk/250-Final-Project-Tester | MyTester.java | 740 | //the following code only works for xml files given by prof | line_comment | en | true |
24927_5 | // 1 dist, 1 exe build in the package
ReleaseTemplate.release("community") {
distribution("standard").from {
exe = Launch4jExeTemplate.exe {
from = "/release/standard/exe"
}
companionFiles = "/release/standard/companion"
}
}
// or could we do dist ?
ReleaseTemplate.release("community") {
dist {
exe = Launch4jExeTemplate.exe {
from = "/release/standard/exe"
}
companionFiles = "/release/standard/companion"
}
}
// or with a distribution template, could be shortened still more
ReleaseTemplate.release("community") {
distribution("standard").from {
template = Launch4jDistributionTemplate.dist {
resourcesDir = "/release/standard"
}
}
}
// or better yet?
ReleaseTemplate.release("community") {
dist(Launch4jDistributionTemplate){
resourcesDir = "/release/community/gui"
}
}
// or better yet?
// we can translate the release name from either camel case or snake case.
// The distribution will assume we are using the default distribution (for this release name) if none
// is provided we can either create or retrieve it as necessary.
task communityRelease {
dist(Launch4jDistributionTemplate){
resourcesDir = "/release/community/gui"
}
}
// accessors
releases.community.distributions.community.resourcesDir
releases.community.distributions.community.exeTask
releases.community.distributions.community.distributionBuildTask
releases.community.distributions.community.distributionAssembleTask
// 1 dist, 2 exe builds in the package
// N.B. would require that the names of the outputs from the exe tasks MUST be different!
ReleaseTemplate.release("community") {
dist {
template = Launch4jDistributionTemplate.dist {
exe("gui") {
resourcesDir = "/release/community/gui"
custom {
headerType = "gui"
}
}
exe("console") {
resourcesDir = "/release/community/console"
custom {
headerType = "console"
}
}
}
}
}
// or this! We could define some kind of an interface
// that would require either a no-args constructor
// or a constructor(Project).
ReleaseTemplate.release("community") {
dist(Launch4jDistributionTemplate){
exe("gui") {
resourcesDir = "/release/community/gui"
config {
headerType = "gui"
}
}
exe("console") {
resourcesDir = "/release/community/console"
config {
headerType = "console"
}
}
}
}
// or, considering launch4j.properties...
task communityRelease(type: ReleaseTemplateTask) {
dist(Launch4jDistributionTemplate){
exe("gui") {
resourcesDir = "/release/community/shared"
config("/release/shared/launch4j.properties") {
myCustomProperty = "someCustomValue"
dependsOn someCustomJarTask
copyConfigurable = someCustomJarTask.outputs.files
}
}
exe("console") {
resourcesDir = "/release/community/shared"
}
}
}
// 2 dist, 1 exe in each package
ReleaseTemplate.release("allEditions") {
distribution("community").from {
template = Launch4jDistributionTemplate.dist {
resourcesDir = "/editions/community"
}
}
distribution("ultimate").from {
template = Launch4jDistributionTemplate.dist {
resourcesDir = "/editions/ultimate"
}
}
}
// 2 dist, 2 exe builds in each package
ReleaseTemplate.release("community") {
dist("community", Launch4jDistributionTemplate){
exe("gui") {
resourcesDir = "/release/community/gui" // copies exe build info and companions
custom {
headerType = "gui"
}
}
exe("console") {
resourcesDir = "/release/community/console"
custom {
headerType = "console"
}
}
}
dist("ultimate", Launch4jDistributionTemplate){
exe("gui") {
resourcesDir = "/release/ultimate/gui"
custom {
headerType = "gui"
}
}
exe("console") {
resourcesDir = "/release/ultimate/console"
custom {
headerType = "console"
}
}
}
}
// and considering breaking the whole thing down into more manageable pieces
task communityDistribution(type: Launch4jDistributionTemplateTask) {
exe("gui", Launch4jExeTemplate) {
resourcesDir = "/release/community/shared"
config("/release/shared/launch4j.properties") {
myCustomProperty = "someCustomValue"
dependsOn someCustomJarTask
copyConfigurable = someCustomJarTask.outputs.files
}
}
exe("console", Launch4jExeTemplate) {
resourcesDir = "/release/community/shared"
}
}
// and breaking the exe build out of the distribution...
task communityDisributionGuiExe(type: Launch4jExeTemplateTask) {
resourcesDir = "/release/community/shared"
config {
myCustomProperty = "someCustomValue"
dependsOn someCustomJarTask
copyConfigurable = someCustomJarTask.outputs.files
}
}
| alessandroscarlatti/launch4j-gradle-plugin | syntax-demo.java | 1,337 | // we can translate the release name from either camel case or snake case. | line_comment | en | false |
25044_13 |
import java.util.Random;
/**
* A Deck of 52 Cards which can be dealt and shuffled
*
* Some functions could be made much faster with some extra memory.
* I invite anyone to do so ;-)
*
* <P>Source Code: <A HREF="http://www.cs.ualberta.ca/~davidson/poker/src/poker/Deck.java">Deck.java</A><P>
*
* @author Aaron Davidson
* @version 1.0.1
*/
public class Deck {
public static final int NUM_CARDS = 52;
private Card[] gCards = new Card[NUM_CARDS];
private char position;
private Random r = new Random();
/**
* Constructor.
*/
public Deck() {
position = 0;
for (int i=0;i<NUM_CARDS;i++) {
gCards[i] = new Card(i);
}
}
/**
* Constructor w/ shuffle seed.
* @param seed the seed to use in randomly shuffling the deck.
*/
public Deck(long seed) {
this();
if (seed == 0) seed = System.currentTimeMillis();
r.setSeed(seed);
}
/**
* Places all cards back into the deck.
* Note: Does not sort the deck.
*/
public void reset() { position = 0; }
/**
* Shuffles the cards in the deck.
*/
public void shuffle() {
Card tempCard;
int i,j;
for (i=0; i<NUM_CARDS; i++) {
j = i + randInt(NUM_CARDS-i);
tempCard = gCards[j];
gCards[j] = gCards[i];
gCards[i] = tempCard;
}
position = 0;
}
/**
* Obtain the next card in the deck.
* If no cards remain, a null card is returned
* @return the card dealt
*/
public Card deal() {
return (position < NUM_CARDS ? gCards[position++] : null);
}
/**
* Find position of Card in Deck.
*/
public int findCard(Card c) {
int i = position;
int n = c.getIndex();
while (i < NUM_CARDS && n != gCards[i].getIndex())
i++;
return (i < NUM_CARDS ? i : -1);
}
private int findDiscard(Card c) {
int i = 0;
int n = c.getIndex();
while (i < position && n != gCards[i].getIndex())
i++;
return (n == gCards[i].getIndex() ? i : -1);
}
/**
* Remove all cards in the given hand from the Deck.
*/
public void extractHand(Hand h) {
for (int i=1;i<=h.size();i++)
this.extractCard(h.getCard(i));
}
/**
* Remove a card from within the deck.
* @param c the card to remove.
*/
public void extractCard(Card c) {
int i = findCard(c);
if (i != -1) {
Card t = gCards[i];
gCards[i] = gCards[position];
gCards[position] = t;
position++;
} else {
System.err.println("*** ERROR: could not find card " + c);
}
}
/**
* Remove and return a randomly selected card from within the deck.
*/
public Card extractRandomCard() {
int pos = position+randInt(NUM_CARDS-position);
Card c = gCards[pos];
gCards[pos] = gCards[position];
gCards[position] = c;
position++;
return c;
}
/**
* Return a randomly selected card from within the deck without removing it.
*/
public Card pickRandomCard() {
return gCards[position+randInt(NUM_CARDS-position)];
}
/**
* Place a card back into the deck.
* @param c the card to insert.
*/
public void replaceCard(Card c) {
int i = findDiscard(c);
if (i != -1) {
position--;
Card t = gCards[i];
gCards[i] = gCards[position];
gCards[position] = t;
}
}
/**
* Obtain the position of the top card.
* (the number of cards dealt from the deck)
* @return the top card index
*/
public int getTopCardIndex() {
return position;
}
/**
* Obtain the number of cards left in the deck
*/
public int cardsLeft() {
return NUM_CARDS-position;
}
/**
* Obtain the card at a specific index in the deck.
* Does not matter if card has been dealt or not.
* If i < topCardIndex it has been dealt.
* @param i the index into the deck (0..51)
* @return the card at position i
*/
public Card getCard(int i) {
return gCards[i];
}
public String toString() {
StringBuffer s = new StringBuffer();
s.append("* ");
for (int i=0;i<position;i++)
s.append(gCards[i].toString()+" ");
s.append("\n* ");
for (int i=position;i<NUM_CARDS;i++)
s.append(gCards[i].toString()+" ");
return s.toString();
}
private int randInt(int range) {
return (int)(r.nextDouble()*range);
}
}
| lukassaul/kelly-poker | Deck.java | 1,429 | /**
* Obtain the number of cards left in the deck
*/ | block_comment | en | false |
25245_0 | //write a program to calculate the area of square & rectangle overloading the area method.
class p6
{
void area(int l)
{
System.out.println("Area of square=> "+(l*l));
}
void area(int l,int b)
{
System.out.println("Area of Rectangle=> "+(l*b));
}
public static void main(String []args)
{
p6 one=new p6();
one.area(6);
one.area(8,8);
}
}
| Rutvik5o/Practice-Programming | p6.java | 128 | //write a program to calculate the area of square & rectangle overloading the area method.
| line_comment | en | false |
25670_6 | /*
* class Customer defines a registered customer. It keeps track of the customer's name and address.
* A unique id is generated when when a new customer is created.
*
* Implement the Comparable interface and compare two customers based on name
*/
public class Customer implements Comparable<Customer>
{
private String id;
private String name;
private String shippingAddress;
Cart cart;
/** Main constructor that creates a customer with their specified id, name and address.
*
* @param id - is the string id of the customer.
* @param name - is the string name of the customer.
* @param address - is the address of the customer in a string.
*/
public Customer(String id, String name, String address)
{
this.id = id;
this.name = name;
this.shippingAddress = address;
cart = new Cart(id);
}
/** Constructor for customer.
* @param id - is the assigned id to a customer.
*/
public Customer(String id)
{
this.id = id;
this.name = "";
this.shippingAddress = "";
}
/** Constructor that creates a customer with their specified id, name, address and cart.
*
* @param id - is the string id of the customer.
* @param name - is the string name of the customer.
* @param address - is the address of the customer in a string.
* @param cart - is the cart assigned to the customer
*/
public Customer(String id, String name, String address, Cart cart)
{
this.id = id;
this.name = name;
this.shippingAddress = address;
this.cart = cart;
}
/** Gets the id of the customer.
* @return the id of the customer.
*/
public String getId()
{
return id;
}
/*
* Set the id for the customer.
*/
public void setId(String id)
{
this.id = id;
}
/** Gets the name of the customer.
* @return the name of the customer.
*/
public String getName()
{
return name;
}
/*
* Set the name of the customer.
*/
public void setName(String name)
{
this.name = name;
}
/** Gets the shipping address of the customer.
* @return the shipping address of the customer.
*/
public String getShippingAddress()
{
return shippingAddress;
}
/*
* Set the shipping address of the customer.
*/
public void setShippingAddress(String shippingAddress)
{
this.shippingAddress = shippingAddress;
}
/** Gets the cart that belongs to the customer.
* @return the customer's cart.
*/
public Cart getCustCart()
{
return cart;
}
/*
* Gives a string representation of the customer object.
* Prints the name, id and shipping address of the customer as a formatted string.
*/
public void print()
{
System.out.printf("\nName: %-20s ID: %3s Address: %-35s", name, id, shippingAddress);
}
/*
* Two customers are equal if they have the same product Id.
* This method is inherited from superclass Object and overridden here
*/
public boolean equals(Object other)
{
Customer otherC = (Customer) other;
return this.id.equals(otherC.id);
}
//compareTo method (comparable interface) for SORTCUSTS action
public int compareTo(Customer otherCust) {
return this.getName().compareTo(otherCust.getName());
}
}
| jenniferchung14/E-Commerce-System-Simulator | Customer.java | 912 | /** Gets the name of the customer.
* @return the name of the customer.
*/ | block_comment | en | false |
25693_0 | /*
Name : Hoo Ern Ping
ID : B200152B
*/
package application;
public class Customer {
//-------instance variable--------
private String customerId;
private String customerName;
private int quantity;
private String shippingMethod;
//-------default constructor-------
public Customer(){
customerId = "";
customerName = "";
quantity = 0;
shippingMethod = "";
}
//------------Constructor with parameter------------------
public Customer(String customerId,
String customerName,
int quantity,
String shippingMethod){
this.customerId = customerId;
this.customerName = customerName;
this.quantity = quantity;
this.shippingMethod = shippingMethod;
}
//----------accessor methods or get methods------------
public String getCustomerId(){
return customerId;
}
public String getCustomerName(){
return customerName;
}
public int getQuantity(){
return quantity;
}
public String getShippingMethod(){
return shippingMethod;
}
//----------mutator methods or set methods--------------
public void setCustomerId(String newCustomerId){
customerId = newCustomerId;
}
public void setCustomerName(String newCustomerName){
customerName = newCustomerName;
}
public void setQuantity(int newQuantity){
quantity = newQuantity;
}
public void setShippingMethod(String newShippingMethod){
shippingMethod = newShippingMethod;
}
//------------------task method------------------------
//Compute the unit price
public double calcTotalPrice(){
double unit = getQuantity();
double totalPrice = 0.0;
if(unit >= 216){
totalPrice = unit * 2.00;
}
else if(unit >= 108){
totalPrice = unit * 2.27;
}
else if(unit >= 48){
totalPrice = unit * 2.63;
}
else {
totalPrice = unit * 2.85;
}
return totalPrice;
}
//Compute shipping charge
public double calcTotalShippingCharge(){
double chargePerUnit = 0.0;
if(getShippingMethod().equalsIgnoreCase("Truck")) {
chargePerUnit = 0.20;
}else if(getShippingMethod().equalsIgnoreCase("Rail")) {
chargePerUnit = 0.18;
}else if(getShippingMethod().equalsIgnoreCase("Ship")) {
chargePerUnit = 0.12;
}else {
chargePerUnit = 0.0;
}
return chargePerUnit * getQuantity();
}
//------------------toString Method-----------------------
public String toString() {
return "\nCustomer ID: "+getCustomerId()+
"\nCustomer Name: "+getCustomerName()+
"\nQuantity: "+getQuantity()+
"\nTotal Price: "+String.format("%.2f",calcTotalPrice())+
"\nTotal Shipping: "+String.format("%.2f",calcTotalShippingCharge());
}
}
| HooEP01/the-zone-system | Customer.java | 686 | /*
Name : Hoo Ern Ping
ID : B200152B
*/ | block_comment | en | true |
26033_2 | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalField;
import java.util.concurrent.Exchanger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ForumDB {
private Connection connection;
private int id = 0;
/*
* Constructor for the ForumDB class
*
* @return a new forumdb object
*/
public ForumDB() {
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("JDBC:sqlite:forum.db");
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Prints all the users from the database
*/
public void printUsers() {
try {
var s = connection.createStatement();
System.out.println("Current users:");
var rs = s.executeQuery("select name from Users;");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Adds a new subforum to the forum
*
* @param name the name of the subforum to be added
*/
public void addSubforum(String name) {
try {
var ps = connection.prepareStatement("INSERT INTO Subforum (name) VALUES (?);");
ps.setString(1, name);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Adds a new post to the subforum
*
* @param subforum_id id of the subforum where post is to be added
* @param post_title heading of the post to be added
* @param post_body body, the text of the forum post to be added
* @param post_date the purported date when the post was posted
* @param userid the id of the user who posted the post
*/
public void addPostToSubforum(int subforum_id, String post_title, String post_body, String post_date,
int userid)
{
try {
String post_text = post_title.toUpperCase() + "\n\n" + post_body;
var ps = connection.prepareStatement("INSERT INTO Posts (userid, subforumid, time, text) VALUES (?, ?, ?, ?);");
ps.setInt(1, userid);
ps.setInt(2, subforum_id);
ps.setString(3, post_date);
ps.setString(4, post_text);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Censors a subforum post based on id
*
* @param postID the id of the post to be censored.
*/
public void censorPost (int postID) {
try {
var ps = connection.prepareStatement("UPDATE Posts SET body = '[CENSORED]' WHERE id = ?;");
ps.setInt(1, postID);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Sets the body of the post to a specified string.
*
* @param postID id of the post to be altered
* @param body the text string that the body of the post is going to be replaced with
*/
public void setPostBody (int postID, String body) {
try {
var ps = connection.prepareStatement("UPDATE Posts SET text = ? WHERE id = ?;");
ps.setString(1, body);
ps.setInt(2, postID);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Adds a user to the list of moderators based on the id
*
* @param userID id of the user to be promoted to the moderator status
*/
public void appointModerator(int userID) {
try {
var ps = connection.prepareStatement("INSERT INTO ModeratorList (userid) SELECT Users.id FROM Users WHERE Users.id = ?;");
ps.setInt(1, userID);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Gets the name of the user with the specified id
*
* @param userid id of the user to get the username of
* @return the name of the user
*/
public String getUserName(int userid) {
try {
var ps = connection.prepareStatement("select name from Users where id = ?;");
ps.setInt(1, userid);
var rs = ps.executeQuery();
rs.next();
System.out.println(rs.getString("name"));
String name = rs.getString("name");
ps.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return e.getStackTrace().toString();
}
}
/*
* set
*/
public void setUserName(int userid, String name) {
try {
var ps = connection.prepareStatement("UPDATE Users SET name=? where id = ?;");
ps.setString(1, name);
ps.setInt(2, userid);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Post createPost(String title, String body, Date date, int authorId) {
int postID = -1; //is supposed to be a post containing [ERROR]
try {
var ps = connection.prepareStatement("INSERT INTO Posts (title, body, userid, date) VALUES (?, ?, ?, ?) RETURNING id ;");
ps.setString(1, title);
ps.setString(2, body);
ps.setInt(3, authorId);
ps.setString(4, new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()));
var rs = ps.executeQuery();
postID = rs.getInt("id");
rs.close();
ps.close();
return new Post(postID, this);
} catch (Exception e) {
e.printStackTrace();
return new Post(postID, this);
}
}
public String getPostTitle(int id) {
try {
var ps = connection.prepareStatement("SELECT title FROM Posts WHERE id = ?;");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
String title = rs.getString("title");
ps.close();
rs.close();
return title;
} catch (Exception e) {
e.printStackTrace();
return "[ERROR]" + e.getStackTrace();
}
}
public String getPostBody(int postId) {
try {
var ps = connection.prepareStatement("SELECT body FROM Posts WHERE id = ?;");
ps.setInt(1, postId);
ResultSet rs = ps.executeQuery();
String body = rs.getString("body");
ps.close();
rs.close();
return body;
} catch (Exception e) {
e.printStackTrace();
return "[ERROR]" + e.getStackTrace();
}
}
public String getPostDate(int id) {
try {
var ps = connection.prepareStatement("SELECT date FROM Posts WHERE id = ?;");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
String date = rs.getString("date");
ps.close();
rs.close();
return date;
} catch (Exception e) {
e.printStackTrace();
return new Date().toString();
}
}
public String getPostAuthor(int postId) {
try {
var ps = connection.prepareStatement("SELECT name FROM Users, Posts WHERE Posts.userid = Users.id AND Posts.id = ?;");
ps.setInt(1, postId);
ResultSet rs = ps.executeQuery();
String name = rs.getString("name");
ps.close();
rs.close();
return name;
} catch (Exception e) {
e.printStackTrace();
return "[ERROR]";
}
}
public Subforum[] getSubforums() {
List<Subforum> subforums = new ArrayList<Subforum>();
try {
var s = connection.createStatement();
var rs = s.executeQuery("SELECT id FROM Subforum;");
while (rs.next()) {
subforums.add(new Subforum(rs.getInt("id"), this));
}
s.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return subforums.toArray(new Subforum[0]);
}
public String getSubforumTitle(int id) {
try {
var ps = connection.prepareStatement("SELECT name FROM Subforum WHERE id = ?;");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
String title = rs.getString("name");
ps.close();
rs.close();
return title;
} catch (Exception e) {
e.printStackTrace();
return "[ERROR]" + e.getStackTrace();
}
}
public Post[] getSubforumPosts(int subforum_id) {
List<Post> posts = new ArrayList<Post>();
try {
var ps = connection.prepareStatement("SELECT id FROM Posts WHERE subforumid = ?;");
ps.setInt(1, subforum_id);
var rs = ps.executeQuery();
while (rs.next()) {
posts.add(new Post(rs.getInt("id"), this));
}
ps.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return posts.toArray(new Post[0]);
}
public void postPostToSubforum(int subforum_id, int post_id) {
try {
var ps = connection.prepareStatement("UPDATE Posts SET subforumid = ? WHERE id = ?;");
ps.setInt(1, subforum_id);
ps.setInt(2, post_id);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void removePostFromSubforum(int post_id) {
try {
var ps = connection.prepareStatement("UPDATE Posts SET subforumid = NULL WHERE id = ?;");
ps.setInt(1, post_id);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean isUserAdmin(int userid) {
boolean result = false;
try {
var ps = connection.prepareStatement("SELECT * FROM AdminList WHERE userid = ?;");
ps.setInt(1, userid);
ResultSet rs = ps.executeQuery();
if(rs.isBeforeFirst()) { // it returned something
result = true;
}
ps.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private boolean isUserModerator(int userid) {
boolean result = false;
try {
var ps = connection.prepareStatement("SELECT * FROM ModeratorList WHERE userid = ?;");
ps.setInt(1, userid);
ResultSet rs = ps.executeQuery();
if(rs.isBeforeFirst()) { // it returned something
result = true;
}
ps.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public User getUser(int userid) {
try {
if(getUserName(userid).equals("null")) {
return null;
}
else if (isUserAdmin(userid)) {
return new Admin(userid, this);
}
else if (isUserModerator(userid)) {
return new Moderator(userid, this);
}
else
{
return new User(userid, this);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| c00291296/java-forum | ForumDB.java | 2,715 | /*
* Adds a new subforum to the forum
*
* @param name the name of the subforum to be added
*/ | block_comment | en | false |
26940_1 | import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
// TODO:
// 1- get the character count ina file and write to another file
// 2- take two files and concatanete the two files ina single output file
public class IO {
public void readWriteEven(String fin, String fout) {
String s;
int i = 1;
try {
FileReader fr = new FileReader(fin);
BufferedReader br = new BufferedReader(fr);
FileOutputStream f = new FileOutputStream(fout);
PrintStream os = new PrintStream(f);
while ((s = br.readLine()) != null) {
if (i % 2 == 0)
os.println(s);
i++;
}
br.close();
fr.close();
os.close();
f.close();
} catch (IOException e) {
System.out.println("error io:" + e);
}
}
}
| kaandesu/java-io | IO.java | 240 | // 1- get the character count ina file and write to another file | line_comment | en | true |
26942_0 | import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
public class FP {
/**
* Main method
* @param args
*/
public static void main(String[] args) {
List<Integer> numbers = List.of(12, 9, 13, 4, 6, 2, 4, 12, 15);
printAllNumbersInListStructure(numbers);
printAllNumbersInListFuntional(numbers);
printAllNumbersInListFuntional1(numbers);
printEvenNumbersInListStructure(numbers);
printEvenNumbersInListFunctional(numbers);
printEvenNumberInListLambda(numbers);
printOddNumbersInListFunctional(numbers);
List<String> courses = List.of("Spring", "Spring Boot", "API", "Microservices", "AWS", "PCF", "Azure", "Docker", "Kubernetes");
courses.stream()
.forEach(System.out::println);
courses.stream()
.filter(course -> course.contains("Spring"))
.forEach(System.out::println);
courses.stream()
.filter(course -> course.length() >= 4)
.forEach(System.out::println);
List<String> fruits = List.of("Apple", "Orange", "Banana", "Pineapple", "Mango", "Grape");
Predicate<? super String> predicate = fruit -> fruit.startsWith("A");
Optional<String> optional = fruits.stream().filter(predicate).findFirst();
System.out.println(optional);
System.out.println(optional.isEmpty());
System.out.println(optional.isPresent());
System.out.println(optional.get());
Optional<String> fruit = Optional.of("Apple");
System.out.println(fruit);
Optional<String> empty = Optional.empty();
System.out.println(empty);
}
/**
* Print all numbers in list structure
* @param numbers
*/
private static void printAllNumbersInListStructure(List<Integer> numbers) {
for (int number : numbers) {
System.out.println(number);
}
}
/**
* Print all numbers in list functional
* @param numbers
*/
private static void printAllNumbersInListFuntional(List<Integer> numbers) {
numbers.stream()
.forEach(FP::print); // Method reference
}
/**
* Print a number
* @param number
*/
private static void print(int number) {
System.out.println(number);
}
/**
* Print all numbers in list functional
* @param numbers
*/
private static void printAllNumbersInListFuntional1(List<Integer> numbers) {
numbers.stream()
.forEach(System.out::println); // Method reference
}
/**
* Print even numbers in list structure
* @param numbers
*/
private static void printEvenNumbersInListStructure(List<Integer> numbers) {
for (int number : numbers) {
if (number % 2 == 0) {
System.out.println(number);
}
}
}
/**
* Print even numbers in list functional
* @param numbers
*/
private static void printEvenNumbersInListFunctional(List<Integer> numbers) {
numbers.stream()
.filter(FP::isEven) // Method reference
.forEach(System.out::println); // Method reference
}
/**
* Check if a number is even
* @param number
* @return
*/
private static boolean isEven(int number) {
return number % 2 == 0;
}
/**
* Print even numbers in list functional lambda expression
* @param numbers
*/
private static void printEvenNumberInListLambda(List<Integer> numbers) {
numbers.stream()
.filter(number -> number % 2 == 0)
.forEach(System.out::println);
}
/**
* Print odd numbers in list functional
* @param numbers
*/
private static void printOddNumbersInListFunctional(List<Integer> numbers) {
numbers.stream()
.filter(number -> number % 2 != 0)
.forEach(System.out::println);
}
}
| seanmayer/java-functional-programming | FP.java | 961 | /**
* Main method
* @param args
*/ | block_comment | en | true |
27354_0 | import java.util.Stack;
// 用单调栈维护当前位置右边更小的元素,从栈底到栈定元素递增
// 对每个元素,将栈中大于该元素的元素弹出,并将该元素压栈
class Solution {
public int[] finalPrices(int[] prices) {
int n = prices.length;
int[] ans = new int[n];
Stack<Integer> stack = new Stack<>();
for(int i = n - 1; i >= 0; i --){
if(stack.empty()){
ans[i] = 0;
stack.add(prices[i]);
} else {
while(!stack.empty() && prices[i] < stack.peek()){
stack.pop();
}
if(stack.empty()){
ans[i] = 0;
} else {
ans[i] = stack.peek();
}
stack.add(prices[i]);
}
}
for(int i = 0; i < n; i ++){
ans[i] = prices[i] - ans[i];
}
return ans;
}
} | xuan-xuan7/Leetcode | 1475.java | 259 | // 用单调栈维护当前位置右边更小的元素,从栈底到栈定元素递增 | line_comment | en | true |
27443_1 | public class Website {
public static void main(String[] args) {
String website = "www.nekastranica.com?name=Jon&surname=Stark";
int lengthOfUrl = website.length();
// given a website we find its URL length
int counter = 0;
String surname = " ";
String name = " ";
String invert = " ";
String invertN = " ";
// counters, inverters, name and surename
for (int i = lengthOfUrl - 1; i > 0; i--) {
char reader = website.charAt(i);
if (reader != '=') {
surname += reader;
counter++;
} else {
break;
}
}
// we read character by character till we get to = sign
int surenameLength = surname.length();
for (int j = surenameLength - 1; j >= 0; j--) {
char reader1 = surname.charAt(j);
invert += reader1;
// we find the length of a value that we get and then we invert it
// to get a surename
// as we were reading characters from the right side
}
counter += 10;
for (int d = lengthOfUrl - counter; d > 0; d--) {
char reader2 = website.charAt(d);
if (reader2 != '=') {
name += reader2;
} else {
break;
}
}
// we already counted the lenth of a surename with counter now we add
// 10, for the rest of characters till the name begins
// we do the same
int nameLength = name.length();
for (int e = nameLength - 1; e >= 0; e--) {
char reader3 = name.charAt(e);
invertN += reader3;
}
// same bla bla :)
System.out.printf("%s%s ", invertN, invert);
// print it out, TA DAAA :)
}
}
| medinaobralija/homeworksBeforeMentorProgram | Website.java | 501 | // counters, inverters, name and surename | line_comment | en | true |
27718_2 | // https://www.hackerearth.com/practice/data-structures/disjoint-data-strutures/basics-of-disjoint-data-structures/practice-problems/algorithm/marriage-problem/editorial/
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
int parent[], women[], men[], size[];
public void union(int a, int b) {
int u = find(a);
int v = find(b);
if (u == v) return;
if (size[u] > size[v]) {
parent[v] = u;
women[u] += women[v];
men[u] += men[v];
size[u] += size[v];
} else {
parent[u] = v;
women[v] += women[u];
men[v] += men[u];
size[v] += size[u];
}
}
public int find(int a) {
while (parent[a] != a) {
a = parent[a];
}
return a;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt(), y = sc.nextInt(), q1 = sc.nextInt();
parent = new int[x+y]; men = new int[x+y]; women = new int[x+y]; size = new int[x+y];
for (int i = 0; i < x+y; i++) {
parent[i] = i;
size[i] = 1;
women[i] = 0;
men[i] = 0;
if (i < x) men[i] = 1;
else women[i] = 1;
}
while(q1--) {
a = sc.nextInt(); b = sc.nextInt();
union(a, b);
}
int q2 = sc.nextInt();
while(q2--) {
a = sc.nextInt()+x; b = sc.nextInt()+x;
union(a, b);
}
int q3 = sc.nextInt();
while(q3--) {
a = sc.nextInt(); b = sc.nextInt()+x;
union(a, b);
}
HashMap<Integer, LinkedList<Integer>> cc = new HashMap<Integer, LinkedList<Integer>>();
int ans = 0;
for (for int i = 0; i < x; i++) {
ans += (y - women[find(i)]);
}
System.out.println(ans);
}
}
| maiquynhtruong/algorithms-and-problems | marriage-problem.java | 699 | /* Name of the class has to be "Main" only if the class is public. */ | block_comment | en | false |
27756_0 | import java.io.PrintStream;
import java.util.*;
/**
* Codejam to I/O for Women 2015 Problem D: Googlander
* Check README.md for explanation.
*/
public class Main {
private String solve(Scanner scanner) {
int r=scanner.nextInt(), c=scanner.nextInt();
long[][] dp=new long[r+1][c+1];
for (int i=1;i<=c;i++)
dp[1][i]=1;
for (int i=1;i<=r;i++)
dp[i][1]=1;
for (int i=2;i<=r;i++) {
for (int j=2;j<=c;j++) {
dp[i][j]=1;
for (int x=2;x<=i;x++) {
for (int y=2;y<=j;y++) {
dp[i][j]+=dp[x-1][y-1];
}
}
}
}
return String.valueOf(dp[r][c]);
}
public static void main(String[] args) throws Exception {
System.setOut(new PrintStream("output.txt"));
Scanner scanner=new Scanner(System.in);
int times=scanner.nextInt();
long start=System.currentTimeMillis();
for (int t=1;t<=times;t++) {
System.out.println(String.format("Case #%d: %s", t, new Main().solve(scanner)));
}
long end=System.currentTimeMillis();
System.err.println(String.format("Time used: %.3fs", (end-start)/1000.0));
}
} | ckcz123/codejam | IO for Women/2015/D.java | 391 | /**
* Codejam to I/O for Women 2015 Problem D: Googlander
* Check README.md for explanation.
*/ | block_comment | en | true |
28784_2 | package project;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Rat extends JFrame implements ActionListener
{
JLabel l1,l2;
JButton b1,b2;
public Rat(String str)
{
super(str);
this.setLayout(null);
// Toolkit t=this.getToolkit();
//this.setSize(t.getScreenSize());
this.setSize(980,760);
this.setResizable(false);
this.setTitle("Welcome to online java test conducting system!!!");
ImageIcon i=new ImageIcon("Slide1.JPG");
setBackground(Color.black);
l1=new JLabel(i);
l1.setBounds(0,0,980,760);
add(l1);
/*ImageIcon i=new ImageIcon("RAT Logo.jpg");
l1=new JLabel(i);
l1.setBounds(0,0,1400,730);
add(l1);*/
b1=new JButton("Close");
Font f=new Font("Times New Roman",Font.BOLD,20);
b1.setFont(f);
b1.setBounds(400,500,100,40);
l1.add(b1);
b1.addActionListener(this);
b2=new JButton("Next");
Font ff=new Font("Times New Roman",Font.BOLD,20);
b2.setFont(ff);
b2.setBounds(750,500,80,40);
l1.add(b2);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
this.dispose();
}
if(ae.getSource()==b2)
{
JavaQuiz k= new JavaQuiz("Online Java Quiz",this);
k.setVisible(true);
this.setVisible(false);
}
}
public static void main(String a[])
{
Rat r=new Rat("Welcome to online java test conducting system!!!!");
r.setVisible(true);
}
}
| srish/Java-Test-Conducting-System | Rat.java | 621 | /*ImageIcon i=new ImageIcon("RAT Logo.jpg");
l1=new JLabel(i);
l1.setBounds(0,0,1400,730);
add(l1);*/ | block_comment | en | true |
29582_0 | public interface Sports {
public void basketball();
public void football();
}
interface tiyu1 extends Sports {
public void volleyball();
public void badminton();
}
//tiyu1接口自己声明了2个方法,从Sports接口继承了2个方法,这样,实现tiyu1接口的类必须要实现4个方法
| ferry-luo/java_practice | src/Sports.java | 85 | //tiyu1接口自己声明了2个方法,从Sports接口继承了2个方法,这样,实现tiyu1接口的类必须要实现4个方法 | line_comment | en | true |
29589_0 | package dbconnection;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;
public class Sports
{
static int a=1;
static int correct=0;
static int incorrect=0;
public static void Sports1()
{
JFrame f=new JFrame();
Container c= f.getContentPane();
c.setBackground(new Color(112,128,144));
JPanel panel=new JPanel();
JButton submit=new JButton("Submit");
submit.setBounds(400,350,120,30);
JButton Ex=new JButton("Exit");
Ex.setBounds(002,440,60,30);
JButton Ho=new JButton("Continue");
Ho.setBounds(300,200,100,50);
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dummy","root","Tonyullas");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from Sports s where s.NUM='"+a+"'");
while(rs.next())
{
if (a==11)
{
JLabel Res=new JLabel("Correct answers "+correct);
Res.setBounds(70,60,500,40);
Res.setFont(new Font("Serif", Font.BOLD, 40));
Res.setForeground(new Color(255,255,255));
JLabel Res1=new JLabel("Wrong answers "+incorrect);
Res1.setBounds(70,120,550,40);
Res1.setFont(new Font("Serif", Font.BOLD, 30));
Res1.setForeground(new Color(255,255,255));
panel.add(Res);
f.add(Res);
panel.add(Res1);
f.add(Res1);
f.add(Ex);
f.add(Ho);
Ho.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Quiz1.OnlineQuiz();
f.setVisible(false);
}
});
Ex.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Exit.exiting();
f.setVisible(false);
}
});
}
else
{
String Op=rs.getString(7);
JLabel NUM=new JLabel(rs.getString(1)+". ");
NUM.setBounds(70,60,500,40);
NUM.setFont(new Font("Serif", Font.BOLD, 20));
NUM.setForeground(new Color(255,255,255));
JLabel QUN=new JLabel(rs.getString(2));
QUN.setFont(new Font("Serif", Font.BOLD, 20));
QUN.setForeground(new Color(255,255,255));
panel.setLayout(new FlowLayout());
QUN.setBounds(100,60,700,40);
JRadioButton O1=new JRadioButton(rs.getString(3));
O1.setBounds(245,122,130,30);
O1.setSelected(true);
O1.setActionCommand(rs.getString(3));
JRadioButton O2=new JRadioButton(rs.getString(4));
O2.setBounds(245,172,130,30);
O2.setActionCommand(rs.getString(4));
JRadioButton O3=new JRadioButton(rs.getString(5));
O3.setBounds(245,222,130,30);
O3.setActionCommand(rs.getString(5));
JRadioButton O4=new JRadioButton(rs.getString(6));
O4.setBounds(245,272,130,30);
O4.setActionCommand(rs.getString(6));
ButtonGroup group=new ButtonGroup();
group.add(O1);
group.add(O2);
group.add(O3);
group.add(O4);
submit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String Cmd =group.getSelection().getActionCommand();
if(Cmd.equals(Op))
{
System.out.println(Op);
JOptionPane.showMessageDialog(f,"Correct answer");
a++;
correct++;
Sports1();
f.setVisible(false);
}
else
{
JOptionPane.showMessageDialog(f,"Wrong answer.\nCorrect answer is :" +Op);
a++;
incorrect++;
Sports1();
f.setVisible(false);
}
}
});
Ex.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Exit.exiting();
f.setVisible(false);
}
});
Ho.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Continue1.Continue();
f.setVisible(false);
}
});
panel.add(submit);
panel.add(QUN);
panel.add(NUM);
f.add(submit);
f.add(Ex);
f.add(QUN);
f.add(NUM);
f.add(panel);
f.add(O1);
f.add(O2);
f.add(O3);
f.add(O4);
}}
con.close();
}catch(Exception ei)
{ System.out.println(ei);}
f.setSize(900,500);
f.setLayout(null);
f.setVisible(true);
f.setLocationRelativeTo(null);
}
}
| UllasCL/OnlineQuiz | Sports.java | 1,541 | //localhost:3306/dummy","root","Tonyullas"); | line_comment | en | true |
29683_0 | public class House implements Cloneable, Comparable<House> {
private int id;
private double area;
private java.util.Date whenBuilt;
public House(int id, double area) {
this.id = id;
this.area = area;
whenBuilt = new java.util.Date();
}
public int getId() {
return id;
}
public double getArea() {
return area;
}
public java.util.Date getWhenBuilt() {
return whenBuilt;
}
@Override /** Override the protected clone method defined in
the Object class, and strengthen its accessibility */
public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException ex) {
return null;
}
}
@Override // Implement the compareTo method defined in Comparable
public int compareTo(House o) {
if (area > o.area)
return 1;
else if (area < o.area)
return -1;
else
return 0;
}
}
| rdejong/LiangJava | House.java | 234 | /** Override the protected clone method defined in
the Object class, and strengthen its accessibility */ | block_comment | en | false |
29754_2 | package cs10;
import java.awt.Color;
import java.awt.Graphics;
/**
* A geometric entity with a color
*
* @author Chris Bailey-Kellogg, Dartmouth CS 10, Spring 2016, based on a related concept from previous terms
* @author CBK, revised Fall 2016
*/
public interface Shape {
/**
* Moves the shape by dx in the x coordinate and dy in the y coordinate
*/
public void moveBy(int dx, int dy);
/**
* Whether or not the point is inside the shape
*/
public boolean contains(int x, int y);
/**
* @return The shape's color
*/
public Color getColor();
/**
* @param color The shape's color
*/
public void setColor(Color color);
/**
* Draws the shape
*/
public void draw(Graphics g);
}
| rodrigo-cb/collaborative-painter | Shape.java | 224 | /**
* Whether or not the point is inside the shape
*/ | block_comment | en | true |
30363_1 | import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.text.*;
import java.util.*;
import java.util.List; // resolves problem with java.awt.List and java.util.List
/**
* A class that represents a picture. This class inherits from SimplePicture and
* allows the student to add functionality to the Picture class.
*
* @author Barbara Ericson [email protected]
*/
public class Picture extends SimplePicture
{
///////////////////// constructors //////////////////////////////////
/**
* Constructor that takes no arguments
*/
public Picture()
{
/*
* not needed but use it to show students the implicit call to super() child
* constructors always call a parent constructor
*/
super();
}
/**
* Constructor that takes a file name and creates the picture
*
* @param fileName
* the name of the file to create the picture from
*/
public Picture(String fileName)
{
// let the parent class handle this fileName
super(fileName);
}
/**
* Constructor that takes the width and height
*
* @param height
* the height of the desired picture
* @param width
* the width of the desired picture
*/
public Picture(int height, int width)
{
// let the parent class handle this width and height
super(width, height);
}
/**
* Constructor that takes a picture and creates a copy of that picture
*
* @param copyPicture
* the picture to copy
*/
public Picture(Picture copyPicture)
{
// let the parent class do the copy
super(copyPicture);
}
/**
* Constructor that takes a buffered image
*
* @param image
* the buffered image to use
*/
public Picture(BufferedImage image)
{
super(image);
}
/**
* Method to return a string with information about this picture.
*
* @return a string with information about the picture such as fileName,
* height and width.
*/
public String toString()
{
String output = "Picture, filename " + getFileName() + " height "
+ getHeight() + " width " + getWidth();
return output;
}
public void grayscale()
{
Pixel[][] pixel = this.getPixels2D();
for (int i = 0; i < pixel.length; i++) // Pixel[] rpwArrau: pixels
{
for (int i2 = 0; i2 < pixel[i].length; i2++) // Pixel pixel0bj: rowArray
{
int average = ((pixel[i][i2]).getRed() + (pixel[i][i2]).getBlue() + (pixel[i][i2]).getGreen())/3;
pixel[i][i2].setRed(average);
pixel[i][i2].setBlue(average);
pixel[i][i2].setGreen(average);
}
}
}
public void Photoshop(Picture newPic)
{
Pixel[][] pixels = this.getPixels2D();
Pixel[][] greenScreen = newPic.getPixels2D();
for (int row = 0; row < greenScreen.length; row++)
{
for (int col = 0; col < greenScreen[0].length; col++)
{
int rVal = greenScreen[row][col].getRed() +10;
int bVal = greenScreen[row][col].getBlue() +10;
int gVal = greenScreen[row][col].getGreen();
if (gVal > rVal && gVal > bVal)
{
greenScreen[row][col].setColor(pixels[row][col].getColor());
}
}
}
}
}
| alaynamnguyen/Chictech | Picture.java | 926 | /**
* A class that represents a picture. This class inherits from SimplePicture and
* allows the student to add functionality to the Picture class.
*
* @author Barbara Ericson [email protected]
*/ | block_comment | en | true |
31246_0 | /*
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
*/
class Robber {
public int rob(int[] nums) {
int n=nums.length;
if(nums==null||n==0)return 0;
if(n==1)return nums[0];
if(n==2)return Math.max(nums[0],nums[1]);
int dp[]=new int[n];
dp[0]=nums[0];
dp[1]=Integer.max(nums[1],nums[0]);
for(int i=2;i<n;i++){
dp[i]=Integer.max(nums[i]+dp[i-2],dp[i-1]);
}
return dp[n-1];
}
}
| Pratyush-Kumar-Jaiswal/leetcode | Robber.java | 416 | /*
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
*/ | block_comment | en | true |
31740_0 | /*
===================================================== 1657. Determine if Two Strings Are Close ======================================================
Problem Statement : Two strings are considered close if you can attain one from the other using the following operations:
Operation 1: Swap any two existing characters.
For example, abcde -> aecdb
Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
You can use the operations on either string as many times as necessary.
Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
Examples :
Example 1:
Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"
Example 2:
Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
Example 3:
Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"
*/
public class 20 {
public boolean closeStrings(String w1, String w2) {
char[] c1 = w1.toCharArray();
char[] c2 = w2.toCharArray();
for(int i=0;i<c1.length&&i<c2.length;i++){
if(w1.indexOf(c2[i])==-1){
return false;
}
}
Arrays.sort(c1);
Arrays.sort(c2);
if(Arrays.equals(c1, c2)){
return true;
}
int arr1[]=count(c1);
int arr2[]=count(c2);
if(Arrays.equals(arr1, arr2)){
return true;
}
return false;
}
}
| manikerisaurabh/LeetCode-75 | 20.java | 561 | /*
===================================================== 1657. Determine if Two Strings Are Close ======================================================
Problem Statement : Two strings are considered close if you can attain one from the other using the following operations:
Operation 1: Swap any two existing characters.
For example, abcde -> aecdb
Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
You can use the operations on either string as many times as necessary.
Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
Examples :
Example 1:
Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"
Example 2:
Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
Example 3:
Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"
*/ | block_comment | en | true |
32082_0 |
/**
* Write a description of class Eagle here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Eagle extends Animal implements Flying, Walking, Swimming
{
private String toy;
public Eagle(){
super("The Real Uncle Sam", "The most interesting animal in the zoo");
toy = "flute";
}
public Eagle(String name, String description){
super(name, description);
this.toy = toy;
}
@Override
public String makeNoise(){
return "AYEEEEEEEEE!";
}
@Override
public String eat(){
return "Can eat anything..... including you";
}
@Override
public String fly(){
return "Of course it can fly";
}
@Override
public String walk(){
return "He always flies after taking 3 steps.";
}
public String swim(){
return "He takes a deep breath and swims for only 2 seconds and then flies out because he is in shock of his God-given abilites.";
}
public String play(){
return "The eagle often plays with its " + toy + ".";
}
public String attack(){
return "The combination of his beak and his piercing noise gives him the ability to KO every opponent he faces.";
}
}
| SPHS-CS/JavaZoo2016 | Eagle.java | 313 | /**
* Write a description of class Eagle here.
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | true |
32489_0 | //Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x.
class q2_4 {
//answer - Note: the book's answer shows creating two lists and then joining them. However, I think this solution is cleaner.
public static void partitionAroundX(DoublyLinkedList<Integer> pList, Integer pX) {
Node<Integer> runner = pList.head;
Node<Integer> temp;
while (runner != null) {
if (runner.data <= pX) {
temp = runner;
runner = runner.next;
pList.addFirst(temp.data);
pList.delete(temp);
} else {
runner = runner.next;
}
}
}
public static void main(String[] args) {
//create a linked list of 25 random integers between 0 and 99
DoublyLinkedList<Integer> intList = new DoublyLinkedList<Integer>();
int min = 0;
int max = 99;
for (int i = 0; i < 25; i++) {
intList.addFirst(new Integer(min + (int)(Math.random() * ((max - min) + 1))));
}
System.out.print("\nun-partitioned");
printList(intList);
partitionAroundX(intList, new Integer(50));
System.out.print("\npartitioned");
printList(intList);
}
public static void printList(DoublyLinkedList<Integer> pList) {
System.out.println("\n--------------");
Node<Integer> runner = pList.head;
if (runner == null) {
System.out.println("list is empty");
return;
}
while (runner != null) {
System.out.print(String.format("%02d<->", runner.data));
runner = runner.next;
}
System.out.println("\n--------------");
}
}
class DoublyLinkedList<E> {
Node<E> head;
Node<E> tail;
public void delete(Node<E> node) {
if (node.next != null) {
if (head == node) {
head = node.next;
}
node.next.prev = node.prev;
}
if (node.prev != null) {
if (tail == node) {
tail = node.prev;
}
node.prev.next = node.next;
}
}
public Node<E> addFirst(E data) {
Node<E> node = new Node<E>(data);
if (head != null) {
node.next = head;
head.prev = node;
}
if (tail == null) {
tail = node;
}
head = node;
return node;
}
public Node<E> addLast(E data) {
Node<E> node = new Node<E>(data);
if (tail != null) {
node.prev = tail;
tail.next = node;
}
if (head == null) {
head = node;
}
tail = node;
return node;
}
}
class Node<E> {
Node<E> next;
Node<E> prev;
E data;
public Node(E e) {
data = e;
}
} | manimaul/ctci | q2_4.java | 868 | //Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. | line_comment | en | true |
32599_2 | import java.awt.Point;
import java.util.LinkedList;
import java.util.Queue;
/*************************************
* We created the static BFS class *
* to be able to access BFS anywhere *
*************************************/
public final class BFS {
Point beginning;
Point end;
int[][] bfsMap;
LinkedList<Point> visited;
Queue<bfsTuple> queue;
/*********************************************
* Get BFS grid from beginning and end point *
*********************************************/
public static int[][] getPath(Point beginning, Point end) {
OceanMap oceanMap = OceanMap.getInstance();
int[][] bfsMap = new int[oceanMap.getDimension()][oceanMap.getDimension()];
/* Create a map of MAX_VALUE for finding min distance */
for(int x=0;x<oceanMap.getDimension();x++) {
for(int y=0;y<oceanMap.getDimension();y++) {
bfsMap[x][y] = Integer.MAX_VALUE;
}
}
LinkedList<Point> visited = new LinkedList<Point>();
Queue<bfsTuple> queue = new LinkedList<bfsTuple>();
/* Add end point to visited and queue, with beginning distance of 0 */
visited.add(end);
queue.add(new bfsTuple(end, 0));
/* Find adjacent points for every point in queue and add them to queue if not visited */
while(!queue.isEmpty()) {
bfsTuple cur = queue.poll();
bfsMap[cur.getX()][cur.getY()] = cur.getDistance();
LinkedList<Point> adj = getAdj(cur.getPoint());
for(Point pt : adj) {
if(!visited.contains(pt)) {
visited.add(pt);
queue.add(new bfsTuple(pt,cur.getDistance()+1));
}
}
}
return bfsMap;
}
/************************************************
* Get valid adjacent points from specific point*
************************************************/
public static LinkedList<Point> getAdj(Point point) {
LinkedList<Point> validAdj = new LinkedList<Point>();
OceanMap oceanMap = OceanMap.getInstance();
int x = (int)point.getX();
int y = (int)point.getY();
/* Check south */
if(oceanMap.getState(x,y+1) == 0) {
validAdj.add(new Point(x,y+1));
}
/* Check north */
if(oceanMap.getState(x,y-1) == 0) {
validAdj.add(new Point(x,y-1));
}
/* Check east */
if(oceanMap.getState(x+1,y) == 0) {
validAdj.add(new Point(x+1,y));
}
/* Check north */
if(oceanMap.getState(x-1,y) == 0) {
validAdj.add(new Point(x-1,y));
}
return validAdj;
}
}
| vincenttaglia/columbus-game-java | BFS.java | 744 | /* Create a map of MAX_VALUE for finding min distance */ | block_comment | en | true |
32846_12 | ///usr/bin/env jbang "$0" "$@" ; exit $?
//REPOS mavencentral,jitpack
//DEPS io.quarkus:quarkus-bom:${quarkus.version:2.2.0.CR1}@pom
//DEPS io.quarkus:quarkus-qute
//DEPS https://github.com/w3stling/rssreader/tree/v2.5.0
//DEPS io.quarkus:quarkus-rest-client-reactive
//DEPS io.quarkus:quarkus-rest-client-reactive-jackson
//JAVA 16+
import com.apptastic.rssreader.Item;
import com.apptastic.rssreader.RssReader;
import io.quarkus.qute.Engine;
import io.quarkus.runtime.QuarkusApplication;
import io.quarkus.runtime.annotations.QuarkusMain;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.QueryParam;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@QuarkusMain
public class update implements QuarkusApplication {
@Inject
Engine qute;
// static public class Items{}
public Collection<Item> getPosts(String feedUrl, int limit) throws Exception {
Collection<Item> sorted = new PriorityQueue<>(Collections.reverseOrder());
RssReader reader = new RssReader();
Stream<Item> rssFeed = reader.read(feedUrl);
sorted.addAll(rssFeed.limit(limit).collect(Collectors.toList()));
return sorted;
}
// @RestClient
// PlaylistService playlistService;
public int run(String... args) throws Exception {
String bio = """
Otavio works as a Principal Software Engineer in the Red Hat Integration team. He is currently focusing his work on all things related to https://camel.apache.org[Apache Camel] :camel:.
He has been working with messaging, integration, cloud and testing for more than 15 years. He continues to be passionate :heart: about these topics.
Posts about his experiences and troubles with computers, ocasionally appear on his blogs in https://orpiske.net[English] and https://angusyoung.org[Portuguese].
He is excited about Open Source, https://www.orpiske.net/talks/[speaks regularly] at conferences and contributes all sorts of projects. He is a regular committer at the https://camel.apache.org[Apache Camel] project, and makes or has made sporadic contributions to https://getfedora.org[Fedora], https://gentoo.org[Gentoo], https://www.eclipse.org/paho/[Eclipse Paho], https://activemq.apache.org[Apache ActiveMQ] and others in the past.
He can be found on twitter as https://twitter.com/otavio021[@otavio021], https://bsky.app/[@orpiske.bsky.social] and on Mastodon as https://toot.community/@orpiske[@[email protected]], speaking in English :uk: and Portuguese :brazil: about technology, science and life.
He maintains a professional profile on https://www.linkedin.com/in/orpiske/[LinkedIn].
""";
Collection<Item> sortedPt = getPosts("https://www.angusyoung.org/feed", 1);
Collection<Item> sortedEn = getPosts("https://orpiske.net/feed", 2);
Files.writeString(Path.of("readme.adoc"), qute.parse(Files.readString(Path.of("template.adoc.qute")))
.data("bio", bio)
.data("postsEn", sortedEn)
.data("postsPt", sortedPt)
.render());
return 0;
}
}
| orpiske/orpiske | update.java | 957 | //orpiske.net[English] and https://angusyoung.org[Portuguese]. | line_comment | en | true |
33470_0 | /**
* Created by David on 10/14/2014.
*/
import java.util.*;
public class bash {
private String currentDirectory;
private String currentFile;
private ArrayList<String> history;
private String[] currentCommand;
public bash()
{
history = new ArrayList<String>();
currentCommand = new String[100];
currentDirectory = new String("/root");
currentFile = new String("curFile");
this.startBash();
}
private void startBash()
{
this.printPrompt();
String input = new String();
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
this.parseText(input);
}
private void printPrompt()
{
System.out.print(currentDirectory + " $ ");
}
private void parseText(String text)
{
String delims = "[ ]+";
String tokens[] = text.split(delims);
}
}
| huntdog1541/VituralConsole1 | bash.java | 223 | /**
* Created by David on 10/14/2014.
*/ | block_comment | en | true |
33538_15 | //~--- JDK imports ------------------------------------------------------------
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
public class Pacman extends Thread {
private static final String IMAGE_SOURCE = "src/pacman/img/";
static String[] pacmanSequencesL = { IMAGE_SOURCE + "pac32_left.png", IMAGE_SOURCE + "pac32_left_wide.png",
IMAGE_SOURCE + "pac32_left_widest.png", IMAGE_SOURCE + "pacman_closed.png" };
static String[] pacmanSequencesR = { IMAGE_SOURCE + "pac32_right.png", IMAGE_SOURCE + "pac32_right_widest.png",
IMAGE_SOURCE + "pac32_right_wide.png", IMAGE_SOURCE + "pacman_closed.png" };
static String[] pacmanSequencesU = { IMAGE_SOURCE + "pac32_up.png", IMAGE_SOURCE + "pac32_up_wide.png",
IMAGE_SOURCE + "pac32_up_widest.png", IMAGE_SOURCE + "pacman_closed.png" };
static String[] pacmanSequencesD = { IMAGE_SOURCE + "pac32_down.png", IMAGE_SOURCE + "pac32_down_wide.png",
IMAGE_SOURCE + "pac32_down_widest.png", IMAGE_SOURCE + "pacman_closed.png" };
int current = 0;
// don't move until told
private char direction = 'x';
boolean isRunning = true;
int score = 0;
Image[] pictureUp = new Image[pacmanSequencesU.length];
Image[] pictureRight = new Image[pacmanSequencesR.length];
Image[] pictureLeft = new Image[pacmanSequencesL.length];
Image[] pictureDown = new Image[pacmanSequencesD.length];
int totalPictures = 0;
Cell[][] cells;
int livesLeft;
Maze maze;
private int pacmanRow, pacmanCol;
private String score_string;
Thread thread;
// int pause = 200;
public Pacman(int initialRow, int initialColumn, Maze startMaze, int lives) {
pacmanRow = initialRow;
pacmanCol = initialColumn;
maze = startMaze;
livesLeft = lives;
cells = maze.getCells();
Toolkit kit = Toolkit.getDefaultToolkit();
for (int i = 0; i < pacmanSequencesL.length; i++) {
pictureLeft[i] = kit.getImage(pacmanSequencesL[i]);
}
for (int i = 0; i < pacmanSequencesR.length; i++) {
pictureRight[i] = kit.getImage(pacmanSequencesR[i]);
}
for (int i = 0; i < pacmanSequencesU.length; i++) {
pictureUp[i] = kit.getImage(pacmanSequencesU[i]);
}
for (int i = 0; i < pacmanSequencesD.length; i++) {
pictureDown[i] = kit.getImage(pacmanSequencesD[i]);
}
}
/*
* Draw Pacman
*
*/
public void drawPacman(Graphics g) {
if (direction == 'u') {
if (current > pictureUp.length - 1) {
current = 0;
}
g.drawImage(pictureUp[current], pacmanRow * 20, pacmanCol * 20, 22, 22, maze);
}
if (direction == 'd') {
if (current > pictureDown.length - 1) {
current = 0;
}
g.drawImage(pictureDown[current], pacmanRow * 20, pacmanCol * 20, 22, 22, maze);
}
if (direction == 'l') {
if (current > pictureLeft.length - 1) {
current = 0;
}
g.drawImage(pictureLeft[current], pacmanRow * 20, pacmanCol * 20, 22, 22, maze);
}
if (direction == 'r') {
if (current > pictureRight.length - 1) {
current = 0;
}
g.drawImage(pictureRight[current], pacmanRow * 20, pacmanCol * 20, 22, 22, maze);
}
}
/*
* Get the current row
*
*/
protected int getRow() {
return pacmanRow;
}
/*
* Get the current column
*
*/
protected int getCol() {
return pacmanCol;
}
/*
* Move horizontally
*
*/
protected void moveRow(int x) {
if (isCellNavigable(pacmanCol, pacmanRow + x)) {
pacmanRow = pacmanRow + x;
}
}
/*
* Move vertically
*
*/
protected void moveCol(int y) {
if (isCellNavigable(pacmanCol + y, pacmanRow)) {
pacmanCol = pacmanCol + y;
}
}
/*
* Set direction
*
*/
public void setDirection(char direction) {
this.direction = direction;
}
/*
* Run method
*/
@Override
public void run() {
while (isRunning) {
if (direction == 'u') {
moveCol(-1);
}
if (direction == 'd') {
moveCol(1);
}
if (direction == 'l') {
moveRow(-1);
}
if (direction == 'r') {
moveRow(1);
}
eatPellet(pacmanCol, pacmanRow);
maze.checkCollision();
maze.repaint();
try {
Thread.sleep(150);
} catch (InterruptedException e) {
System.err.println(e);
}
}
}
// TODO - implement audio
/**
* Check if next move will be pellet Detect Collision and "eat pellet"
*
*/
public void eatPellet(int column, int row) {
if (cells[column][row].getType() == 'd') {
score += 10;
cells[column][row].type = 'o';
PacmanGUI.newDisp();
}
if (cells[column][row].getType() == 'p') {
score += 50;
cells[column][row].type = 'o';
PacmanGUI.newDisp();
maze.setEdible();
}
}
/*
* Move Pacman
*
*/
public void movePacman(int x, int y) {
pacmanRow = pacmanRow + x;
pacmanCol = pacmanCol + y;
current++;
System.out.println("ROW " + pacmanRow + ", COL " + pacmanCol); // print out current row and column to console
}
/*
* Check whether a cell is navigable
*
*/
public boolean isCellNavigable(int column, int row) {
return ((cells[column][row].getType() == 'o') || (cells[column][row].getType() == 'd')
|| (cells[column][row].getType() == 'p'));
}
/*
* Get the current score
*
*/
public int getScore() {
return score;
}
/*
* Get number of lives left
*
*/
public int getLives() {
return livesLeft;
}
protected void endgame() {
this.isRunning = false;
}
}
| Stealthii/Pacman | src/Pacman.java | 1,791 | /*
* Get the current score
*
*/ | block_comment | en | true |
33548_0 | import android.util.Pair;
import com.tencent.biz.pubaccount.readinjoy.common.ReadInJoyDisplayUtils;
import com.tencent.biz.pubaccount.readinjoy.common.ReadInJoyUtils;
import com.tencent.biz.pubaccount.readinjoy.struct.BaseArticleInfo;
import com.tencent.biz.pubaccount.readinjoy.view.ReadInJoyBaseAdapter;
import com.tencent.image.URLDrawable;
import com.tencent.image.URLDrawable.URLDrawableOptions;
import com.tencent.mobileqq.hotpatch.NotVerifyClass;
import com.tencent.qphone.base.util.QLog;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class iax
implements Runnable
{
public iax(ReadInJoyBaseAdapter paramReadInJoyBaseAdapter, long paramLong1, List paramList, int paramInt1, int paramInt2, long paramLong2)
{
boolean bool = NotVerifyClass.DO_VERIFY_CLASS;
}
public void run()
{
if (ReadInJoyBaseAdapter.a(this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyViewReadInJoyBaseAdapter) != this.jdField_a_of_type_Long) {
return;
}
int i;
label26:
LinkedList localLinkedList;
int j;
if (this.jdField_a_of_type_JavaUtilList == null)
{
i = 0;
localLinkedList = new LinkedList();
j = this.jdField_a_of_type_Int;
label40:
if (j >= this.jdField_a_of_type_Int + this.jdField_b_of_type_Int) {
break label594;
}
if ((j < i) && (j >= 0)) {
break label89;
}
}
label66:
label89:
Object localObject2;
int k;
label203:
Object localObject1;
label229:
Object localObject3;
for (;;)
{
j += 1;
break label40;
i = this.jdField_a_of_type_JavaUtilList.size();
break label26;
if (ReadInJoyBaseAdapter.a(this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyViewReadInJoyBaseAdapter) != this.jdField_a_of_type_Long) {
break;
}
for (;;)
{
try
{
localObject2 = this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyViewReadInJoyBaseAdapter.a(this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyViewReadInJoyBaseAdapter.p, ((Long)this.jdField_a_of_type_JavaUtilList.get(j)).longValue());
k = this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyViewReadInJoyBaseAdapter.getItemViewType(j);
if (k != 4) {
break label229;
}
if (((BaseArticleInfo)localObject2).mVideoCoverUrl == null) {
break label203;
}
URL localURL = ((BaseArticleInfo)localObject2).mVideoCoverUrl;
localLinkedList.add(ibv.a(localURL, ReadInJoyDisplayUtils.b()));
}
catch (Exception localException)
{
localException.printStackTrace();
}
if (ReadInJoyBaseAdapter.a(this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyViewReadInJoyBaseAdapter) == this.jdField_a_of_type_Long) {
break;
}
return;
if (((BaseArticleInfo)localObject2).mSinglePicture != null) {
localObject1 = ((BaseArticleInfo)localObject2).mSinglePicture;
} else {
localObject1 = ReadInJoyUtils.b(((BaseArticleInfo)localObject2).mFirstPagePicUrl);
}
}
if (k != 3) {
break label762;
}
if ((((BaseArticleInfo)localObject2).mPictures == null) || (((BaseArticleInfo)localObject2).mPictures.length <= 0))
{
localObject3 = ReadInJoyBaseAdapter.a(this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyViewReadInJoyBaseAdapter, ((BaseArticleInfo)localObject2).mJsonPictureList, "pictures");
if ((localObject3 != null) && (((JSONArray)localObject3).length() > 0))
{
localObject1 = ((JSONArray)localObject3).optJSONObject(0);
if (localObject1 == null)
{
localObject1 = ((BaseArticleInfo)localObject2).mFirstPagePicUrl;
label294:
localLinkedList.add(ibv.a(ReadInJoyUtils.b((String)localObject1), ReadInJoyDisplayUtils.a()));
localObject1 = ((JSONArray)localObject3).optJSONObject(1);
if (localObject1 != null) {
break label390;
}
localObject1 = ((BaseArticleInfo)localObject2).mFirstPagePicUrl;
label327:
localLinkedList.add(ibv.a(ReadInJoyUtils.b((String)localObject1), ReadInJoyDisplayUtils.a()));
localObject1 = ((JSONArray)localObject3).optJSONObject(2);
if (localObject1 != null) {
break label400;
}
}
label390:
label400:
for (localObject1 = ((BaseArticleInfo)localObject2).mFirstPagePicUrl;; localObject1 = ((JSONObject)localObject1).optString("picture"))
{
localLinkedList.add(ibv.a(ReadInJoyUtils.b((String)localObject1), ReadInJoyDisplayUtils.a()));
break;
localObject1 = ((JSONObject)localObject1).optString("picture");
break label294;
localObject1 = ((JSONObject)localObject1).optString("picture");
break label327;
}
}
}
else
{
if ((((BaseArticleInfo)localObject2).mPictures.length < 1) || (localObject2.mPictures[0] == null))
{
localObject1 = ((BaseArticleInfo)localObject2).mSinglePicture;
label433:
localLinkedList.add(ibv.a((URL)localObject1, ReadInJoyDisplayUtils.a()));
if ((((BaseArticleInfo)localObject2).mPictures.length >= 2) && (localObject2.mPictures[1] != null)) {
break label534;
}
localObject1 = ((BaseArticleInfo)localObject2).mSinglePicture;
label470:
localLinkedList.add(ibv.a((URL)localObject1, ReadInJoyDisplayUtils.a()));
if ((((BaseArticleInfo)localObject2).mPictures.length >= 3) && (localObject2.mPictures[2] != null)) {
break label544;
}
}
label534:
label544:
for (localObject1 = ((BaseArticleInfo)localObject2).mSinglePicture;; localObject1 = localObject2.mPictures[2])
{
localLinkedList.add(ibv.a((URL)localObject1, ReadInJoyDisplayUtils.a()));
break;
localObject1 = localObject2.mPictures[0];
break label433;
localObject1 = localObject2.mPictures[1];
break label470;
}
label554:
localLinkedList.add(ibv.a(((BaseArticleInfo)localObject2).mSinglePicture, ReadInJoyDisplayUtils.b()));
}
}
for (;;)
{
localLinkedList.add(ibv.a(((BaseArticleInfo)localObject2).mSinglePicture, ReadInJoyDisplayUtils.a()));
break label66;
label594:
if (ReadInJoyBaseAdapter.a(this.jdField_a_of_type_ComTencentBizPubaccountReadinjoyViewReadInJoyBaseAdapter) != this.jdField_a_of_type_Long) {
break;
}
localObject1 = localLinkedList.iterator();
while (((Iterator)localObject1).hasNext())
{
localObject2 = (ibv)((Iterator)localObject1).next();
if ((localObject2 != null) && (((ibv)localObject2).jdField_a_of_type_JavaNetURL != null))
{
localObject3 = URLDrawable.URLDrawableOptions.obtain();
((URLDrawable.URLDrawableOptions)localObject3).mRequestWidth = ((Integer)((ibv)localObject2).jdField_a_of_type_AndroidUtilPair.first).intValue();
((URLDrawable.URLDrawableOptions)localObject3).mRequestHeight = ((Integer)((ibv)localObject2).jdField_a_of_type_AndroidUtilPair.second).intValue();
((URLDrawable.URLDrawableOptions)localObject3).mPlayGifImage = true;
URLDrawable.getDrawable(((ibv)localObject2).jdField_a_of_type_JavaNetURL, (URLDrawable.URLDrawableOptions)localObject3).startDownload(true);
}
}
if (!QLog.isColorLevel()) {
break;
}
QLog.e("ReadInJoyBaseAdapter", 2, "preloadImg size:" + localLinkedList.size() + " cost:" + (System.currentTimeMillis() - this.jdField_b_of_type_Long));
return;
label762:
if ((k == 2) || (k == 6)) {
break label554;
}
if (k != 1) {
if (k != 5) {
break label66;
}
}
}
}
}
/* Location: E:\apk\QQ_91\classes5-dex2jar.jar!\iax.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | waterwitness/qooq | classes5/iax.java | 2,457 | /* Location: E:\apk\QQ_91\classes5-dex2jar.jar!\iax.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | block_comment | en | true |
33599_0 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
public class Main1926 {
private static int n=0;
private static int m=0;
private static int max=0;
private static int pictureCount=0;
private static List<List<Dot>> pallet=new ArrayList<>();
public static void main(String[] args) throws IOException {
// 그림 정보 입력: 0 과 1을 공백 기준으로 입력받기
makePallet();
// 연결되어있는 1들을 기준으로 그림 찾기
findPictures();
//출력: 그림의 갯수, 가장 넓은 그림의 넓이
System.out.println(pictureCount);
System.out.println(max);
}
private static void findPictures() {
for (int i = 0; i <n ;i++) {;
for (int j = 0; j <m; j++) {
Dot dot =pallet.get(i).get(j);
if (dot.number!=1||dot.visited)
continue;
int area = BFS(dot);
max=Math.max(max,area);
pictureCount++;
}
}
}
private static int BFS(Dot startDot) {
Queue<Dot> queue = new LinkedList<>();
int area = 0;
queue.add(startDot);
while (!queue.isEmpty()) {
Dot currentDot = queue.poll();
area++;
pallet.get(startDot.y).get(startDot.x).visited=true;
for (Direction direction : Direction.values()) {
int newX = currentDot.x + direction.x;
int newY = currentDot.y + direction.y;
if(!isValidPos(newX, newY))
continue;
Dot newDot = pallet.get(newY).get(newX);
if(newDot.number == 1 && !newDot.visited){
newDot.visited = true;
queue.add(newDot);
}
}
}
return area;
}
private static boolean isValidPos(int x, int y) {
return x >= 0 && x < m && y >= 0 && y < n;
}
private static void makePallet() throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
n = Integer.parseInt(s.split(" ")[0]);
m = Integer.parseInt(s.split(" ")[1]);
int i=0;
while(i<n){
String paint = br.readLine();
List<Dot> dots=new ArrayList<>();
List<Integer> line = Arrays.stream(paint.split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());
for (int j = 0; j < line.size(); j++) {
Dot dot = Dot.of(j, i);
dot.number= line.get(j);
dots.add(dot);
}
pallet.add(dots);
i++;
}
}
enum Direction{
NORTH(0,-1),
EAST(1,0),
WEST(-1,0),
SOUTH(0,1);
private final int x;
private final int y;
Direction(int x, int y) {
this.x = x;
this.y = y;
}
}
static class Dot {
private int x;
private int y;
private int number;
private boolean visited=false;
private Dot(int x, int y) {
this.x = x;
this.y = y;
}
public static Dot of(int x, int y){
return new Dot(x,y);
}
}
} | YeaChan05/morugorithm | Main1926.java | 896 | // 그림 정보 입력: 0 과 1을 공백 기준으로 입력받기 | line_comment | en | true |