method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
23c6f800-31cb-464a-b692-474c0a237328 | 8 | private static String[][] filter(String[][] input, String filter) {
if (filter.equals("") || input.length==0) return input;
else {
ArrayList<Integer> selected = new ArrayList<Integer>();
for (int j = 0; j<input.length; j++) {
for (int i = 0; i < input[0].length; i++) {
String check=input[j][i].replaceAll(" ", "");
check.toLowerCase();
if (check.contains(filter.toLowerCase())) {
selected.add(j);
}
}
}
int size=input[0].length;
String[][] result = new String[selected.size()][size];
int index = 0;
for (int i = 0; i < input.length; i++) {
if (selected.contains(i)) {
for (int j = 0; j < input[0].length; j++) {
result[index][j] = input[i][j];
}
index++;
}
}
return result;
}
} |
f4a55104-ad5e-4a77-b6d7-8182f4fc68d2 | 7 | private String useAbondVariables(String s, int frame) {
int n = model.getABondCount();
if (n <= 0)
return s;
int lb = s.indexOf("%abond[");
int rb = s.indexOf("].", lb);
int lb0 = -1;
String v;
int i;
ABond bond;
while (lb != -1 && rb != -1) {
v = s.substring(lb + 7, rb);
double x = parseMathExpression(v);
if (Double.isNaN(x))
break;
i = (int) Math.round(x);
if (i < 0 || i >= n) {
out(ScriptEvent.FAILED, "Angular bond " + i + " does not exist.");
break;
}
v = escapeMetaCharacters(v);
bond = model.getABond(i);
s = replaceAll(s, "%abond\\[" + v + "\\]\\.angle", bond.getAngle(frame));
s = replaceAll(s, "%abond\\[" + v + "\\]\\.strength", bond.getStrength());
s = replaceAll(s, "%abond\\[" + v + "\\]\\.bondangle", bond.getAngle());
s = replaceAll(s, "%abond\\[" + v + "\\]\\.atom1", bond.atom1.getIndex());
s = replaceAll(s, "%abond\\[" + v + "\\]\\.atom2", bond.atom2.getIndex());
s = replaceAll(s, "%abond\\[" + v + "\\]\\.atom3", bond.atom3.getIndex());
lb0 = lb;
lb = s.indexOf("%abond[");
if (lb0 == lb) // infinite loop
break;
rb = s.indexOf("].", lb);
}
return s;
} |
2d0d7553-47f2-4e81-add4-65b728642829 | 1 | public void setTankVolume(int tankVolume) throws CarriageException {
if (tankVolume < 0) {
throw new CarriageException("Tank volume is under zero");
}
this.tankVolume = tankVolume;
} |
19409242-eb1d-4502-bfea-4a8d65ec7900 | 0 | @Override
public int attack(double agility, double luck) {
System.out.println("I tried to do a special attack but I haven't set it so I failed at this turn...");
return 0;
} |
41089538-5354-467e-bf85-fcbec955e0da | 4 | @Override
public void init( GLAutoDrawable drawable ) {
// Use debug pipeline
boolean glDebug=true;
boolean glTrace=false;
GL gl = drawable.getGL();
if(glDebug) {
try {
// Debug ..
gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Debug", null, gl, null) );
} catch (Exception e) {e.printStackTrace();}
}
if(glTrace) {
try {
// Trace ..
gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", null, gl, new Object[] { System.err } ) );
} catch (Exception e) {e.printStackTrace();}
}
} |
2c8acfbf-0b62-4069-bc1e-e5f9ce97d57d | 3 | private static Object read(String s){
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("saves/"+s+".json"));
return obj;
} catch (FileNotFoundException e) {
System.out.println("[SAVING] Save file '" + s + "' not found.");
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
} |
a392dc5a-18cb-409f-979a-18b30ddbc6ac | 2 | public void updateList(String[] users) {
clearList();
for(String user : users) {
if(!user.equals(mInterface.getUser()))
mListModel.addElement(user);
}
} |
fc03c9cc-7e7e-464e-98fa-8899786b0bd9 | 0 | public void setIsSensitive(boolean isSensitive) {
this.isSensitive = isSensitive;
} |
3b7d8460-d682-466a-b394-6ab75f86c7c9 | 8 | public void execute() {
this.validateConnectionParams();
// validate input folder names
if(this.srcFolder == null){
throw new BuildException("Missing srcFolder param");
}
if(this.destFolder == null){
throw new BuildException("Missing destFolder param");
}
if(this.outFolder == null){
throw new BuildException("Missing outFolder param");
}
File srcFile = new File(srcFolder);
File destFile = new File(destFolder);
File outFile = new File(outFolder);
if (!srcFile.exists()) {
throw new BuildException("The srcFolder does not exist");
}
// clear out folder, prompt if exist
if (outFile.exists() && outFile.list().length > 0) {
Console console = System.console();
String input = console.readLine("The outFolder is not empty, do you want to delete? Answer yes or no:");
if (input.equalsIgnoreCase("yes")) {
LeapUtils.deleteFile(outFile);
} else {
System.out.println("Can not perform leapmetadiff task, exiting");
return;
}
}
// create out folder
outFile.mkdirs();
try {
// traverse srcFolder recursively and copy a file to out folder
traverseFileRecursively(srcFile, destFile, outFile);
} catch (IOException e) {
throw new BuildException("Got an exception while traversing src folder, " + e.getMessage());
}
System.out.println("Done. Copied "+numCopied+" files.");
} |
11c78391-6ffd-4b83-843b-88eff1dbbb54 | 2 | private void switchState(State newState) {
if (this.currentState != null) {
this.currentState.exit();
}
this.currentState = newState;
if (this.currentState != null) {
this.currentState.enter();
}
} |
2825a3fe-3706-4111-881a-a1c67ff01e99 | 5 | @Override
public void runCommand(CommandSender sender, List<String> args) {
Player receiver = null;
String title = null;
if (args.size() == 2) {
receiver = Bukkit.getPlayer(args.get(0));
title = args.get(1);
} else if (sender instanceof Player && args.size() != 2) {
receiver = (Player) sender;
title = args.get(0);
}
if (plugin.getManager().giveBookToPlayer(receiver, title) && receiver != null) {
sender.sendMessage(colour1 + "You have given " + colour2 + receiver.getName() + colour1 + " the book "
+ colour2 + title);
receiver.sendMessage(colour1 + "You have been given the book " + colour2 + title);
} else
sender.sendMessage(colour3 + "Failed to give book to player.");
} |
d9537654-fd16-4fb5-8bef-9d9b297088a0 | 1 | public Scanner(Reader reader) {
this.lineNumber = 1;
this.charPosition = -1;
this.nextChar = 0;
this.reader = reader;
try {
read();
} catch (IOException e) {
e.printStackTrace();
}
} |
c096b5bf-c7f2-40c9-ab0b-0664c0de4bf8 | 8 | protected Set<Integer> getQualifiedTypes(MOB ableM)
{
final Set<Integer> set=new TreeSet<Integer>();
final boolean checkUnMet=ableM.charStats().getCurrentClass().showThinQualifyList();
for(final Enumeration<Ability> a=CMClass.abilities();a.hasMoreElements();)
{
final Ability A=a.nextElement();
final int level=CMLib.ableMapper().qualifyingLevel(ableM,A);
if((CMLib.ableMapper().qualifiesByLevel(ableM,A))
&&(level<(CMLib.ableMapper().qualifyingClassLevel(ableM,A)+1))
&&(CMLib.ableComponents().getSpecialSkillRemainder(ableM, A).specificSkillLimit() > 0)
&&(!checkUnMet || CMLib.ableMapper().getUnmetPreRequisites(ableM,A).size()==0))
{
Integer acode =Integer.valueOf(A.classificationCode() & Ability.ALL_ACODES);
Integer dcode =Integer.valueOf(A.classificationCode() & Ability.ALL_DOMAINS);
if(!set.contains(acode))
set.add(acode);
if(!set.contains(dcode))
set.add(dcode);
}
}
return set;
} |
fb047aee-06d7-4107-872b-c49de6ae1e09 | 8 | public void paint(int x, int y, int w, int h, Graphics2D g,
Component u, String iconType) {
FlamencoIconAdapter fia = null;
if (iconType.equals("add-topic")) {
fia = new AddTopic();
} else if (iconType.equals("remove-topic")) {
fia = new RemoveTopic();
} else if (iconType.equals("change-topic")) {
fia = new ChangeTopic();
} else if (iconType.equals("add-image")) {
fia = new AddImage();
} else if (iconType.equals("insert-link")) {
fia = new InsertLink();
} else if (iconType.equals("remove-link")) {
fia = new RemoveLink();
} else if (iconType.equals("insert-hyperlink")) {
fia = new InsertHyperlink();
} else if (iconType.equals("remove-hyperlink")) {
fia = new RemoveHyperlink();
}
Graphics2D gg = JXMLNoteIcon.prepareG(x, y, w, h,
fia.getOrigWidth(), fia.getOrigHeight(), g);
fia.paint(gg);
}
}
// ////////////////////////////////////////////////////////////////////////////////
// interfaces
// ////////////////////////////////////////////////////////////////////////////////
interface DoSomethingWithNode {
public void anything(DefaultMutableTreeNode node);
}
// ////////////////////////////////////////////////////////////////////////////////
// Supporting methods
// ////////////////////////////////////////////////////////////////////////////////
private JMenu makeMenu(String label) {
return JRecentlyUsedMenu.makeMenu(label);
}
private JMenuItem makeItem(String label, Icon icon, String actionCommand) {
return JRecentlyUsedMenu.makeMenuItem(label, icon, actionCommand, this);
}
private void createIds(DefaultMutableTreeNode node, DefaultMutableTreeNode ids) {
ids.setUserObject((Object) ((HelpTopic) node.getUserObject()).getTopicId());
int i;
for(i = 0; i < node.getChildCount(); i++) {
DefaultMutableTreeNode n = (DefaultMutableTreeNode) node.getChildAt(i);
DefaultMutableTreeNode in = new DefaultMutableTreeNode();
ids.add(in);
createIds(n, in);
}
}
private void writeObject(JarOutputStream jout, Object obj)
throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(jout);
if (obj instanceof HelpEntry) {
HelpEntry he = (HelpEntry) obj;
he.writeObject(oout);
} else if (obj instanceof DefaultMutableTreeNode) { // tree of HelpTopics
DefaultMutableTreeNode node = (DefaultMutableTreeNode) obj;
DefaultMutableTreeNode ids = new DefaultMutableTreeNode();
createIds(node, ids);
oout.writeObject(ids);
Enumeration<DefaultMutableTreeNode> en = (Enumeration<DefaultMutableTreeNode>) node.breadthFirstEnumeration();
while (en.hasMoreElements()) {
DefaultMutableTreeNode topic = en.nextElement();
HelpTopic ht = (HelpTopic) topic.getUserObject();
ht.writeObject(oout);
}
} else if (obj instanceof HelpTopic) {
HelpTopic ht = (HelpTopic) obj;
ht.writeObject(oout);
} else {
if (obj!=null) {
System.out.println("Writing "+obj.getClass().getName());
}
oout.writeObject(obj);
}
}
private Window getWindow(Component c) {
return SwingUtilities.getWindowAncestor(c);
}
// ////////////////////////////////////////////////////////////////////////////////
// Image handling
// ////////////////////////////////////////////////////////////////////////////////
private XMLNoteImageIcon nullImage = null;
public XMLNoteImageIcon getIcon(String id) {
if (nullImage == null) {
nullImage = new XMLNoteImageIcon(
new JXMLNoteIcon("NoImage", 50, 50));
nullImage.setId("__null__");
}
XMLNoteImageIcon img = _images.get(id);
if (img == null) {
img = _imageBackingStore.get(id); // To support undo/redo
if (img == null) {
_images.put("__null__", nullImage);
return nullImage;
} else {
_images.put(id, img);
_imageBackingStore.remove(id);
return img;
}
} else {
return img;
}
}
public XMLNoteImageIcon getIcon(URL url,String description,XMLNoteImageIconSize size) {
XMLNoteImageIcon icn=new XMLNoteImageIcon(url,description,size);
String id=UUID.randomUUID().toString();
icn.setId(id);
_images.put(id, icn);
return icn;
}
private Vector<XMLNoteImageIcon> _imagesToBeRemoved = null;
private void addImageDocListeners() {
_document.addDocumentPreListener(new DocumentPreListener() {
public boolean insertUpdate(DocumentEvent e) {
return false; // no veto
}
public boolean changeUpdate(DocumentEvent e) {
return false; // no veto
}
public boolean removeUpdate(DocumentEvent e) {
int offset = e.getOffset();
int len = e.getLength();
try {
_imagesToBeRemoved = _document.imagesInRange(offset, len);
return false;
} catch (BadLocationException e1) {
// unexpected
DefaultXMLNoteErrorHandler.exception(e1);
return true; // let nothing happen
}
}
});
_document.addDocumentPostListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
int offset=e.getOffset();
int length=e.getLength();
try {
Vector<XMLNoteImageIcon> v=_document.imagesInRange(offset, length);
Iterator<XMLNoteImageIcon> it = v.iterator();
while (it.hasNext()) {
XMLNoteImageIcon icn = it.next();
_imageBackingStore.remove(icn.getId());
_images.put(icn.getId(),icn);
}
} catch (BadLocationException E) {
DefaultXMLNoteErrorHandler.exception(E);
}
}
public void removeUpdate(DocumentEvent e) {
if (_imagesToBeRemoved != null) {
Iterator<XMLNoteImageIcon> it = _imagesToBeRemoved.iterator();
while (it.hasNext()) {
XMLNoteImageIcon icn = it.next();
_imageBackingStore.put(icn.getId(), icn);
_images.remove(icn.getId());
}
_imagesToBeRemoved=null;
}
}
});
}
// ////////////////////////////////////////////////////////////////////////////////
// GUI Creation
// ////////////////////////////////////////////////////////////////////////////////
public interface ToolsProvider {
public void addTools(JXMLNoteToolBar bar);
}
public int getMaxCount() {
return 6;
}
@SuppressWarnings("unchecked")
public Vector<String> getList() {
XMLNotePreferences prefs = _preferences;
Vector<String> vec = new Vector<String>();
String val = prefs.getString("recently_used_files", null);
if (val != null) {
ByteArrayInputStream bin = new ByteArrayInputStream(val.getBytes());
XMLDecoder dec = new XMLDecoder(bin);
vec = (Vector<String>) dec.readObject();
dec.close();
}
return vec;
}
public void putList(Vector<String> list) {
XMLNotePreferences prefs = _preferences;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
XMLEncoder enc = new XMLEncoder(bout);
enc.writeObject(list);
enc.flush();
enc.close();
String xml = bout.toString();
prefs.put("recently_used_files", xml);
}
public String clearListText() {
return _tr._("Clear");
}
private void createGui(ToolsProvider toolprovider) {
BorderLayout layout = new BorderLayout();
layout.setVgap(3);
layout.setHgap(3);
super.setLayout(layout);
try {
_document = new XMLNoteDocument();
} catch (BadStyleException e) {
DefaultXMLNoteErrorHandler.fatal(e, -1,
"Unexpected: bad style exception");
}
_document.setXMLNoteImageIconProvider(this);
_document.addDocumentAdminListener(new DocumentAdminListener() {
public boolean documentWillBeReset(DocumentAdminEvent e) {
return false;
}
public void documentHasBeenReset(DocumentAdminEvent e) {
}
public boolean documentWillBeCleared(DocumentAdminEvent e) {
return false;
}
public void documentHasBeenCleared(DocumentAdminEvent e) {
}
public void documentChangedState(DocumentAdminEvent e) {
//System.out.println("document changed="+_document.changed());
}
});
_editor = new JXMLNoteEditor(_document,new MarkMarkupProviderMaker() {
public MarkMarkupProvider create(String markId, String markClass) {
if (markClass.startsWith("TopicLink:")) {
return _markProvider;
} else {
return _hyperlinkProvider;
}
}
});
_toolbar = _editor.toolbar();
_toolbar.initToolBar();
_treeModel = new DefaultTreeModel(null);
loadTopics();
_tree = new JTreeMovable(_treeModel);
_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
JPanel editPane = new JPanel();
editPane.setLayout(new BorderLayout());
editPane.add(_toolbar, BorderLayout.NORTH);
editPane.add(_editor, BorderLayout.CENTER);
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
new JScrollPane(_tree), editPane);
_splitpane = pane;
pane.setContinuousLayout(true);
_helpToolbar = new JXMLNoteToolBar(this, null, 36);
_helpToolbar.removeAllSections();
_helpToolbar.addSection("file", _tr._("File operations"));
_helpToolbar.add("file", JXMLNoteToolBar.ACTION_NEW,
_tr._("Begin new Help File"), this);
_helpToolbar.add("file", JXMLNoteToolBar.ACTION_SAVE,
_tr._("Save a Help File"), this);
_helpToolbar.add("file", JXMLNoteToolBar.ACTION_LOAD,
_tr._("Open a Help File"), this);
_helpToolbar.addSection("topics", _tr._("Topic actions"));
_helpToolbar.add("topics", "add-topic", _tr._("Add a new topic"), this,
new JXMLNoteIcon("add-topic", _painter));
_helpToolbar.add("topics", "change-topic", _tr._("Change a topic"),
this, new JXMLNoteIcon("change-topic", _painter));
_helpToolbar.add("topics", "remove-topic", _tr._("Remove a topic"),
this, new JXMLNoteIcon("remove-topic", _painter));
_helpToolbar.add("topics", "insert-link", _tr._("Insert link"),
this, new JXMLNoteIcon("insert-link", _painter));
_helpToolbar.add("topics", "remove-link", _tr._("Remove link"),
this, new JXMLNoteIcon("remove-link", _painter));
_helpToolbar.add("topics", "insert-hyperlink", _tr._("Insert hyperlink"),
this, new JXMLNoteIcon("insert-hyperlink", _painter));
_helpToolbar.add("topics", "remove-hyperlink", _tr._("Remove hyperlink"),
this, new JXMLNoteIcon("remove-hyperlink", _painter));
_helpToolbar.addSection("image", _tr._("Image handling"));
_helpToolbar.add("image", "add-image", _tr._("Add an image"), this,
new JXMLNoteIcon("add-image", _painter));
_helpToolbar.addSection("test", _tr._("Test help"));
_helpToolbar.add("test",JXMLNoteToolBar.ACTION_HELP,_tr._("Test the help file"), this);
toolprovider.addTools(_helpToolbar);
_helpToolbar.initToolBar();
super.add(_helpToolbar, BorderLayout.NORTH);
super.add(pane, BorderLayout.CENTER);
_tree.addTreeSelectionListener(this);
}
private void setTitle() {
if (_frame != null) {
if (_helpjar == null) {
_frame.setTitle(_tr._("Help File Editor"));
} else {
String title = _tr._("Help File Editor: %s");
_frame.setTitle(String.format(title, _helpjar.getName()));
}
}
}
// ////////////////////////////////////////////////////////////////////////////////
// Loading and saving
// ////////////////////////////////////////////////////////////////////////////////
private void loadTopics() {
cleanup(false);
class R extends SwingWorker<String,String> {
private DefaultListModel _list;
private JDialog _dlg;
private boolean _finished;
public String doInBackground() {
try {
if (_helpjar != null && _helpjar.canRead()) {
publish(String.format(_tr._("Opening Help File %s"),_helpjar));
JarFile hj = new JarFile(_helpjar);
publish(String.format(_tr._("Reading Help Topics")));
ZipEntry ze = hj.getEntry("HelpTopics.xnhlp");
if (ze != null) {
try {
InputStream in = hj.getInputStream(ze);
ObjectInputStream dec = new ObjectInputStream(in);
if (NEW_READ) {
Hashtable<String, HelpTopic> htt = new Hashtable<String, HelpTopic>();
DefaultMutableTreeNode ids = (DefaultMutableTreeNode) dec.readObject();
Enumeration<DefaultMutableTreeNode> en = (Enumeration<DefaultMutableTreeNode>) ids.breadthFirstEnumeration();
while (en.hasMoreElements()) {
DefaultMutableTreeNode id = en.nextElement();
HelpTopic ht = new HelpTopic();
ht.readObject(dec);
htt.put(ht.getTopicId(), ht);
}
en = (Enumeration<DefaultMutableTreeNode>) ids.breadthFirstEnumeration();
while (en.hasMoreElements()) {
DefaultMutableTreeNode id = en.nextElement();
String t_id = (String) id.getUserObject();
id.setUserObject(htt.get(t_id));
}
_topics = ids;
} else {
_topics = (DefaultMutableTreeNode) dec.readObject();
}
in.close();
} catch (Exception e) {
DefaultXMLNoteErrorHandler.exception(e);
}
@SuppressWarnings("unchecked")
Enumeration<DefaultMutableTreeNode> en = (Enumeration<DefaultMutableTreeNode>) _topics.breadthFirstEnumeration();
while (en.hasMoreElements()) {
DefaultMutableTreeNode topic = en.nextElement();
HelpTopic ht = (HelpTopic) topic.getUserObject();
publish(String.format(_tr._("Help Topic %s (id=%s)"),ht.getName(),ht.getTopicId()));
ZipEntry hze = hj.getEntry(ht.getTopicId() + ".top");
try {
InputStream in = hj.getInputStream(hze);
ObjectInputStream dec = new ObjectInputStream(in);
HelpEntry he;
if (NEW_READ) {
he = new HelpEntry();
he.readObject(dec);
} else {
he = (HelpEntry) dec.readObject();
}
in.close();
if (he != null) {
_help.put(ht.getTopicId(), he);
}
} catch (Exception e) {
DefaultXMLNoteErrorHandler.exception(e);
}
}
{
ZipEntry kze = hj.getEntry("ImageIds.vec");
publish(String.format(_tr._("Reading Image Vector")));
try {
InputStream in = hj.getInputStream(kze);
ObjectInputStream dec = new ObjectInputStream(in);
@SuppressWarnings("unchecked")
Vector<String> keys = (Vector<String>) dec.readObject();
int nimg=keys.size();
int iimg=0;
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String id = it.next();
ZipEntry ize = hj.getEntry(id + ".img");
in = hj.getInputStream(ize);
//dec = new ObjectInputStream(in);
HelpImage himg = new HelpImage();
himg.read(in);
iimg+=1;
publish(String.format(_tr._("Reading Image %d of %d (size=%.1fkb) (%s)"),iimg,nimg,himg.sizeInKb(),id));
XMLNoteImageIcon img = new XMLNoteImageIcon(
himg.getId(), himg.getImageIcon(),
himg.getDescription(),
himg.getSize());
_images.put(img.getId(), img);
}
} catch (Exception e) {
DefaultXMLNoteErrorHandler.exception(e);
}
}
publish(String.format(_tr._("Done reading Help File")));
}
hj.close();
_newfile = false;
}
} catch (Exception E) {
DefaultXMLNoteErrorHandler.exception(E);
}
return "done" ;
}
protected void process(List<String> stuff) {
Iterator<String> it=stuff.iterator();
while (it.hasNext()) {
String s=it.next();
_list.insertElementAt(s,0);
}
}
protected void done() {
_finished=true;
try {
Thread.sleep(1000);
} catch (Exception E) {}
_dlg.setVisible(false);
}
public boolean finished() {
return _finished;
}
public R(DefaultListModel l,JDialog dlg) {
_list=l;
_dlg=dlg;
_finished=false;
}
}
JDialog dlg=new JDialog(SwingUtilities.getWindowAncestor(this),_tr._("Loading..."));
DefaultListModel model=new DefaultListModel();
JList list=new JList(model);
dlg.add(new JScrollPane(list));
dlg.setModal(true);
dlg.setMinimumSize(new Dimension(700,400));
R worker=new R(model,dlg);
worker.execute();
dlg.pack();
JXMLNoteSwingUtils.centerOnParent(SwingUtilities.getWindowAncestor(this), dlg);
if (!worker.finished()) {
dlg.setVisible(true);
}
_treeModel.setRoot(_topics);
if (_tree!=null && _tree.getRowCount()>1) {
_tree.setSelectionRow(1);
}
}
private void writeTopics() {
writeTopics(_helpjar);
}
private void writeTopics(File file) {
if (_newfile) {
File lastpath=new File(_preferences.getString("lastpath", "."));
JFileChooser chooser = new JFileChooser(lastpath);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Help files", "xnhlp");
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
lastpath=chooser.getCurrentDirectory();
_preferences.put("lastpath", lastpath.getAbsolutePath());
file = chooser.getSelectedFile();
String fl = file.getAbsolutePath();
if (!fl.endsWith(".xnhlp")) {
file = new File(fl + ".xnhlp");
}
} else {
return;
}
}
String jarName = file.getAbsolutePath();
try {
FileOutputStream fout = new FileOutputStream(jarName);
JarOutputStream jout = new JarOutputStream(fout);
{
ZipEntry ze = new ZipEntry("HelpTopics.xnhlp");
jout.putNextEntry(ze);
writeObject(jout, _topics);
}
{
@SuppressWarnings("unchecked")
Enumeration<DefaultMutableTreeNode> en = _topics
.breadthFirstEnumeration();
while (en.hasMoreElements()) {
DefaultMutableTreeNode topic = en.nextElement();
HelpTopic ht = (HelpTopic) topic.getUserObject();
HelpEntry he = (HelpEntry) _help.get(ht.getTopicId());
ZipEntry hze = new ZipEntry(ht.getTopicId() + ".top");
jout.putNextEntry(hze);
if (he == null) { he = new HelpEntry(); }
writeObject(jout, he);
}
}
{
Set<String> skeys = _images.keySet();
Vector<String> keys = new Vector<String>();
Iterator<String> it = skeys.iterator();
while (it.hasNext()) {
String id = it.next();
XMLNoteImageIcon icn = _images.get(id);
if (icn.type() == XMLNoteImageIcon.Type.IMAGEICON) {
keys.add(id);
}
}
ZipEntry kze = new ZipEntry("ImageIds.vec");
jout.putNextEntry(kze);
writeObject(jout, keys);
it = keys.iterator();
while (it.hasNext()) {
XMLNoteImageIcon img = _images.get(it.next());
HelpImage himg = new HelpImage(img.getId(),
img.getOriginal(), img.getDescription(),
img.getSize());
ZipEntry ize = new ZipEntry(img.getId() + ".img");
jout.putNextEntry(ize);
himg.write(jout);
//writeObject(jout, himg);
}
}
jout.close();
fout.close();
_helpjar = new File(jarName);
setTitle();
_saved = true;
_newfile = false;
} catch (IOException e) {
DefaultXMLNoteErrorHandler.exception(e);
}
}
private void loadTopic(HelpTopic topic) {
_imageBackingStore.clear();
if (topic == null) {
_document.clear();
} else {
HelpEntry entry = (HelpEntry) _help.get(topic.getTopicId());
if (entry != null) {
try {
//String xml = XMLNoteUtils.prettyPrintXML(entry.getXmlnote());
//System.out.println(xml);
_document.resetFromXML(entry.getXmlnote());
} catch (BadDocumentException e) {
DefaultXMLNoteErrorHandler.exception(e);
}
} else {
_document.clear();
}
}
}
private void saveDocument() {
if (_selected!=null) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) _selected.getLastPathComponent();
HelpTopic t = (HelpTopic) node.getUserObject();
String id = t.getTopicId();
HelpEntry he = (HelpEntry) _help.get(id);
if (he != null) {
try {
he.setXmlnote(_document.toXML());
_document.setChanged(false);
_saved = false; // the helpfile needs saving
} catch (BadDocumentException e1) {
DefaultXMLNoteErrorHandler.exception(e1);
he.setXmlnote(XMLNoteDocument.emptyXML());
}
}
}
}
private HelpEntry getSelectedEntry() {
if (_selected == null) {
return null;
} else {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) _selected
.getLastPathComponent();
HelpTopic t = (HelpTopic) node.getUserObject();
String id = t.getTopicId();
HelpEntry he = (HelpEntry) _help.get(id);
return he;
}
}
public void checkDocumentSaved() {
if (_helpjar != null) {
if (_document.changed()) {
int result = JOptionPane
.showConfirmDialog(
this,
_tr._("Current topic is changed, do you want to store it?"),
_tr._("Save Topic"), JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
saveDocument();
}
}
}
}
public void checkTopicsSaved() {
if (_helpjar != null) {
checkDocumentSaved();
if (!_saved) {
int result = JOptionPane.showConfirmDialog(this,
_tr._("This help file has changed, store it?"),
_tr._("Save Help File"), JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
writeTopics();
}
}
}
}
public boolean cleanup(boolean affectHelpJar) {
if (_helpjar != null) {
checkTopicsSaved();
}
_topics = new DefaultMutableTreeNode(new HelpTopic("Help Topics",""));
_treeModel.setRoot(_topics);
if (affectHelpJar) {
_helpjar = null;
}
_selected = null;
_help = new Hashtable<String, HelpEntry>();
_images = new Hashtable<String, XMLNoteImageIcon>();
_imageBackingStore = new Hashtable<String, XMLNoteImageIcon>();
_document.clear();
if (_tree!=null) {
_tree.setSelectionRow(0);
}
return true;
}
// ////////////////////////////////////////////////////////////////////////////////
// Handle actions
// ////////////////////////////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent e) {
//System.out.println(e);
String cmd = e.getActionCommand();
if (cmd.equals("load")) {
openHelp();
} else if (cmd.equals("new")) {
newHelp();
} else if (cmd.equals("save")) {
saveHelp();
} else if (cmd.equals("add-topic")) {
newTopic();
} else if (cmd.equals("remove-topic")) {
removeTopic();
} else if (cmd.equals("change-topic")) {
changeTopic();
} else if (cmd.equals("insert-link")) {
insertLink();
} else if (cmd.equals("remove-link")) {
removeLink();
} else if (cmd.equals("insert-hyperlink")) {
insertHyperLink();
} else if (cmd.equals("remove-hyperlink")) {
removeHyperLink();
} else if (cmd.startsWith("recent:")) {
openRecent(cmd.substring(7));
} else if (cmd.equals("add-image")) {
addImage();
} else if (cmd.equals("help")) {
testHelp();
}
}
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getPath();
DefaultMutableTreeNode dnode = (DefaultMutableTreeNode) path
.getLastPathComponent();
if (_selected != null) {
checkDocumentSaved();
}
_selected = path;
if (dnode != _topics) {
loadTopic((HelpTopic) dnode.getUserObject());
_editor.setUnresponsive(false);
} else {
_document.clear();
_editor.setUnresponsive(true);
}
}
private void newHelp() {
if (!cleanup(true)) {
return;
}
_newfile = true;
_helpjar = new File(String.format("Help_%d.xnhlp", _next++));
setTitle();
}
private void saveHelp() {
if (_helpjar != null) {
saveDocument();
writeTopics();
if (_recent != null && _helpjar != null) {
_recent.addRecentUse(_helpjar.getAbsolutePath());
}
} else {
JOptionPane.showMessageDialog(this,
_tr._("Please open a help file or create a new one first"),
_tr._("Save Help"), JOptionPane.INFORMATION_MESSAGE);
}
}
private void openRecent(String file) {
File f = new File(file);
if (f.canRead()) {
if (!cleanup(true)) {
return;
}
_helpjar = f;
loadTopics();
setTitle();
if (_recent != null) {
_recent.addRecentUse(f.getAbsolutePath());
}
} else {
_recent.removeRecentUse(file);
}
}
private void openHelp() {
File lastpath=new File(_preferences.getString("lastpath", "."));
JFileChooser chooser = new JFileChooser(lastpath);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Help files", "xnhlp");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
lastpath=chooser.getCurrentDirectory();
_preferences.put("lastpath", lastpath.getAbsolutePath());
File file = chooser.getSelectedFile();
String fl = file.getAbsolutePath();
if (!fl.endsWith(".xnhlp")) {
file = new File(fl + ".xnhlp");
}
if (file.canRead()) {
if (!cleanup(true)) {
return;
}
_helpjar = file;
loadTopics();
setTitle();
if (_recent != null) {
_recent.addRecentUse(file.getAbsolutePath());
}
}
}
}
private void newTopic() {
if (_selected == null) {
JOptionPane.showMessageDialog(this,
_tr._("Select a parent topic first"), _tr._("New Topic"),
JOptionPane.INFORMATION_MESSAGE);
return;
}
HelpTopic tp=TopicDlg.showDlg(getWindow(this), _tr._("Create a new Topic"));
if (tp!=null) {
if (!tp.getName().equals("")) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) _selected
.getLastPathComponent();
DefaultMutableTreeNode n = new DefaultMutableTreeNode(tp);
_treeModel.insertNodeInto(n, node, node.getChildCount());
HelpEntry he = new HelpEntry();
_help.put(tp.getTopicId(), he);
TreePath p = _selected.pathByAddingChild(n);
_tree.scrollPathToVisible(p);
_tree.setSelectionPath(p);
} else {
JOptionPane.showMessageDialog(this,
_tr._("Topic text may not be empty"),
_tr._("New Topic"), JOptionPane.INFORMATION_MESSAGE);
}
}
}
private void changeTopic() {
if (_selected == null) {
JOptionPane.showMessageDialog(this, _tr._("Select a topic first"),
_tr._("Change Topic"), JOptionPane.INFORMATION_MESSAGE);
return;
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode) _selected
.getLastPathComponent();
HelpTopic topic = (HelpTopic) node.getUserObject();
HelpTopic tp=TopicDlg.showDlg(getWindow(this), _tr._("Change Topic"),topic);
if (tp != null) {
if (!tp.getName().equals("")) {
topic.setName(tp.getName());
topic.setKey(tp.getKey());
_treeModel.nodeChanged(node);
_saved = false;
} else {
JOptionPane.showMessageDialog(this,
_tr._("Topic text may not be empty"),
_tr._("Change Topic"), JOptionPane.INFORMATION_MESSAGE);
}
}
}
private void removeTopic() {
checkDocumentSaved();
if (_selected == null) {
JOptionPane.showMessageDialog(this, _tr._("Select a topic first"),
_tr._("Remove Topic"), JOptionPane.INFORMATION_MESSAGE);
return;
}
DefaultMutableTreeNode node = (DefaultMutableTreeNode) _selected.getLastPathComponent();
if (node.isLeaf()) {
int result = JOptionPane.showConfirmDialog(this,
_tr._("Do you want to remove the selected topic?"),
_tr._("Delete Topic"), JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
_treeModel.removeNodeFromParent(node);
// Remove all associated images in the document
Vector<XMLNoteImageIcon> images=_document.getAllImages();
Iterator<XMLNoteImageIcon> it=images.iterator();
while (it.hasNext()) { _images.remove(it.next().getId()); }
_document.clear();
}
} else {
JOptionPane.showMessageDialog(this, _tr._("Remove the children of this topic first"),
_tr._("Remove Topic"), JOptionPane.INFORMATION_MESSAGE);
}
}
private void insertHyperLink() {
if (_editor.getSelectionEnd()>_editor.getSelectionStart()) {
String link=JOptionPane.showInputDialog(this, _tr._("Please input a hyperlink" ), _tr._("Insert Hyperlink"));
if (link!=null && !link.trim().equals("")) {
UUID newid=UUID.randomUUID();
try {
_editor.insertMark(newid.toString(),"HyperLink:"+link);
} catch (Exception e1) {
DefaultXMLNoteErrorHandler.exception(e1);
}
} else {
JOptionPane.showMessageDialog(this, _tr._("Please insert a hyperlink"),
_tr._("Insert Hyperlink"), JOptionPane.INFORMATION_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(this, _tr._("You need to select text to be able to insert a hyperlink"),
_tr._("Insert Hyperlink"), JOptionPane.INFORMATION_MESSAGE);
}
}
private void removeHyperLink() {
removeLink();
}
private void insertLink() {
if (_editor.getSelectionEnd()>_editor.getSelectionStart()) {
final JJDialog dlg=new JJDialog(getWindow(this),_tr._("Insert link to Topic"));
final JTree tree = new JTree(_treeModel);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setMinimumSize(new Dimension(350,500));
JScrollPane pane=new JScrollPane(tree,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JPanel pnl=new JPanel();
pnl.setLayout(new BorderLayout());
pnl.add(pane,BorderLayout.CENTER);
JButton cancel=new JButton(_tr._("Cancel"));
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tree.clearSelection();
dlg.setVisible(false);
}
});
JButton ok=new JButton(_tr._("Ok"));
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dlg.setVisible(false);
}
});
ok.setDefaultCapable(true);
JPanel p=new JPanel();
p.setLayout(new FlowLayout(FlowLayout.RIGHT));
p.add(cancel);p.add(ok);
this.getRootPane().setDefaultButton(ok);
pnl.add(p,BorderLayout.SOUTH);
dlg.add(pnl);
dlg.pack();
dlg.centerOnParent();
dlg.setModal(true);
dlg.setVisible(true);
if (tree.getSelectionPath()!=null) {
DefaultMutableTreeNode o=(DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent();
HelpTopic tp=(HelpTopic) o.getUserObject();
UUID newid=UUID.randomUUID();
try {
_editor.insertMark(newid.toString(),"TopicLink:"+tp.getTopicId());
} catch (Exception e1) {
DefaultXMLNoteErrorHandler.exception(e1);
}
}
} else {
JOptionPane.showMessageDialog(this, _tr._("You need to select text to be able to insert a link to a topic"),
_tr._("Insert link"), JOptionPane.INFORMATION_MESSAGE);
}
}
public void removeLink() {
Vector<XMLNoteMark> marks;
if (_editor.getSelectionEnd()>_editor.getSelectionStart()) {
try {
marks=_editor.getMarksForSelection();
} catch (NoSelectionException e) {
// Unexpected
DefaultXMLNoteErrorHandler.exception(e);
marks=null;
}
} else {
marks=_editor.getMarksForCaret();
}
if (marks==null || marks.size()==0) {
JOptionPane.showMessageDialog(this, _tr._("You need to have the caret in a link or have a link selected to be able to remove it"),
_tr._("Remove link"), JOptionPane.INFORMATION_MESSAGE);
} else {
int i,n;
for(i=0,n=marks.size();i<n;i++) {
XMLNoteMark m=marks.get(i);
try {
_document.removeMark(m.id());
} catch (MarkNoExistException e) {
// again: unexpected
DefaultXMLNoteErrorHandler.exception(e);
}
}
}
}
private void addImage() {
if (_selected == null) {
return;
}
File lastPath=new File(_preferences.getString("imagedir","~"));
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(lastPath);
chooser.setAccessory(new ImagePreview(chooser));
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images",
"jpg", "png", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
File dir=chooser.getCurrentDirectory();
_preferences.put("imagedir", dir.getAbsolutePath());
if (file.canRead()) {
String id = UUID.randomUUID().toString();
URL url;
String width = JOptionPane.showInputDialog(this, _tr
._("Please give the desired width of the image in cm"),
_tr._("3"));
if (width != null && !width.trim().equals("")) {
int widthInCm = Integer.parseInt(width);
if (widthInCm < 1) {
widthInCm = 1;
}
double points = ((72.0 / 2.54) * widthInCm);
int widthInPt = (int) Math.round(points);
try {
url = new URL("file:///" + file.getCanonicalPath());
XMLNoteImageIconSize sz=new XMLNoteImageIconSize(widthInPt,-1,XMLNoteImageIconSize.TYPE_PT);
XMLNoteImageIcon icon = new XMLNoteImageIcon(url,file.getName(), sz);
icon.setId(id);
_images.put(id, icon);
int offset = _editor.getCaretPosition();
_editor.getDocument().insertImage(offset, id);
} catch (Exception e) {
DefaultXMLNoteErrorHandler.exception(e);
}
}
}
}
}
private void testHelp() {
try {
final JDialog dlg=new JDialog(_frame,_tr._("Testing Help"),true);
JarFile jarfile;
jarfile = new JarFile(_helpjar.getAbsolutePath());
JHelpViewer viewer=new JHelpViewer(jarfile,_preferences);
JPanel panel=new JPanel();
BorderLayout layout=new BorderLayout();
layout.setHgap(3);layout.setVgap(3);
panel.setLayout(layout);
final ActionListener closeAction=new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
_preferences.put("testHelp.w", dlg.getSize().width);
_preferences.put("testHelp.h", dlg.getSize().height);
_preferences.put("testHelp.x", dlg.getLocation().x);
_preferences.put("testHelp.y", dlg.getLocation().y);
dlg.setVisible(false);
}
};
JMenuBar bar=new JMenuBar();
JMenu window=JRecentlyUsedMenu.makeMenu("_Window");
JMenuItem close=JRecentlyUsedMenu.makeMenuItem("_Close", null, "close", closeAction);
window.add(close);
bar.add(window);
JPanel menuAndTools=new JPanel();
menuAndTools.setLayout(new BorderLayout());
//menuAndTools.setLayout(new BoxLayout(menuAndTools,BoxLayout.Y_AXIS));
menuAndTools.add(bar,BorderLayout.NORTH);
JXMLNoteToolBar tbar=viewer.toolbar();
tbar.initToolBar();
menuAndTools.add(tbar,BorderLayout.SOUTH);
panel.add(menuAndTools,BorderLayout.NORTH);
panel.add(viewer,BorderLayout.CENTER);
dlg.add(panel);
dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dlg.setPreferredSize(new Dimension(_preferences.getInt("testHelp.w", 500),_preferences.getInt("testHelp.h",400)));
dlg.setLocation(_preferences.getInt("testHelp.x",_frame.getLocation().x+30),
_preferences.getInt("testHelp.y",_frame.getLocation().y+30)
);
dlg.pack();
dlg.setVisible(true);
} catch (Exception e) {
DefaultXMLNoteErrorHandler.exception(e);
}
}
// ////////////////////////////////////////////////////////////////////////////////
// Install menu on frame
// ////////////////////////////////////////////////////////////////////////////////
/**
* Instals the JHelpEditor menu on the frame.
*
* @param frame
*/
public void installMenu(JFrame frame) {
_frame = frame;
setTitle();
JMenuBar _bar = new JMenuBar();
JMenu file = makeMenu("_File");
_bar.add(file);
file.add(makeItem("_New help file", null, "new"));
file.add(makeItem("_Open help file", null, "load"));
file.add(makeItem("_Save help file", null, "save"));
_recent = new JRecentlyUsedMenu("_Recent help files", this, this);
file.add(_recent);
JMenu topics = makeMenu("_Topics");
_bar.add(topics);
topics.add(makeItem("_New topic", null, "add-topic"));
topics.add(makeItem("_Remove topic", null, "remove-topic"));
topics.add(makeItem("_Change topic", null, "change-topic"));
topics.addSeparator();
topics.add(makeItem("_Insert link", null, "insert-link"));
topics.add(makeItem("Remove _link", null, "remove-link"));
topics.add(makeItem("_Hyperlink", null, "insert-hyperlink"));
topics.add(makeItem("Remove hyperlink", null, "remove-hyperlink"));
topics.addSeparator();
topics.add(makeItem("_Add image", null, "add-image"));
frame.setJMenuBar(_bar);
}
// ////////////////////////////////////////////////////////////////////////////////
// Preferences
// ////////////////////////////////////////////////////////////////////////////////
public void storePrefs() {
XMLNotePreferences prefs = _preferences;
prefs.put("splitbar", _splitpane.getDividerLocation());
}
public void applyPrefs() {
XMLNotePreferences prefs = _preferences;
int div = prefs.getInt("splitbar", 150);
_splitpane.setDividerLocation(div);
}
// ////////////////////////////////////////////////////////////////////////////////
// Constructor
// ////////////////////////////////////////////////////////////////////////////////
public JHelpEditor(ToolsProvider prov,XMLNotePreferences prefs) {
_preferences=prefs;
_helpjar = null;
_tr = new DefaultXMLNoteTranslator();
_saved = true;
_next = 1;
_painter = new MyIconPainter();
_markProvider=new DefaultMarkMarkupProvider(MarkMarkupProvider.MarkupType.UNDERLINED,_cTopic);
_markProvider.setTextColor(_cTopic);
_hyperlinkProvider=new DefaultMarkMarkupProvider(MarkMarkupProvider.MarkupType.UNDERLINED,_cHyperlink);
_hyperlinkProvider.setTextColor(_cHyperlink);
createGui(prov);
addImageDocListeners();
applyPrefs();
newHelp();
}
}
class ImagePreview extends JComponent implements PropertyChangeListener {
ImageIcon thumbnail = null;
File file = null;
static int _iconWidth = 140;
public ImagePreview(JFileChooser fc) {
setPreferredSize(new Dimension(150, 150));
fc.addPropertyChangeListener(this);
super.setBorder(BorderFactory.createEtchedBorder());
}
public void loadImage() {
if (file == null) {
thumbnail = null;
return;
}
// Don't use createImageIcon (which is a wrapper for getResource)
// because the image we're trying to load is probably not one
// of this program's own resources.
ImageIcon tmpIcon = new ImageIcon(file.getPath());
if (tmpIcon != null) {
if (tmpIcon.getIconWidth() > _iconWidth) {
thumbnail = new ImageIcon(BufferedImageBuilder.getScaledInstance(tmpIcon.getImage(), _iconWidth, -1));
} else { // no need to miniaturize
thumbnail = tmpIcon;
}
}
}
public void propertyChange(PropertyChangeEvent e) {
boolean update = false;
String prop = e.getPropertyName();
// If the directory changed, don't show an image.
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
file = null;
update = true;
// If a file became selected, find out which one.
} else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
file = (File) e.getNewValue();
update = true;
}
// Update the preview accordingly.
if (update) {
thumbnail = null;
if (isShowing()) {
loadImage();
repaint();
}
}
}
protected void paintComponent(Graphics g) {
if (thumbnail == null) {
loadImage();
}
if (thumbnail != null) {
int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;
if (y < 0) {
y = 0;
}
if (x < 5) {
x = 5;
}
thumbnail.paintIcon(this, g, x, y);
}
}
}
class JJDialog extends JDialog {
private Window _parent=null;
public void centerOnParent () {
int x;
int y;
// Find out our parent
Point topLeft = _parent.getLocationOnScreen();
Dimension parentSize = _parent.getSize();
Dimension mySize = this.getSize();
if (parentSize.width > mySize.width)
x = ((parentSize.width - mySize.width)/2) + topLeft.x;
else
x = topLeft.x;
if (parentSize.height > mySize.height)
y = ((parentSize.height - mySize.height)/2) + topLeft.y;
else
y = topLeft.y;
this.setLocation (x, y);
}
public JJDialog(Window parent,String title) {
super(parent,title);
_parent=parent;
}
}
class TopicDlg extends JJDialog implements ActionListener {
private JTextField _topicName;
private JTextField _topicKey;
private JLabel _topicId;
private boolean _canceled=false;
public String topicName() {
return _topicName.getText().trim();
}
public String topicKey() {
return _topicKey.getText().trim();
}
public void actionPerformed(ActionEvent e) {
String c=e.getActionCommand();
if (c.equals("cancel")) {
_canceled=true;
this.setVisible(false);
} else {
this.setVisible(false);
}
}
public boolean canceled() {
return _canceled;
}
public static HelpTopic showDlg(Window parent,String title) {
return showDlg(parent,title,new HelpTopic("",""));
}
public static HelpTopic showDlg(Window parent,String title,HelpTopic tp) {
TopicDlg dlg=new TopicDlg(parent,title,tp);
dlg.pack();
dlg.centerOnParent();
dlg.setVisible(true);
if (!dlg.canceled()) {
HelpTopic top=new HelpTopic(dlg.topicName(),dlg.topicKey());
top.setTopicId(tp.getTopicId());
return top;
} else {
return null;
}
} |
b733a36a-cd21-4051-8dae-c6ed39e96ed1 | 1 | public boolean dropTable(String tableName) {
if (!tableHashMap.containsKey(tableName)) {
return false;
}
tableHashMap.remove(tableName);
return true;
} |
2d3a02ec-379a-45ac-8ef9-5070c6e6e13e | 8 | private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
} |
bf361283-eea1-4d62-b07f-e59352374f3c | 8 | private void setFieldSequenceInTradeFile(String header) {
String token;
String tradeId = "Trade_id";
String sellerAcct = "Seller_acct";
String buyerAcct = "Buyer_acct";
String amount = "Amount";
String tradeDate = "Trade_date";
String settledDate = "Settled_date";
StringTokenizer st = new StringTokenizer(header, ",");
for (int i = 0; i < 6; i++) {
token = st.nextToken();
if (token.equals(tradeId)) {
fieldSequenceInTradeFile.put(tradeId, i);
continue;
}
if (token.equals(sellerAcct)) {
fieldSequenceInTradeFile.put(sellerAcct, i);
continue;
}
if (token.equals(buyerAcct)) {
fieldSequenceInTradeFile.put(buyerAcct, i);
continue;
}
if (token.equals(amount)) {
fieldSequenceInTradeFile.put(amount, i);
continue;
}
if (token.equals(tradeDate)) {
fieldSequenceInTradeFile.put(tradeDate, i);
continue;
}
if (token.equals(settledDate)) {
fieldSequenceInTradeFile.put(settledDate, i);
}
}
if (fieldSequenceInTradeFile.isEmpty()) {
System.out.println("an error occurred during parsing file header! file name: " +
shortTradeFileName);
}
} |
85b89f88-ca5b-4b92-b001-2e3f18915540 | 5 | @Override
public void paintComponent (Graphics g) {
if (champion == null) {
if (isSelected) {
if (isEnemy) {
g.drawImage (EPICKING_BG, 0, 0, null);
g.drawImage (EPICKING, 0, 0, null);
} else {
g.drawImage (PICKING_BG, 0, 0, null);
g.drawImage (PICKING, 0, 0, null);
}
} else {
g.drawImage (OPEN_BG, 0, 0, null);
g.drawImage (OPEN, 0, 0, null);
}
} else if (isSelected) {
champion.getIcon().paintIcon (this, g, 61, 7);
g.drawImage ((isEnemy) ? EPICKING : PICKING, 0, 0, null);
} else {
champion.getIcon().paintIcon (this, g, 61, 7);
g.drawImage (LOCKED, 0, 0, null);
}
} |
14ce63ef-7075-4d4e-b488-d6186d98efb3 | 5 | static public File getFileHandler(String file)
{
try {
File aFile = new File(file);
if (aFile == null || !aFile.exists()) {
boolean success = aFile.createNewFile();
if (success)
aFile = new File(file);
else
return null;
}
if (!aFile.canWrite()) {
return null;
}
return aFile;
}
catch (IOException e)
{
return null;
}
} |
3b065a70-326c-4e97-93a1-051695ad0bb4 | 6 | public Map(int mapSize) {
int fullMapSize = mapSize + 2;
grid = new Room[fullMapSize][fullMapSize];
for (int i = 0; i < fullMapSize; i++) {
for (int j = 0; j < fullMapSize; j++) {
if (i == 0 || i == fullMapSize - 1 || j == 0
|| j == fullMapSize - 1) {
grid[i][j] = new Room(RoomType.wall, false);
} else {
// System.out.println("Genning a new room:");
grid[i][j] = new Room(RoomType.randomRoom(mapSize), false);
}
}
}
placeEntrance();
// display full map, for debugging:
/*for (int i = 0; i < fullMapSize; i++) {
for (int j = 0; j < fullMapSize; j++) {
System.out.print(grid[i][j].getRoomType().getAsciiMap());
}
System.out.println();
}*/
} |
481cfc3d-0546-4efc-8917-308e06af649c | 0 | public String getQuestName() {
return QuestName;
} |
d9c6e621-1554-4a05-b878-c8c1bec0a2cd | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ObjectEntry other = (ObjectEntry) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
} |
7823cb8c-4fc0-44c4-b0f0-df1d42b5c25f | 0 | public int getWidth() {
return width;
} |
0b904ceb-50a6-4a87-98fc-a1f8777e3ad0 | 9 | private void optimizeMondayTimeTableForIIIAndIVGymnasium() {
// mondayTimeTable = new LinkedHashMap<>();
// tuesdayTimeTable = new LinkedHashMap<>();
// wednesdayTimeTable = new LinkedHashMap<>();
// thursdayTimeTable = new LinkedHashMap<>();
// fridayTimeTable = new LinkedHashMap<>();
List<LinkedHashMap> daysTimeTablesForItr = addDaysTimeTablesForIteration();
// System.out.println("days time table in III and IV: " + daysTimeTablesForItr);
LinkedHashMap<String, String> teachersTimeTable;
HashMap<String, Teacher> teachersMapForDeletion = copyTeacherForDeletion();
for (int lectureNumber = 1; lectureNumber <= properties.getHoursPerDay(); lectureNumber++) {
// System.out.println("--------------Lecture-----------------");
// System.out.println("teachersListOfIIIAndIV: " + teachersListOfIIIAndIVForOptm);
for (String teacherName : teachersListOfIIIAndIVForOptm) {
// System.out.println("--------------Teacher-----------------");
for (LinkedHashMap dayTimeTable : daysTimeTablesForItr) {
// System.out.println("-----------------Day-------------");
// System.out.println("lecture number: " + lectureNumber);
// System.out.println("daytimetable: " + dayTimeTable);
teachersTimeTable = getTeachersTimeTable(teacherName, dayTimeTable);
Teacher teacher = teachersMapForDeletion.get(teacherName);
List<Group> teachersGroups = teacher.getTeachersGroups();
int teachersGroupsTotal = teachersGroups.size();
// System.out.println("teachersGroupsTotal: " + teachersGroupsTotal);
if (teachersGroupsTotal == 0) {
// System.out.println("Tuscia");
teachersTimeTable.put(String.valueOf(lectureNumber), lectureNumber + ": -----");//Add group, because all the groups for teacher was added already
// System.out.println("add empty at the end");
continue;
}
int counter = 0;
counter = countThatThereIsIIIAndIVGymnGroups(teachersGroups, counter);
if (counter == 0) {
teachersTimeTable.put(String.valueOf(lectureNumber), lectureNumber + ": -----");//Add group, because all the groups for teacher was added already
continue;
}
Group group = getRandomGroup(teachersGroups, teachersGroupsTotal);
while (group == null || group.isIiGymnasiumGroup() || group.isiGymnasiumGroup()) {
group = getRandomGroup(teachersGroups, teachersGroupsTotal);
}
boolean isGroupAllowedToAdd = isMandatoryConditionsMet(teacher, teachersGroups, group, lectureNumber, dayTimeTable);
// System.out.println("Grupe idejimui: " + group);
// System.out.println("isGroupAllowedToAdd: " + isGroupAllowedToAdd);
if (isGroupAllowedToAdd) {
// System.out.println("Mokytojas: " + teacherName);
// System.out.println("Grupe, kai galima deti ja: " + group);
addGroupToTeachersTimeTable(group, teachersTimeTable, lectureNumber, teachersGroups);
} else {
teachersTimeTable.put(String.valueOf(lectureNumber), lectureNumber + ": -----");
}
}
}
}
} |
2b967eaa-50aa-4dec-b6b5-9b8fcb962bec | 0 | private NotInterestedMessage(ByteBuffer buffer) {
super(Type.NOT_INTERESTED, buffer);
} |
117a7d3c-4004-4180-beb0-0722b44a6b7d | 9 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if(cmd.getName().equalsIgnoreCase("Nick")) {
if(sender instanceof Player) {
Player p = (Player) sender;
PlayerUtil pu = new PlayerUtil(p);
if(pu.hasPermission("Nostalgia.Command.nick", PermissionType.NORMAL)) {
if(args.length == 0) {
pu.setNickname(p.getName());
pu.updateName();
p.sendMessage(LangUtil.nickChanged(p.getDisplayName()));
} else if (args.length >= 1) {
if(StringUtil.startsWithIgnoreCase(args[0], "p:")) {
if(pu.hasPermission("Nostalgia.Command.nick.others", PermissionType.NORMAL)){
String playerName = StringUtil.removePrefix(args[0], 2);
Player t = Nostalgia.getPlayer(playerName);
if(t != null) {
PlayerUtil tu = new PlayerUtil(t);
if(args.length == 1) {
tu.setNickname(t.getName());
tu.updateName();
t.sendMessage(LangUtil.nickChanged(t.getDisplayName()));
} else {
String buildnick = StringUtil.arrangeString(args, " ", 1);
String nick = StringUtil.colorize(buildnick, p, "nick", PermissionType.NORMAL);
tu.setNickname(nick);
tu.updateName();
t.sendMessage(LangUtil.nickChanged(t.getDisplayName()));
}
} else {
p.sendMessage(LangUtil.mustBeOnline(playerName));
}
} else {
MessageUtil.noPermission(p, "Nostalgia.Command.nick.others");
}
} else {
String buildnick = StringUtil.arrangeString(args, " ", 0);
String nick = StringUtil.colorize(buildnick, p, "nick", PermissionType.NORMAL);
pu.setNickname(nick);
pu.updateName();
p.sendMessage(LangUtil.nickChanged(p.getDisplayName()));
}
} else {
p.sendMessage(LangUtil.fourthWall());
}
} else {
MessageUtil.noPermission(p, "Nostalgia.Command.nick");
}
} else {
sender.sendMessage(LangUtil.mustBePlayer());
}
}
return false;
} |
b1e1286c-4b0b-472f-8121-a20bf5e620b3 | 6 | public HashMap<String, Integer> getTopPublishers() throws Exception{
Connection connect = null;
Statement statement = null;
ResultSet resultSet = null;
HashMap<String, Integer> publishersMap = new HashMap<String, Integer>();
try {
// First connect to the database
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarysystem?user=admin&password=123456");
statement = connect.createStatement();
// Select the name(s) of the top publisher(s) and also the book count(s)
resultSet = statement.executeQuery("SELECT HP.name, COUNT(*) "
+ "FROM Book B, HasPUblisher HP "
+ "WHERE B.isbn = HP.isbn "
+ "GROUP BY HP.name "
+ "HAVING COUNT(*) >= ALL (SELECT COUNT(*) "
+ "FROM Book B1, HasPublisher HP1 "
+ "WHERE B1.isbn = HP1.isbn "
+ "GROUP BY HP1.name)");
// Add genres and their counts into collection genreMap one at a time
while(resultSet.next()){
publishersMap.put(resultSet.getString(1), resultSet.getInt(2));
}
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
finally
{
try {
if(connect != null){
connect.close();
}
if(statement != null){
statement.close();
}
if(resultSet != null){
resultSet.close();
}
} catch (Exception e) {
}
}
return publishersMap;
} |
e42b76bb-50fe-4d52-98cc-03d89a970239 | 6 | private void startGame(int x, int y, ArrayList<String> args) {
if (autoCrapTalk) {
sendMessage(util.CrapTalker.insult(util.CrapTalker.INSULTS_START));
}
try {
game = new Game(x, y, args);
player = game.getPlayer(args.indexOf(clientName));
if (mui instanceof ConnectionWindow) {
((ConnectionWindow) mui).setGame(game, player);
} else {
System.out.println("mui should be a ConnectionWindow now!!");
}
} catch (InvalidMoveException e) {
this.sendDisconnect("Invalid startstone position");
}
System.out.println("PlayerNumber: " + args.indexOf(clientName));
if (selectedAI == 1) {
ai = new SmartAI(game, player);
} else if (selectedAI == 2) {
ai = new RandomAI(game, player);
} else if (selectedAI == 3) {
ai = new CustomAI(game, player,0,0,1);
}
status = INGAME;
} |
f9e0f86d-3d75-4bdd-bb26-6480725fc74f | 0 | public void setInternal(T internal) {
this.internal = internal;
} |
347b7f15-3733-4f19-9a84-6c840d5e6a3a | 7 | public final int gen_caps_and_promotions(Move[] moves, int startIndex) {
int moveIndex = gen_caps(moves, startIndex);
int from,to,pieceType;
if(toMove == WHITE_TO_MOVE) {
for (int i = 0; i < w_pawns.count; i++) {
from = w_pawns.pieces[i]; // Index the current pawn is on
to = from + 16; // Up
pieceType = boardArray[to];
// Pawn can move forward
if (pieceType == EMPTY_SQUARE) {
// Reached the last rank add promotion
if (rank(to) == 7) {
moves[moveIndex++].move = Move.createMove(W_PAWN, from, to, 0, PROMOTION_QUEEN, 0);
}
}
}
} else { // Black to move
for (int i = 0; i < b_pawns.count; i++) {
from = b_pawns.pieces[i]; // Index the current pawn is on
to = from - 16; // Down
pieceType = boardArray[to];
if (pieceType == EMPTY_SQUARE) {
if (rank(to) == 0) {
moves[moveIndex++].move = Move.createMove(B_PAWN, from, to, 0, PROMOTION_QUEEN, 0);
}
}
}
}
return moveIndex;
} // END gen_caps_and_promotions |
0d79c097-2c62-41fe-a2f8-f2fe4291a6a3 | 3 | private long memoryAuditReport() {
long companionOverHeads = 0;
companionOverHeads += sourceVertexIds.length * 4;
companionOverHeads += distrLocks.length * 4;
long bufferMem = 0;
long maxMem = 0;
for(IntegerBuffer buf : buffers) {
long est = buf.memorySizeEst();
bufferMem += est;
maxMem = Math.max(maxMem, est);
}
long distributionMem = 0;
long maxDistMem = 0;
long avoidMem = 0;
for(DiscreteDistribution dist : distributions) {
long est = dist.memorySizeEst();
distributionMem += est;
maxDistMem = Math.max(est, maxDistMem);
avoidMem += dist.avoidCount() * 6;
}
NumberFormat nf = NumberFormat.getInstance(Locale.US);
logger.info("======= MEMORY REPORT ======");
logger.info("Companion internal: " + nf.format(companionOverHeads / 1024. / 1024.) + " mb");
logger.info("Buffer mem: " + nf.format(bufferMem / 1024. / 1024.) + " mb");
logger.info("Avg bytes per buffer: " + nf.format(bufferMem * 1.0 / buffers.length / 1024.) + " kb");
logger.info("Max buffer was: " + nf.format(maxMem / 1024.) + "kb");
logger.info("Distribution mem: " + nf.format(distributionMem / 1024. / 1024.) + " mb");
logger.info("- of which avoids: " + nf.format(avoidMem / 1024. / 1024.) + " mb");
logger.info("Avg bytes per distribution: " + nf.format((distributionMem * 1.0 / distributions.length / 1024.)) + " kb");
logger.info("Max distribution: " + nf.format(maxDistMem / 1024.) + " kb");
long totalMem = companionOverHeads + bufferMem + distributionMem;
logger.info("** Total: " + nf.format(totalMem / 1024. / 1024. / 1024.) + " GB (low-mem limit " + Runtime.getRuntime().maxMemory() * 0.25 / 1024. / 1024. / 1024. + "GB)" );
isLowInMemory = totalMem > maxMemoryBytes;
if (isLowInMemory) {
compactMemoryUsage();
}
return totalMem;
} |
0aaa5714-7106-4278-942c-1e33a47feefc | 3 | public int compare(IdFloat idFloat, IdFloat idFloat1) {
if (idFloat.vertexId == idFloat1.vertexId) return 0;
int comp = -Float.compare(idFloat.value, idFloat1.value); // Descending order
return (comp != 0 ? comp : (idFloat.vertexId < idFloat1.vertexId ? -1 : 1));
} |
8209e8ea-a31a-4173-96e2-c33091afddeb | 6 | public static void run(RobotController myRC)
{
rc = myRC;
RobotType t = rc.getType();
try
{
if (t == RobotType.SOLDIER)
{
// if(rc.senseHQLocation().distanceSquaredTo(rc.senseEnemyHQLocation()) < Constants.theMagicNumber) {
// team235.secretRushStratGG.Soldier.soldierCode(rc);
// }
// else {
// Soldier.soldierCode(rc);
// }
Soldier.soldierCode(rc);
}
else if(t == RobotType.HQ)
{
// if(rc.senseHQLocation().distanceSquaredTo(rc.senseEnemyHQLocation()) < Constants.theMagicNumber) {
// team235.secretRushStratGG.HQ.hqCode(rc);
// }
// else {
// HQ.hqCode(rc);
// }
HQ.hqCode(rc);
}
else if(t == RobotType.GENERATOR || t == RobotType.SUPPLIER)
{
// if(rc.senseHQLocation().distanceSquaredTo(rc.senseEnemyHQLocation()) < Constants.theMagicNumber) {
// while(true) {
// rc.yield();
// }
// }
Supplier.supplierCode(rc);
}
else
{
while(true)
{
rc.yield();
}
}
}
catch (Exception e)
{
System.out.println("caught exception before it killed us:");
e.printStackTrace();
}
} |
1d03a1e9-a097-46da-9c31-aba10470dea0 | 3 | public static ChessPiece from(PieceColor color, PieceType type) {
for (ChessPiece chessPiece : values()) {
if (chessPiece.type == type && chessPiece.color == color) {
return chessPiece;
}
}
throw new IllegalArgumentException(String.format("There is no chess piece of type and color: [%s, %s]", type, color));
} |
a033272c-05fa-463d-bc3c-7f0270abee30 | 4 | public static String defineGroup(HashMap<String,List<String>> pDictionary) {
// groupref
String isPartOf = "http://purl.org/dc/terms/isPartOf";
if (pDictionary.containsKey(isPartOf)) {
List<String> check_groupref = pDictionary.get(isPartOf);
if (check_groupref.size() > 1) {
for (int i=0; i < check_groupref.size() ; i++) {
if (check_groupref.get(i).toString().contains("/group/")) {
allVars.put("groupId",
check_groupref.get(i).toString().split("/")
[check_groupref.get(i).toString().split("/").length-1].toString());
break;
} else {allVars.put("groupId", ".");}
}
} else {allVars.put("groupId", "");}
}
return null;
} |
471655ea-d3e8-4981-908b-a0723d43ce62 | 4 | public Direction getOpposingDirection() {
switch(this) {
case NORTH: return SOUTH;
case WEST: return EAST;
case SOUTH: return NORTH;
case EAST: return WEST;
}
return null;
} |
27b14b6e-b3d1-4f91-866c-e48a743dbb1e | 8 | public static void main(String[] args) throws IOException {
//String fileName = "/Users/Dany/Documents/FALL-2013-COURSES/Imp_Data_structures/workspace/MaximumClique/src/com/maximumclique/input/C125.9.clq.txt";
//readDIMACS(fileName);
readDIMACS(args[1]);
MC mc = null;
if (args[0].equals("MC")) mc = new MC(n,A,degree);
else if (args[0].equals("MC0")) mc = new MC0(n,A,degree);
else if (args[0].equals("MCQ1")) mc = new MCQ(n,A,degree,1);
else if (args[0].equals("MCQ2")) mc = new MCQ(n,A,degree,2);
else if (args[0].equals("MCQ3")) mc = new MCQ(n,A,degree,3);
/*else if (args[0].equals("MCSa1")) mc = new MCSa(n,A,degree,1);
else if (args[0].equals("MCSa2")) mc = new MCSa(n,A,degree,2);
else if (args[0].equals("MCSa3")) mc = new MCSa(n,A,degree,3);
else if (args[0].equals("MCSb1")) mc = new MCSb(n,A,degree,1);
else if (args[0].equals("MCSb2")) mc = new MCSb(n,A,degree,2);
else if (args[0].equals("MCSb3")) mc = new MCSb(n,A,degree,3);
else if (args[0].equals("BBMC1")) mc = new BBMC(n,A,degree,1);
else if (args[0].equals("BBMC2")) mc = new BBMC(n,A,degree,2);
else if (args[0].equals("BBMC3")) mc = new BBMC(n,A,degree,3);*/
else return;
System.gc();
if (args.length > 2) mc.timeLimit = 1000 * (long)Integer.parseInt(args[2]);
long cpuTime = System.currentTimeMillis();
mc.search();
cpuTime = System.currentTimeMillis() - cpuTime;
System.out.println(mc.maxSize +" "+ mc.nodes +" "+ cpuTime);
for (int i=0;i<mc.n;i++) if (mc.solution[i] == 1) System.out.print(i+1 +" ");
System.out.println();
} |
87334800-8dcd-4fb0-9c9c-4d8e602ea210 | 7 | private static void execSQL(String query) throws SPARULException {
Connection conn = null;
Statement stmt = null;
ResultSet result = null;
try {
conn = JDBCPoolConnection.getPoolConnection();
stmt = conn.createStatement();
result = stmt.executeQuery(query);
} catch (Exception e) {
throw new SPARULException(e);
} finally {
try {
if (result != null) {
result.close();
}
} catch (Exception e) {
logger.warn("Cannot close ResultSet", e);
}
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e) {
logger.warn("Cannot close Statement", e);
}
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
logger.warn("Cannot close Connection", e);
}
}
} |
65dae1b9-f6c2-48a8-ba29-60273cf66ef1 | 7 | @SuppressWarnings("deprecation")
public void removePlayer(Player player, String pourJoueur, String pourJoueursArene){
if(ArenaManager.getArenaManager().isInArena(player)){
PlayerArena pa = PlayerArena.getPlayerArenaByPlayer(player);
pa.clear(this.objective);
pa.getPlayer().updateInventory();
pa.restore();
pa.getPlayer().updateInventory();
pa.teleportToLobby();
if(!pourJoueur.isEmpty()){
pa.sendMessage(pourJoueur);
}
this.players.remove(player);
pa.remove();
if(!pourJoueursArene.isEmpty()){
broadcast(pourJoueursArene);
}
if(this.players.size() == 1 && this.status == Status.INGAME){
for(PlayerArena winner : this.getPlayers()){
this.stop("", Status.JOINABLE);
this.win(winner.getPlayer());
}
}
if(this.players.isEmpty()){
this.stop("", Status.JOINABLE);
}
SignManager.updateSigns(this);
}
} |
4abf6db5-11cd-43b1-a237-6315a911690e | 5 | @Override
public void mouseMoved(MouseEvent e) {
Component source = e.getComponent();
Point location = e.getPoint();
direction = 0;
if (location.x < dragInsets.left) {
direction += WEST;
}
if (location.x > source.getWidth() - dragInsets.right - 1) {
direction += EAST;
}
if (location.y < dragInsets.top) {
direction += NORTH;
}
if (location.y > source.getHeight() - dragInsets.bottom - 1) {
direction += SOUTH;
}
// Mouse is no longer over a resizable border
if (direction == 0) {
source.setCursor(sourceCursor);
} else // use the appropriate resizable cursor
{
int cursorType = cursors.get(direction);
Cursor cursor = Cursor.getPredefinedCursor(cursorType);
source.setCursor(cursor);
}
} |
b0a7a2db-1827-43c9-b174-e9a5b09f1ab0 | 7 | @EventHandler
public void GhastWaterBreathing(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Ghast.WaterBreathing.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof Fireball) {
Fireball a = (Fireball) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getGhastConfig().getBoolean("Ghast.WaterBreathing.Enabled", true) && shooter instanceof Ghast && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, plugin.getGhastConfig().getInt("Ghast.WaterBreathing.Time"), plugin.getGhastConfig().getInt("Ghast.WaterBreathing.Power")));
}
}
} |
8b76c85a-329e-45e1-a4e4-70ed18031758 | 8 | @EventHandler( priority = EventPriority.HIGHEST )
public void onPlayerToggleSprintEvent( PlayerToggleSprintEvent event )
{
Player player = event.getPlayer();
if ( event.isSprinting() )
{
String className = getPlayerClass( player );
int speed = getConfig().getInt( "classes." + className + ".speed", -1 );
if ( getMetadata( player, "adminRun" ) == null )
setMetadata( player, "adminRun", player.getGameMode() == GameMode.CREATIVE );
if ( player.hasPermission( "inations.admin" ) && ( (Boolean) getMetadata( player, "adminRun" ) ) )
{
if ( player.getItemInHand().getTypeId() == 57 )
{
event.getPlayer().addPotionEffect( new PotionEffect( PotionEffectType.SPEED, 100000, 9 ), true );
}
else if ( player.getItemInHand().getTypeId() == 41 )
{
event.getPlayer().addPotionEffect( new PotionEffect( PotionEffectType.SPEED, 100000, 7 ), true );
}
else if ( player.getItemInHand().getTypeId() == 42 )
{
event.getPlayer().addPotionEffect( new PotionEffect( PotionEffectType.SPEED, 100000, 5 ), true );
}
else
{
event.getPlayer().addPotionEffect( new PotionEffect( PotionEffectType.SPEED, 100000, 3 ), true );
}
}
else
{
if ( speed > -1 )
event.getPlayer().addPotionEffect( new PotionEffect( PotionEffectType.SPEED, 100000, speed ), true );
}
}
else
{
event.getPlayer().removePotionEffect( PotionEffectType.SPEED );
}
} |
f6778ea2-5cd6-4971-ac38-5751f6f4d67f | 5 | public String removeBlocks(String completeCode) {
int depth = 0;
String blockContents = "";
char[] charList = completeCode.toCharArray();
completeCode = "";
for(char c : charList) {
if(c == '{') {
depth++;
} else if(c == '}') {
depth--;
if(depth == 0) {
Block block = new Block(blockContents, getInterpreter());
getInterpreter().blocks.put(block.getBlockID(), block);
blockContents = "";
long blockID = block.getBlockID();
completeCode += "=:" + blockID + ";";
}
} else {
if(depth > 0) {
blockContents += c;
} else {
completeCode += c;
}
}
}
return completeCode;
} |
c08c4796-d24e-4000-9f51-aefcb54f3249 | 3 | public static Block getAttachedChest(Block block) {
if (block.getType() == Material.CHEST)
for (BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST}) {
Block b = block.getRelative(face);
if (b.getType() == Material.CHEST) {
return b;
}
}
return null;
} |
ca2649c6-b865-4c8f-9eaf-4e3ac0b4ad00 | 4 | final static String intNormal(double number)
{
String res = normal(number);
StringBuffer buf = new StringBuffer(res);
int pos = res.indexOf('.');
if (pos > -1)
{
pos = buf.length() - 1;
char ch;
boolean con;
do
{
ch = buf.charAt(pos);
if ((ch == '0') || (ch == '.'))
{
buf.deleteCharAt(pos--);
con = (ch == '0');
}
else
{
con = false;
}
}
while (con);
}
return buf.toString();
} |
c35a9553-7868-4612-88f9-c310be124a05 | 5 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.GOLD + "[" + ChatColor.AQUA + "WGTP" + ChatColor.GOLD + "] " + ChatColor.RED + "Only Players can use this command!");
return true;
}
Player player = (Player) sender;
if (player.hasPermission("wgtp.enable")) {
if (args.length == 1) {
String id = args[0];
RegionManager regionManager = plugin.worldGuardPlugin.getRegionManager(player.getWorld());
ProtectedRegion protectedRegion = regionManager.getRegion(id);
String world = player.getWorld().getName();
if (protectedRegion != null) {
if (plugin.getConfig().getStringList("disabledRegions").contains(id + ";" + world)) {
List<String> list = plugin.getConfig().getStringList("disabledRegions");
list.remove(id + ";" + world);
plugin.getConfig().set("disabledRegions", list);
plugin.saveConfig();
player.sendMessage(ChatColor.GOLD + "[" + ChatColor.AQUA + "WGTP" + ChatColor.GOLD + "] " + ChatColor.GREEN + "Successfully enabled TP in the region \"" + id + "\"!");
return true;
} else {
player.sendMessage(ChatColor.GOLD + "[" + ChatColor.AQUA + "WGTP" + ChatColor.GOLD + "] " + ChatColor.RED + "TP in this region was already enabled!");
return true;
}
} else {
player.sendMessage(ChatColor.GOLD + "[" + ChatColor.AQUA + "WGTP" + ChatColor.GOLD + "] " + ChatColor.RED + "The region \"" + id + "\" does not exist in this world!");
return true;
}
} else {
player.sendMessage(ChatColor.GOLD + "[" + ChatColor.AQUA + "WGTP" + ChatColor.GOLD + "] " + ChatColor.RED + "Invalid usage! Type /tpenable <regionName>.");
return true;
}
} else {
player.sendMessage(ChatColor.GOLD + "[" + ChatColor.AQUA + "WGTP" + ChatColor.GOLD + "] " + ChatColor.RED + "You do not have permission to execute this command!");
return true;
}
} |
4107a923-66e5-41ff-8a77-2a4d6903df14 | 5 | public static PortRange getInstance(String value) {
int lowerBound = UNBOUND;
int upperBound = UNBOUND;
// first off, make sure there's actually content here
if ((value.length() == 0) || (value.equals("-")))
return new PortRange();
// there's content, so figure where the '-' is, if at all
int dashPos = value.indexOf('-');
if (dashPos == -1) {
// there's no dash, so it's just a single number
lowerBound = upperBound = Integer.parseInt(value);
} else if (dashPos == 0) {
// it starts with a dash, so it's just upper-range bound
upperBound = Integer.parseInt(value.substring(1));
} else {
// it's a number followed by a dash, so get the lower-bound...
lowerBound = Integer.parseInt(value.substring(0, dashPos));
int len = value.length();
// ... and see if there is a second port number
if (dashPos != (len - 1)) {
// the dash wasn't at the end, so there's an upper-bound
upperBound = Integer.parseInt(value.substring(dashPos + 1,
len));
}
}
return new PortRange(lowerBound, upperBound);
} |
af4e4123-2aa3-491a-b0ab-0bfe155677db | 4 | @Override
public ArrayList<Movie> getAllMovies(ResultSet rsetMovie)
throws SQLException {
ArrayList<Movie> movies = new ArrayList<Movie>();
try {
// for every album do...
while (rsetMovie.next()) {
ResultSet rsetGenre;
ResultSet rsetDirector;
ResultSet rsetRating;
ResultSet rsetReview;
ResultSet rsetUser;
ResultSet rsetId = null;
Statement stId = connection.createStatement();
PreparedStatement stUser = connection
.prepareStatement("select Name from Account where Id = ?;");
PreparedStatement stGenre = connection
.prepareStatement("select Name from Genre where Id = ?;");
PreparedStatement stDirector = connection
.prepareStatement("select Name from Contributor inner join Creator where Media_Id = ? and Creator.id = Contributor.Creator_Id;");
PreparedStatement stRating = connection
.prepareStatement("select avg(Rating) from Rating where Media_Id = ?;");
PreparedStatement stReview = connection
.prepareStatement("select Title, Text, Account_Id from Review where Media_Id = ?;");
Movie movie = RowConverter.convertRowToMovie(rsetMovie);
stGenre.setInt(1, rsetMovie.getInt("Genre_Id"));
rsetGenre = stGenre.executeQuery();
rsetGenre.first();
movie.setGenre(rsetGenre.getString("Name"));
stDirector.setInt(1, movie.getId());
rsetDirector = stDirector.executeQuery();
while (rsetDirector.next())
movie.addDirector(rsetDirector.getString("Name"));
// get the rating.
stRating.setInt(1, movie.getId());
rsetRating = stRating.executeQuery();
while (rsetRating.next())
movie.setRating(rsetRating.getFloat(1));
// finally, get reviews..
stReview.setInt(1, movie.getId());
rsetReview = stReview.executeQuery();
while (rsetReview.next()) {
Review review = RowConverter.convertRowToReview(rsetReview);
stUser.setInt(1, rsetReview.getInt("Account_Id"));
rsetUser = stUser.executeQuery();
rsetUser.first();
review.setUser(rsetUser.getString("Name"));
movie.addReview(review);
}
// ops, need user too..
stUser.setInt(1, rsetMovie.getInt("Account_Id"));
rsetUser = stUser.executeQuery();
rsetUser.first();
movie.setUser(rsetUser.getString("Name"));
movies.add(movie);
// ha-ha
listClose(new Statement[] { stId, stUser, stGenre, stDirector,
stRating, stReview }, new ResultSet[] { rsetGenre,
rsetDirector, rsetRating, rsetReview, rsetUser, rsetId });
}
} finally {
closeResultSet(rsetMovie);
}
return movies;
} |
b4bbbb2e-a456-449b-8d23-38b7f189ec80 | 7 | public void CreateDefaults()
{
try
{
PrintStream fout = new PrintStream(new File("defaults.txt"));
String DefaultNameInput = nameTextFieldDefault.getText();
fout.println(DefaultNameInput);
String DefaultRankInput = (String) rankComboBoxDefault.getSelectedItem();
fout.println(DefaultRankInput);
int DefaultExperienceInput = xpSliderDefault.getValue();
fout.println(DefaultExperienceInput);
if (medalsOnRadioButton.isSelected() == true)
{
fout.println(true);
boolean DefaultKEY = keyCheckBoxDefault.isSelected();
fout.println(DefaultKEY);
boolean DefaultMOH = mohCheckBoxDefault.isSelected();
fout.println(DefaultMOH);
boolean DefaultPCC = pccCheckBoxDefault.isSelected();
fout.println(DefaultPCC);
boolean DefaultCOB = cobCheckBoxDefault.isSelected();
fout.println(DefaultCOB);
boolean DefaultLSA = lsaCheckBoxDefault.isSelected();
fout.println(DefaultLSA);
int DefaultREM = remComboBoxDefault.getSelectedIndex();
if (DefaultREM > 0)
fout.println(true);
else
fout.println(false);
if (remComboBoxDefault.getSelectedIndex()==1)
fout.println("I");
else if (remComboBoxDefault.getSelectedIndex()==2)
fout.println("II");
else if (remComboBoxDefault.getSelectedIndex()==3)
fout.println("III");
}
if (medalsOffRadioButton.isSelected() == true)
{
fout.println(false);
fout.println(false);
fout.println(false);
fout.println(false);
fout.println(false);
fout.println(false);
fout.println(false);
fout.println("OFF");
}
fout.println((String) rankcapComboBoxDefault.getSelectedItem());
fout.println((int)windowFrame.getX());
fout.println((int)windowFrame.getY());
fout.close();
} catch (FileNotFoundException e) {
}
} |
c68233c6-424b-4a81-8d2f-e7558530e98f | 9 | private static String fixNumberedParagraphs(String document) {
boolean hasDot = contains(document, "<p[^>]*>7\\. ") && contains(document, "<p[^>]*>8\\. ") && contains(document, "<p[^>]*>9\\. ");
boolean hasDash = contains(document, "<p[^>]*>7 - ") && contains(document, "<p[^>]*>8 - ") && contains(document, "<p[^>]*>9 - ");
boolean hasLink = contains(document, "<a id=\"7\\.\">") && contains(document, "<a id=\"8\\.\">") && contains(document, "<a id=\"9\\.\">");
if (hasDash) {
document = document.replaceAll("<p>([1-9][0-9]*) - ", "<p><a class=\"numpara\" id=\"p$1\">$1.</a> ");
} else if (hasDot) {
document = document.replaceAll("(<p[^>]*>)([1-9][0-9]*)\\. ", "$1<a class=\"numpara\" id=\"p$2\">$2.</a> ");
} else if (hasLink) {
document = document.replaceAll("<a id=\"([1-9][0-9]*)\\.\">", "<a class=\"numpara\" id=\"p$1\">");
}
return document;
} |
bf50f4d4-e1db-4f73-b4f7-dbcbce1baf24 | 7 | public void mostrarRespuesta(List<String> respuesta) {
if (respuesta == null)
mostrar("Respuesta nula, hubo un error en el procesamiento de la consulta");
else if (respuesta.get(0).equals("0"))
mostrar("No se ha obtenido ninguna tupla");
else if (respuesta.get(0).equals(QueryManager.ERROR)) {
System.out.println("La consulta ha retornado el siguiente error:");
System.out.println(respuesta.get(1));
} else if (respuesta.get(0).equals(QueryManager.CANTFILAS))
if (respuesta.get(1).equals("0"))
System.out
.println("La consulta no ha actualizado ninguna fila");
else
System.out.println("La consulta ha actualizado "
+ respuesta.get(1) + " filas");
else {
int cantColumnas = Integer.valueOf((String) respuesta.get(0));
int cantFilas = (respuesta.size() - 1) / cantColumnas;
System.out
.println("DEBUG: Tamaño de respuesta:" + respuesta.size());
System.out.println("DEBUG: NºColumnas:" + cantColumnas
+ " NºFilas:" + cantFilas);
for (int i = 0; i < cantFilas; i++) {
for (int j = 1; j <= cantColumnas; j++) {
System.out.print(respuesta.get(j + (i * cantColumnas))
+ " ");
}
System.out.println("");
}
}
controlador.avisarCierreDeSocket();
mostrar("Proceso finalizado.");
} |
8100144d-1499-4b92-b2ac-e7d868aa9e5a | 6 | private boolean parseHandshake(JSONObject o) throws ProtocolException {
try {
if(!(o.get("message").equals("connect"))){
throw new ProtocolException("Expected 'connect' handshake, but got '"
+ o.get("message") + "' key");
}
if(!(o.getInt("revision") == 1)){
throw new ProtocolException("Wrong protocol revision: supporting 1, but got " +
o.getInt("revision"));
}
if(!o.getString("password").equals(password)){
Debug.warn("GUI sent wrong password");
throw new ProtocolException("Wrong password!");
}
Debug.debug("Correct password");
gotHandshake = true;
container.set(this);
try {
if(!o.getString("laserstyle").equals("start-stop")){
alternativeLaserStyle = true;
}
}
catch(JSONException e){}
return true;
}
catch (JSONException e){
throw new ProtocolException("Invalid or incomplete packet: " + e.getMessage());
}
} |
c67a7250-aedc-43cc-9108-ea0edd4bb602 | 1 | private AssociationList associationListPost(int aiNumOfRecs)
{
AssociationList laAssocList = genAssocData(aiNumOfRecs);
// Call the API to post the Association
AssociationResponseList laAssocResponseList = laClient
.postAssociations(laAssocList);
Assert.assertNotNull(laAssocResponseList);
System.out.println(laAssocResponseList.toString());
Assert.assertEquals(laAssocResponseList.getStatus(), "SUCCESS");
// Loop through the responses
for (AssociationResponse laAssocResponse : laAssocResponseList.getResponseList())
{
Assert.assertEquals(laAssocResponse.getStatus(), "SUCCESS");
}
return laAssocList;
} |
a75e7d2e-5156-4df3-bd21-a36f9de4de23 | 0 | public InternalDragAndDropListener() {} |
334a4dc0-a476-4a32-aca1-f351f631d60e | 9 | protected void onMessage(String channel, String sender, String login, String hostname,
String message)
{
//guaranteed to not be my message
DbCmds.seeOrErrorClose(sender);
if (go)
{
int p;
if ((p = message.toLowerCase().indexOf("whitespace")) != -1)
sendMessage(channel,"s/" + message.substring(p,p + 10) + "/Definitions");
}
boolean command = false;
if (message.startsWith(getNick() + ":") || message.startsWith(getNick() + ","))
{
message = message.substring(getNick().length() + 1);
command = true;
}
message = message.trim();
if (message.startsWith("!"))
{
message = message.substring(1);
command = true;
}
if (!command) return;
if (message.isEmpty()) return;
String msg[] = message.split("\\s",2);
if (msg[0].isEmpty()) return;
command(channel,sender,msg[0].toLowerCase(),msg.length == 1 ? "" : msg[1]);
} |
49c33303-44f8-49d8-b6b5-9a8e91ffaf7e | 5 | public static double[] doLinearRegressionFromTo(int start,int end,double[][] args) //input int start, int end
{ //input double[1]=array of prices
double[] answer = new double[3];
int n = 0;
int numDays=end-start;
double[] x = new double[numDays];
double[] y = new double[numDays];
for(int i=0;i<numDays;i++){x[i]=args[0][i+start];}
for(int i=0;i<numDays;i++){y[i]=args[1][i+start];}
double sumx = 0.0, sumy = 0.0;
for(int i=0;i<x.length;i++) {
sumx += x[i];
sumy += y[i];
n++;
}
double xbar = sumx / n;
double ybar = sumy / n;
double xxbar = 0.0, yybar = 0.0, xybar = 0.0;
for (int i = 0; i < n; i++) {
xxbar += (x[i] - xbar) * (x[i] - xbar);
yybar += (y[i] - ybar) * (y[i] - ybar);
xybar += (x[i] - xbar) * (y[i] - ybar);
}
double beta1 = xybar / xxbar;
double beta0 = ybar - beta1 * xbar;
//System.out.println("y = " + beta1 + " * x + " + beta0);
double ssr = 0.0;
for (int i = 0; i < n; i++) {
double fit = beta1*x[i] + beta0;
ssr += (fit - ybar) * (fit - ybar);
}
double R2 = ssr / yybar;
//System.out.println("R^2 = " + R2);
answer[0]=beta1; //returns m(gradient)
answer[1]=beta0; //returns c(y-intercept)
answer[2]=R2; //returns R-squared
return answer;
} |
7bd2bfb4-072f-4ff4-bb21-bc57331b2aff | 0 | public void setJ(byte[] value) {
this.j = value;
} |
1ecfbbe1-8955-45c7-b909-d0159beca71a | 9 | private void getBucketNameErrors(ArrayList<String> errors)
{
/**
From http://docs.amazonwebservices.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/AmazonS3Client.html#createBucket(java.lang.String, com.amazonaws.services.s3.model.Region)
Bucket names should not contain underscores
Bucket names should be between 3 and 63 characters long
Bucket names should not end with a dash
Bucket names cannot contain adjacent periods
Bucket names cannot contain dashes next to periods (e.g., "my-.bucket.com" and "my.-bucket" are invalid)
Bucket names cannot contain uppercase characters
*/
if (null != bucketName)
{
if (bucketName.indexOf('_') != -1)
{
errors.add("Bucket names should not contain underscores");
}
if (bucketName.length() < 3 || bucketName.length() > 63)
{
errors.add("Bucket names should be between 3 and 63 characters long");
}
if (bucketName.endsWith("-"))
{
errors.add("Bucket names should not end with a dash");
}
if (bucketName.indexOf("..") != -1)
{
errors.add("Bucket names cannot contain adjacent periods");
}
if (bucketName.indexOf("-.") != -1 || bucketName.indexOf(".-") != -1)
{
errors.add("Bucket names cannot contain dashes next to periods");
}
if (!bucketName.equals(bucketName.toLowerCase()))
{
errors.add("Bucket names cannot contain uppercase characters");
}
}
} |
e05f3408-8669-4b37-9f35-48981ecc20ab | 2 | private int determineRowSwap(Double[][] mat, int row, int col)
{
for (int i = row + 1; i < mat.length; i++)
{
if (mat[i][col] != 0)
return i;
}
return -1;
} |
7e5a599d-a993-41b2-b4bf-8c412157dc32 | 2 | boolean isGeometric(int[] arr) {
int d = arr[1]/arr[0];
for (int i = 2; i < arr.length; i++) {
if (arr[i]/arr[i - 1] != d) {
return false;
}
}
return true;
} |
3edce6de-0599-4e5d-bfbc-0d4f40faa8d8 | 0 | public Participant createNewParticipant(String id, String name, InetAddress addr) {
String color = textColors.get(participants.size() % textColors.size());
return new Participant(id, name, addr, color);
} |
fac35c9f-d08b-4dfd-8676-a63236381402 | 6 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Message other = (Message) obj;
if (!Objects.equals(this.header, other.header)) {
return false;
}
if (!Objects.equals(this.from, other.from)) {
return false;
}
if (!Objects.equals(this.to, other.to)) {
return false;
}
if (!Objects.equals(this.data, other.data)) {
return false;
}
return true;
} |
ea88cda7-7b4d-46b4-875f-5c8127759635 | 2 | public void loadGroups() {
groupListModel.clear();
List<ImgGroup> groups = imageBrowser.getGroups();
if (groups == null) {
return;
}
for (ImgGroup g : groups) {
groupListModel.addElement(g);
}
groupListModel.addElement(newGroupLabel);
} |
4652225d-20c1-4287-91b9-ba750a9360e8 | 9 | public static void main(String[] args) {
//other variables
String valueStr="";int n=0;
PrintWriter pw = null;FileWriter fichero = null;File in=null;Scanner s = new Scanner(System.in);
//CREATE A PRIORITY QUEUE
PriorityQueue pq = new PriorityQueue();
//Start program
System.out.println("number of items (random) -1 to end program : \n");
n = s.nextInt();
while(n!=-1)
{
if(n>100) System.out.println("number of items > 100 introduce other: \n");
else{
try {
fichero = new FileWriter("Heap_Sort.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
pw= new PrintWriter(fichero);
//create random "keys" and "values";
for(int y=0;y<n;y++){
pw.println((int)Math.floor(Math.random()*(100-0+1)+0));
int lenghValue=(int) Math.floor(Math.random()*(8-1+1)+1);
for(int yy=0;yy<lenghValue;yy++)
{
valueStr+=(char)Math.floor(Math.random()*(90-65+1)+65);
}
pw.println(valueStr);
valueStr="";
}
pw.close();
System.out.println("file Heap_Sort.txt finished! \n");
System.out.println("reading file....\n");
in=new File("Heap_Sort.txt");
Scanner sc = null;
try {
sc = new Scanner(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(sc.hasNextLine()) {
// Read entry's key
int key = Integer.valueOf(sc.nextLine().trim());
// Read entry's value
String value = sc.nextLine();
Element e = new Element(key, value);
// Priority queue insertion
if(!pq.insert(e)){
System.out.println("key = "+ e.getKey()+" already exits , value : "+ e.getValue());}
}
System.out.println("=========================\nKey ---> Value\n=========================\n");
while(pq.size() != 0) {
// Remove
Tipo_Element e = pq.remove();
System.out.println(e.getKey() + " ---> " + e.getValue());
}
}
System.out.println("number of items (random) -1 to end program : \n");
n = s.nextInt();
}
} |
063a4e3d-e5e8-414a-ae20-cd3270ae851a | 2 | public JSONObject append(String key, Object value) throws JSONException {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key, new JSONArray().put(value));
} else if (object instanceof JSONArray) {
this.put(key, ((JSONArray) object).put(value));
} else {
throw new JSONException("JSONObject[" + key
+ "] is not a JSONArray.");
}
return this;
} |
18f70ca0-69fe-4f7d-b41a-4eea22ea5e83 | 1 | @Test
public void dotProductTest() {
for (int i = 0; i < TESTS; i++) {
double x1 = rand.nextInt();
double y1 = rand.nextInt();
double x2 = rand.nextInt();
double y2 = rand.nextInt();
double dot = x1 * x2 + y1 * y2;
assertEquals(dot, new Vector(x1, y1).dot(new Vector(x2, y2)), PRECISION);
}
} |
86f65762-2de1-4e39-a402-73d54856a2d5 | 6 | public Item getSelectedItem() {
if (!opened()) {
return nil();
}
if (indexSelectedItem > -1) {
Component component = ctx.widgets.component(WIDGET_MAIN, indexSelectedItem);
return component.valid() ? new Item(ctx, component) : nil();
}
for (Component component : ctx.widgets.widget(WIDGET_MAIN).components()) {
if (component.itemId() > -1) {
indexSelectedItem = component.index();
return component.valid() ? new Item(ctx, component) : nil();
}
}
return nil();
} |
819a1a8b-a030-493d-8803-4b1a069694bf | 6 | 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(ControledePresenca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ControledePresenca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ControledePresenca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ControledePresenca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ControledePresenca().setVisible(true);
}
});
} |
c19caf89-4860-4b70-a271-098be0804106 | 3 | public static void addLibrary(File file) throws IOException {
URL fileURL=file.toURI().toURL();
List<String> string = new ArrayList<String>();
JarFile jarFile=new JarFile(file);
Enumeration<JarEntry> entries=jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry=entries.nextElement();
String name=entry.getName();
if (name.endsWith(".class")) {
name=name.substring(0,name.length() - 6);
name=name.replace('/','.');
string.add(name);
}
}
jarFile.close();
Iterator i = string.iterator();
while (i.hasNext()){
System.out.println(i.next());
}
} |
866f5b47-a90d-433d-be62-12bbf8a446ad | 7 | public void testConstructor_int_int_int_int_int_int_int_Chronology() throws Throwable {
DateTime test = new DateTime(2002, 6, 9, 1, 0, 0, 0, GregorianChronology.getInstance()); // +01:00
assertEquals(GregorianChronology.getInstance(), test.getChronology());
assertEquals(TEST_TIME_NOW, test.getMillis());
try {
new DateTime(Integer.MIN_VALUE, 6, 9, 0, 0, 0, 0, GregorianChronology.getInstance());
fail();
} catch (IllegalArgumentException ex) {}
try {
new DateTime(Integer.MAX_VALUE, 6, 9, 0, 0, 0, 0, GregorianChronology.getInstance());
fail();
} catch (IllegalArgumentException ex) {}
try {
new DateTime(2002, 0, 9, 0, 0, 0, 0, GregorianChronology.getInstance());
fail();
} catch (IllegalArgumentException ex) {}
try {
new DateTime(2002, 13, 9, 0, 0, 0, 0, GregorianChronology.getInstance());
fail();
} catch (IllegalArgumentException ex) {}
try {
new DateTime(2002, 6, 0, 0, 0, 0, 0, GregorianChronology.getInstance());
fail();
} catch (IllegalArgumentException ex) {}
try {
new DateTime(2002, 6, 31, 0, 0, 0, 0, GregorianChronology.getInstance());
fail();
} catch (IllegalArgumentException ex) {}
new DateTime(2002, 7, 31, 0, 0, 0, 0, GregorianChronology.getInstance());
try {
new DateTime(2002, 7, 32, 0, 0, 0, 0, GregorianChronology.getInstance());
fail();
} catch (IllegalArgumentException ex) {}
} |
96ce1307-d9f2-4488-8900-a18e3f3f9c37 | 3 | public Object unify(Object o, int hash, Comparator comparator) {
// /#ifdef JDK12
cleanUp();
// /#endif
int slot = Math.abs(hash % buckets.length);
for (Bucket b = buckets[slot]; b != null; b = b.next) {
Object old = b.get();
if (old != null && comparator.compare(o, old) == 0)
return old;
}
put(hash, o);
return o;
} |
5ff365d6-e81a-4325-9247-a4bfd307409d | 6 | public boolean canAttack(Unit defender) {
if (!isOffensiveUnit()
|| defender == null
|| defender.getTile() == null) return false;
Tile tile = defender.getTile();
return (isNaval())
? (tile.getSettlement() == null && defender.isNaval())
: (!defender.isNaval() || defender.isBeached());
} |
e11b6e8b-b2ec-4352-b2c5-6eddbb07a448 | 4 | private String readPassword(boolean askTwice) {
sysOut.println(bundle.getString("password_in_plaintext"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
sysOut.print(bundle.getString("password") + ": ");
String first = br.readLine();
if (askTwice == false) {
return first;
}
sysOut.print(bundle.getString("password_repeat") + ": ");
String second = br.readLine();
if (first.equals(second)) {
return first;
} else {
displayError(bundle.getString("error"),
bundle.getString("passwords_do_not_match"));
}
}
} catch (IOException ioEx) {
displayError(bundle.getString("err_password_read"),
ioEx.getLocalizedMessage());
}
return null;
} |
69f3f1e9-3328-4292-acb9-e739a1c2d665 | 8 | void output(int code, OutputStream outs) throws IOException {
cur_accum &= masks[cur_bits];
if (cur_bits > 0)
cur_accum |= (code << cur_bits);
else
cur_accum = code;
cur_bits += n_bits;
while (cur_bits >= 8) {
char_out((byte) (cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if (free_ent > maxcode || clear_flg) {
if (clear_flg) {
maxcode = MAXCODE(n_bits = g_init_bits);
clear_flg = false;
} else {
++n_bits;
if (n_bits == maxbits)
maxcode = maxmaxcode;
else
maxcode = MAXCODE(n_bits);
}
}
if (code == EOFCode) {
// At EOF, write the rest of the buffer.
while (cur_bits > 0) {
char_out((byte) (cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
flush_char(outs);
}
} |
f4697f64-3fcd-4805-9384-b91ba6225d09 | 3 | public String mapMethodName(String cls, String name, String descriptor) {
// Check the class itself first.
String key = cls + "/" + name + ";" + descriptor;
if (methods.containsKey(key)) {
return methods.get(key);
}
// Then all of its ancestors
for (String ancestor : inheritance.getAncestors(cls)) {
key = ancestor + "/" + name + ";" + descriptor;
if (methods.containsKey(key)) {
return methods.get(key);
}
}
return name;
} |
4ad7927f-9316-480c-87dc-d82e9e59fb31 | 2 | public Quaternion nlerp( Quaternion dest, float lerpFactor, boolean shortest )
{
Quaternion correctedDest = dest;
if ( shortest && this.dot( dest ) < 0 )
correctedDest = new Quaternion( -dest.getX(), -dest.getY(), -dest.getZ(), -dest.getW() );
return correctedDest.sub( this ).mul( lerpFactor ).add( this ).normalized();
} |
16b5867e-45f1-43f8-ae92-19ae6d1023f8 | 2 | public static String[] RemoveEmptyStrings(String[] strings)
{
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < strings.length; i++)
if (!strings[i].equals(""))
result.add(strings[i]);
String[] resultArray = new String[result.size()];
result.toArray(resultArray);
return resultArray;
} |
7d01dc88-1b34-498c-a870-ed57013516b4 | 9 | public Object remove(Object key)
{
Object result;
if (RESERVED_KEYS.containsKey(key)) {
if (key.equals(OgnlContext.THIS_CONTEXT_KEY)) {
result = getCurrentObject();
setCurrentObject(null);
} else {
if (key.equals(OgnlContext.ROOT_CONTEXT_KEY)) {
result = getRoot();
setRoot(null);
} else {
if (key.equals(OgnlContext.CONTEXT_CONTEXT_KEY)) {
throw new IllegalArgumentException("can't remove " + OgnlContext.CONTEXT_CONTEXT_KEY
+ " from context");
} else {
if (key.equals(OgnlContext.TRACE_EVALUATIONS_CONTEXT_KEY)) {
throw new IllegalArgumentException("can't remove "
+ OgnlContext.TRACE_EVALUATIONS_CONTEXT_KEY + " from context");
} else {
if (key.equals(OgnlContext.LAST_EVALUATION_CONTEXT_KEY)) {
result = _lastEvaluation;
setLastEvaluation(null);
} else {
if (key.equals(OgnlContext.KEEP_LAST_EVALUATION_CONTEXT_KEY)) {
throw new IllegalArgumentException("can't remove "
+ OgnlContext.KEEP_LAST_EVALUATION_CONTEXT_KEY + " from context");
} else {
if (key.equals(OgnlContext.CLASS_RESOLVER_CONTEXT_KEY)) {
result = getClassResolver();
setClassResolver(null);
} else {
if (key.equals(OgnlContext.TYPE_CONVERTER_CONTEXT_KEY)) {
result = getTypeConverter();
setTypeConverter(null);
} else {
throw new IllegalArgumentException("unknown reserved key '" + key + "'");
}
}
}
}
}
}
}
}
} else {
result = _values.remove(key);
}
return result;
} |
9970a4f6-b7c1-40be-909b-c3ad0ff1ee9e | 0 | public AppTest( String testName )
{
super( testName );
} |
c760caaa-6d55-4257-833f-cf386004b1bd | 1 | public boolean hasPlayer(Player p){
if(players.contains(p.getName())){
return true;
}else{
return false;
}
} |
44f42509-28a9-4ea0-af48-f88c0a39f825 | 8 | public boolean isDefined()
{
if(!isPlain()){
// Über Kindelemente iterieren
for(final Data data : this) {
if(!data.isDefined()) {
return false;
}
}
return true;
}
final AttributeType attributeType = getAttributeType();
// Alle Attribute, die einen "undefiniert Wert" zu Verfügung stellen, implementieren
// das Interface "UndefinedAttributeValueAccess"
if(attributeType instanceof UndefinedAttributeValueAccess) {
final UndefinedAttributeValueAccess undefinedAttributeValueAccess = (UndefinedAttributeValueAccess)attributeType;
// Alle Typen, bis auf den <code>StringAttributeType</code> können entscheiden ob
// die jeweiligen Attribute definiert sind (wenn der Wert des Attributes gleich dem "undefiniert Wert" ist, dann
// ist das Attribut nicht definiert).
// Am Attribut kann als Default-Wert der Wert "_Undefiniert" gesetzt werden. Dies entspricht aber dem
// undefiniert Wert und könnte somit nicht erkannt werden, wenn nur der Attributwert mit dem undefiniert Wert
// verglichen werden würde.
// Darum wird an dieser Stelle geprüft, ob am Attribut ein Default-Wert gesetzt wird. Falls dies der Fall ist,
// ist das Attribut definiert (es ist ja nicht möglich einen Undefiniert Wert anzugeben).
if(attributeType instanceof StringAttributeType) {
// Prüfen ob Default-Data am Attribut oder am Attributtyp vorhanden ist.
if(_info instanceof AbstractAttributeInfo && ((AbstractAttributeInfo)_info).getDefaultAttributeValue() != null) {
// wenn Defaultwert vorhanden, dann ist der Wert auf jeden Fall definiert, weil es keinen undefinierten Zustand gibt.
return true;
}
else if(attributeType.getDefaultAttributeValue() != null) {
// wenn Defaultwert vorhanden, dann ist der Wert auf jeden Fall definiert, weil es keinen undefinierten Zustand gibt.
return true;
}
}
return undefinedAttributeValueAccess.isDefined(this);
}
else {
// Für diesen AttributeType wurde kein "undefiniert Wert" festgelegt (Beispielsweise DoubleAttributeType).
// Da es keinen undefiniert Wert gibt, sind automatisch alle Werte gültig.
return true;
}
} |
868729f5-c6fa-4dda-8342-270e9c5f6189 | 6 | public FormatVersion formatVersion() {
// Already set?
if (formatVersion != null) return formatVersion;
// OK, guess format version
if (effectStrings == null) effectStrings = split(effectString);
int len = effectStrings.length;
// Error or Warning string is not added under normal situations
String lastField = effectStrings[len - 2]; // Actually las array item is after the last ')', so we use the previous one
if (lastField.startsWith("ERROR") || lastField.startsWith("WARNING")) len--;
// Guess format
if (len <= 11) return FormatVersion.FORMAT_SNPEFF_2;
if (len <= 12) return FormatVersion.FORMAT_SNPEFF_3;
return FormatVersion.FORMAT_SNPEFF_4;
} |
84f087e3-b61b-456c-b183-3a51a830ab70 | 1 | public void clearBoard(){
int[] field = getGameField();
for (int i=0; i<9; i++){field[i] = 0;}
this.turn = 1;
return;
} |
b9a4a310-8349-40d9-8a81-5b245a66b9e5 | 1 | public String getExtensionFrequency() {
Map<String, Integer> map = analytic.getExtensionFrequency();
StringBuilder sb = new StringBuilder();
List<Entry<String, Integer>> entries = new ArrayList<Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
for(Entry<String, Integer> extension : entries){
sb.append(extension.getKey());
sb.append(" - ");
sb.append(extension.getValue());
sb.append(NEWLINE);
}
return sb.toString();
} |
cf8ff115-098e-437e-9661-b1714686ab0a | 3 | public ObservableIssue getSelectedIssue() {
if (model != null && table != null) {
List<ObservableIssue> selectedIssues = table.getSelectionModel().getSelectedItems();
if (selectedIssues.size() == 1) {
final ObservableIssue selectedIssue = selectedIssues.get(0);
return selectedIssue;
}
}
return null;
} |
027d7006-8efd-46db-94bf-d57a6e758c20 | 1 | public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("C:/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i)
{
i.printStackTrace();
}
} |
0f98b86c-41aa-488b-8455-effbfb90bb01 | 8 | public void testValidEdge4() {
try {
TreeNode tree = new TreeNode("tree", 3);
TreeNode subtree1 = new TreeNode("spare-subtree1");
TreeNode subtree2 = new TreeNode("spare-subtree2");
tree.setBranch(new TreeNode[]{ new TreeNode("subtree"), subtree1, subtree2});
setTree(tree);
TreeNode realTree = ((Question1)answer);
((Question1)answer).deleteSubTree(realTree, 0);
assertTrue(null, "Your code has incorrectly deleted a leaf node from a 3-branching tree",
((String)(realTree.getData())).equals("tree")
&& realTree.getBranch().length == 3
&& realTree.getBranch()[0] == null
&& realTree.getBranch()[1] == subtree1
&& realTree.getBranch()[2] == subtree2);
} catch(TreeException exn) {
fail(exn, "Your code threw a `TreeException`. Possible causes: \n* Remember that the `root` node has a `label`.\n* Maybe you are using your parameters incorrectly?\n* Maybe you are using `==` instead of the `equals` method when testing labels?");
} catch(NullPointerException exn) {
fail(exn, "Your code threw an `NullPointerException`. Possible causes: \n* Remember that the `root` node has a `label`.\n* Maybe you are using your node parameter incorrectly?\n* Maybe you have assumed that edge numbering starts at 1?\n* Has your code forgotten to `exclude` the branch array's size as an index value?");
} catch(ArrayIndexOutOfBoundsException exn) {
fail(exn, "Your code threw an `ArrayIndexOutOfBoundsException`. Possible causes: \n* Remember that the `root` node has a `label`.\n* Maybe you are using your node parameter incorrectly?\n* Maybe you have assumed that edge numbering starts at 1?\n* Has your code forgotten to `exclude` the branch array's size as an index value?");
} catch(Throwable exn) {
fail(exn, "No exception's should be generated, but your code threw: " + exn.getClass().getName());
} // end of try-catch
} // end of method testValidEdge4 |
dc13ae78-3f89-4931-ab88-387c4f680671 | 6 | public void init(){
mobTextures[0] = Loader.getTexture(ResourceLoader.getResource("res/char/Sci4.png"), 0);
mobTextures[1] = Loader.getTexture(ResourceLoader.getResource("res/char/Sci3.png"), 0);
mobTextures[2] = Loader.getTexture(ResourceLoader.getResource("res/char/Sci2.png"), 0);
mobTextures[3] = Loader.getTexture(ResourceLoader.getResource("res/char/Sci1.png"), 0);
menu = new MainMenu();
try {
Tile.tileIds.add(new BaseTile(0, null, Loader.getTexture(Main.class.getResource("/Stone.png"), 0), false));
Tile.tileIds.add(new BaseCollidableTile(1, null, Loader.getTexture(Main.class.getResource("/Block.png"), 0), true));
Tile.tileIds.add(new BaseCollidableTile(2, null, TextureLoader.getTexture("PNG", Main.class.getResourceAsStream("/glass.png")), false));
Tile.tileIds.add(new BaseCollidableTile(3, null, Loader.getTexture(Main.class.getResource("/glass.png"), 1), false));
Tile.tileIds.add(new StoneTile(4, null, Loader.getTexture(Main.class.getResource("/StoneWall.png"), 0), true, true));
Tile.tileIds.add(new StoneTile(5, null, Loader.getTexture(Main.class.getResource("/StoneLength.png"), 0), true, true));
Tile.tileIds.add(new StoneTile(6, null, Loader.getTexture(Main.class.getResource("/StoneLength.png"), 1), true, true));
Tile.tileIds.add(new BaseTile(7, null, Loader.getTexture(Main.class.getResource("/dirt.png"), 0), false));
} catch (IOException e) {
e.printStackTrace();
}
map = new World(64, 40, 40);
map.loadMapFromFile("/map.txt");
new Item(ItemType.HealthUp, Loader.getTexture(Main.class.getResource("/heartup.png"), 0), 2);
try {
playerTextures[0] = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/char/Char4.png"));
playerTextures[1] = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/char/Char3.png"));
playerTextures[2] = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/char/Char2.png"));
playerTextures[3] = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/char/Char1.png"));
map.addPlayer(new Player(new Vector2(256 + 8, 256 + 8), new Colour(1, 1, 1, 1), playerTextures));
map.addMob(new Enemy(new Vector2(5 * 64, 15 * 64), new Colour(1, 1, 1, 1), mobTextures));
} catch (IOException e1){
e1.printStackTrace();
}
shaderProgram = glCreateProgram();
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
StringBuilder fragmentShaderSource = new StringBuilder();
try {
String line;
BufferedReader reader = new BufferedReader(new FileReader("res/lightshader.fs"));
while ((line = reader.readLine()) != null) {
fragmentShaderSource.append(line).append("\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
glShaderSource(fragmentShader, fragmentShaderSource);
glCompileShader(fragmentShader);
if (glGetShaderi(fragmentShader, GL_COMPILE_STATUS) == GL_FALSE) {
System.err.println("Fragment shader not compiled!");
}
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glValidateProgram(shaderProgram);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, WIDTH, HEIGHT, 0, -1, 1);
glMatrixMode(GL_PROJECTION);
glEnable(GL_STENCIL_TEST);
glClearColor(0, 0, 0, 0);
} |
4d7e1393-6fbf-403b-8615-52f11bbecaed | 5 | protected boolean findEntry() {
keywordOffsetArray = new Vector<Integer>();
boolean matchCase = Search.getMatchCase();
searchKeyword = Search.getSearchString();
styledText.redraw();
String str;
Pattern p;
if (!matchCase)
{
str = styledText.getText().toLowerCase();
p = Pattern.compile(searchKeyword.toLowerCase());
}
else
{
str = styledText.getText();
p = Pattern.compile(searchKeyword);
}
Matcher m = p.matcher(str);
while (m.find()) { // find next match
int match = m.start();
if (!keywordOffsetArray.contains(m.start()))
{
// add offset of match to array
keywordOffsetArray.add(match);
}
}
// jump to first match
if (!keywordOffsetArray.isEmpty())
{
if (!searchKeyword.isEmpty())
{
mntmFindNext.setEnabled(true);
}
styledText.setTopIndex(styledText.getLineAtOffset(keywordOffsetArray.get(0) - searchKeyword.length()));
offsetIndex++;
Search.shlSearch.setVisible(false);
return true;
}
else
{
return false;
}
} |
429e9d80-570e-4130-976b-4492547a3663 | 5 | private void button5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button5MouseClicked
if(numberofpins < 4)
{
if(numberofpins == 0)
{
Login_form.setString1("4");
}
if(numberofpins == 1)
{
Login_form.setString2("4");
}
if(numberofpins == 2)
{
Login_form.setString3("4");
}
if(numberofpins == 3)
{
Login_form.setString4("4");
}
numberofpins +=1;
jLabel2.setText(Integer.toString(numberofpins));
}
else
{
System.out.print(Timetable_main_RWRAF.checkDelete());
JOptionPane.showMessageDialog(null,"You've already entered your 4 digit pin!", "Timetable Management Program", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_button5MouseClicked |
692d63f8-00cc-4a66-8fff-cdde393c713f | 1 | @Override
public int attack(double agility, double luck) {
if(random.nextInt(100) < luck)
{
System.out.println("I just threw a brandish spear!");
return random.nextInt((int) agility) * 2;
}
return 0;
} |
49e3b46e-1649-4dbc-9eed-d30f1d9001a5 | 3 | @Override
public Seat getResearvedSeat(Passenger passenger) throws UnsupportedOperationException {
for (int i = 0; i < passengerList.size(); i++) {
List<Passenger> _rowIteretor = passengerList.get(i);
for (int j = 0; j < _rowIteretor.size(); j++) {
Passenger _passenger = _rowIteretor.get(j);
if (passenger.equals(_passenger)) {
Column c = Column.values()[j];
return new Seat(this, i+1, c);
}
}
}
return null;
} |
2448f458-6b40-40b1-804a-49c70d5597c3 | 4 | private void AddBorder(Node child) {
Node bChild = child.getFirstChild();
String direction = "";
String bRoomName = "";
while (bChild != null) {
String bNodeName = bChild.getNodeName();
if (bNodeName == "direction") {
direction = bChild.getFirstChild().getNodeValue();
try {
direction = ShortenDirection(direction);
} catch (Exception e) {
System.out.println(e);
}
}
else if (bNodeName == "name") {
bRoomName = bChild.getFirstChild().getNodeValue();
}
bChild = bChild.getNextSibling();
}
roomInDirection.put(direction, bRoomName);
} |
83e52e14-c347-4625-b00b-20bf8f8b6960 | 4 | public SimpleUrlShortener(final String apiUrl,
final Map<String, String> apiCredentials) {
String apiUrlFormatted = apiUrl;
if (apiCredentials != null) {
for (String credentialName : apiCredentials.keySet()) {
String credential = apiCredentials.get(credentialName);
if (credential == null) {
continue;
}
apiUrlFormatted = apiUrlFormatted.replace("%%" + credentialName + "%%", credential);
}
}
this.apiUrl = apiUrlFormatted;
String testAuthentication = this.shortenUrl("http://dev.bukkit.org/server-mods/wikisearch");
if (testAuthentication == null) {
throw new IllegalArgumentException("invalid API credentials");
}
} |
85313704-cb6e-4163-b412-d7e19ff1c02b | 8 | private boolean validateUserInput(String reminderDesc, String reminderDate,
String reminderTime) {
if (null != reminderDesc && reminderDesc.equals("")) {
JOptionPane.showMessageDialog(addReminderViewObj,
"Description Required");
return false;
}
if (null != reminderTime && reminderTime.equals("")) {
JOptionPane.showMessageDialog(addReminderViewObj, "Time Required");
return false;
} else if (false == AppHelper.isValidTime(reminderTime)) {
JOptionPane.showMessageDialog(addReminderViewObj,
"Time is not in proper format!");
return false;
}
if (null != reminderDate && reminderDate.equals("")) {
JOptionPane.showMessageDialog(addReminderViewObj, "Date Required");
return false;
} else if (false == AppHelper.isValidDate(reminderDate)) {
JOptionPane.showMessageDialog(addReminderViewObj,
"Date is not in proper format!");
return false;
}
return true;
} |
5598b234-00d3-4559-85ee-a4b355b574a8 | 9 | public LambdaMeansPredictor(List<Instance> instances) {
if (CommandLineUtilities.hasArg("cluster_lambda")) {
cluster_lambda = CommandLineUtilities.getOptionValueAsFloat("cluster_lambda");
}
clustering_training_iterations = 10;
if (CommandLineUtilities.hasArg("clustering_training_iterations")) {
clustering_training_iterations = CommandLineUtilities.getOptionValueAsInt("clustering_training_iterations");
}
// init the first cluster.
FeatureVector mean = new FeatureVector();
int count = 0;
for (Instance instance : instances) {
for (Entry<Integer, Double> entry : instance.getFeatureVector().getVector().entrySet()) {
if (mean.containIndex(entry.getKey())) {
mean.add(entry.getKey(), mean.get(entry.getKey())+entry.getValue());
}
else {
mean.add(entry.getKey(),entry.getValue());
}
}
// init assignments
assignments.add(0);
count ++;
}
for (Entry<Integer, Double> entry : mean.getVector().entrySet()) {
mean.add(entry.getKey(), entry.getValue()/count);
}
clusters.add(mean);
// init lambda if it is not specified by the user.
if (cluster_lambda == 0.0 && instances.size() != 0) {
for (Instance instance : instances) {
cluster_lambda += MathUtilities.SquaredL2Distance(mean, instance);
}
cluster_lambda /= instances.size();
System.out.println("Lambda value is:" + cluster_lambda);
}
} |
6527ecac-9812-4479-98c0-7773347dea60 | 8 | public static String toContentType(File file) {
String fName = file.getName();
String[] parts = fName.split("\\.");
String ext = parts[parts.length - 1].toLowerCase();
if (ext.equals("png") || ext.equals("jpg") || ext.equals("jpeg") || ext.equals("gif"))
return "image/" + ext;
else if (ext.equals("mp4") || ext.equals("ogv"))
return "video/" + ext;
else if (ext.equals("mp3") || ext.equals("ogg"))
return "audio/" + ext;
else
return null;
} |
f8eb4880-4b48-4bd1-bcdc-2c0ed5e93f94 | 7 | public double[] getVotesForInstanceOrig(Instance inst) {
DoubleVector combinedVote = new DoubleVector();
double[] ensembleVotes = new double[inst.numClasses()];
double qbcEntropy = 0.0;
int success = 0;
for (int i = 0; i < this.ensemble.length; i++) {
DoubleVector vote = new DoubleVector(this.ensemble[i]
.getVotesForInstance(inst));
// This will call the HoeffdingTree's getVotesForInstance Function
if (vote.sumOfValues() > 0.0) {
vote.normalize();
if ((this.useWeightOption != null)
&& this.useWeightOption.isSet()) {
vote.scaleValues(1.0 / (this.error[i] * this.error[i]));
System.out.println("Ensemble : " + i + " Error: " + this.error[i]);
}
//
//Ignore the ensembles which have high error ratio
//
if (this.error[i] < 0.3) {
combinedVote.addValues(vote);
}
}
//
// this is the votes of the ensembles for the classes
//
if (this.error[i] < 0.3) {
success++;
ensembleVotes[combinedVote.maxIndex()] += combinedVote.getValue(combinedVote.maxIndex());
}
}
// For confidence measure add to the pool and in order to fit the confidence value between 0 and 1 divide by success val
if ((combinedVote.getValue(combinedVote.maxIndex()) / success) >= confidenceThreshold) {
qbcEntropy = queryByCommitee(ensembleVotes, inst.numClasses(), 0);
System.out.println("QBC Entropy: " + qbcEntropy);
double activeLearningRatio = (qbcEntropy) + (combinedVote.getValue(combinedVote.maxIndex()) / this.ensemble.length);
inst.setClassValue(combinedVote.maxIndex());
instConfPool.addVotedInstance(inst, combinedVote
.getValue(combinedVote.maxIndex()), activeLearningRatio);
}
return combinedVote.getArrayRef();
} |
2bb7441b-152d-46ee-b614-1c749afa4c41 | 9 | public void addNotificationListener(NotificationListener listener,
NotificationFilter filter,
Object handback)
throws IllegalArgumentException {
synchronized (entries) {
// Optimization to coalesce attribute name filters
if (filter instanceof BaseAttributeFilter) {
BaseAttributeFilter newFilter = (BaseAttributeFilter) filter;
Iterator items = entries.iterator();
while (items.hasNext()) {
BaseNotificationBroadcasterEntry item =
(BaseNotificationBroadcasterEntry) items.next();
if ((item.listener == listener) &&
(item.filter != null) &&
(item.filter instanceof BaseAttributeFilter) &&
(item.handback == handback)) {
BaseAttributeFilter oldFilter =
(BaseAttributeFilter) item.filter;
String newNames[] = newFilter.getNames();
String oldNames[] = oldFilter.getNames();
if (newNames.length == 0) {
oldFilter.clear();
} else {
if (oldNames.length != 0) {
for (int i = 0; i < newNames.length; i++)
oldFilter.addAttribute(newNames[i]);
}
}
return;
}
}
}
// General purpose addition of a new entry
entries.add(new BaseNotificationBroadcasterEntry
(listener, filter, handback));
}
} |
01f0df3b-6936-429e-ad34-0822d43bc64e | 9 | private void BtPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtPesquisaActionPerformed
int[] parametro = new int[4];
parametro[0] = 70;
parametro[1] = 300;
parametro[2] = 200;
parametro[3] = 70;
preenche.FormataJtable(TbPesquisa, parametro);
switch (CbPesquisa.getSelectedIndex()) {
case 0: {
preenche.PreencherJtable(TbPesquisa, funcionario.consultageral());
break;
}
case 1: {
if (TfPesquisa.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Digite o Código do funcionário que deseja consultar!", "Digite o codigo", JOptionPane.INFORMATION_MESSAGE);
TfPesquisa.grabFocus();
} else {
funcionario.setCodigo(Integer.parseInt(TfPesquisa.getText()));
preenche.PreencherJtable(TbPesquisa, funcionario.consultacodigo());
}
break;
}
case 2: {
if (TfPesquisa.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Digite o Nome do funcionário que deseja consultar!", "Digite o nome", JOptionPane.INFORMATION_MESSAGE);
TfPesquisa.grabFocus();
} else {
funcionario.getPessoafis().setNome(TfPesquisa.getText());
preenche.PreencherJtable(TbPesquisa, funcionario.consultanome());
}
break;
}
case 3: {
if (TfPesquisa.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Digite a função do funcionário que deseja consultar!", "Digite a função", JOptionPane.INFORMATION_MESSAGE);
TfPesquisa.grabFocus();
} else {
funcionario.setFuncao(TfPesquisa.getText());
preenche.PreencherJtable(TbPesquisa, funcionario.consultafuncao());
}
break;
}
case 4: {
if (TfPesquisa.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Digite o CPF do funcionário que deseja consultar!", "Digite o CPF", JOptionPane.INFORMATION_MESSAGE);
TfPesquisa.grabFocus();
} else {
funcionario.getPessoafis().setCpf(TfPesquisa.getText());
preenche.PreencherJtable(TbPesquisa, funcionario.consultaCPF());
}
break;
}
}
}//GEN-LAST:event_BtPesquisaActionPerformed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.