Datasets:

Modalities:
Text
Formats:
parquet
Libraries:
Datasets
Dask
file_id
int64
1
250k
content
stringlengths
0
562k
repo
stringlengths
6
115
path
stringlengths
1
147
1
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.cips.wifilocalizationdemo; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Customize dimensions originally defined in res/values/dimens.xml (such as screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; public static final int map_always_here_pressed=0x7f020001; public static final int plan_map=0x7f020002; } public static final class id { public static final int RelativeLayout1=0x7f080000; public static final int action_settings=0x7f080006; public static final int frameLayout_1=0x7f080001; public static final int imageButton1=0x7f080003; public static final int imageView1=0x7f080002; public static final int textView_Status=0x7f080005; public static final int textView_Tips=0x7f080004; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class menu { public static final int main=0x7f070000; } public static final class string { public static final int action_settings=0x7f050001; public static final int app_name=0x7f050000; public static final int hello_world=0x7f050002; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
jiangqideng/WiFiLocalizationDemo
R.java
2
/*--- iGeo - http://igeo.jp Copyright (c) 2002-2013 Satoru Sugihara This file is part of iGeo. iGeo is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3. iGeo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with iGeo. If not, see <http://www.gnu.org/licenses/>. ---*/ package igeo; /** Instantiable class of ISwitchR interface to be used as to switch methods to return reference instance. @see ISwitchR @author Satoru Sugihara */ public class Ir implements ISwitchR{ public static final Ir i=new Ir(); }
sghr/iGeo
Ir.java
3
import java.util.*; class Fathe { public void call() { System.out.println("Call"); } } class Chill extends Fathe { public void debit() { System.out.println("debit"); } } class Ot { public static void main(String s[]) { Fathe f=new Chill(); f.call();//gets successfully called as obvious f.debit();//wont get called (compilation error)because we cant call method of class using // the ref variable of another class.f is a reference variable of Fathe class but contains reference vaiable of // Chill class. } }
asad9711/Key-Points-in-Java
Ot.java
4
//******************************************************* // C.java // the class reprsents C // Author: liron mizrahi //******************************************************* public class C { public void foo(D d) { System.out.println("cd"); } }// end of class C
lironmiz/Computer-Science-in-Java
C.java
5
package StudentInformationSystem; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.DefaultCellEditor; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.event.CellEditorListener; import javax.swing.table.DefaultTableModel; import java.awt.Font; import javax.swing.UIManager; import com.github.lgooddatepicker.components.DatePicker; public class StudentInformationSystem { private JFrame frame; private JTextField sID; private JTextField fName; private JTextField mName; private JTextField lName; private JTextField Age; private JTextField mother; private JTextField father; private JTextField cp; private JTextField address; private JTable table_2; private static Connection con = null; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { // Class.forName("org.sqlite.JDBC"); // con = DriverManager.getConnection("jdbc:sqlite:C:\\\\Users\\\\Von\\\\Desktop\\\\sql.db"); //con.setAutoCommit(false); StudentInformationSystem window = new StudentInformationSystem(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public StudentInformationSystem() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { JComboBox bading = new JComboBox(); bading.setForeground(new Color(240, 128, 128)); bading.setBackground(new Color(255, 228, 225)); frame = new JFrame(); frame.setResizable(false); frame.getContentPane().setBackground(new Color(255, 204, 204)); frame.getContentPane().setForeground(new Color(204, 153, 51)); frame.setBounds(100, 100, 1014, 406); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); DefaultTableModel model = new DefaultTableModel(); JLabel lblNewLabel = new JLabel("First Name : "); lblNewLabel.setBounds(20, 44, 86, 14); frame.getContentPane().add(lblNewLabel); //StudentID, FirstName, MiddleName, LastName, Birthdate, Age, Gender, MothersnName, FathersName, CellphoneNumber, Address model.addColumn(""); model.addColumn("Student ID"); model.addColumn("Name"); model.addColumn("Gender"); model.addColumn("Age"); model.addColumn("Birthday"); model.addColumn("Mother"); model.addColumn("Father"); model.addColumn("Cell No."); model.addColumn("Address"); table_2 = new JTable(model); table_2.setForeground(new Color(255, 182, 193)); table_2.setBackground(new Color(240, 128, 128)); table_2.getColumnModel().getColumn(0).setPreferredWidth(23); table_2.getColumn("").setCellRenderer(new JCheckRender()); table_2.getColumn("").setCellEditor(new JCheckBoxEditor()); JLabel lblNewLabel_1 = new JLabel("Middle Name :"); lblNewLabel_1.setBounds(20, 69, 103, 14); frame.getContentPane().add(lblNewLabel_1); JLabel lblNewLabel_2 = new JLabel("Last Name : "); lblNewLabel_2.setBounds(20, 90, 86, 14); frame.getContentPane().add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("Birthdate :"); lblNewLabel_3.setBounds(20, 115, 86, 14); frame.getContentPane().add(lblNewLabel_3); JLabel lblNewLabel_4 = new JLabel("Age : "); lblNewLabel_4.setBounds(20, 140, 59, 14); frame.getContentPane().add(lblNewLabel_4); JLabel lblNewLabel_5 = new JLabel("Gender :"); lblNewLabel_5.setBounds(20, 163, 59, 14); frame.getContentPane().add(lblNewLabel_5); JLabel lblNewLabel_6 = new JLabel("Mother's Name :"); lblNewLabel_6.setBounds(20, 188, 103, 14); frame.getContentPane().add(lblNewLabel_6); JLabel lblNewLabel_7 = new JLabel("Father's Name :"); lblNewLabel_7.setBounds(20, 213, 103, 14); frame.getContentPane().add(lblNewLabel_7); JLabel lblNewLabel_8 = new JLabel("Cellphone Number : "); lblNewLabel_8.setBounds(20, 236, 127, 14); frame.getContentPane().add(lblNewLabel_8); JLabel lblNewLabel_9 = new JLabel("Student ID :"); lblNewLabel_9.setFont(UIManager.getFont("Button.font")); lblNewLabel_9.setBounds(20, 25, 86, 14); frame.getContentPane().add(lblNewLabel_9); JLabel lblNewLabel_10 = new JLabel("Address : "); lblNewLabel_10.setBounds(20, 261, 86, 14); frame.getContentPane().add(lblNewLabel_10); sID = new JTextField(); sID.setBackground(new Color(255, 228, 225)); sID.setBounds(93, 22, 201, 17); frame.getContentPane().add(sID); sID.setColumns(10); fName = new JTextField(); fName.setBackground(new Color(255, 228, 225)); fName.setBounds(93, 44, 201, 17); frame.getContentPane().add(fName); fName.setColumns(10); mName = new JTextField(); mName.setBackground(new Color(255, 228, 225)); mName.setBounds(103, 69, 191, 17); frame.getContentPane().add(mName); mName.setColumns(10); lName = new JTextField(); lName.setBackground(new Color(255, 228, 225)); lName.setBounds(103, 90, 191, 17); frame.getContentPane().add(lName); lName.setColumns(10); Age = new JTextField(); Age.setBackground(new Color(255, 228, 225)); Age.setColumns(10); Age.setBounds(62, 137, 232, 17); frame.getContentPane().add(Age); mother = new JTextField(); mother.setBackground(new Color(255, 228, 225)); mother.setColumns(10); mother.setBounds(120, 185, 174, 17); frame.getContentPane().add(mother); father = new JTextField(); father.setBackground(new Color(255, 228, 225)); father.setColumns(10); father.setBounds(120, 210, 174, 17); frame.getContentPane().add(father); cp = new JTextField(); cp.setBackground(new Color(255, 228, 225)); cp.setColumns(10); cp.setBounds(132, 233, 162, 17); frame.getContentPane().add(cp); address = new JTextField(); address.setBackground(new Color(255, 228, 225)); address.setColumns(10); address.setBounds(89, 258, 205, 17); frame.getContentPane().add(address); DatePicker Bdate = new DatePicker(); Bdate.getComponentDateTextField().setBackground(Color.PINK); Bdate.setBounds(90, 113, 204, 20); JButton btnNewButton = new JButton("ADD"); btnNewButton.setForeground(new Color(240, 128, 128)); btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String sid=sID.getText(); String fname=fName.getText(); String mname=mName.getText(); String lname=lName.getText(); String bday=Bdate.getDateStringOrEmptyString(); String age=Age.getText(); String gender = bading.getSelectedItem().toString(); String mtname=mother.getText(); String ftname=father.getText(); String cnum=cp.getText(); String addr=address.getText(); try { PreparedStatement stmt= con.prepareStatement( "INSERT INTO Students (StudentID, FirstName, MiddleName, LastName, Birthdate, Age, Gender, MothersnName, FathersName, CellphoneNumber, Address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, sid); stmt.setString(2, fname); stmt.setString(3, mname); stmt.setString(4, lname); stmt.setString(5, bday); stmt.setString(6, age); stmt.setString(7, gender); stmt.setString(8, mtname); stmt.setString(9, ftname); stmt.setString(10, cnum); stmt.setString(11, addr); stmt.executeUpdate(); con.commit(); stmt.close(); String query = "Select * from Students"; PreparedStatement pst = con.prepareStatement(query); ResultSet resultset = pst.executeQuery(); while(resultset.next()) { model.addRow(new Object[] {false, resultset.getString("StudentID"), resultset.getString("FirstName")+ " " +resultset.getString("LastName"), resultset.getString("Gender"), resultset.getString("Age"), resultset.getString("Birthdate"),resultset.getString("MothersnName"),resultset.getString("FathersName"),resultset.getString("CellphoneNumber"),resultset.getString("Address")}); } }catch (Exception j) { j.printStackTrace(); } } }); btnNewButton.setBounds(426, 317, 180, 23); frame.getContentPane().add(btnNewButton); JButton btnNewButton_3 = new JButton("DELETE"); btnNewButton_3.setForeground(new Color(240, 128, 128)); btnNewButton_3.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int cons = 0; for(int i = 0; i < table_2.getRowCount(); i++) { boolean isSel = (boolean) table_2.getValueAt(i, 0); PreparedStatement stmt = null; if(isSel) { System.out.println("Deleting a row in the table..."); String sql = "DELETE FROM Students WHERE StudentID = ?"; try { stmt = con.prepareStatement(sql); stmt.setString(1, (String) table_2.getValueAt(i, 1)); stmt.executeUpdate(); con.commit(); stmt.close(); cons++; } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } Statement as; try { as = con.createStatement(); ResultSet resultset = as.executeQuery("SELECT * FROM Students"); model.setRowCount(0); while(resultset.next()) { model.addRow(new Object[] {false, resultset.getString("StudentID"), resultset.getString("FirstName")+ " " +resultset.getString("LastName"), resultset.getString("Gender"), resultset.getString("Age"), resultset.getString("Birthdate"),resultset.getString("MothersnName"),resultset.getString("FathersName"),resultset.getString("CellphoneNumber"),resultset.getString("Address")}); } as.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JOptionPane.showMessageDialog(null, cons+" item deleted successfully!"); } }); btnNewButton_3.setBounds(695, 317, 180, 23); frame.getContentPane().add(btnNewButton_3); bading.setModel(new DefaultComboBoxModel(new String[] {"Male", "Female", "Prefer not to say"})); bading.setBounds(76, 161, 218, 18); frame.getContentPane().add(bading); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(304, 11, 684, 295); frame.getContentPane().add(scrollPane_1); scrollPane_1.setViewportView(table_2); frame.getContentPane().add(Bdate); } } class JCheckBoxEditor extends DefaultCellEditor { /** * */ private static final long serialVersionUID = 3846878501975009951L; public JCheckBoxEditor() { super(new JCheckBox()); } @Override public void addCellEditorListener(CellEditorListener l) { // TODO Auto-generated method stub super.addCellEditorListener(l); } }
CrLn-66/Butete
a.java
6
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { //FBIP 3R //divide and conquer if (lists == null || lists.length == 0) return null; if (lists.length == 1) return lists[0]; int mid = (lists.length - 1) / 2; ListNode list1 = mergeKLists(Arrays.copyOfRange(lists, 0, mid + 1)); //copyOfRange does not include the last index ListNode list2 = mergeKLists(Arrays.copyOfRange(lists, mid + 1, lists.length)); return mergeTwoLists(list1, list2); } private ListNode mergeTwoLists(ListNode l1, ListNode l2){ if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val < l2.val){ l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } } }
EdwardHXu/FBIP-LC
23.java
7
/* * Decompiled with CFR 0.152. * * Could not load the following classes: * net.minecraft.util.math.MathHelper */ import i.gishreloaded.deadcode.wrappers.Wrapper; import net.minecraft.util.math.MathHelper; public class d { public double a; public double b; public double c; public d() { this.a = 0.1; } public d(double d2) { this.a = d2; } public d(double d2, double d3) { this.a = d2; this.b = d3; this.c = d3; } public void a() { this.b = 0.0; this.c = 0.0; } public void a(boolean bl) { this.c = MathHelper.clamp((double)(this.c + (bl ? this.a : -this.a) * (double)Wrapper.INSTANCE.getMinecraft().getTickLength() * (double)1.8f), (double)0.0, (double)1.0); this.b = d.a(this.c); } public double b() { return this.b; } private static /* synthetic */ double a(double d2) { return 1.0 - Math.pow(1.0 - d2, 3.0); } }
n3xtbyte/deadcode-source
d.java
8
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import com.sun.security.auth.module.Krb5LoginModule; import java.io.*; import java.lang.reflect.Constructor; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.security.PrivilegedExceptionAction; import java.util.*; import javax.security.auth.Subject; import javax.security.auth.kerberos.KerberosKey; import javax.security.auth.kerberos.KerberosTicket; import javax.security.auth.login.*; import org.ietf.jgss.*; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; /** * Kerberos command line tool. */ public class K { private static Oid oidk; private static Oid oids; static { try { oidk = new Oid("1.2.840.113554.1.2.2"); oids = new Oid("1.3.6.1.5.5.2"); } catch (Exception e) { throw new AssertionError(e); } } private static boolean isNative = false; private static boolean isDebug = false; private static int outputStyle = 0; // 0: auto, 1:color, 2:prefix private static boolean sm = false; private static boolean verbose = false; public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: java K <common option>* <command> <option>*\n\n" + "Common options:\n\n" + " -n[=lib] uses native provider\n" + " -d turns on debug\n"); System.out.println(q_help); System.out.println(); System.out.println(p_help); System.out.println(); System.out.println(w_help); System.out.println(); System.out.println(c_help); } else { for (int i=0; i<args.length; i++) { if (args[i].equals("-d")) { isDebug = true; System.setProperty("sun.security.nativegss.debug", "true"); System.setProperty("sun.security.spnego.debug", "true"); System.setProperty("sun.security.krb5.debug", "true"); System.setProperty("sun.security.jgss.debug", "true"); } else if (args[i].startsWith("-n")) { isNative = true; if (args[i].length() > 2) { if (args[i].charAt(2) == '=') { System.setProperty("sun.security.jgss.lib", args[i].substring(3)); } else { throw new Exception("Unknown command " + args[i]); } } } else { String command = args[i]; args = Arrays.copyOfRange(args, i + 1, args.length); System.setProperty("sun.security.jgss.native", Boolean.toString(isNative)); switch (command) { case "q": q(args); break; case "p": p(args); break; case "w": w(args); break; case "c": c(args); break; default: throw new Exception("Unknown command " + command); } return; } } } } /** * Login to a KDC. user/pass, user/keytab, -/- (default ccache), * -/keytab (unbound), user/-- (default keytab), -/-- (unbound default keytab). * @param name username * @param pt password or keytab * @param init true if is initiator * @return the subject */ private static Subject krb5login(String name, String pt, boolean init) throws LoginException { Subject subject = new Subject(); if (isNative) { System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); return subject; } Krb5LoginModule krb5 = new Krb5LoginModule(); Map<String, String> map = new HashMap<String, String>(); Map<String, Object> shared = new HashMap<String, Object>(); map.put("doNotPrompt", "true"); if (isDebug) { map.put("debug", "true"); } if (init) { map.put("isInitiator", "true"); } else { map.put("storeKey", "true"); map.put("isInitiator", "false"); } if (!name.equals("-")) { map.put("principal", name); } if (pt.equals("-")) { map.put("useTicketCache", "true"); } else if (pt.equals("--")) { if (name.equals("-")) { map.put("principal", "*"); } map.put("useKeyTab", "true"); } else if (new File(pt).exists()) { if (name.equals("-")) { map.put("principal", "*"); } map.put("useKeyTab", "true"); map.put("keyTab", pt); } else { map.put("useFirstPass", "true"); shared.put("javax.security.auth.login.name", name); shared.put("javax.security.auth.login.password", pt.toCharArray()); } krb5.initialize(subject, null, shared, map); krb5.login(); krb5.commit(); return subject; } /** * Creates a GSSName, whose type depends on the service's format. * Could be name, name@REALM, name@host. */ private static GSSName createName(GSSManager manager, String service) throws GSSException { if (service.indexOf('@') >= 0) { String second = service.substring(service.indexOf('@') + 1); if (second.toUpperCase().equals(second)) { // Just a realm return manager.createName(service, GSSName.NT_USER_NAME); } else { return manager.createName( service, GSSName.NT_HOSTBASED_SERVICE); } } else { return manager.createName(service, GSSName.NT_USER_NAME); } } static String q_help = "java K [-n] [-d] q <user> <key_or_tab> [<impersonate>] <peer> [-t] [-s] [-d] [-m]" + "\n\nGenerates an AP_REQ." + "\nFor example: java K q username password -m -t\n" + "\n user my username, '-' uses the one in ccache" + "\n key_or_tab password/keytab, '-' ccache, '--' default keytab" + "\n impersonate impersonates this guy, if provided" + "\n peer peer principal name" + "\n -talk talks to peer" + "\n -spnego uses SPNEGO, otherwise, krb5" + "\n -mutual requests mutual" + "\n -deleg requests cred deleg"; public static void q(final String[] args) throws Exception { Subject subj = krb5login(args[0], args[1], true);; Subject.doAs(subj, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { boolean deleg = false; boolean mutual = false; boolean talk = false; boolean useSPNEGO = false; String nextAlg = args[2]; String nextNextAlg = null; String service, impersonate; for (int i=3; i<args.length; i++) { String s = args[i]; if (s.equalsIgnoreCase("-s")) { useSPNEGO = true; } else if (s.equalsIgnoreCase("-d")) { deleg = true; } else if (s.equalsIgnoreCase("-t")) { talk = true; } else if (s.equalsIgnoreCase("-m")) { mutual = true; } else { nextNextAlg = s; } } if (nextNextAlg == null) { impersonate = null; service = nextAlg; } else { impersonate = nextAlg; service = nextNextAlg; } GSSManager manager = GSSManager.getInstance(); GSSCredential cred = null;//manager.createCredential(GSSCredential.INITIATE_ONLY); if (impersonate != null) { GSSName other = manager.createName(impersonate, GSSName.NT_USER_NAME); Class c = Class.forName("com.sun.security.jgss.ExtendedGSSCredential"); cred = (GSSCredential)c.getMethod("impersonate", GSSName.class).invoke(cred, other); //cred = ((ExtendedGSSCredential)cred).impersonate(other); } GSSContext context = manager.createContext( createName(manager, service), useSPNEGO ? oids : oidk, cred, GSSContext.DEFAULT_LIFETIME); if (deleg) context.requestCredDeleg(deleg); context.requestMutualAuth(mutual); byte[] token = new byte[0]; while (!context.isEstablished()) { token = context.initSecContext(token, 0, token.length); if (token != null) { writeToken("AP-REQ", token); } System.out.println("isEstablished/isProtReady: " + context.isEstablished() + "/" + context.isProtReady()); if (!context.isEstablished()) { token = readToken("AP-REP"); } } statusContext(context); if (talk) { talkOut(context, "Client to server"); talkIn(context); } context.dispose(); if (cred != null) { cred.dispose(); } if (isDebug) print(subj); return null; } }); } static String p_help = "java K [-n] [-d] p <user> <key_or_tab> [-t] [-s] [<backend> [-t] [-s] [-d] [-m]]\n" + "\nAccepts an AP_REQ and possibly creates another" + "\nFor example: java K p service keytab -t backend -t\n" + "\n user my username, '-' uses ccache" + "\n key_or_tab my password or keytab, '-' means ccache" + "\n -talk talks with client" + "\n -spnego uses SPNEGO, otherwise, krb5" + "\n backend if exists, getDeleg and creates an AP-REQ to backend" + "\n -talk talks with backend" + "\n -spnego uses SPNEGO to backend, otherwise, krb5" + "\n -mutual requests mutual to backend" + "\n -deleg requests cred deleg to backend"; public static void p(final String[] args) throws Exception { Subject subj = krb5login(args[0], args[1], false); Subject.doAs(subj, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { String service = null; boolean deleg = false; boolean mutual = false; boolean talkToClient = false; boolean talkToBackend = false; boolean useSPNEGOToClient = false; boolean useSPNEGOToBackend = false; for (int i=2; i<args.length; i++) { String s = args[i]; if (s.equalsIgnoreCase("-s")) { if (service == null) useSPNEGOToClient = true; else useSPNEGOToBackend = true; } else if (s.equalsIgnoreCase("-d")) { deleg = true; } else if (s.equalsIgnoreCase("-t")) { if (service == null) talkToClient = true; else talkToBackend = true; } else if (s.equalsIgnoreCase("-m")) { mutual = true; } else { service = s; } } GSSManager manager = GSSManager.getInstance(); GSSContext context = manager.createContext(manager.createCredential( args[0].equals("-") ? null : createName(manager, args[0]), GSSCredential.INDEFINITE_LIFETIME, useSPNEGOToClient ? oids : oidk, GSSCredential.ACCEPT_ONLY)); while (!context.isEstablished()) { byte[] token = readToken("AP-REQ"); token = context.acceptSecContext(token, 0, token.length); if (token != null) { writeToken("AP-REP", token); } System.out.println("isEstablished/isProtReady: " + context.isEstablished() + "/" + context.isProtReady()); } statusContext(context); if (talkToClient) { talkIn(context); talkOut(context, "Server to client"); } if (service != null) { GSSName serverName = createName(manager, service); GSSCredential ded = context.getDelegCred(); System.out.println("Use delegated credentials as " + context.getSrcName()); context.dispose(); //System.out.println(ded.getRemainingInitLifetime(oid)); context = manager.createContext( serverName, useSPNEGOToBackend ? oids : oidk, ded, GSSContext.DEFAULT_LIFETIME); context.requestMutualAuth(mutual); if (deleg) { context.requestCredDeleg(true); } byte[] token = new byte[0]; while (!context.isEstablished()) { token = context.initSecContext(token, 0, token.length); if (token != null) { writeToken("AP-REQ", token); } System.out.println("isEstablished/isProtReady: " + context.isEstablished() + "/" + context.isProtReady()); if (!context.isEstablished()) { token = readToken("AP-REP"); } } statusContext(context); if (talkToBackend) { talkOut(context, "Server to backend"); talkIn(context); } context.dispose(); if (ded != null) { ded.dispose(); } } else { context.dispose(); } if (isDebug) print(subj); return null; } }); } private static void statusContext(GSSContext context) throws GSSException { System.out.println("getSrcName/getTargName: " + context.getSrcName() + " -> " + context.getTargName()); System.out.println("State: mutual" + (context.getMutualAuthState()?"+":"-") + " deleg" + (context.getCredDelegState()?"+":"-") + " anonymous" + (context.getAnonymityState()?"+":"-") + " conf" + (context.getConfState()?"+":"-") + " integ" + (context.getIntegState()?"+":"-") + " replay" + (context.getReplayDetState()?"+":"-") + " sequence" + (context.getSequenceDetState()?"+":"-")); } private static void talkOut(GSSContext context, String msg) throws Exception { byte[] data = msg.getBytes(); byte[] data2 = data; MessageProp prop = new MessageProp(true); writeToken("wrap", context.wrap(data, 0, data.length, prop)); writeToken("wrap", context.wrap(data2, 0, data2.length, prop)); writeToken("wrap", context.wrap(data, 0, data.length, prop)); writeToken("wrap", context.wrap(data2, 0, data2.length, prop)); } private static void showProp(String label, MessageProp prop) { System.out.println(label + " priv" + (prop.getPrivacy()?"+":"-") + " dup" + (prop.isDuplicateToken()?"+":"-") + " gap" + (prop.isGapToken()?"+":"-") + " old" + (prop.isOldToken()?"+":"-") + " unseq" + (prop.isUnseqToken()?"+":"-")); // Wait until 8201627 is resolved. if (prop.isDuplicateToken() || prop.isGapToken() || prop.isOldToken() || prop.isUnseqToken()) { throw new RuntimeException("Bad prop"); } } private static void talkIn(GSSContext context) throws Exception { MessageProp prop; byte[] token1 = readToken("wrap"); byte[] token2 = readToken("wrap"); byte[] token3 = readToken("wrap"); byte[] token4 = readToken("wrap"); prop = new MessageProp(true); byte[] msg = context.unwrap(token1, 0, token1.length, prop); showProp("unwrap: \"" + new String(msg) + "\"", prop); prop = new MessageProp(true); byte[] msg2 = context.unwrap(token2, 0, token2.length, prop); showProp("unwrap: \"" + new String(msg2) + "\"", prop); prop = new MessageProp(true); byte[] msg3 = context.unwrap(token3, 0, token3.length, prop); showProp("unwrap: \"" + new String(msg) + "\"", prop); prop = new MessageProp(true); byte[] msg4 = context.unwrap(token4, 0, token4.length, prop); showProp("unwrap: \"" + new String(msg2) + "\"", prop); } static void writeToken(String name, byte[] token) throws Exception { String start = "-----START " + name + "-----"; String end = "-----END " + name + "-----"; System.out.println(start); System.out.println(Base64.getEncoder().encodeToString(token)); System.out.println(end); } static byte[] readToken(String name) throws Exception { String start = "-----START " + name + "-----"; String end = "-----END " + name + "-----"; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); boolean in = false; System.out.println(">>> Waiting for " + name + "..."); while (true) { String line = br.readLine(); if (line == null) throw new Exception("No token to read"); if (line.equals(start)) { in = true; } else if (in) { if (line.equals(end)) { return Base64.getDecoder().decode(sb.toString()); } else { sb.append(line); } } } } private static void print(Subject s) { System.out.println(s.getPrincipals()); for (Object o: s.getPrivateCredentials()) { if (o instanceof KerberosTicket) { KerberosTicket kt = (KerberosTicket)o; System.out.println("KerberosTicket: " + kt.getClient() + " -> " + kt.getServer()); } else if (o instanceof KerberosKey) { KerberosKey kk = (KerberosKey)o; System.out.println("KerberosKey: " + kk); } else { System.out.println(o.getClass()); } } } /////////////////////////////////////////////////////////////////// static String w_help = "java K [-n] [-d] w [user] [pass] [scheme] <url>*" + "\n\nGrab a URL" + "\nFor example: java K w - - kerberos http://www.protected.com\n" + "\n user my username" + "\n pass my password" + "\n scheme Negotiate or Kerberos or NTLM etc" + "\n url URL"; public static void w(String[] args) throws Exception { String HTTPLOG = "sun.net.www.protocol.http.HttpURLConnection"; Logger.getLogger(HTTPLOG).setLevel(Level.ALL); Handler h = new ConsoleHandler(); h.setLevel(Level.ALL); Logger.getLogger(HTTPLOG).addHandler(h); System.setProperty("http.maxRedirects", "10"); String userName = null; String password = null; for (String arg : args) { if (arg.startsWith("http")) { System.err.println("\u001b[1;37;41m" + arg); System.err.println("\u001b[m\n"); URL url = new URL(arg); InputStream ins = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(ins)); String str; int pos = 0; while ((str = reader.readLine()) != null) { if (pos++ > 10) { System.out.print("."); } else { System.out.println(str); } } System.out.println(); } else if (arg.equalsIgnoreCase("negotiate") || arg.equalsIgnoreCase("kerberos")) { System.setProperty("http.auth.preference", arg); } else if (userName == null) { userName = arg; } else if (password == null) { password = arg; Authenticator.setDefault( new MyAuthenticator(userName, password.toCharArray())); userName = null; password = null; } else { throw new Exception("what is " + arg); } } } static class MyAuthenticator extends Authenticator { String user; char[] pass; public MyAuthenticator (String user, char[] pass) { this.user = user; this.pass = pass; } public PasswordAuthentication getPasswordAuthentication () { System.err.println("::::: PROVIDING " + getRequestingScheme() + " PASSWORD AND USERNAME"); return new PasswordAuthentication (user, pass); } } /////////////////////////////////////////////////////////////////// static String c_help = "java K c <option>* <command>+" + "\n\nChoreograph several commands talking to each other" + "\nFor example: java K c \"K -n q - - server -d\" \"K p server keytab backend\" -d 3000 \"K p backend keytab\"\n" + "\n -c always uses color output" + "\n -p always uses prefix output" + "\n -j <java> uses this executable" + "\n -d <delay> delay in milliseconds" + "\n -s Run with security manager" + "\n -v Display full data" + "\n command Arguments of a java command"; public static void c(String[] args) throws Exception { String java = System.getProperty("java.home") + "/bin/java"; Files.write(Paths.get("policy"), Arrays.asList( "grant {", " permission java.security.AllPermission;", "};" )); for (int i = 0; i < args.length; i++) { String arg = args[i]; switch (arg) { case "-c": outputStyle = 1; break; case "-p": outputStyle = 2; break; case "-s": sm = true; break; case "-j": java = args[++i]; break; case "-d": Thread.sleep(Long.parseLong(args[++i])); break; case "-v": verbose = true; break; default: run(java, arg); } } } static String inheritProperty(String k) { String v = System.getProperty(k); return v == null ? "" : (" -D" + k + "=" + v + " "); } static void run(String java, String s) throws Exception { if (sm) { s = "-Djava.security.manager -Djava.security.policy=policy " + s; } new Runner(java + " " + inheritProperty("java.class.path") + inheritProperty("java.security.krb5.conf") + inheritProperty("sun.security.jgss.lib") + inheritProperty("sun.security.krb5.acceptor.sequence.number.nonmutual") + " -ea -esa " + s); } static class Runner { Process p; Printer pt; Runner(String cmd) throws Exception { p = new ProcessBuilder(cmd.split(" +")).start(); pt = Printer.get(); new ReadThread(this).start(); new ErrThread(this).start(); } } static class ReadThread extends Thread { Runner r; static String WAIT_HEAD = ">>> Waiting for "; static String DATA_START = "-----START "; static String DATA_END = "-----END "; ReadThread(Runner r) { this.r = r; } @Override public void run() { BufferedReader br = new BufferedReader( new InputStreamReader(r.p.getInputStream())); try { String block = null; String label = null; while (true) { String s = br.readLine(); if (s == null) break; r.pt.p(s.length() > 100 && !verbose ? (s.substring(0, 100) + "...") : s); if (s.startsWith(WAIT_HEAD)) { String name = s.substring(WAIT_HEAD.length(), s.length() - 3); String data = Data.dataFor(name, r); if (data != null) { r.pt.p3(">>> See " + name); r.p.getOutputStream().write(data.getBytes()); r.p.getOutputStream().flush(); } else { Data.setRunner(name, r); } } else if (s.startsWith(DATA_START)) { label = s.substring(DATA_START.length(), s.length() - 5); block = s + "\n"; } else if (s.startsWith(DATA_END)) { block += s + "\n"; Runner r2 = Data.runnerFor(label, r); if (r2 != null) { r2.pt.p3(">>> See " + label); r2.p.getOutputStream().write(block.getBytes()); r2.p.getOutputStream().flush(); } else { Data.setData(label, block, r); } label = null; } else if (label != null) { block += s + "\n"; } } } catch (IOException ioe) { ioe.printStackTrace(); } } } static class ErrThread extends Thread { Runner r; ErrThread(Runner r) { this.r = r; } @Override public void run() { BufferedReader br = new BufferedReader( new InputStreamReader(r.p.getErrorStream())); try { while (true) { String s = br.readLine(); if (s == null) break; r.pt.p4(s); } } catch (IOException ioe) { ioe.printStackTrace(); } } } static class Data { // Proc waiting for data: label, null, r // Data waiting for proc: label, data, r static LinkedList<Object[]> data = new LinkedList<>(); public synchronized static void setData(String label, String block, Runner r) { data.add(new Object[] {label, block, r}); } public synchronized static Runner runnerFor(String label, Runner me) { Iterator<Object[]> iter = data.iterator(); while (iter.hasNext()) { Object[] d = iter.next(); if (d[0].equals(label) && d[1] == null && d[2] != me) { iter.remove(); return (Runner) d[2]; } } return null; } public synchronized static void setRunner(String name, Runner r) { data.add(new Object[] {name, null, r}); } public synchronized static String dataFor(String name, Runner me) { Iterator<Object[]> iter = data.iterator(); while (iter.hasNext()) { Object[] d = iter.next(); if (d[0].equals(name) && d[1] != null && d[2] != me) { iter.remove(); return (String) d[1]; } } return null; } } static abstract class Printer { int c; int fore; static int now = 2; static Printer get() { int cc = now++; if (outputStyle == 0) { if (System.getenv("windir") != null) { return new Mono(cc); } else { return new Color(cc, cc == 7 ? 30 : 37); } } else if (outputStyle == 1) { return new Color(cc, cc == 7 ? 30 : 37); } else { return new Mono(cc); } } abstract void p(String s); abstract void p3(String s); abstract void p4(String s); static class Color extends Printer { Color(int c, int fore) { this.c = c; this.fore = fore; } void p(String s) { // color System.out.println("\u001b[1;" + fore + ";4" + c + "m" + s + "\u001b[m"); } void p3(String s) { // italic System.out.println("\u001b[1;3;" + fore + ";4" + c + "m" + s + "\u001b[m"); } void p4(String s) { // underline System.out.println("\u001b[1;4;" + fore + ";4" + c + "m" + s + "\u001b[m"); } } static class Mono extends Printer { Mono(int c) { this.c = c; } void p(String s) { // color System.out.println(c + ": " + s); } void p3(String s) { // italic System.out.println(c + "> " + s); } void p4(String s) { // underline System.out.println(c + "< " + s); } } } }
wangweij/ktest
K.java
9
/* This file does nothing but load the SBML library */ import org.sbml.libsbml.*; public class A { public Model getModel() { return new Model(0,0); } /** * The following static block is needed in order to load the * the libSBML Java module when the application starts. */ static { String varname; String shlibname; if (System.getProperty("mrj.version") != null) { varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. shlibname = "libsbmlj.jnilib and/or libsbml.dylib"; } else { varname = "LD_LIBRARY_PATH"; // We're not on a Mac. shlibname = "libsbmlj.so and/or libsbml.so"; } try { System.loadLibrary("sbmlj"); Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error encountered while attempting to load libSBML:"); e.printStackTrace(); System.err.println("Please check the value of your " + varname + " environment variable and/or" + " your 'java.library.path' system property" + " (depending on which one you are using) to" + " make sure it lists all the directories needed to" + " find the " + shlibname + " library file and the" + " libraries it depends upon (e.g., the XML parser)."); System.exit(1); } catch (ClassNotFoundException e) { e.printStackTrace(); System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely your -classpath option and/or" + " CLASSPATH environment variable do not" + " include the path to the file libsbmlj.jar."); System.exit(1); } catch (SecurityException e) { System.err.println("Error encountered while attempting to load libSBML:"); e.printStackTrace(); System.err.println("Could not load the libSBML library files due to a"+ " security exception.\n"); System.exit(1); } } }
bio-ontology-research-group/sbml-harvester
A.java
10
import java.io.File; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; import net.minecraft.server.MinecraftServer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class x extends i { private static final Logger a = ; private long b; private int c; public String c() { return "debug"; } public int a() { return 3; } public String b(m ☃) { return "commands.debug.usage"; } public void a(MinecraftServer ☃, m ☃, String[] ☃) throws bz { if (☃.length < 1) { throw new cf("commands.debug.usage", new Object[0]); } if (☃[0].equals("start")) { if (☃.length != 1) { throw new cf("commands.debug.usage", new Object[0]); } a(☃, this, "commands.debug.start", new Object[0]); ☃.aq(); this.b = MinecraftServer.av(); this.c = ☃.ap(); } else if (☃[0].equals("stop")) { if (☃.length != 1) { throw new cf("commands.debug.usage", new Object[0]); } if (!☃.c.a) { throw new bz("commands.debug.notStarted", new Object[0]); } long ☃ = MinecraftServer.av(); int ☃ = ☃.ap(); long ☃ = ☃ - this.b; int ☃ = ☃ - this.c; a(☃, ☃, ☃); ☃.c.a = false; a(☃, this, "commands.debug.stop", new Object[] { Float.valueOf((float)☃ / 1000.0F), Integer.valueOf(☃) }); } else { throw new cf("commands.debug.usage", new Object[0]); } } private void a(long ☃, int ☃, MinecraftServer ☃) { File ☃ = new File(☃.d("debug"), "profile-results-" + new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss").format(new Date()) + ".txt"); ☃.getParentFile().mkdirs(); try { FileWriter ☃ = new FileWriter(☃); ☃.write(b(☃, ☃, ☃)); ☃.close(); } catch (Throwable ☃) { a.error("Could not save profiler results to " + ☃, ☃); } } private String b(long ☃, int ☃, MinecraftServer ☃) { StringBuilder ☃ = new StringBuilder(); ☃.append("---- Minecraft Profiler Results ----\n"); ☃.append("// "); ☃.append(d()); ☃.append("\n\n"); ☃.append("Time span: ").append(☃).append(" ms\n"); ☃.append("Tick span: ").append(☃).append(" ticks\n"); ☃.append("// This is approximately ").append(String.format("%.2f", new Object[] { Float.valueOf(☃ / ((float)☃ / 1000.0F)) })).append(" ticks per second. It should be ").append(20).append(" ticks per second\n\n"); ☃.append("--- BEGIN PROFILE DUMP ---\n\n"); a(0, "root", ☃, ☃); ☃.append("--- END PROFILE DUMP ---\n\n"); return ☃.toString(); } private void a(int ☃, String ☃, StringBuilder ☃, MinecraftServer ☃) { List<oo.a> ☃ = ☃.c.b(☃); if ((☃ == null) || (☃.size() < 3)) { return; } for (int ☃ = 1; ☃ < ☃.size(); ☃++) { oo.a ☃ = (oo.a)☃.get(☃); ☃.append(String.format("[%02d] ", new Object[] { Integer.valueOf(☃) })); for (int ☃ = 0; ☃ < ☃; ☃++) { ☃.append("| "); } ☃.append(☃.c).append(" - ").append(String.format("%.2f", new Object[] { Double.valueOf(☃.a) })).append("%/").append(String.format("%.2f", new Object[] { Double.valueOf(☃.b) })).append("%\n"); if (!☃.c.equals("unspecified")) { try { a(☃ + 1, ☃ + "." + ☃.c, ☃, ☃); } catch (Exception ☃) { ☃.append("[[ EXCEPTION ").append(☃).append(" ]]"); } } } } private static String d() { String[] ☃ = { "Shiny numbers!", "Am I not running fast enough? :(", "I'm working as hard as I can!", "Will I ever be good enough for you? :(", "Speedy. Zoooooom!", "Hello world", "40% better than a crash report.", "Now with extra numbers", "Now with less numbers", "Now with the same numbers", "You should add flames to things, it makes them go faster!", "Do you feel the need for... optimization?", "*cracks redstone whip*", "Maybe if you treated it better then it'll have more motivation to work faster! Poor server." }; try { return ☃[((int)(System.nanoTime() % ☃.length))]; } catch (Throwable ☃) {} return "Witty comment unavailable :("; } public List<String> a(MinecraftServer ☃, m ☃, String[] ☃, cj ☃) { if (☃.length == 1) { return a(☃, new String[] { "start", "stop" }); } return Collections.emptyList(); } }
MCLabyMod/LabyMod-1.9
x.java
11
public static void splitTheBlop(Monster curr) { if (!curr.canSplit()) { players[BLOPSPLIT] = new Player(); // Assuming Player is the appropriate class for players array curr.setHealth((int)(Math.random() * (101 - 50 + 1) + 50)); curr.setCanSplit(true); } else { if (curr.getHealth() == 100) { int Number = (int)(Math.random() * (76 - 25 + 1) + 25); curr.damage(Number); players[BLOPSPLIT] = new Blop(curr.getRow(), curr.getCol(), playerImages[4]); curr.setCanSplit(false); } } }
1588974/Array-List
e.java
12
import java.io.InputStream; import java.io.FileInputStream; public class Main { public static void main(String args[]) { try { // file input.txt is loaded as input stream // input.txt file contains: // This is a content of the file input.txt InputStream input = new FileInputStream("input.txt"); System.out.println("Data in the file: "); // Reads the first byte int i = input.read(); while(i != -1) { System.out.print((char)i); // Reads next byte from the file i = input.read(); } input.close(); } catch(Exception e) { e.getStackTrace(); } } }
Hansajith98/hacktoberfest2021-Excluded
Java/FileTextAsInputStream.java
13
// Program to print BFS traversal from a given // source vertex. BFS(int s) traverses vertices // reachable from s. #include<bits/stdc++.h> using namespace std; // This class represents a directed graph using // adjacency list representation class Graph { int V; // No. of vertices // Pointer to an array containing adjacency // lists vector<list<int>> adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints BFS traversal from a given source s void BFS(int s); }; Graph::Graph(int V) { this->V = V; adj.resize(V); } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::BFS(int s) { // Mark all the vertices as not visited vector<bool> visited; visited.resize(V,false); // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << " "; queue.pop_front(); // Get all adjacent vertices of the dequeued // vertex s. If a adjacent has not been visited, // then mark it visited and enqueue it for (auto adjecent: adj[s]) { if (!visited[adjecent]) { visited[adjecent] = true; queue.push_back(adjecent); } } } } // Driver program to test methods of graph class int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Breadth First Traversal " << "(starting from vertex 2) \n"; g.BFS(2); return 0; }
manan-shxrma/dsalgo
graphs/bFSgraph.cpp
14
class Solution { public List<List<Integer>> threeSum(int[] nums) { if (nums.length < 3) return new ArrayList<>(); List<List<Integer>> ans = new ArrayList<>(); Arrays.sort(nums); for (int i = 0; i + 2 < nums.length; ++i) { if (i > 0 && nums[i] == nums[i - 1]) continue; // choose nums[i] as the first num in the triplet, // and search the remaining nums in [i + 1, n - 1] int l = i + 1; int r = nums.length - 1; while (l < r) { final int sum = nums[i] + nums[l] + nums[r]; if (sum == 0) { ans.add(Arrays.asList(nums[i], nums[l++], nums[r--])); while (l < r && nums[l] == nums[l - 1]) ++l; while (l < r && nums[r] == nums[r + 1]) --r; } else if (sum < 0) { ++l; } else { --r; } } } return ans; } }
Next-Gen-UI/Code-Dynamics
Leetcode/0015. 3Sum/0015.java
15
// AI class, a main component of the CFM Project // This component is really the brains of the program since it is used to simplify expressions and solve equations // and to determine if student answers are algebraically equivalent with the correct answers. // By G. Baugher package cfm_files; import java.util.Scanner; public class AI { static String origText, origValue, expression, messages = ""; static String[] answer = { "", "" }; static double enteredValue; static Term[] overallExpr = initArrayOfTerms(); static boolean equation = false; public static class Term { // Creates a class for representing algebraic terms, each having a coefficient, a variable, and an exponent. public double coeff; public char variable; public int expon; public Term( double coef, char var, int expo ) { this.coeff = coef; this.variable = var; this.expon = expo; } public double getCoeff() { return coeff; } public char getVar() { return variable; } public int getExpon() { return expon; } public void setCoeff(double coef) { coeff = coef; } public void setVar(char var) { variable = var; } public void setExpon(int expo) { expon = expo; } public Term() { coeff = 0.0; variable = ' '; expon = 0; }; } public static Term initTerm(Term term) { term.setCoeff(0.0); term.setVar(' '); term.setExpon(0); return term; } public static Term[] initArrayOfTerms( ) { Term[] arrayOfTerms = new Term[19]; int i; for (i=0; i<19; i++) { arrayOfTerms[i] = new Term(); initTerm( arrayOfTerms[i] ); } return arrayOfTerms; } public static int numNonEmptyTerms ( Term[] inputExpr ) { int numOfLastTerm = inputExpr.length-1; boolean lastEmptyTerm = false; while (!lastEmptyTerm) { if ((inputExpr[numOfLastTerm].coeff == 0) && (inputExpr[numOfLastTerm].variable == ' ')) { numOfLastTerm--; if (numOfLastTerm == 0) lastEmptyTerm = true; } else lastEmptyTerm = true; } return numOfLastTerm + 1; } public static String elimOrAddSigns( String expression) { // Eliminates initial plus signs or terminal signs in an expression and also adds 1's before variables int i, len = expression.length(), count = 0; char ch; if ( expression.length() != 0 ) { // Do nothing if expression is void. if ( expression.length() == 1 ) { // Check if single character expression has no number or variable ch = expression.charAt(0); if ( "=+-*/()[]{}^.–".indexOf(ch) != -1 ) { expression = ""; messages += "Error - incorrect expression: no algebra terms or numbers in the expression. "; }; } else { while ((len > 1) && (count < len)) { // System.out.println( "len: " + len + " count: " + count ); count+=2; // Remove any initial '+' sign or any '+' or '-' sign at end of expression. len = expression.length(); if ((expression.charAt(len-1) == '+') || (expression.charAt(len-1) == '-')) expression = expression.substring(0,len-1); if (expression.charAt(0) == '+') expression = expression.substring(1); // Add coefficient of 1 in front of any letter not already having a coefficient if (Character.isLetter( expression.charAt(0) )) expression = "1" + expression; for ( i = 0; i < expression.length() - 2; i++ ) { ch = expression.charAt(i); if ((( ch == '+') || (ch == '-')) || ((ch == '(') || (ch == ')')) ) if (Character.isLetter( expression.charAt(i+1) )) expression = expression.substring(0,i+1) + "1" + expression.substring(i+1); }; }; } } return expression; } public static String removeSpaces( String exp ) { int i; exp = exp.trim(); while (exp.indexOf(' ') != -1) { for(i=0; i<exp.length(); i++) { if (exp.charAt(i)==' ') { exp = exp.substring(0,i) + exp.substring(i+1); } } }; return exp; } public static String prepareEquation( String expression ) { int i, count = 0, location = 0; equation = false; String leftSide = "", rightSide = ""; // Determine if there are equal signs (and if more than one) and if one, set equation to true. for (i=0; i < expression.length(); i++ ) { if ( expression.charAt(i) == '=' ) { count++; location = i; }; }; equation = (count == 1); if (count > 1) { messages += "Error - incorrect expression: multiple equal signs. "; } // If equation, divide into two sides and eliminate initial plus signs or terminal signs in leftSide or rightSide expressions if (equation) { leftSide = expression.substring(0,location); rightSide = expression.substring(location+1); System.out.println("Left Side: " + leftSide + " Right Side: " + rightSide ); leftSide = elimOrAddSigns( leftSide ); rightSide = elimOrAddSigns( rightSide ); expression = leftSide + '=' + rightSide; }; return expression; } public static String removeDoubleSigns( String expression ) { boolean completed = false; int j; char ch; String twoChar, tempString = expression; // Change ++ to +, +- or -+ to -, and -- to +, if any of these are in the string if ( expression.length() > 2 ) { while ( !completed) { for ( j = 0; j < expression.length() - 1; j++ ) { twoChar = expression.substring(j,j+2); ch = '#'; if (twoChar.compareTo("++") == 0) { ch = '+'; messages += "Double plus signs should be changed to + only. "; }; if ((twoChar.compareTo("+-") == 0) || (twoChar.compareTo("-+") == 0)) { ch = '-'; messages += "+- or -+ should be changed to - only. "; }; if (twoChar.compareTo("--") == 0) { ch = '+'; messages += "Double minus signs should be changed to a + sign. "; }; if (ch != '#') { expression = expression.substring(0,j) + ch + expression.substring(j+2); //j--; } }; if ( tempString.compareTo(expression) == 0 ) completed = true; tempString = expression; }; } return expression; } public static String removeOtherCharacters( String expression ) { int i = 0; char ch; boolean ok; if ( expression.length() > 0 ) while ( i < expression.length()-1 ) { ok = false; ch = expression.charAt(i); if ((Character.isDigit(ch)) || (Character.isLetter(ch))) ok = true; if ("=+-*/()[]{}^.–".indexOf(ch) != -1) ok = true; if (!ok) { System.out.println( "Error - expression has an unacceptable character: " + ch + " (character removed). " ); expression = expression.substring(0,i) + expression.substring(i+1); }; i++; }; return expression; } public static String removeTermsWithZeroCoefficients( String expression ) { // This needs to be written or the code written and added into combineLikeTerms() or determineExpr() return expression; } public static String prepareExpOrEq( String origText ) { // Prepares the string in various ways, detects unwanted characters, determines if equation, etc. // Remove any spaces and switch upper to lower case letters String expression = removeSpaces( origText ).toLowerCase(); // Detect and remove characters other than numbers, letters, operation signs, equal signs, and parentheses or brackets. expression = removeOtherCharacters( expression ); // Remove any double signs such as '--' or '+-' expression = removeDoubleSigns( expression ); // Eliminate initial plus signs or terminal signs in the whole expression or add 1's before variables if no coefficient expression = elimOrAddSigns( expression ); // If equation, prepare the two sides separately expression = prepareEquation( expression ); // System.out.println("Messages: " + messages); return expression; } // end of prepareExpOrEq public static Term[] determineExpr( String origExpr, int beginPos, int endPos) { // Analyzes the string character by character and converts to an array of Terms boolean nowExpon = false, prevIsDigit = false, prevIsLetter = false; // (assuming no parentheses in the expression) int i, index, signMultiplier = 1, numOfTerm = 0; char ch; String numStr = ""; double number = 0; double coeff[] = new double[19]; char variable[] = new char[19]; int expon[] = new int[19]; for ( index = 0; index < 19; index++ ) { coeff[index] = 0; variable[index] = ' '; expon[index] = 0; }; Term[] exprAsArrayOfTerms = initArrayOfTerms(); i = beginPos; ch = origExpr.charAt(i); if ((ch == '+') || ( ch == '-')) { if (ch == '-') signMultiplier = -1; i++; }; while ( i < endPos ) { ch = origExpr.charAt(i); if ( !(Character.isDigit(ch) || (ch == '.') ) && prevIsDigit) { number = Double.parseDouble(numStr); if (nowExpon) { expon[numOfTerm] = (int) number; nowExpon = false; } else { coeff[numOfTerm] = signMultiplier*number; }; numStr = ""; prevIsDigit = false; }; if (Character.isDigit(ch) || (ch == '.')) { numStr += ch; prevIsDigit = true; }; if (Character.isLetter(ch)) { expon[numOfTerm] = 1; if (prevIsLetter) messages += "Error: adjacent letters found. "; else { variable[numOfTerm] = ch; prevIsLetter = true; }; } else { prevIsLetter = false; }; if (ch == '^') { if (nowExpon) messages += "Error: multiple adjacent exponent symbols (^) found. "; if (!(prevIsLetter)) messages += "Error: exponent not preceeded by a variable. "; nowExpon = true; }; if ((ch == '+') || (ch == '-')) { exprAsArrayOfTerms[numOfTerm].setCoeff(coeff[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setVar(variable[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setExpon(expon[numOfTerm]); numOfTerm++; if (ch == '+') signMultiplier = 1; if (ch == '-') signMultiplier = -1; }; if (i == endPos-1) { if (Character.isDigit(ch)) { number = Double.parseDouble(numStr); if (nowExpon) { expon[numOfTerm] = (int) number; exprAsArrayOfTerms[numOfTerm].setCoeff(coeff[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setVar(variable[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setExpon(expon[numOfTerm]); } else { exprAsArrayOfTerms[numOfTerm].setCoeff(signMultiplier*number); exprAsArrayOfTerms[numOfTerm].setVar(' '); exprAsArrayOfTerms[numOfTerm].setExpon(0); }; }; if (Character.isLetter(ch)) { expon[numOfTerm] = 1; exprAsArrayOfTerms[numOfTerm].setCoeff(coeff[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setVar(variable[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setExpon(expon[numOfTerm]); }; System.out.println( "At endPos-1 which is " + i + " Ch: " + ch ); System.out.print( "numOfTerm: " + numOfTerm + " Number: " + number + " Expression building: "); displayExpr( exprAsArrayOfTerms ); }; i++; }; return exprAsArrayOfTerms; } // end of determineExpr public static void displayExpr( Term[] expr ) { // Used various places where expressions are to be displayed in the console int index, num = numNonEmptyTerms( expr ); for (index = 0; index < num; index++ ) { System.out.print( " " + expr[index].coeff ); if ( expr[index].expon != 0 ) { System.out.print( expr[index].variable + "^" + expr[index].expon ); } if (index != num-1) System.out.print( " +" ); else System.out.println(" "); }; } public static String convertToStr( Term[] expr ) { // Used several places to convert an array of Terms into a string int i, numOfTerms = numNonEmptyTerms( expr ); String newExpr = ""; for (i=0; i < numOfTerms; i++) { // Build new expression after distributing if ( expr[i].expon == 0 ) { newExpr += Double.toString( expr[i].coeff ); } else { newExpr += Double.toString( expr[i].coeff ) + expr[i].variable + "^" + Integer.toString((int) expr[i].expon ); } if ( i < numOfTerms - 1) newExpr += "+"; } return newExpr; } public static Term[] distributeMonomial( Term[] monomial, Term[] insideExpr) { // Distributes a single term (monomial) to an expression int index; Term[] resultExpr = initArrayOfTerms(); for (index = 0; index < numNonEmptyTerms( insideExpr ); index++ ) { resultExpr[index].setCoeff( monomial[0].coeff*insideExpr[index].coeff ); char monVar = monomial[0].variable; char insVar = insideExpr[index].variable; if ((monVar == insVar)||(insVar == 32)) { resultExpr[index].setVar(monomial[0].variable); resultExpr[index].setExpon( monomial[0].expon + insideExpr[index].expon); } else { resultExpr[index].variable = insideExpr[index].variable; resultExpr[index].expon = insideExpr[index].expon; }; }; return resultExpr; } public static Term[] deleteTerm( int index, Term[] expression ) { // To eliminate the "processed" highExpon term from the input expression int m, numOfTerms = numNonEmptyTerms( expression ); if ( index == numOfTerms - 1 ) { initTerm( expression[ index ] ); } else { for ( m = index; m < numOfTerms-1; m++ ) { expression[m].setCoeff( expression[m+1].coeff ); expression[m].setVar( expression[m+1].variable ); expression[m].setExpon( expression[m+1].expon ); }; initTerm( expression[numOfTerms-1] ); }; return expression; } public static Term[] combineLikeTerms( Term[] inputExpr) { // Starting with the highest exponent, searches for like terms and combines int i, j, highExpon, highIndex = 0, origNumOfTerms, numOfTerms; double sumOfCoeffs; //char highVar; Term[] outputExpr = initArrayOfTerms(); origNumOfTerms = inputExpr.length; numOfTerms = numNonEmptyTerms( inputExpr ); i = 0; while ( ( i < origNumOfTerms ) && ( numOfTerms != 0 ) ) { numOfTerms = numNonEmptyTerms( inputExpr ); // set the high exponent term to be the first term highExpon = inputExpr[0].expon; //highVar = inputExpr[0].variable; highIndex = 0; if (numOfTerms > 0) { for ( j = 1; j < numOfTerms; j++ ) { if (highExpon < inputExpr[j].expon ) { // add a condition of the variables being the same highExpon = inputExpr[j].getExpon(); highIndex = j; //highVar = inputExpr[j].getVar(); }; }; // Stores highest exponent term in outputExpr, then removes it from the inputExpr array outputExpr[i].setVar( inputExpr[highIndex].variable ); outputExpr[i].setExpon( inputExpr[highIndex].expon ); outputExpr[i].setCoeff( inputExpr[highIndex].coeff ); inputExpr = deleteTerm( highIndex, inputExpr ); numOfTerms = numNonEmptyTerms( inputExpr ); }; // To look for a term that is "like" the outputExpr[i] term and combine it for ( j = 0; j < numOfTerms; j++ ) { if (( outputExpr[i].variable == inputExpr[j].variable ) && ( outputExpr[i].expon == inputExpr[j].expon)) { // To store the combined term in the output expression sumOfCoeffs = inputExpr[j].coeff + outputExpr[i].coeff; outputExpr[i].setCoeff( sumOfCoeffs ); // To eliminate the "processed" like term from the input expression inputExpr = deleteTerm( j, inputExpr ); numOfTerms = numNonEmptyTerms( inputExpr ); }; }; // End of for j Loop i++; } return outputExpr; } // End of combineLikeTerms public static Term[] simpSingleParExpr( String expression ) { // Handles when the expression has one set of parentheses int i, j, k, l, m = 0, n = 0; String newExpr = "", beginStr = "", endStr = ""; boolean parError = false, endMultiplier = false; Term[] expressionList = initArrayOfTerms(); Term[] nestExpr = initArrayOfTerms(); Term[] multiplierTerm = initArrayOfTerms(); Term[] resultExpr = initArrayOfTerms(); // Determine positions of open and close parentheses ParPos pp = new ParPos(); pp.determParPos(expression); // Process parentheses except for any term after the parentheses k = pp.Open1; i = expression.lastIndexOf('+', k); j = expression.lastIndexOf('-', k); l = expression.lastIndexOf('–', k); if ((j!=-1) || (l!=-1)) j = Math.max(j, l); if ((i!=-1)||(j!=-1)) { k = Math.max(i, j); multiplierTerm = determineExpr( expression, k, pp.Open1); } else { multiplierTerm = determineExpr( expression, 0, pp.Open1); k = 0; }; if (k != 0) beginStr = expression.substring(0,k) + "+"; nestExpr = determineExpr( expression, pp.Open1+1, pp.Close1 ); if (numNonEmptyTerms(multiplierTerm) == 1) { resultExpr = distributeMonomial( multiplierTerm, nestExpr); }; // Determine if any final term to distribute and distribute it; determine any trailing added part of expression if (pp.Close1 < expression.length()-1) { i = expression.indexOf('+',pp.Close1); j = expression.indexOf('-',pp.Close1); l = expression.lastIndexOf('–',pp.Close1); m = pp.Close1; if (i!=-1) m = i; if ((j!=-1) || (l!=-1)) j = Math.max(j, l); if (j!=-1) { n = j; if (i!=-1) m = Math.min( m, n ); else m = j; }; if (( i == -1 ) && ( j == -1 )) { multiplierTerm = determineExpr( expression, pp.Close1+1, expression.length() ); endMultiplier = true; endStr = ""; } else { multiplierTerm = determineExpr( expression, pp.Close1+1, m); endMultiplier = true; if (m>pp.Close1) endStr = "+" + expression.substring( m ); else endStr = "+" + expression.substring(m+1); }; if (endMultiplier) if ((numNonEmptyTerms(multiplierTerm) == 1) && (multiplierTerm[0].coeff != 0)) { resultExpr = distributeMonomial( multiplierTerm, resultExpr); }; }; // Combine all parts and prepare expression and combine like terms newExpr = convertToStr( resultExpr ); expression = beginStr + newExpr + endStr; expression = prepareExpOrEq( expression ); expressionList = determineExpr( expression, 0, expression.length() ); expressionList = combineLikeTerms ( expressionList ); if (parError) System.out.println( "Incorrect entry. Try again." ); return expressionList; } // end of simpSinglePar public static Term[] addTwoExpressions( Term[] exp1, Term[] exp2 ) { // Adds two expressions (arrays of terms) int i, numOfTerms; String newExpr = ""; Term[] expression = initArrayOfTerms(); numOfTerms = numNonEmptyTerms( exp1 ); for (i=0; i < numOfTerms; i++) { // Build first part of new expression if (( exp1[i].expon == 0 ) && (exp1[i].coeff != 0 )) { newExpr += Double.toString( exp1[i].coeff ); } else { newExpr += Double.toString( exp1[i].coeff ) + exp1[i].variable + "^" + Integer.toString((int) exp1[i].expon ); } if ( i < numOfTerms - 1) newExpr += "+"; } newExpr += "+"; numOfTerms = numNonEmptyTerms( exp2 ); for (i=0; i < numOfTerms; i++) { // Build second part of new expression if (( exp2[i].expon == 0 ) && (exp2[i].coeff != 0 )) { newExpr += Double.toString( exp2[i].coeff ); } else { if ((exp2[i].variable != ' ') || (exp2[i].coeff != 0 )) newExpr += Double.toString( exp2[i].coeff ) + exp2[i].variable + "^" + Integer.toString((int) exp2[i].expon ); } if ( i < numOfTerms - 1) newExpr += "+"; } newExpr = prepareExpOrEq( newExpr ); expression = determineExpr( newExpr, 0, newExpr.length() ); expression = combineLikeTerms( expression ); return expression; } static class ParPos { int Open1 = -1, Open2 = -1, Close1 = -1, Close2 = -1; boolean parError = false; public ParPos determParPos( String exp ) { int i, j; char ch; ParPos pp = new ParPos(); for ( i = 0; i < exp.length(); i++ ) { ch = exp.charAt(i); if ((ch == '(') && (Open1 == -1)) { Open1 = i; } if ((ch == '(') && ((Open1 != -1) && (Open1 != i))) Open2 = i; }; j = exp.indexOf(')'); if (j != -1) if (j < Open1) { parError = true; System.out.println( "Error: closing parentheses before opening parentheses."); } else { Close1 = j; }; j = exp.indexOf(')',j+1); if (j != -1) if ((j < Open2) || (j < Open1)) { parError = true; System.out.println( "Error: closing parentheses before opening parentheses."); } else { Close2 = j; }; return pp; } public void setOpen1( int position ) { Open1 = position; }; public void setOpen2( int position ) { Open2 = position; }; public void setClose1( int position ) { Close1 = position; }; public void setClose2( int position ) { Close2 = position; }; } public static Term[] simpDoubleParExpr( String origExpression ) { // Handles when the expression has two sets of parentheses by use of simpSinglePar twice int k; String beginExpr = "", endExpr = ""; Term[] firstExpr = initArrayOfTerms(); Term[] secondExpr = firstExpr; Term[] expression = firstExpr; // Determine end of first set of parentheses ParPos pp = new ParPos(); pp.determParPos(origExpression); k = pp.Close1; beginExpr = origExpression.substring(0,k+1); firstExpr = combineLikeTerms(simpSingleParExpr( beginExpr )); endExpr = origExpression.substring(k+1); secondExpr = combineLikeTerms(simpSingleParExpr( endExpr )); expression = addTwoExpressions( firstExpr, secondExpr ); if (pp.parError) System.out.println( "Incorrect entry. Try again." ); expression = combineLikeTerms( expression ); return expression; } // End of simpDoublePar public static Term[] simpNestParExpr( String expression ) { // Handles expressions with one set of parentheses inside another set of parentheses String newExpr = ""; Term[] expressionTerms = initArrayOfTerms(); Term[] nestExpr = expressionTerms; ParPos pp = new ParPos(); pp.determParPos(expression); // Simplify inner nested parentheses newExpr = expression.substring( pp.Open1+1, pp.Close2); newExpr = prepareExpOrEq( newExpr ); nestExpr = simpSingleParExpr( newExpr ); // Build new string expression after combining strings newExpr = convertToStr( nestExpr ); expression = expression.substring(0,pp.Open1) + "(" + newExpr + ")" + expression.substring( pp.Close2+1 ); expression = prepareExpOrEq( expression ); // Simplify complete expression string expressionTerms = simpSingleParExpr( expression ); if (pp.parError) System.out.println( "Incorrect entry. Try again." ); return expressionTerms; } // End of simpNestParExpr public static Term[] simpAdjacParExpr( String exp ) { // Handles expressions with two parentheses adjacent to each other (where they must be multiplied) int i, j, k = 0, l, len, endLen, numOfTerms1, numOfTerms2; double multiplier = 1; String beginStr = "", endStr = ""; boolean multiplyingDone = false, backDistribute = false; char ch; Term[] expression = initArrayOfTerms(); Term[] multiplierExpr = expression; Term[] firstExpr = expression; Term[] tempExpr = expression; Term[] secondExpr = expression; Term[] resultExpr = expression; Term[] endMultiplierTerm = expression; exp = prepareExpOrEq( exp ); len = exp.length(); // Determine positions of openings and closings of parentheses ParPos pp = new ParPos(); pp.determParPos(exp); // Handle any part of the expression before the first parentheses if (pp.Open1 != 0) { beginStr = exp.substring( 0, pp.Open1); // If just one character before opening parentheses, set multiplier to -1 if a negative sign or to a digit if a digit if (beginStr.length() == 1) { ch = beginStr.charAt(0); if (ch == '-') multiplier = -1; if (Character.isDigit(ch)) multiplier = Double.valueOf( ch ) - 48; beginStr = ""; multiplierExpr[0].setCoeff( multiplier ); }; // If multiple characters before opening parentheses, determine if any are multipliers to the parentheses if (beginStr.length() > 1) { k = pp.Open1; i = exp.lastIndexOf('+', k); j = exp.lastIndexOf('-', k); l = exp.lastIndexOf('–', k); if ((j!=-1) || (l!=-1)) j = Math.max(j, l); if ((i!=-1)||(j!=-1)) { k = Math.max(i, j); multiplierExpr = determineExpr( exp, k, pp.Open1); } else { multiplierExpr = determineExpr( exp, 0, pp.Open1); k = 0; }; if (k != 0) beginStr = exp.substring(0,k) + "+"; }; }; // Handle any part of the expression after the parentheses if (pp.Close2 < len-1) { endStr = exp.substring( pp.Close2+1, len); endLen = endStr.length(); if (endLen == 1) { ch = endStr.charAt(0); if (Character.isDigit(ch)) { multiplier = Integer.valueOf( ch ) - 48; backDistribute = true; endMultiplierTerm = determineExpr( endStr, 0, 1); }; }; if (endLen > 1) { i = endStr.indexOf('+'); j = endStr.indexOf('-'); k = -1; if ((i==-1) && (j==-1)) { endMultiplierTerm = determineExpr( endStr, 0, endLen); backDistribute = true; } else { if (i!=-1) { k = i; if (j!=-1) k = Math.min( i, j ); } else { if (j!=-1) k = j; }; }; if (k!=-1) { if (k>0) { endMultiplierTerm = determineExpr( endStr, 0, k); backDistribute = true; endStr = endStr.substring(k); } else if (k==0) { backDistribute = false; }; } else { endMultiplierTerm = determineExpr( endStr, 0, endStr.length()-1 ); }; }; }; // Perform the multiplication of the two expressions in parentheses firstExpr = determineExpr( exp, pp.Open1, pp.Close1 ); firstExpr = combineLikeTerms( firstExpr ); numOfTerms1 = numNonEmptyTerms( firstExpr ); secondExpr = determineExpr( exp, pp.Open2, pp.Close2 ); secondExpr = combineLikeTerms( secondExpr ); numOfTerms2 = numNonEmptyTerms( secondExpr ); if (numOfTerms1 == 1) { resultExpr = distributeMonomial( firstExpr, secondExpr ); multiplyingDone = true; }; if ((numOfTerms2 == 1) && (!multiplyingDone)) { resultExpr = distributeMonomial( secondExpr, firstExpr ); multiplyingDone = true; }; if (!multiplyingDone) { for (i=0; i < 9; i++) initTerm( resultExpr[i] ); for (j = 0; j < numOfTerms1; j++ ) { Term[] term = initArrayOfTerms(); term[0] = firstExpr[j]; tempExpr = distributeMonomial( term, secondExpr ); resultExpr = addTwoExpressions( resultExpr, tempExpr ); }; multiplyingDone = true; }; // Distribute any multiplier to the result of above parentheses multiplication, and add in beginStr and endExpr if (pp.Open1 != 0) { resultExpr = distributeMonomial( multiplierExpr, resultExpr ); }; if (backDistribute) { resultExpr = distributeMonomial( endMultiplierTerm, resultExpr ); }; if (beginStr.length() > 0) { tempExpr = determineExpr( beginStr, 0, beginStr.length() ); resultExpr = addTwoExpressions( tempExpr, resultExpr ); }; if (endStr.length() > 0) { tempExpr = determineExpr( endStr, 0, endStr.length() ); resultExpr = addTwoExpressions( tempExpr, resultExpr ); }; expression = combineLikeTerms( resultExpr ); if (pp.parError) System.out.println( "Incorrect entry. Try again." ); return expression; } // end of simpAdjParExpr public static Term[] roundCoeffs( Term[] expression ) { // Used to handle roundoff errors or to limit the digits displayed after the decimal point int i, numOfTerms = numNonEmptyTerms( expression ); Term[] outputExpr = initArrayOfTerms(); for (i=0; i < numOfTerms; i++) { outputExpr[i].setCoeff( Math.rint( expression[i].getCoeff()*1000 )/1000 ); outputExpr[i].setVar( expression[i].getVar() ); outputExpr[i].setExpon( expression[i].getExpon() ); } return outputExpr; } public static String add1inFrontOfParentheses( String expression, ParPos pp ) { int i, j, k; if (pp.Open1 != -1) { i = expression.lastIndexOf('+', pp.Open1); j = expression.lastIndexOf('-', pp.Open1); k = pp.Open1-1; if ((k==i) || (k==j)) { expression = expression.substring(0,k+1) + "1" + expression.substring(k+1); pp.setOpen1( pp.Open1 + 1 ); pp.setClose1( pp.Close1 + 1 ); if (pp.Open2 != -1) { pp.setOpen2( pp.Open2 + 1 ); pp.setClose2( pp.Close2 + 1 ); } }; }; if (pp.Open2 != -1) { i = expression.lastIndexOf('+',pp.Open2); j = expression.lastIndexOf('-',pp.Open2); k = pp.Open2-1; if ((k==i) || (k==j)) { expression = expression.substring(0,k+1) + "1" + expression.substring(k+1); pp.setOpen2( pp.Open2 + 1 ); pp.setClose2( pp.Close2 + 1 ); }; }; return expression; } public static Term[] simplifyExpr( String expression ) { // The main component to distinguish the type of expression and send it to a particular method to simplify it String type = ""; boolean parError = false; Term[] result = initArrayOfTerms(); expression = prepareExpOrEq( expression ); // Determine positions of parentheses (and if correctly ordered or has error) ParPos pp = new ParPos(); pp.determParPos(expression); parError = pp.parError; // Determine the type of expression: if no parentheses, single, double, or nested. if ((expression.indexOf('(')==-1) && (expression.indexOf(')')==-1)) type = "noPar"; else if ((pp.Open2 == -1) && (pp.Close2 == -1)) type = "singlePar"; if (( pp.Open2 != -1) && (pp.Close1 != -1)) if (pp.Open2 < pp.Close1) type = "nestedPar"; else type = "doublePar"; if (pp.Close1 == pp.Open2 - 1) { type = "adjacentPar"; }; // Place a 1 in front of parentheses when parentheses are added or subtracted expression = add1inFrontOfParentheses( expression, pp ); System.out.println( "Expression: " + expression ); System.out.print( " Type: " ); // Pass the expression to the appropriate method to simplify it switch( type ) { case "noPar": { System.out.println( "No Parentheses"); result = determineExpr( expression, 0, expression.length() ); result = combineLikeTerms( result ); }; break; case "singlePar": { System.out.println( "Single Parentheses"); result = simpSingleParExpr( expression ); }; break; case "doublePar": { System.out.println( "Double Parentheses"); result = simpDoubleParExpr( expression ); }; break; case "nestedPar": { System.out.println( "Nested Parentheses"); result = simpNestParExpr( expression ); }; break; case "adjacentPar": { System.out.println( "Adjacent Parentheses"); result = simpAdjacParExpr( expression ); }; break; default: System.out.println( "No discernable type" ); }; result = combineLikeTerms( result ); result = roundCoeffs( result ); if (!parError) { System.out.print( "\nFinal Simplified Expression: "); displayExpr( result ); } else { System.out.println( "Incorrect entry. Try again." ); }; return result; } // End of simplifyExpr public static double evaluateExpr( Term[] expression, double value ) { // Given a value for the variable, this method evaluates a whole expression double termVal = 0, tempVal = 1, answer = 0; int index, i, numOfTerms = numNonEmptyTerms( expression ); for (index=0; index < numOfTerms; index++) { termVal = 0; tempVal = 1; for (i=0; i<expression[index].expon; i++) tempVal *= value; termVal = expression[index].coeff*tempVal; answer = answer + termVal; }; return answer; } // End of evaluateExpr public static String simplifyEquation( String equationStr ) { // Converts left & right sides to expression, combines on left side, converts equation back to string int location; String leftSide = "", rightSide = "", simplifiedEquation = ""; Term[] leftExpr = initArrayOfTerms(); Term[] rightExpr = leftExpr; Term[] combinedExpr = leftExpr; Term[] negOne = determineExpr( "-1", 0, 2); equationStr = removeSpaces( equationStr ); location = equationStr.indexOf('='); leftSide = equationStr.substring(0,location); rightSide = equationStr.substring(location+1); //System.out.println( "left: " + leftSide + " right: " + rightSide); leftSide = prepareExpOrEq( leftSide ); rightSide = prepareExpOrEq( rightSide ); //System.out.println( "prepped left: " + leftSide + " prepped right: " + rightSide); leftExpr = simplifyExpr( leftSide ); rightExpr = simplifyExpr( rightSide ); //System.out.println( "simplified left: " + convertToStr( leftExpr ) + " simplified right: " + convertToStr( rightExpr ) ); combinedExpr = addTwoExpressions( leftExpr, distributeMonomial( negOne, rightExpr ) ); //System.out.print( "Combined Sides: "); displayExpr( combinedExpr ); if ( numNonEmptyTerms( combinedExpr ) > 0 ) simplifiedEquation = convertToStr( combinedExpr ); else simplifiedEquation = "0"; simplifiedEquation = prepareExpOrEq( simplifiedEquation + "=0" ); return simplifiedEquation; } // End of simpEquation public static String[] solveEquation( String equation ) { // Once equation is simplified, this method solves it and returns answerwers in an array of type String // If equation has degree < 3, equation is solved using -b/a (linear) or by quadratic formula (quadratic) int i, location, degree, numOfTerms; double[] a = new double[19]; Term[] expression = initArrayOfTerms(); String[] answer = new String[2]; for (i=0; i<2; i++) { answer[i] = ""; }; location = equation.indexOf('='); expression = determineExpr( equation, 0, location); numOfTerms = numNonEmptyTerms( expression ); degree = 0; for (i=0; i < numOfTerms; i++) { if (expression[i].expon > degree) degree = expression[i].expon; }; if (degree == 0) { if (expression[0].coeff == 0) answer[0] = "All real numbers"; else answer[0] = "No solutions"; }; if (degree == 1) { answer[0] = String.valueOf( -1*expression[1].coeff / expression[0].coeff ); }; if (degree == 2) { for ( i=0; i < numOfTerms; i++) { if (expression[i].expon == 2) a[2] = expression[i].coeff; if (expression[i].expon == 1) a[1] = expression[i].coeff; if (expression[i].expon == 0) a[0] = expression[i].coeff; }; if (a[1]*a[1]-4*a[2]*a[0] >= 0) { answer[0]=String.valueOf((-1*a[1]+Math.sqrt(a[1]*a[1]-4*a[2]*a[0]))/(2*a[2])); answer[1]=String.valueOf((-1*a[1]-Math.sqrt(a[1]*a[1]-4*a[2]*a[0]))/(2*a[2])); } else answer[0] = "No solution in the real numbers."; }; if (degree > 2) answer[0] = "This program currently only solves equations up to degree 2."; return answer; } // End of solveEq public static String round2LineAnswer ( String[] twoLineAnswer ) { double line1ofAnswer = Double.parseDouble(twoLineAnswer[0]), line2ofAnswer = Double.parseDouble(twoLineAnswer[1]); line1ofAnswer = line1ofAnswer*1000; line2ofAnswer = line2ofAnswer*1000; line1ofAnswer = Math.round(line1ofAnswer); line2ofAnswer = Math.round(line2ofAnswer); line1ofAnswer = line1ofAnswer/1000; line2ofAnswer = line2ofAnswer/1000; String result = Double.toString( line1ofAnswer ) + "," + Double.toString( line2ofAnswer ); return result; } public static void AITest() { int i; boolean passed, allPassed = true; String origExpression, finalExpr; String[] equationAnswer; Term[] exprTerms = initArrayOfTerms(); String ANSI_RED = "\u001B[31m"; String ANSI_BLACK = "\u001B[30m"; String[] testName = { "Multiple Signs/Extra Characters", "Multiple Variables", "Expression with 0 Coefficients", "Combine Like Terms - No Parentheses", "Single Parentheses", "Double Parentheses", "Nested Parentheses", "Adjacent Parentheses", "Linear Equation", "Quadratic Equation" }; String[] origExpr = { "-&-2+-@-3x-+(2x++6)-", "4x - 2y + 6 - x + y^2 + y -3","8x - 5 + 0x + 2x^2 - 0 - 7x - 0x^2 +9", "5x - 2x^2 + 4 - 7x + x^2 +1 - 6x^3", "3x+-5(3x-6+4x^2-5x-7)2-5-", "3x+1x(3x-6+4)+5-(2x^2-5x-7)-5--7x", "-3x+x(3x-6+4(2x^2-5x-7)--5)-7x", "--3x+1x(3x-6+4)(2x^2-5x-7)-5-7x", "-3( 2x - 5 ) -7( x + 4 ) = 5( -3x - 2 ) + 9", "3x( 2x - 5 ) - 7( x^2 + 4x - 3 ) = -5x( 3x - 2 ) + 9x^2" }; String[] answer = { "1.0x^1-4.0", "1.0y^2+3.0x^1-1.0y^1+3.0", "2.0x^2+1.0x^1+4.0", "-6.0x^3-1.0x^2-2.0x^1+5.0", "-40.0x^2+23.0x^1+125.0", "1.0x^2+13.0x^1+7.0", "8.0x^3-17.0x^2-39.0x^1", "6.0x^4-19.0x^3-11.0x^2+10.0x^1-5.0", "6.0", "10.188,0.412"}; System.out.println( " A I T E S T : \n" ); for ( i=0; i < testName.length; i++ ) { System.out.println( "TEST: " + testName[i] ); passed = false; origExpression = prepareExpOrEq( origExpr[i] ); if ( origExpression.indexOf('=') == -1 ) { exprTerms = simplifyExpr( prepareExpOrEq( origExpr[i] )); finalExpr = prepareExpOrEq(convertToStr( exprTerms )); System.out.println( "Original expression: " + origExpr[i] + " Simplified expression: " + finalExpr + " Correct Answer: " + answer[i] ); } else { equationAnswer = solveEquation( simplifyEquation( origExpression) ); if ( testName[i] == "Quadratic Equation" ) { // Handle the special case of a quadratic equation with two answers finalExpr = round2LineAnswer( equationAnswer ); } else finalExpr = prepareExpOrEq( equationAnswer[0] ); System.out.println( "Original equation: " + origExpr[i] + " Calculated answer(s): " + finalExpr + " Correct Answer: " + answer[i] ); } if ( finalExpr.compareTo( answer[i] ) == 0) { passed = true; } else { allPassed = false; }; System.out.println( "TEST: " + testName[i] + " Passed = " + ANSI_RED + passed + ANSI_BLACK + "\n"); }; /* The AI code was not designed to handle this test since can only handle two sets of parentheses Double Parentheses with Adjacent; String str5 = "2 - 3x( 4x^2 - 5x ) - 5( x + 2 )( 6x - 9 )", ans5 = "-12.0x^3-15.0x^2-15.0x^1+92.0"; */ System.out.println( "All Tests Passed = " + ANSI_RED + allPassed + ANSI_BLACK + "\n\n"); } public static void main(String[] args) { AITest(); // Input original expression System.out.println("Enter your expression or equation: (only one variable & up to 2 sets of parentheses allowed)"); Scanner sc = new Scanner( System.in ); try { origText = sc.nextLine(); } catch (Exception e) { e.printStackTrace(); } // The method prepareExpOrEq removes spaces, double signs, leading or trailing unnecessary signs, detects unacceptable characters, etc. and determines // whether or not the inputed string is an equation expression = prepareExpOrEq( origText ); if (!equation) overallExpr = simplifyExpr(expression); // Uses various methods to simplify the expression (distributing, combining like terms, etc.) System.out.print( "After simplifying expression: "); displayExpr( overallExpr ); if (!equation) { // After simplifying the expression, this section evaluates the expression for an inputed value of the variable. System.out.println( "\nExpression Evaluator: Enter a value for the variable: \n" ); try { origValue = sc.nextLine(); } catch (Exception e) { e.printStackTrace(); } finally { sc.close(); } enteredValue = Double.valueOf( origValue ); System.out.println( "The expression evaluates to the answer " + evaluateExpr( overallExpr, enteredValue )); } if (equation) { expression = simplifyEquation( expression ); // simpEquation uses simplifyExpr to simplify both sides separately then combine all terms on the left side System.out.println( "Simplified and combined equation: " + expression ); answer = solveEquation( expression ); // solveEq distinguishes the degree of the equation and solves it accordingly (up to degree 2) System.out.print( "Solution Set: { " ); System.out.print( answer[0]); if (answer[1]!="") { System.out.print(", " + answer[1] + " }"); } else { System.out.println( " }" ); }; }; } }
gabaugher/CFM
AI.java
16
import java.net.*; import java.io.*; import java.util.Scanner; class IP{ public static void main(String args[]) throws IOException{ Scanner sc = new Scanner(System.in); System.out.println("Enter the name of website"); String web = sc.nextLine(); try{ InetAddress ip =InetAddress.getByName(web); // ip.getByName(web); System.out.println("The ip is"+ip); } catch(Exception e){ System.out.println(e); } } }
karan9970/Web
IP.java
17
public class Solution { public int numOfArrays(int n, int m, int k) { final int mod = 1000000007; int[][] dp = new int[m+1][k+1]; int[][] prefix = new int[m+1][k+1]; int[][] prevDp = new int[m+1][k+1]; int[][] prevPrefix = new int[m+1][k+1]; for (int j = 1; j <= m; j++) { prevDp[j][1] = 1; prevPrefix[j][1] = j; } for (int i = 2; i <= n; i++) { for (int maxNum = 1; maxNum <= m; maxNum++) { for (int cost = 1; cost <= k; cost++) { dp[maxNum][cost] = (int)(((long)maxNum * prevDp[maxNum][cost]) % mod); if (maxNum > 1 && cost > 1) { dp[maxNum][cost] = (dp[maxNum][cost] + prevPrefix[maxNum - 1][cost - 1]) % mod; } prefix[maxNum][cost] = (prefix[maxNum - 1][cost] + dp[maxNum][cost]) % mod; } } for (int j = 1; j <= m; j++) { System.arraycopy(dp[j], 0, prevDp[j], 0, k+1); System.arraycopy(prefix[j], 0, prevPrefix[j], 0, k+1); } } return prefix[m][k]; } }
chirag1261/Leetcode
DP/Build Array Where You Can Find The Maximum Exactly K Comparisons
18
package com.example.lf; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int action_settings=0x7f080002; public static final int rl=0x7f080000; public static final int textview1=0x7f080001; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class menu { public static final int main=0x7f070000; } public static final class string { public static final int action_settings=0x7f050002; public static final int app_name=0x7f050000; public static final int hello_world=0x7f050001; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
ShriKrishnaTS/JITS-To-Track-a-School-vehicle
R.java
19
package rpgGridBrawl; public class Flee extends GridBrawl { GameData game; public Flee() {} public GameData execute(GameData crt) { game = crt; interact.tellPlayer(7, 4, false); // "Choose a Brawler to be removed from the brawl:" boolean[] cowards = this.sortCowards(game); String options = interact.reportOnFleeOptions(cowards); interact.tellPlayer(options, true); int selection = interact.getFleeSelection(cowards); if (selection == -1) { game.setSuccessfulTurn(false); return game; } interact.tellPlayer(interact.msgBuild(game, 53, selection), false); // "You have selected to remove the " + BRWLRS[selection] + " from the board."; boolean confirm = interact.confirm(); if (!confirm) { game.setSuccessfulTurn(false); return game; } game = clearSpace(game, selection); if (game.isRedsTurn()) game.setRedCanPlace(true); else game.setBlueCanPlace(true); interact.space(); interact.tellPlayer(interact.msgBuild(game, 54, selection), false); // "The " + BRWLRS[selection] + " has fled the brawl!" interact.space(); game = updateLastUsed(game, selection); game.setSuccessfulTurn(true); return game; } private boolean[] sortCowards(GameData game) { int bLength = game.getAllBrawlers().length; boolean[] cowards = new boolean[bLength]; boolean colorMatch = false; for (int b = 0; b < bLength; b++) { Brawler jimbo = game.getBrawler(b); colorMatch = ((game.isRedsTurn() && jimbo.isRed()) || (!game.isRedsTurn() && jimbo.isBlue())); if ((jimbo instanceof Character) && !colorMatch) cowards[b] = false; // you can't make your opponent's Characters flee. else if (jimbo.isOnBoard() && (1 == jimbo.getFloor()) && !jimbo.isUsedLast()) cowards[b] = true; } return cowards; } } // end of Flee class
JKisling/RPG_Grid_Brawl
Flee.java
20
import java.io.IOException; import java.math.BigInteger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Q1 */ @WebServlet("/q1") public class Q1 extends HttpServlet { private static final long serialVersionUID = 1L; private static final String X_VALUE = "6876766832351765396496377534476050002970857483815262918450355869850085167053394672634315391224052153"; BigInteger baseNum; /** * @see HttpServlet#HttpServlet() */ public Q1() { super(); baseNum = new BigInteger(X_VALUE); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String primeNum = request.getParameter("key"); BigInteger num = new BigInteger(primeNum); // To get the result Y value as indicated in writeup BigInteger result = num.divide(baseNum); // Give response to the client response.getWriter().println(result); response.getWriter().println( "SanYingZhanLvBu,9679-6671-5614,5239-8284-2426,3175-8296-3793"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d = new Date(); response.getWriter().println(df.format(d)); } }
l-wang/Twitter-Analytics-Web-Services
Q1.java
21
/* * 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 prate */ import java.io.*; import java.util.*; import javax.swing.JOptionPane; public class ProfessorGUI extends javax.swing.JFrame { int x; int y; ArrayList<ArrayList<String>> ob1 = new ArrayList<ArrayList<String>>(); static Professor professorObj = new Professor(); /** * Creates new form test */ public ProfessorGUI(Professor ob) { professorObj = ob; x = -1; y = -2; for (int i = 0; i < 8; i++) ob1.add(new ArrayList<String>()); changeArrayList(); initComponents(); } private void changeArrayList() { List<String> x=professorObj.getCourses(); for(String i: x) { int sem=i.charAt(8)-'0'; ob1.get(sem-1).add(i.substring(0,5)); } for(ArrayList<String> i:ob1) { String z[]=i.toArray(new String[0]); System.out.println(i.toString()); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); Gender = new javax.swing.JTextField(professorObj.getGender()); Contact = new javax.swing.JTextField(professorObj.getContactNo()); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); Name = new javax.swing.JTextField(professorObj.getName()); DoB = new javax.swing.JFormattedTextField(professorObj.getDob()); jLabel9 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); Address = new javax.swing.JTextArea(professorObj.getaddress()); jLabel10 = new javax.swing.JLabel(); ID = new javax.swing.JTextField(""+professorObj.getUID()); jLabel2 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); Qualification = new javax.swing.JTextArea(professorObj.getQualification()); jScrollPane4 = new javax.swing.JScrollPane(); AoI = new javax.swing.JTextArea(professorObj.getAreaofInterest()); jLabel4 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); courseList = new javax.swing.JList<>(); jScrollPane5 = new javax.swing.JScrollPane(); SemesterList = new javax.swing.JList<>(); uploadAttendance = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jScrollPane8 = new javax.swing.JScrollPane(); courseList2 = new javax.swing.JList<>(); jScrollPane9 = new javax.swing.JScrollPane(); SemesterList2 = new javax.swing.JList<>(); uploadMarks = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setLocation(600,200); jTabbedPane1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jTabbedPane1.setFont(new java.awt.Font("Sylfaen", 1, 14)); // NOI18N jLabel1.setText("Name :"); Gender.setEditable(false); Contact.setEditable(false); jLabel3.setText("Date of Birth :"); jLabel5.setText("Contact Number :"); Name.setEditable(false); DoB.setEditable(false); jLabel9.setText("Address :"); Address.setEditable(false); Address.setColumns(15); Address.setRows(2); Address.setWrapStyleWord(true); jScrollPane2.setViewportView(Address); jLabel10.setText("Gender :"); ID.setEditable(false); ID.setToolTipText(""); jLabel2.setText("Qualification :"); jLabel11.setText("Area of Interest :"); Qualification.setEditable(false); Qualification.setColumns(15); Qualification.setRows(2); Qualification.setWrapStyleWord(true); jScrollPane3.setViewportView(Qualification); AoI.setEditable(false); AoI.setColumns(15); AoI.setRows(2); AoI.setWrapStyleWord(true); jScrollPane4.setViewportView(AoI); jLabel4.setText("I.D."); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jLabel11)) .addGap(53, 53, 53) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel5) .addComponent(jLabel10) .addComponent(jLabel4)) .addGap(51, 51, 51) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Contact) .addComponent(Name) .addComponent(jScrollPane3) .addComponent(jScrollPane2) .addComponent(DoB) .addComponent(Gender) .addComponent(ID)))) .addGap(60, 60, 60)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(34, 34, 34) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(ID, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(Gender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(DoB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Contact, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(42, 42, 42)) ); jTabbedPane1.addTab("Personal Details", jPanel1); jLabel7.setText("Select Semester : "); jLabel8.setText("Select Courses :"); courseList.setDragEnabled(true); jScrollPane1.setViewportView(courseList); SemesterList.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Semester 1", "Semester 2", "Semester 3", "Semester 4", "Semester 5", "Semester 6", "Semester 7", "Semester 8" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); SemesterList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); SemesterList.setToolTipText(""); SemesterList.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); SemesterList.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { SemesterListValueChanged(evt); } }); jScrollPane5.setViewportView(SemesterList); uploadAttendance.setText("Open Sheet"); uploadAttendance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { uploadAttendanceActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel7) .addGap(64, 64, 64) .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addGap(74, 74, 74) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(uploadAttendance) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(228, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addComponent(uploadAttendance) .addGap(42, 42, 42)) ); jTabbedPane1.addTab("Upload Attendence", jPanel2); jLabel14.setText("Select Semester : "); jLabel15.setText("Select Courses :"); courseList2.setDragEnabled(true); courseList2.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { courseList2ValueChanged(evt); } }); jScrollPane8.setViewportView(courseList2); SemesterList2.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Semester 1", "Semester 2", "Semester 3", "Semester 4", "Semester 5", "Semester 6", "Semester 7", "Semester 8" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); SemesterList2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); SemesterList2.setToolTipText(""); SemesterList2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); SemesterList2.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { SemesterList2ValueChanged(evt); } }); jScrollPane9.setViewportView(SemesterList2); uploadMarks.setText("Open Sheet"); uploadMarks.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { uploadMarksActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel14) .addGap(64, 64, 64) .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel15) .addGap(74, 74, 74) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(uploadMarks) .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(228, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14) .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel15) .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addComponent(uploadMarks) .addGap(41, 41, 41)) ); jTabbedPane1.addTab("Upload Marks", jPanel4); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 527, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 493, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void SemesterListValueChanged(javax.swing.event.ListSelectionEvent evt) { ArrayList<String> ob; switch (SemesterList.getSelectedIndex()) { case 0: ob=ob1.get(0); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 1: ob=ob1.get(1); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 2: ob=ob1.get(2); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 3: ob=ob1.get(3); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 4: ob=ob1.get(4); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 5: ob=ob1.get(5); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 6: ob=ob1.get(6); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 7: ob=ob1.get(7); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; } } private void courseList2ValueChanged(javax.swing.event.ListSelectionEvent evt) { // TODO add your handling code here: } private void SemesterList2ValueChanged(javax.swing.event.ListSelectionEvent evt) { // TODO add your handling code here: } private void uploadAttendanceActionPerformed(java.awt.event.ActionEvent evt) { int sem=SemesterList.getSelectedIndex()+1; String courseCode=courseList.getSelectedValue(); AttendanceWriter ob=new AttendanceWriter(); ob.writeAttendance(sem,courseCode); // TODO add your handling code here: } private void uploadMarksActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ProfessorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ProfessorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ProfessorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ProfessorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ProfessorGUI(professorObj).setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JTextArea Address; private javax.swing.JTextArea AoI; private javax.swing.JTextField Contact; private javax.swing.JFormattedTextField DoB; private javax.swing.JTextField Gender; private javax.swing.JTextField ID; private javax.swing.JTextField Name; private javax.swing.JTextArea Qualification; private javax.swing.JList<String> SemesterList; private javax.swing.JList<String> SemesterList2; private javax.swing.JList<String> courseList; private javax.swing.JList<String> courseList2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane8; private javax.swing.JScrollPane jScrollPane9; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JButton uploadAttendance; private javax.swing.JButton uploadMarks; // End of variables declaration }
pAditya198/OOP_Project
j.java
22
/** * Contains all the Constants used in HiJynx */ import java.awt.*; public class c{ public static final int MARGIN = 25; public static final int SMALL = 30; public static final int MED = 50; public static final int LARGE = 70; public static final int HUGE = 200; public static final int UP = 0; public static final int RIGHT = 1; public static final int DOWN = 2; public static final int LEFT = 3; public static final int STATIC = 4; // Edit these: public static final int WIDTH = 1024-15; public static final int HEIGHT = 768-35; public static final int SIZE = MED; public static final int LIFE = 200; public static final int SPEED = 5; // hundredth lengths moved per timer tick public static final int TICK = 25; // milliseconds between ticks public static final int MAXFISH = 100; }
nixhope/MockFish
c.java
23
//Write a program for error detecting code using CRC-CCITT(16-bits) import java.util.Scanner; public class CRC { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("At Sender Side: "); // Input Data Stream System.out.print("Enter message bits: "); String message = sc.nextLine(); System.out.print("Enter generator: "); String generator = sc.nextLine(); int data[] = new int[message.length() + generator.length() - 1]; int divisor[] = new int[generator.length()]; for (int i = 0; i < message.length(); i++) data[i] = Integer.parseInt(message.charAt(i) + ""); for (int i = 0; i < generator.length(); i++) divisor[i] = Integer.parseInt(generator.charAt(i) + ""); // Calculation of CRC for (int i = 0; i < message.length(); i++) { if (data[i] == 1) { for (int j = 0; j < divisor.length; j++) data[i + j] ^= divisor[j]; } } // Append the remainder to the original message for (int i = 0; i < message.length(); i++) data[i] = Integer.parseInt(message.charAt(i) + ""); // Display CRC System.out.print("The checksum code is: "); for (int i = 0; i < data.length; i++) System.out.print(data[i]); System.out.println(); System.out.println("At Receiver Side: "); // Check for input CRC code System.out.print("Enter checksum code: "); message = sc.nextLine(); System.out.print("Enter generator: "); generator = sc.nextLine(); data = new int[message.length() + generator.length() - 1]; divisor = new int[generator.length()]; for (int i = 0; i < message.length(); i++) data[i] = Integer.parseInt(message.charAt(i) + ""); for (int i = 0; i < generator.length(); i++) divisor[i] = Integer.parseInt(generator.charAt(i) + ""); // Calculation of remainder for (int i = 0; i < message.length(); i++) { if (data[i] == 1) for (int j = 0; j < divisor.length; j++) data[i + j] ^= divisor[j]; } // Display validity of data boolean valid = true; for (int i = 0; i < data.length; i++) if (data[i] == 1) { valid = false; break; } if (valid) System.out.println("Data stream is valid"); else System.out.println("Data stream is invalid. CRC error occurred."); } } // fix the generator same at both sender and receiver side // output:- // At Sender Side: // Enter message bits: 100100 // Enter generator: 1101 // The checksum code is: 100100001 // At Receiver Side: // Enter checksum code: 11011 // Enter generator: 1101 // Data stream is invalid. CRC error occurred.
saadhussain01306/computer_net_lab
2.Crc.java
24
/*Write a program to implement random early detection (RED) congestion control algorithm*/ import java.util.Random; import java.util.Scanner; public class RedCongestionControl { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the maximum number of packets:");//number of packets to be sent int maxPackets = scanner.nextInt(); System.out.println("Enter the queue size:");//size of the queue the packets can be stored int queueSize = scanner.nextInt(); System.out.println("Enter the maximum probability:"); double maxProbability = scanner.nextDouble(); System.out.println("Enter the minimum probability:");//used to calculated the drop probabilty (max-min) double minProbability = scanner.nextDouble(); System.out.println("Enter the threshold value:");//the value after which the congestion control comes to action int threshold = scanner.nextInt(); simulateCongestion(maxPackets, queueSize, maxProbability, minProbability, threshold); } private static void simulateCongestion(int maxPackets, int queueSize, double maxProbability, double minProbability, int threshold) { Random rand = new Random(System.currentTimeMillis()); int queueLength = 0; for (int i = 0; i < maxPackets; i++) { double dropProbability = calculateDropProbability(queueLength, queueSize, maxProbability, minProbability, threshold); if (queueLength >= threshold && rand.nextDouble() < dropProbability) { System.out.println("Packet dropped (CONGESTION AVOIDANCE)"); //checking the threshold value and the probabilty to check whether to accept or reject the packet } else { System.out.println("Packet accepted " + (i + 1)); queueLength++; } } } private static double calculateDropProbability(int currentQueueLength, int queueSize, double maxProbability, double minProbability, int threshold) { double slope = (maxProbability - minProbability) / (queueSize - threshold); return minProbability + slope * (currentQueueLength - threshold); } } /* output:- Enter the maximum number of packets: 100 Enter the queue size: 20 Enter the maximum probability: 0.8 Enter the minimum probability: 0.2 Enter the threshold value: 10 Packet accepted 1 Packet accepted 2 Packet accepted 3 Packet accepted 4 Packet accepted 5 Packet accepted 6 Packet accepted 7 Packet accepted 8 Packet accepted 9 Packet accepted 10 Packet accepted 11 Packet accepted 12 Packet accepted 13 Packet accepted 14 Packet accepted 15 Packet accepted 16 Packet accepted 17 Packet dropped (CONGESTION AVOIDANCE) Packet accepted 19 Packet accepted 20 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 23 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 33 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 40 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 47 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Output 2:- Enter the maximum number of packets: 50 Enter the queue size: 10 Enter the maximum probability: 0.6 Enter the minimum probability: 0.4 Enter the threshold value: 5 Packet accepted 1 Packet accepted 2 Packet accepted 3 Packet accepted 4 Packet accepted 5 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 9 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 13 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 17 Packet dropped (CONGESTION AVOIDANCE) Packet accepted 19 Packet accepted 20 Packet accepted 21 Packet accepted 22 Packet accepted 23 Packet accepted 24 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 27 Packet dropped (CONGESTION AVOIDANCE) Packet accepted 29 Packet dropped (CONGESTION AVOIDANCE) Packet accepted 31 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) */
saadhussain01306/computer_net_lab
8.RED.java
25
import java.io.*; import java.lang.*; class X1 { public static void main(String[]args) throws IOException { BufferedReader venki=new BufferedReader(new InputStreamReader(System.in)); long comp,Cos=0,COs=0,COS=0; double dis; System.out.println("\nEnter the Number of Computers you want to buy : "); comp=Integer.parseInt(venki.readLine()); System.out.println("\nEnter the Number of years you want to deal with : \nNOTE : YOU GET 15% DISCOUNT YOU DEAL FOR MORE THAN 5 YEARS!!"); int year=Integer.parseInt(venki.readLine()); Cos=31500*comp; COs=31000*comp; COS=29000*comp; if(comp<20) { System.out.println("\nAmount to paid : "+Cos); if(year>5) { dis=Cos-(Cos*0.15); System.out.println("\nAmount to Paid with discount : "+dis); } } else if(comp>=20 && comp<=39) { System.out.println("\nAmount to be paid : "+COs); if(year>5) { dis=COs-(COs*0.15); System.out.println("\nAmount to be paid with discount : "+ dis); } } else { System.out.println("\nAmount to be paid : "+ COS); if(year>5) { dis=COS-(COS*0.15); System.out.println("\nAmount to be paid with discount : "+dis); } } } }
flick-23/JAVA-Programs
X1.java
26
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class J here. * * @author (your name) * @version (a version number or a date) */ public class J extends VirtualKeyboard { /** * Act - do whatever the J wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public J() { image.drawString("J", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("J", x, y); wordtoguess.setAlphabetGuessed("J",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
J.java
27
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class Y here. * * @author (your name) * @version (a version number or a date) */ public class Y extends VirtualKeyboard { /** * Act - do whatever the Y wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public Y() { image.drawString("Y", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("Y", x, y); wordtoguess.setAlphabetGuessed("Y",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
Y.java
28
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class X here. * * @author (your name) * @version (a version number or a date) */ public class X extends VirtualKeyboard { /** * Act - do whatever the X wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public X() { image.drawString("X", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("X", x, y); wordtoguess.setAlphabetGuessed("X",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
X.java
29
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class W here. * * @author (your name) * @version (a version number or a date) */ public class W extends VirtualKeyboard { /** * Act - do whatever the W wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public W() { image.drawString("W", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("W", x, y); wordtoguess.setAlphabetGuessed("W",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
W.java
30
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class N here. * * @author (your name) * @version (a version number or a date) */ public class N extends VirtualKeyboard { /** * Act - do whatever the N wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public N() { image.drawString("N", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("N", x, y); wordtoguess.setAlphabetGuessed("N",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
N.java
31
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class Q here. * * @author (your name) * @version (a version number or a date) */ public class Q extends VirtualKeyboard { /** * Act - do whatever the Q wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public Q() { image.drawString("Q", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("Q", x, y); wordtoguess.setAlphabetGuessed("Q",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
Q.java
32
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class E here. * * @author (your name) * @version (a version number or a date) */ public class E extends VirtualKeyboard { /** * Act - do whatever the E wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public E() { image.drawString("E", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /*Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("E", x, y); wordtoguess.setAlphabetGuessed("E", getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
E.java
33
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class F here. * * @author (your name) * @version (a version number or a date) */ public class F extends VirtualKeyboard { /** * Act - do whatever the F wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public F() { image.drawString("F", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("F", x, y); wordtoguess.setAlphabetGuessed("F",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
F.java
34
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class V here. * * @author (your name) * @version (a version number or a date) */ public class V extends VirtualKeyboard { /** * Act - do whatever the V wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public V() { image.drawString("V", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("V", x, y); wordtoguess.setAlphabetGuessed("V",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
V.java
35
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class D here. * * @author (your name) * @version (a version number or a date) */ public class D extends VirtualKeyboard { /** * Act - do whatever the D wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public D() { image.drawString("D", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { //Hangman hangman = (Hangman) getWorld(); //wordtoguess = hangman.getWordToGuess(); WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("D", x, y); wordtoguess.setAlphabetGuessed("D", getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
D.java
36
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class P here. * * @author (your name) * @version (a version number or a date) */ public class P extends VirtualKeyboard { /** * Act - do whatever the P wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public P() { image.drawString("P", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("P", x, y); wordtoguess.setAlphabetGuessed("P",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
P.java
37
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class S here. * * @author (your name) * @version (a version number or a date) */ public class S extends VirtualKeyboard { /** * Act - do whatever the S wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public S() { image.drawString("S", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("S", x, y); wordtoguess.setAlphabetGuessed("S",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
S.java
38
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class U here. * * @author (your name) * @version (a version number or a date) */ public class U extends VirtualKeyboard { /** * Act - do whatever the U wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public U() { image.drawString("U", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("U", x, y); wordtoguess.setAlphabetGuessed("U",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
U.java
39
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class I here. * * @author (your name) * @version (a version number or a date) */ public class I extends VirtualKeyboard { /** * Act - do whatever the I wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public I() { image.drawString("I", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("I", x, y); wordtoguess.setAlphabetGuessed("I",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
I.java
40
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class L here. * * @author (your name) * @version (a version number or a date) */ public class L extends VirtualKeyboard { /** * Act - do whatever the L wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public L() { image.drawString("L", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("L", x, y); wordtoguess.setAlphabetGuessed("L",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
L.java
41
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class H here. * * @author (your name) * @version (a version number or a date) */ public class H extends VirtualKeyboard { /** * Act - do whatever the H wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public H() { image.drawString("H", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("H", x, y); wordtoguess.setAlphabetGuessed("H",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
H.java
42
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class Z here. * * @author (your name) * @version (a version number or a date) */ public class Z extends VirtualKeyboard { /** * Act - do whatever the Z wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public Z() { image.drawString("Z", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("Z", x, y); wordtoguess.setAlphabetGuessed("Z",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
Z.java
43
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class M here. * * @author (your name) * @version (a version number or a date) */ public class M extends VirtualKeyboard { /** * Act - do whatever the M wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public M() { image.drawString("M", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("M", x, y); wordtoguess.setAlphabetGuessed("M",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
M.java
44
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class O here. * * @author (your name) * @version (a version number or a date) */ public class O extends VirtualKeyboard { /** * Act - do whatever the O wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public O() { image.drawString("O", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("O", x, y); wordtoguess.setAlphabetGuessed("O",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
O.java
45
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class T here. * * @author (your name) * @version (a version number or a date) */ public class T extends VirtualKeyboard { /** * Act - do whatever the T wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public T() { image.drawString("T", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("T", x, y); wordtoguess.setAlphabetGuessed("T",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
T.java
46
package UnionFind; import edu.princeton.cs.algs4.*; // Below is the syntax highlighted version of UnionFind.UF.java from §1.5 Case Study: Union-Find. 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 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] = 1; } } 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; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } 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 IllegalArgumentException("index " + p + " is not between 0 and " + (n-1)); } } 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"); } }
Simply-divine/Union-Find
UF.java
47
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode middleNode(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } }
japygo/LeetCode
0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.java
48
class Solution { public String longestPalindrome(String s) { int left = 0, right = 0, strL = s.length(); String returnStr = ""; for (int i = 0; i < strL; i++) { char charAtI = s.charAt(i); left = i; right = i; // remove dupes for left side character while (left >= 0 && s.charAt(left) == charAtI) { left--; // this number lowest is -1. } // removes dupes for right side character while (right < strL && s.charAt(right) == charAtI) { right++; } // check for further palindrom after accounting for the "dupes" char // from the String. while (left >= 0 && right < strL && s.charAt(left) == s.charAt(right)) { left--; right++; } // update the returnString // left + 1 since the left could enter -1 which the lowest we want here // is 0. if (right - (left + 1) > returnStr.length()) { returnStr = s.substring(left + 1, right); } } return returnStr; } }
kalongn/LeetCode_Solution
5.java
49
class Solution { public String convert(String s, int numRows) { // Get the length of the String input int lenOfS = s.length(); // edge Cases if (lenOfS <= 1 || numRows <= 1) { return s; } // Create a String array String[] strArr = new String[numRows]; // Change to value for every strArr[] from null to an empty String for (int i = 0; i < numRows; i++) { strArr[i] = ""; } // Calculate how large the section is since the relationship is // 3 -> 5, 4 -> 6, 5 ->7 int section = numRows * 2 - 2; // loop over the entire String for (int i = 0; i < lenOfS; i++) { // get the index the item will be added it int index = i % section; // if the index is less then numRows, that mean it is an element insert // vertically. // else if the index is equal or greater then numRwos, that mean it is an // element insert in a reverse diagonal line. Which then we can use the section // and subtract our index from it to get which strArr it will add to. if (index < numRows) { strArr[index] += s.charAt(i); } else { strArr[section - index] += s.charAt(i); } } // concatenate everything into a single string. String returnStr = ""; for (String i : strArr) { returnStr += i; } // return our result. return returnStr; } }
kalongn/LeetCode_Solution
6.java
50
import java.util.*; class p { /* / The Java version of the PL/Vision p package. / Version 2.0 / / Author: Steven Feuerstein / Date: 12/25/98 */ // Delimiter used between data elements. private static String Gdelim = " - "; // Get and Set for delimiter public static void setDelim (String newDelim) { Gdelim = newDelim; } public static String delim () { return Gdelim; } // Overloading for general Object public static void l (Object obj) { System.out.println (obj); } // Overloading for primitive types public static void l (int val) { System.out.println (val); } public static void l (long val) { System.out.println (val); } public static void l (boolean val) { System.out.println (val); } public static void l (float val) { System.out.println (val); } // Combinations of types and objects public static void l (int val1, int val2) { System.out.println (val1 + Gdelim + val2); } public static void l (long val1, long val2) { System.out.println (val1 + Gdelim + val2); } public static void l (boolean val1, boolean val2) { System.out.println (val1 + Gdelim + val2); } public static void l (Date val1, Date val2) { System.out.println (val1 + Gdelim + val2); } public static void l (String val1, String val2) { System.out.println (val1 + Gdelim + val2); } public static void l (String val1, int val2) { System.out.println (val1 + Gdelim + val2); } public static void l (String val1, long val2) { System.out.println (val1 + Gdelim + val2); } public static void l (String val1, Date val2) { System.out.println (val1 + Gdelim + val2); } }
jayvdb/PLSQL-demo-scripts
p.java
51
package gpfinance; import java.util.Random; /** * @date 14-July-2013 * @author Sudheesh Singanamalla */ public class U { /** * Utility class configuration parameters. */ public static final double MAX = 100.0; public static final double MIN = -100.0; public static final boolean debug = true; /** * Set of methods to print the object passed. * p() - prints object with no new line, if debugging * pl() - prints object with a new line, if debugging * m() - prints the object regardless of debug mode */ public static void p(Object o){ if (debug) System.out.print(o); } public static void pl(Object o){ if (debug) System.out.println(o); } public static void m(Object o){ System.out.println(o); } /** * Set of methods to help with random generation of data types. * chance() - 50/50 chance to return true/false * randomVal() - return random double in range [MIN, MAX) */ public static boolean chance(){ return Math.random() < 0.5; } public static double randomVal() { return (MIN + (Math.random() * ((MAX - MIN) + 1.0)) * 0.85); } public static int randomTreeIndex(int size) { return (new Random()).nextInt(size-1) +1; } }
sudheesh001/YahooHackIndia
U.java
52
import java.io.File; // Import the File class import java.io.IOException; // Import the IOException class to handle errors public class CreateFile { public static void main(String[] args) { try { File myObj = new File("filename.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
GDSC-MITS/Contribute-To-HacktoberFest
Java Programs/Createfile.java
53
/* package codechef; // 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 Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while(t>0) { int x = sc.nextInt(); int y = sc.nextInt(); int t1; int r=3*y; t1 = x/r; System.out.println(t1); t--; } } }
asthanegi14/CodeChef-Contest
SONGS
54
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.*; import javax.sound.midi.*; public class F { public static void main(String[] args) throws MidiUnavailableException, InvalidMidiDataException, IOException { //so uhhh i want to read in a midi file //then i need to make those notes light up on the keyboard //simple enough right? //haha jk //oh wait it also needs to wait for the user to press those keys before proceeding //should it also emit the notes before the user plays them? //also need to find music thats within a limited range Vector synthInfos = new Vector(); MidiDevice device = null; MidiDevice keyboard = null; MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo(); Sequencer sequencer; Receiver receiver; Transmitter transmitter = MidiSystem.getTransmitter(); InputStream stream = new FileInputStream(new File("src/minuet.mid")); //new Sequence(Sequence.SMPTE_24, 0, 1); //finds available devices System.out.println(infos.length); for (int i = 0; i < infos.length; i++) { try { device = MidiSystem.getMidiDevice(infos[i]); } catch (MidiUnavailableException e) { // Handle or throw exception... } if (device != null) { synthInfos.add(infos[i]); System.out.println(infos[i].getName()); System.out.println(infos[i].getVendor()); System.out.println(infos[i].getDescription()); System.out.println("number of transmitters " + device.getMaxTransmitters()); System.out.println("number of receivers " + device.getMaxReceivers()); System.out.println(); } } keyboard = MidiSystem.getMidiDevice(infos[7]); sequencer = MidiSystem.getSequencer(); sequencer.setSequence(stream); receiver = keyboard.getReceiver(); sequencer.getTransmitter().setReceiver(receiver); Track track = sequencer.getSequence().getTracks()[0]; int trackSize = track.size(); sequencer.open(); int i = 0; while (i < trackSize) { MidiEvent midiEvent = track.get(i); MidiMessage midiMessage = midiEvent.getMessage(); receiver.send(midiMessage, -1); i++; } sequencer.close(); } }
Texas-Waitlisters/SXSW-2019
F.java
55
import greenfoot.*; /** * Write a description of class Rh here. * * @author (your name) * @version (a version number or a date) */ public class Rh extends Buildings { /** * Act - do whatever the Rh wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
cookiedancer/TCCDirectory
Rh.java
56
package Edureka; public class Fibonacci { public static void main(String[] args) { //initializing the constants int n = 100, t1 = 0, t2 = 1; System.out.print("Upto " + n + ": "); //while loop to calculate fibonacci series upto n numbers while (t1<= n) { System.out.print(t1 + " + "); int sum = t1 + t2; t1 = t2; t2 = sum; } } }
Srutiverma123/Hacktoberfest-2021
Fibonacci.java
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
36
Edit dataset card