index
int64
1
4.83k
file_id
stringlengths
5
9
content
stringlengths
167
16.5k
repo
stringlengths
7
82
path
stringlengths
8
164
token_length
int64
72
4.23k
original_comment
stringlengths
11
2.7k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
142
16.5k
Inclusion
stringclasses
4 values
file-tokens-Qwen/Qwen2-7B
int64
64
3.93k
comment-tokens-Qwen/Qwen2-7B
int64
4
972
file-tokens-bigcode/starcoder2-7b
int64
74
3.98k
comment-tokens-bigcode/starcoder2-7b
int64
4
959
file-tokens-google/codegemma-7b
int64
56
3.99k
comment-tokens-google/codegemma-7b
int64
3
953
file-tokens-ibm-granite/granite-8b-code-base
int64
74
3.98k
comment-tokens-ibm-granite/granite-8b-code-base
int64
4
959
file-tokens-meta-llama/CodeLlama-7b-hf
int64
77
4.12k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
1.11k
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
4,346
88675_1
import java.util.ArrayList; import java.util.List; public class Welt { List<Zelle> aktuelleLebendePopulation = new ArrayList<Zelle>(); public Welt() { } public void tick() { final List<Zelle> naechsteGeneration = new ArrayList<Zelle>(); for (final Zelle zelle : aktuelleLebendePopulation) { zelle.ifHatWenigerAlsZweiLebendeNachbarn(aktuelleLebendePopulation, new Closure() { @Override public void execute(Object... args) { // Regel 1 > stirbt zelle.stirb(); } }); zelle.ifHatMehrAlsDreiLebendeNachbarn(aktuelleLebendePopulation, new Closure() { @Override public void execute(Object... args) { zelle.stirb(); } }); zelle.temp(naechsteGeneration); zelle.NachbarKoordinaten(new Closure() { @Override public void execute(Object... args) { // 8-) final Position position = (Position) args[0]; ifTotAt(position, new Closure() { @Override public void execute(Object... args) { // Zelle an koordinaten ist TOT final Zelle heisenCell = new Zelle(position); heisenCell.ifHatDreiLebendeNachbarn(aktuelleLebendePopulation, new Closure() { @Override public void execute(Object... args) { heisenCell.temp(naechsteGeneration); } }); } }); } }); // für jeden Nachbar, // wenn dieser tot ist, // dann stelle Anzahl der lebenden Nachbarn in der // aktuellen lebenden Population des toten Nachbarn fest // wenn Anzahl == 3 // dann erwecke den Nachbarn von den Toten (Zombies) } aktuelleLebendePopulation = naechsteGeneration; } protected void ifTotAt(Position koordinaten, Closure closure) { ifTotAt(koordinaten.x, koordinaten.y, closure); } public void addZelle(Zelle zelle) { aktuelleLebendePopulation.add(zelle); } public void ifTotAt(int x, int y, Closure closure) { final BooleanHolder lebendeZelleAtXY = new BooleanHolder(); for (final Zelle zelle : aktuelleLebendePopulation) { zelle.locatedAt(x, y, new Closure() { @Override public void execute(Object... args) { lebendeZelleAtXY.setTrue(); } }); } lebendeZelleAtXY.ifFalse(closure); } public static class BooleanHolder { boolean value = false; public void setTrue() { value = true; } public void ifFalse(Closure closure) { if (value == false) closure.execute(); } } }
socramob/tell-dont-ask
src/Welt.java
869
// Zelle an koordinaten ist TOT
line_comment
nl
import java.util.ArrayList; import java.util.List; public class Welt { List<Zelle> aktuelleLebendePopulation = new ArrayList<Zelle>(); public Welt() { } public void tick() { final List<Zelle> naechsteGeneration = new ArrayList<Zelle>(); for (final Zelle zelle : aktuelleLebendePopulation) { zelle.ifHatWenigerAlsZweiLebendeNachbarn(aktuelleLebendePopulation, new Closure() { @Override public void execute(Object... args) { // Regel 1 > stirbt zelle.stirb(); } }); zelle.ifHatMehrAlsDreiLebendeNachbarn(aktuelleLebendePopulation, new Closure() { @Override public void execute(Object... args) { zelle.stirb(); } }); zelle.temp(naechsteGeneration); zelle.NachbarKoordinaten(new Closure() { @Override public void execute(Object... args) { // 8-) final Position position = (Position) args[0]; ifTotAt(position, new Closure() { @Override public void execute(Object... args) { // Zelle an<SUF> final Zelle heisenCell = new Zelle(position); heisenCell.ifHatDreiLebendeNachbarn(aktuelleLebendePopulation, new Closure() { @Override public void execute(Object... args) { heisenCell.temp(naechsteGeneration); } }); } }); } }); // für jeden Nachbar, // wenn dieser tot ist, // dann stelle Anzahl der lebenden Nachbarn in der // aktuellen lebenden Population des toten Nachbarn fest // wenn Anzahl == 3 // dann erwecke den Nachbarn von den Toten (Zombies) } aktuelleLebendePopulation = naechsteGeneration; } protected void ifTotAt(Position koordinaten, Closure closure) { ifTotAt(koordinaten.x, koordinaten.y, closure); } public void addZelle(Zelle zelle) { aktuelleLebendePopulation.add(zelle); } public void ifTotAt(int x, int y, Closure closure) { final BooleanHolder lebendeZelleAtXY = new BooleanHolder(); for (final Zelle zelle : aktuelleLebendePopulation) { zelle.locatedAt(x, y, new Closure() { @Override public void execute(Object... args) { lebendeZelleAtXY.setTrue(); } }); } lebendeZelleAtXY.ifFalse(closure); } public static class BooleanHolder { boolean value = false; public void setTrue() { value = true; } public void ifFalse(Closure closure) { if (value == false) closure.execute(); } } }
False
673
10
726
10
714
7
726
10
839
10
false
false
false
false
false
true
3,035
17324_1
/** Cryptix General Licence Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000 The Cryptix Foundation Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE CRYPTIX FOUNDATION LIMITED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Copyright (C) 2000 The Cryptix Foundation Limited. All rights reserved. * * Use, modification, copying and distribution of this software is subject to * the terms and conditions of the Cryptix General Licence. You should have * received a copy of the Cryptix General Licence along with this library; * if not, you can download a copy from http://www.cryptix.org/ . */ package freenet.crypt; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.tanukisoftware.wrapper.WrapperManager; import freenet.node.Node; import freenet.node.NodeInitException; import freenet.support.Logger; import freenet.support.io.Closer; /** * @author Jeroen C. van Gelderen (gelderen@cryptix.org) */ public class SHA256 { /** Size (in bytes) of this hash */ private static final int HASH_SIZE = 32; private static final Queue<SoftReference<MessageDigest>> digests = new ConcurrentLinkedQueue<>(); /** * It won't reset the Message Digest for you! * @param InputStream * @param MessageDigest * @return * @throws IOException */ public static void hash(InputStream is, MessageDigest md) throws IOException { try { byte[] buf = new byte[4096]; int readBytes = is.read(buf); while(readBytes > -1) { md.update(buf, 0, readBytes); readBytes = is.read(buf); } is.close(); } finally { Closer.close(is); } } private static final Provider mdProvider = Util.mdProviders.get("SHA-256"); /** * Create a new SHA-256 MessageDigest * Either succeed or stop the node. */ public static MessageDigest getMessageDigest() { try { SoftReference<MessageDigest> item = null; while (((item = digests.poll()) != null)) { MessageDigest md = item.get(); if (md != null) { return md; } } return MessageDigest.getInstance("SHA-256", mdProvider); } catch(NoSuchAlgorithmException e2) { //TODO: maybe we should point to a HOWTO for freejvms Logger.error(Node.class, "Check your JVM settings especially the JCE!" + e2); System.err.println("Check your JVM settings especially the JCE!" + e2); e2.printStackTrace(); } WrapperManager.stop(NodeInitException.EXIT_CRAPPY_JVM); throw new RuntimeException(); } /** * Return a MessageDigest to the pool. * Must be SHA-256 ! */ public static void returnMessageDigest(MessageDigest md256) { if(md256 == null) return; String algo = md256.getAlgorithm(); if(!(algo.equals("SHA-256") || algo.equals("SHA256"))) throw new IllegalArgumentException("Should be SHA-256 but is " + algo); md256.reset(); digests.add(new SoftReference<>(md256)); } public static byte[] digest(byte[] data) { MessageDigest md = null; try { md = getMessageDigest(); return md.digest(data); } finally { returnMessageDigest(md); } } public static int getDigestLength() { return HASH_SIZE; } }
hyphanet/fred
src/freenet/crypt/SHA256.java
1,440
/** * @author Jeroen C. van Gelderen (gelderen@cryptix.org) */
block_comment
nl
/** Cryptix General Licence Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000 The Cryptix Foundation Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE CRYPTIX FOUNDATION LIMITED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Copyright (C) 2000 The Cryptix Foundation Limited. All rights reserved. * * Use, modification, copying and distribution of this software is subject to * the terms and conditions of the Cryptix General Licence. You should have * received a copy of the Cryptix General Licence along with this library; * if not, you can download a copy from http://www.cryptix.org/ . */ package freenet.crypt; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.tanukisoftware.wrapper.WrapperManager; import freenet.node.Node; import freenet.node.NodeInitException; import freenet.support.Logger; import freenet.support.io.Closer; /** * @author Jeroen<SUF>*/ public class SHA256 { /** Size (in bytes) of this hash */ private static final int HASH_SIZE = 32; private static final Queue<SoftReference<MessageDigest>> digests = new ConcurrentLinkedQueue<>(); /** * It won't reset the Message Digest for you! * @param InputStream * @param MessageDigest * @return * @throws IOException */ public static void hash(InputStream is, MessageDigest md) throws IOException { try { byte[] buf = new byte[4096]; int readBytes = is.read(buf); while(readBytes > -1) { md.update(buf, 0, readBytes); readBytes = is.read(buf); } is.close(); } finally { Closer.close(is); } } private static final Provider mdProvider = Util.mdProviders.get("SHA-256"); /** * Create a new SHA-256 MessageDigest * Either succeed or stop the node. */ public static MessageDigest getMessageDigest() { try { SoftReference<MessageDigest> item = null; while (((item = digests.poll()) != null)) { MessageDigest md = item.get(); if (md != null) { return md; } } return MessageDigest.getInstance("SHA-256", mdProvider); } catch(NoSuchAlgorithmException e2) { //TODO: maybe we should point to a HOWTO for freejvms Logger.error(Node.class, "Check your JVM settings especially the JCE!" + e2); System.err.println("Check your JVM settings especially the JCE!" + e2); e2.printStackTrace(); } WrapperManager.stop(NodeInitException.EXIT_CRAPPY_JVM); throw new RuntimeException(); } /** * Return a MessageDigest to the pool. * Must be SHA-256 ! */ public static void returnMessageDigest(MessageDigest md256) { if(md256 == null) return; String algo = md256.getAlgorithm(); if(!(algo.equals("SHA-256") || algo.equals("SHA256"))) throw new IllegalArgumentException("Should be SHA-256 but is " + algo); md256.reset(); digests.add(new SoftReference<>(md256)); } public static byte[] digest(byte[] data) { MessageDigest md = null; try { md = getMessageDigest(); return md.digest(data); } finally { returnMessageDigest(md); } } public static int getDigestLength() { return HASH_SIZE; } }
False
1,087
23
1,266
28
1,283
25
1,266
28
1,615
28
false
false
false
false
false
true
3,092
130982_6
package ij.gui; import ij.ImageJ; import ij.IJ; import ij.Prefs; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; /** This class, based on Joachim Walter's Image5D package, adds "c", "z" labels and play-pause icons (T) to the stack and hyperstacks dimension sliders. * @author Joachim Walter */ public class ScrollbarWithLabel extends Panel implements Adjustable, AdjustmentListener { Scrollbar bar; private Icon icon; private StackWindow stackWindow; transient AdjustmentListener adjustmentListener; public ScrollbarWithLabel() { } public ScrollbarWithLabel(StackWindow stackWindow, int value, int visible, int minimum, int maximum, char label) { super(new BorderLayout(2, 0)); this.stackWindow = stackWindow; bar = new Scrollbar(Scrollbar.HORIZONTAL, value, visible, minimum, maximum); GUI.fixScrollbar(bar); icon = new Icon(label); add(icon, BorderLayout.WEST); add(bar, BorderLayout.CENTER); bar.addAdjustmentListener(this); addKeyListener(IJ.getInstance()); } /* (non-Javadoc) * @see java.awt.Component#getPreferredSize() */ public Dimension getPreferredSize() { Dimension dim = new Dimension(0,0); int width = bar.getPreferredSize().width; Dimension minSize = getMinimumSize(); if (width<minSize.width) width = minSize.width; int height = bar.getPreferredSize().height; int iconHeight = icon.getPreferredSize().height; if (iconHeight>height) height = iconHeight; dim = new Dimension(width, (int)(height)); return dim; } public Dimension getMinimumSize() { return new Dimension(80, 15); } /* Adds KeyListener also to all sub-components. */ public synchronized void addKeyListener(KeyListener l) { super.addKeyListener(l); bar.addKeyListener(l); } /* Removes KeyListener also from all sub-components. */ public synchronized void removeKeyListener(KeyListener l) { super.removeKeyListener(l); bar.removeKeyListener(l); } /* * Methods of the Adjustable interface */ public synchronized void addAdjustmentListener(AdjustmentListener l) { if (l == null) { return; } adjustmentListener = AWTEventMulticaster.add(adjustmentListener, l); } public int getBlockIncrement() { return bar.getBlockIncrement(); } public int getMaximum() { return bar.getMaximum(); } public int getMinimum() { return bar.getMinimum(); } public int getOrientation() { return bar.getOrientation(); } public int getUnitIncrement() { return bar.getUnitIncrement(); } public int getValue() { return bar.getValue(); } public int getVisibleAmount() { return bar.getVisibleAmount(); } public synchronized void removeAdjustmentListener(AdjustmentListener l) { if (l == null) { return; } adjustmentListener = AWTEventMulticaster.remove(adjustmentListener, l); } public void setBlockIncrement(int b) { bar.setBlockIncrement(b); } public void setMaximum(int max) { bar.setMaximum(max); } public void setMinimum(int min) { bar.setMinimum(min); } public void setUnitIncrement(int u) { bar.setUnitIncrement(u); } public void setValue(int v) { bar.setValue(v); } public void setVisibleAmount(int v) { bar.setVisibleAmount(v); } public void setFocusable(boolean focusable) { super.setFocusable(focusable); bar.setFocusable(focusable); } /* * Method of the AdjustmenListener interface. */ public void adjustmentValueChanged(AdjustmentEvent e) { if (bar != null && e.getSource() == bar) { AdjustmentEvent myE = new AdjustmentEvent(this, e.getID(), e.getAdjustmentType(), e.getValue(), e.getValueIsAdjusting()); AdjustmentListener listener = adjustmentListener; if (listener != null) { listener.adjustmentValueChanged(myE); } } } public void updatePlayPauseIcon() { icon.repaint(); } class Icon extends Canvas implements MouseListener { private final double SCALE = Prefs.getGuiScale(); private final int WIDTH = (int)(12*SCALE); private final int HEIGHT= (int)(14*SCALE); private BasicStroke stroke = new BasicStroke((float)(2*SCALE)); private char type; private Image image; public Icon(char type) { addMouseListener(this); addKeyListener(IJ.getInstance()); setSize(WIDTH, HEIGHT); this.type = type; } /** Overrides Component getPreferredSize(). */ public Dimension getPreferredSize() { return new Dimension(WIDTH, HEIGHT); } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, WIDTH, HEIGHT); Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (type=='t') drawPlayPauseButton(g2d); else drawLetter(g); } private void drawLetter(Graphics g) { Font font = ImageJ.SansSerif14; if (SCALE>1.0) font = font.deriveFont((float)(font.getSize()*SCALE)); g.setFont(font); g.setColor(Color.black); g.drawString(String.valueOf(type), (int)(2*SCALE), (int)(12*SCALE)); } private void drawPlayPauseButton(Graphics2D g) { if (stackWindow.getAnimate()) { g.setColor(Color.black); g.setStroke(stroke); int s3 = (int)(3*SCALE); int s8 = (int)(8*SCALE); int s11 = (int)(11*SCALE); g.drawLine(s3, s3, s3, s11); g.drawLine(s8, s3, s8, s11); } else { g.setColor(Color.darkGray); GeneralPath path = new GeneralPath(); path.moveTo(3f, 2f); path.lineTo(10f, 7f); path.lineTo(3f, 12f); path.lineTo(3f, 2f); if (SCALE>1.0) { AffineTransform at = new AffineTransform(); at.scale(SCALE, SCALE); path = new GeneralPath(at.createTransformedShape(path)); } g.fill(path); } } public void mousePressed(MouseEvent e) { if (type!='t') return; int flags = e.getModifiers(); if ((flags&(Event.ALT_MASK|Event.META_MASK|Event.CTRL_MASK))!=0) IJ.doCommand("Animation Options..."); else IJ.doCommand("Start Animation [\\]"); } public void mouseReleased(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} } // Icon class }
imagej/ImageJ
ij/gui/ScrollbarWithLabel.java
2,247
/** Overrides Component getPreferredSize(). */
block_comment
nl
package ij.gui; import ij.ImageJ; import ij.IJ; import ij.Prefs; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; /** This class, based on Joachim Walter's Image5D package, adds "c", "z" labels and play-pause icons (T) to the stack and hyperstacks dimension sliders. * @author Joachim Walter */ public class ScrollbarWithLabel extends Panel implements Adjustable, AdjustmentListener { Scrollbar bar; private Icon icon; private StackWindow stackWindow; transient AdjustmentListener adjustmentListener; public ScrollbarWithLabel() { } public ScrollbarWithLabel(StackWindow stackWindow, int value, int visible, int minimum, int maximum, char label) { super(new BorderLayout(2, 0)); this.stackWindow = stackWindow; bar = new Scrollbar(Scrollbar.HORIZONTAL, value, visible, minimum, maximum); GUI.fixScrollbar(bar); icon = new Icon(label); add(icon, BorderLayout.WEST); add(bar, BorderLayout.CENTER); bar.addAdjustmentListener(this); addKeyListener(IJ.getInstance()); } /* (non-Javadoc) * @see java.awt.Component#getPreferredSize() */ public Dimension getPreferredSize() { Dimension dim = new Dimension(0,0); int width = bar.getPreferredSize().width; Dimension minSize = getMinimumSize(); if (width<minSize.width) width = minSize.width; int height = bar.getPreferredSize().height; int iconHeight = icon.getPreferredSize().height; if (iconHeight>height) height = iconHeight; dim = new Dimension(width, (int)(height)); return dim; } public Dimension getMinimumSize() { return new Dimension(80, 15); } /* Adds KeyListener also to all sub-components. */ public synchronized void addKeyListener(KeyListener l) { super.addKeyListener(l); bar.addKeyListener(l); } /* Removes KeyListener also from all sub-components. */ public synchronized void removeKeyListener(KeyListener l) { super.removeKeyListener(l); bar.removeKeyListener(l); } /* * Methods of the Adjustable interface */ public synchronized void addAdjustmentListener(AdjustmentListener l) { if (l == null) { return; } adjustmentListener = AWTEventMulticaster.add(adjustmentListener, l); } public int getBlockIncrement() { return bar.getBlockIncrement(); } public int getMaximum() { return bar.getMaximum(); } public int getMinimum() { return bar.getMinimum(); } public int getOrientation() { return bar.getOrientation(); } public int getUnitIncrement() { return bar.getUnitIncrement(); } public int getValue() { return bar.getValue(); } public int getVisibleAmount() { return bar.getVisibleAmount(); } public synchronized void removeAdjustmentListener(AdjustmentListener l) { if (l == null) { return; } adjustmentListener = AWTEventMulticaster.remove(adjustmentListener, l); } public void setBlockIncrement(int b) { bar.setBlockIncrement(b); } public void setMaximum(int max) { bar.setMaximum(max); } public void setMinimum(int min) { bar.setMinimum(min); } public void setUnitIncrement(int u) { bar.setUnitIncrement(u); } public void setValue(int v) { bar.setValue(v); } public void setVisibleAmount(int v) { bar.setVisibleAmount(v); } public void setFocusable(boolean focusable) { super.setFocusable(focusable); bar.setFocusable(focusable); } /* * Method of the AdjustmenListener interface. */ public void adjustmentValueChanged(AdjustmentEvent e) { if (bar != null && e.getSource() == bar) { AdjustmentEvent myE = new AdjustmentEvent(this, e.getID(), e.getAdjustmentType(), e.getValue(), e.getValueIsAdjusting()); AdjustmentListener listener = adjustmentListener; if (listener != null) { listener.adjustmentValueChanged(myE); } } } public void updatePlayPauseIcon() { icon.repaint(); } class Icon extends Canvas implements MouseListener { private final double SCALE = Prefs.getGuiScale(); private final int WIDTH = (int)(12*SCALE); private final int HEIGHT= (int)(14*SCALE); private BasicStroke stroke = new BasicStroke((float)(2*SCALE)); private char type; private Image image; public Icon(char type) { addMouseListener(this); addKeyListener(IJ.getInstance()); setSize(WIDTH, HEIGHT); this.type = type; } /** Overrides Component getPreferredSize().<SUF>*/ public Dimension getPreferredSize() { return new Dimension(WIDTH, HEIGHT); } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, WIDTH, HEIGHT); Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (type=='t') drawPlayPauseButton(g2d); else drawLetter(g); } private void drawLetter(Graphics g) { Font font = ImageJ.SansSerif14; if (SCALE>1.0) font = font.deriveFont((float)(font.getSize()*SCALE)); g.setFont(font); g.setColor(Color.black); g.drawString(String.valueOf(type), (int)(2*SCALE), (int)(12*SCALE)); } private void drawPlayPauseButton(Graphics2D g) { if (stackWindow.getAnimate()) { g.setColor(Color.black); g.setStroke(stroke); int s3 = (int)(3*SCALE); int s8 = (int)(8*SCALE); int s11 = (int)(11*SCALE); g.drawLine(s3, s3, s3, s11); g.drawLine(s8, s3, s8, s11); } else { g.setColor(Color.darkGray); GeneralPath path = new GeneralPath(); path.moveTo(3f, 2f); path.lineTo(10f, 7f); path.lineTo(3f, 12f); path.lineTo(3f, 2f); if (SCALE>1.0) { AffineTransform at = new AffineTransform(); at.scale(SCALE, SCALE); path = new GeneralPath(at.createTransformedShape(path)); } g.fill(path); } } public void mousePressed(MouseEvent e) { if (type!='t') return; int flags = e.getModifiers(); if ((flags&(Event.ALT_MASK|Event.META_MASK|Event.CTRL_MASK))!=0) IJ.doCommand("Animation Options..."); else IJ.doCommand("Start Animation [\\]"); } public void mouseReleased(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} } // Icon class }
False
1,615
7
1,947
7
1,958
8
1,947
7
2,458
10
false
false
false
false
false
true
799
108464_13
package IPSEN2.models.address; /** * Created by mdbaz on 21-09-2015. */ public class Address { private int addressID; private String street; private String houseNumber; //Huisnummer is een String ivm huisnummers die letters erachter kunnen hebben private String zipCode; private String city; private String country; /** * Instantiates a new Address. * * @param addressID the address id */ public Address(int addressID) { this.addressID = addressID; this.street = null; this.houseNumber = null; this.zipCode = null; this.city = null; this.country = null; } /** * Instantiates a new Address. * * @param addressID the address id * @param street the street * @param houseNumber the house number * @param zipCode the zip code * @param city the city * @param country the country */ public Address(int addressID, String street, String houseNumber, String zipCode, String city, String country) { this.addressID = addressID; this.street = street; this.houseNumber = houseNumber; this.zipCode = zipCode; this.city = city; this.country = country; } /** * Check if only id boolean. * * @return the boolean */ public boolean checkIfOnlyID() { return street == null && houseNumber == null && zipCode == null && city == null && country == null; } /** * Gets street. * * @return the street */ //Getters public String getStreet() { return street; } /** * Gets house number. * * @return the house number */ public String getHouseNumber() { return houseNumber; } /** * Gets zip code. * * @return the zip code */ public String getZipCode() { return zipCode; } /** * Gets city. * * @return the city */ public String getCity() { return city; } /** * Gets address id. * * @return the address id */ public int getAddressID() { return addressID; } /** * Gets country. * * @return the country */ public String getCountry() { return country; } /** * Sets street. * * @param street the street */ //Setters public void setStreet(String street) { this.street = street; } /** * Sets house number. * * @param houseNumber the house number */ public void setHouseNumber(String houseNumber) { this.houseNumber = houseNumber; } /** * Sets zip code. * * @param zipCode the zip code */ public void setZipCode(String zipCode) { this.zipCode = zipCode; } /** * Sets city. * * @param city the city */ public void setCity(String city) { this.city = city; } /** * Sets address id. * * @param addressID the address id */ public void setAddressID(int addressID) { this.addressID = addressID; } /** * Sets country. * * @param country the country */ public void setCountry(String country) { this.country = country; } }
JamieKalloe/Lions-Club-Wijnfestijn
src/IPSEN2/models/address/Address.java
966
/** * Sets zip code. * * @param zipCode the zip code */
block_comment
nl
package IPSEN2.models.address; /** * Created by mdbaz on 21-09-2015. */ public class Address { private int addressID; private String street; private String houseNumber; //Huisnummer is een String ivm huisnummers die letters erachter kunnen hebben private String zipCode; private String city; private String country; /** * Instantiates a new Address. * * @param addressID the address id */ public Address(int addressID) { this.addressID = addressID; this.street = null; this.houseNumber = null; this.zipCode = null; this.city = null; this.country = null; } /** * Instantiates a new Address. * * @param addressID the address id * @param street the street * @param houseNumber the house number * @param zipCode the zip code * @param city the city * @param country the country */ public Address(int addressID, String street, String houseNumber, String zipCode, String city, String country) { this.addressID = addressID; this.street = street; this.houseNumber = houseNumber; this.zipCode = zipCode; this.city = city; this.country = country; } /** * Check if only id boolean. * * @return the boolean */ public boolean checkIfOnlyID() { return street == null && houseNumber == null && zipCode == null && city == null && country == null; } /** * Gets street. * * @return the street */ //Getters public String getStreet() { return street; } /** * Gets house number. * * @return the house number */ public String getHouseNumber() { return houseNumber; } /** * Gets zip code. * * @return the zip code */ public String getZipCode() { return zipCode; } /** * Gets city. * * @return the city */ public String getCity() { return city; } /** * Gets address id. * * @return the address id */ public int getAddressID() { return addressID; } /** * Gets country. * * @return the country */ public String getCountry() { return country; } /** * Sets street. * * @param street the street */ //Setters public void setStreet(String street) { this.street = street; } /** * Sets house number. * * @param houseNumber the house number */ public void setHouseNumber(String houseNumber) { this.houseNumber = houseNumber; } /** * Sets zip code.<SUF>*/ public void setZipCode(String zipCode) { this.zipCode = zipCode; } /** * Sets city. * * @param city the city */ public void setCity(String city) { this.city = city; } /** * Sets address id. * * @param addressID the address id */ public void setAddressID(int addressID) { this.addressID = addressID; } /** * Sets country. * * @param country the country */ public void setCountry(String country) { this.country = country; } }
False
798
21
820
20
948
24
820
20
993
25
false
false
false
false
false
true
90
111127_24
package main.java.Accessor; import main.java.Presentation.Presentation; import main.java.Slide.*; import java.util.Vector; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.FileWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; public class XMLAccessor extends Accessor { // Api om te gebruiken protected static final String DEFAULT_API_TO_USE = "dom"; // XML tags protected static final String SHOWTITLE = "showtitle"; protected static final String SLIDETITLE = "title"; protected static final String SLIDE = "slide"; protected static final String ITEM = "item"; protected static final String LEVEL = "level"; protected static final String KIND = "kind"; protected static final String TEXT = "text"; protected static final String IMAGE = "image"; // Error berichten protected static final String PCE = "Parser Configuration Exception"; protected static final String UNKNOWNTYPE = "Unknown Element type"; protected static final String NFE = "Number Format Exception"; // Geeft de titel van een element terug private String getTitle(Element element, String tagName) { NodeList titles = element.getElementsByTagName(tagName); return titles.item(0).getTextContent(); } // Laad een bestand @Override public void loadFile(Presentation presentation, String filename) throws IOException { // Variabelen int slideNumber; int itemNumber; int maxSlides = 0; int maxItems = 0; try { // Maakt een document builder DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // Maakt een JDOM document Document document = builder.parse(new File(filename)); // Haalt de root element op Element documentElement = document.getDocumentElement(); // Haalt de titel van de presentatie op presentation.setTitle(this.getTitle(documentElement, SHOWTITLE)); // Haalt de slides op NodeList slides = documentElement.getElementsByTagName(SLIDE); maxSlides = slides.getLength(); // Voor elke slide in de presentatie wordt de slide geladen for (slideNumber = 0; slideNumber < maxSlides; slideNumber++) { // Haalt de slide op Element xmlSlide = (Element) slides.item(slideNumber); Slide slide = new Slide(); slide.setTitle(this.getTitle(xmlSlide, SLIDETITLE)); presentation.append(slide); // Haalt de items op NodeList slideItems = xmlSlide.getElementsByTagName(ITEM); maxItems = slideItems.getLength(); // Voor elk item in de slide wordt het item geladen for (itemNumber = 0; itemNumber < maxItems; itemNumber++) { Element item = (Element) slideItems.item(itemNumber); this.loadSlideItem(slide, item); } } } catch (IOException ioException) { System.err.println(ioException.toString()); } catch (SAXException saxException) { System.err.println(saxException.getMessage()); } catch (ParserConfigurationException parcerConfigurationException) { System.err.println(PCE); } } // Laad een slide item protected void loadSlideItem(Slide slide, Element item) { // Standaard level is 1 int level = 1; // Haalt de attributen op NamedNodeMap attributes = item.getAttributes(); String leveltext = attributes.getNamedItem(LEVEL).getTextContent(); // Als er een level is, wordt deze geparsed if (leveltext != null) { try { level = Integer.parseInt(leveltext); } catch (NumberFormatException numberFormatException) { System.err.println(NFE); } } // Haalt het type op String type = attributes.getNamedItem(KIND).getTextContent(); if (TEXT.equals(type)) { slide.append(new TextItem(level, item.getTextContent())); } else { // Als het type een afbeelding is, wordt deze toegevoegd if (IMAGE.equals(type)) { slide.append(new BitmapItem(level, item.getTextContent())); } else { System.err.println(UNKNOWNTYPE); } } } // Slaat een presentatie op naar het gegeven bestand @Override public void saveFile(Presentation presentation, String filename) throws IOException { // Maakt een printwriter PrintWriter out = new PrintWriter(new FileWriter(filename)); // Schrijft de XML header out.println("<?xml version=\"1.0\"?>"); out.println("<!DOCTYPE presentation SYSTEM \"jabberpoint.dtd\">"); // Schrijft de presentatie out.println("<presentation>"); out.print("<showtitle>"); out.print(presentation.getTitle()); out.println("</showtitle>"); // Voor elke slide in de presentatie wordt de slide opgeslagen for (int slideNumber = 0; slideNumber < presentation.getSize(); slideNumber++) { // Haalt de slide op Slide slide = presentation.getSlide(slideNumber); // Schrijft de slide out.println("<slide>"); out.println("<title>" + slide.getTitle() + "</title>"); // Voor elk item in de slide wordt het item opgeslagen Vector<SlideItem> slideItems = slide.getSlideItems(); for (int itemNumber = 0; itemNumber < slideItems.size(); itemNumber++) { // Haalt het item op SlideItem slideItem = (SlideItem) slideItems.elementAt(itemNumber); out.print("<item kind="); // Als het item een tekst item is, wordt deze opgeslagen if (slideItem instanceof TextItem) { out.print("\"text\" level=\"" + slideItem.getLevel() + "\">"); out.print(((TextItem) slideItem).getText()); } else { // Als het item een afbeelding is, wordt deze opgeslagen if (slideItem instanceof BitmapItem) { out.print("\"image\" level=\"" + slideItem.getLevel() + "\">"); out.print(((BitmapItem) slideItem).getName()); } else { System.out.println("Ignoring " + slideItem); } } out.println("</item>"); } out.println("</slide>"); } out.println("</presentation>"); out.close(); } }
AmanTrechsel/JabberPoint
src/main/java/Accessor/XMLAccessor.java
1,921
// Schrijft de slide
line_comment
nl
package main.java.Accessor; import main.java.Presentation.Presentation; import main.java.Slide.*; import java.util.Vector; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.FileWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; public class XMLAccessor extends Accessor { // Api om te gebruiken protected static final String DEFAULT_API_TO_USE = "dom"; // XML tags protected static final String SHOWTITLE = "showtitle"; protected static final String SLIDETITLE = "title"; protected static final String SLIDE = "slide"; protected static final String ITEM = "item"; protected static final String LEVEL = "level"; protected static final String KIND = "kind"; protected static final String TEXT = "text"; protected static final String IMAGE = "image"; // Error berichten protected static final String PCE = "Parser Configuration Exception"; protected static final String UNKNOWNTYPE = "Unknown Element type"; protected static final String NFE = "Number Format Exception"; // Geeft de titel van een element terug private String getTitle(Element element, String tagName) { NodeList titles = element.getElementsByTagName(tagName); return titles.item(0).getTextContent(); } // Laad een bestand @Override public void loadFile(Presentation presentation, String filename) throws IOException { // Variabelen int slideNumber; int itemNumber; int maxSlides = 0; int maxItems = 0; try { // Maakt een document builder DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // Maakt een JDOM document Document document = builder.parse(new File(filename)); // Haalt de root element op Element documentElement = document.getDocumentElement(); // Haalt de titel van de presentatie op presentation.setTitle(this.getTitle(documentElement, SHOWTITLE)); // Haalt de slides op NodeList slides = documentElement.getElementsByTagName(SLIDE); maxSlides = slides.getLength(); // Voor elke slide in de presentatie wordt de slide geladen for (slideNumber = 0; slideNumber < maxSlides; slideNumber++) { // Haalt de slide op Element xmlSlide = (Element) slides.item(slideNumber); Slide slide = new Slide(); slide.setTitle(this.getTitle(xmlSlide, SLIDETITLE)); presentation.append(slide); // Haalt de items op NodeList slideItems = xmlSlide.getElementsByTagName(ITEM); maxItems = slideItems.getLength(); // Voor elk item in de slide wordt het item geladen for (itemNumber = 0; itemNumber < maxItems; itemNumber++) { Element item = (Element) slideItems.item(itemNumber); this.loadSlideItem(slide, item); } } } catch (IOException ioException) { System.err.println(ioException.toString()); } catch (SAXException saxException) { System.err.println(saxException.getMessage()); } catch (ParserConfigurationException parcerConfigurationException) { System.err.println(PCE); } } // Laad een slide item protected void loadSlideItem(Slide slide, Element item) { // Standaard level is 1 int level = 1; // Haalt de attributen op NamedNodeMap attributes = item.getAttributes(); String leveltext = attributes.getNamedItem(LEVEL).getTextContent(); // Als er een level is, wordt deze geparsed if (leveltext != null) { try { level = Integer.parseInt(leveltext); } catch (NumberFormatException numberFormatException) { System.err.println(NFE); } } // Haalt het type op String type = attributes.getNamedItem(KIND).getTextContent(); if (TEXT.equals(type)) { slide.append(new TextItem(level, item.getTextContent())); } else { // Als het type een afbeelding is, wordt deze toegevoegd if (IMAGE.equals(type)) { slide.append(new BitmapItem(level, item.getTextContent())); } else { System.err.println(UNKNOWNTYPE); } } } // Slaat een presentatie op naar het gegeven bestand @Override public void saveFile(Presentation presentation, String filename) throws IOException { // Maakt een printwriter PrintWriter out = new PrintWriter(new FileWriter(filename)); // Schrijft de XML header out.println("<?xml version=\"1.0\"?>"); out.println("<!DOCTYPE presentation SYSTEM \"jabberpoint.dtd\">"); // Schrijft de presentatie out.println("<presentation>"); out.print("<showtitle>"); out.print(presentation.getTitle()); out.println("</showtitle>"); // Voor elke slide in de presentatie wordt de slide opgeslagen for (int slideNumber = 0; slideNumber < presentation.getSize(); slideNumber++) { // Haalt de slide op Slide slide = presentation.getSlide(slideNumber); // Schrijft de<SUF> out.println("<slide>"); out.println("<title>" + slide.getTitle() + "</title>"); // Voor elk item in de slide wordt het item opgeslagen Vector<SlideItem> slideItems = slide.getSlideItems(); for (int itemNumber = 0; itemNumber < slideItems.size(); itemNumber++) { // Haalt het item op SlideItem slideItem = (SlideItem) slideItems.elementAt(itemNumber); out.print("<item kind="); // Als het item een tekst item is, wordt deze opgeslagen if (slideItem instanceof TextItem) { out.print("\"text\" level=\"" + slideItem.getLevel() + "\">"); out.print(((TextItem) slideItem).getText()); } else { // Als het item een afbeelding is, wordt deze opgeslagen if (slideItem instanceof BitmapItem) { out.print("\"image\" level=\"" + slideItem.getLevel() + "\">"); out.print(((BitmapItem) slideItem).getName()); } else { System.out.println("Ignoring " + slideItem); } } out.println("</item>"); } out.println("</slide>"); } out.println("</presentation>"); out.close(); } }
True
1,506
6
1,745
6
1,699
6
1,745
6
2,146
6
false
false
false
false
false
true
836
37543_14
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package org.jetbrains.kotlin.js.backend; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import java.util.Collections; import java.util.Set; /** * Determines whether or not a particular string is a JavaScript keyword or not. */ public class JsReservedIdentifiers { public static final Set<String> reservedGlobalSymbols; static { String[] commonBuiltins = new String[] { // 15.1.1 Value Properties of the Global Object "NaN", "Infinity", "undefined", // 15.1.2 Function Properties of the Global Object "eval", "parseInt", "parseFloat", "isNan", "isFinite", // 15.1.3 URI Handling Function Properties "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", // 15.1.4 Constructor Properties of the Global Object "Object", "Function", "Array", "String", "Boolean", "Number", "Date", "RegExp", "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", // 15.1.5 Other Properties of the Global Object "Math", // 10.1.6 Activation Object "arguments", // B.2 Additional Properties (non-normative) "escape", "unescape", // Window props (https://developer.mozilla.org/en/DOM/window) "applicationCache", "closed", "Components", "content", "controllers", "crypto", "defaultStatus", "dialogArguments", "directories", "document", "frameElement", "frames", "fullScreen", "globalStorage", "history", "innerHeight", "innerWidth", "length", "location", "locationbar", "localStorage", "menubar", "mozInnerScreenX", "mozInnerScreenY", "mozScreenPixelsPerCssPixel", "name", "navigator", "opener", "outerHeight", "outerWidth", "pageXOffset", "pageYOffset", "parent", "personalbar", "pkcs11", "returnValue", "screen", "scrollbars", "scrollMaxX", "scrollMaxY", "self", "sessionStorage", "sidebar", "status", "statusbar", "toolbar", "top", "window", // Window methods (https://developer.mozilla.org/en/DOM/window) "alert", "addEventListener", "atob", "back", "blur", "btoa", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "disableExternalCapture", "dispatchEvent", "dump", "enableExternalCapture", "escape", "find", "focus", "forward", "GeckoActiveXObject", "getAttention", "getAttentionWithCycleCount", "getComputedStyle", "getSelection", "home", "maximize", "minimize", "moveBy", "moveTo", "open", "openDialog", "postMessage", "print", "prompt", "QueryInterface", "releaseEvents", "removeEventListener", "resizeBy", "resizeTo", "restore", "routeEvent", "scroll", "scrollBy", "scrollByLines", "scrollByPages", "scrollTo", "setInterval", "setResizeable", "setTimeout", "showModalDialog", "sizeToContent", "stop", "uuescape", "updateCommands", "XPCNativeWrapper", "XPCSafeJSOjbectWrapper", // Mozilla Window event handlers, same cite "onabort", "onbeforeunload", "onchange", "onclick", "onclose", "oncontextmenu", "ondragdrop", "onerror", "onfocus", "onhashchange", "onkeydown", "onkeypress", "onkeyup", "onload", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmozorientation", "onpaint", "onreset", "onresize", "onscroll", "onselect", "onsubmit", "onunload", // Safari Web Content Guide // http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/SafariWebContent.pdf // WebKit Window member data, from WebKit DOM Reference // (http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/WebKitDOMRef/DOMWindow_idl/Classes/DOMWindow/index.html) // TODO(fredsa) Many, many more functions and member data to add "ontouchcancel", "ontouchend", "ontouchmove", "ontouchstart", "ongesturestart", "ongesturechange", "ongestureend", // extra window methods "uneval", // keywords https://developer.mozilla.org/en/New_in_JavaScript_1.7, // https://developer.mozilla.org/en/New_in_JavaScript_1.8.1 "getPrototypeOf", "let", "yield", // "future reserved words" "abstract", "int", "short", "boolean", "interface", "static", "byte", "long", "char", "final", "native", "synchronized", "float", "package", "throws", "goto", "private", "transient", "implements", "protected", "volatile", "double", "public", // IE methods // (http://msdn.microsoft.com/en-us/library/ms535873(VS.85).aspx#) "attachEvent", "clientInformation", "clipboardData", "createPopup", "dialogHeight", "dialogLeft", "dialogTop", "dialogWidth", "onafterprint", "onbeforedeactivate", "onbeforeprint", "oncontrolselect", "ondeactivate", "onhelp", "onresizeend", // Common browser-defined identifiers not defined in ECMAScript "event", "external", "Debug", "Enumerator", "Global", "Image", "ActiveXObject", "VBArray", "Components", // Functions commonly defined on Object "toString", "getClass", "constructor", "prototype", "valueOf", // Client-side JavaScript identifiers, which are needed for linkers // that don't ensure GWT's window != $wnd, document != $doc, etc. // Taken from the Rhino book, pg 715 "Anchor", "Applet", "Attr", "Canvas", "CanvasGradient", "CanvasPattern", "CanvasRenderingContext2D", "CDATASection", "CharacterData", "Comment", "CSS2Properties", "CSSRule", "CSSStyleSheet", "Document", "DocumentFragment", "DocumentType", "DOMException", "DOMImplementation", "DOMParser", "Element", "Event", "ExternalInterface", "FlashPlayer", "Form", "Frame", "History", "HTMLCollection", "HTMLDocument", "HTMLElement", "IFrame", "Image", "Input", "JSObject", "KeyEvent", "Link", "Location", "MimeType", "MouseEvent", "Navigator", "Node", "NodeList", "Option", "Plugin", "ProcessingInstruction", "Range", "RangeException", "Screen", "Select", "Table", "TableCell", "TableRow", "TableSelection", "Text", "TextArea", "UIEvent", "Window", "XMLHttpRequest", "XMLSerializer", "XPathException", "XPathResult", "XSLTProcessor", // These keywords trigger the loading of the java-plugin. For the // next-generation plugin, this results in starting a new Java process. "java", "Packages", "netscape", "sun", "JavaObject", "JavaClass", "JavaArray", "JavaMember", // GWT-defined identifiers "$wnd", "$doc", "$entry", "$moduleName", "$moduleBase", "$gwt_version", "$sessionId", // Identifiers used by JsStackEmulator; later set to obfuscatable "$stack", "$stackDepth", "$location", }; reservedGlobalSymbols = new ObjectOpenHashSet<>(commonBuiltins.length); Collections.addAll(reservedGlobalSymbols, commonBuiltins); } private JsReservedIdentifiers() { } }
JetBrains/kotlin
js/js.ast/src/org/jetbrains/kotlin/js/backend/JsReservedIdentifiers.java
2,301
// Safari Web Content Guide
line_comment
nl
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package org.jetbrains.kotlin.js.backend; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import java.util.Collections; import java.util.Set; /** * Determines whether or not a particular string is a JavaScript keyword or not. */ public class JsReservedIdentifiers { public static final Set<String> reservedGlobalSymbols; static { String[] commonBuiltins = new String[] { // 15.1.1 Value Properties of the Global Object "NaN", "Infinity", "undefined", // 15.1.2 Function Properties of the Global Object "eval", "parseInt", "parseFloat", "isNan", "isFinite", // 15.1.3 URI Handling Function Properties "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", // 15.1.4 Constructor Properties of the Global Object "Object", "Function", "Array", "String", "Boolean", "Number", "Date", "RegExp", "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", // 15.1.5 Other Properties of the Global Object "Math", // 10.1.6 Activation Object "arguments", // B.2 Additional Properties (non-normative) "escape", "unescape", // Window props (https://developer.mozilla.org/en/DOM/window) "applicationCache", "closed", "Components", "content", "controllers", "crypto", "defaultStatus", "dialogArguments", "directories", "document", "frameElement", "frames", "fullScreen", "globalStorage", "history", "innerHeight", "innerWidth", "length", "location", "locationbar", "localStorage", "menubar", "mozInnerScreenX", "mozInnerScreenY", "mozScreenPixelsPerCssPixel", "name", "navigator", "opener", "outerHeight", "outerWidth", "pageXOffset", "pageYOffset", "parent", "personalbar", "pkcs11", "returnValue", "screen", "scrollbars", "scrollMaxX", "scrollMaxY", "self", "sessionStorage", "sidebar", "status", "statusbar", "toolbar", "top", "window", // Window methods (https://developer.mozilla.org/en/DOM/window) "alert", "addEventListener", "atob", "back", "blur", "btoa", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "disableExternalCapture", "dispatchEvent", "dump", "enableExternalCapture", "escape", "find", "focus", "forward", "GeckoActiveXObject", "getAttention", "getAttentionWithCycleCount", "getComputedStyle", "getSelection", "home", "maximize", "minimize", "moveBy", "moveTo", "open", "openDialog", "postMessage", "print", "prompt", "QueryInterface", "releaseEvents", "removeEventListener", "resizeBy", "resizeTo", "restore", "routeEvent", "scroll", "scrollBy", "scrollByLines", "scrollByPages", "scrollTo", "setInterval", "setResizeable", "setTimeout", "showModalDialog", "sizeToContent", "stop", "uuescape", "updateCommands", "XPCNativeWrapper", "XPCSafeJSOjbectWrapper", // Mozilla Window event handlers, same cite "onabort", "onbeforeunload", "onchange", "onclick", "onclose", "oncontextmenu", "ondragdrop", "onerror", "onfocus", "onhashchange", "onkeydown", "onkeypress", "onkeyup", "onload", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmozorientation", "onpaint", "onreset", "onresize", "onscroll", "onselect", "onsubmit", "onunload", // Safari Web<SUF> // http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/SafariWebContent.pdf // WebKit Window member data, from WebKit DOM Reference // (http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/WebKitDOMRef/DOMWindow_idl/Classes/DOMWindow/index.html) // TODO(fredsa) Many, many more functions and member data to add "ontouchcancel", "ontouchend", "ontouchmove", "ontouchstart", "ongesturestart", "ongesturechange", "ongestureend", // extra window methods "uneval", // keywords https://developer.mozilla.org/en/New_in_JavaScript_1.7, // https://developer.mozilla.org/en/New_in_JavaScript_1.8.1 "getPrototypeOf", "let", "yield", // "future reserved words" "abstract", "int", "short", "boolean", "interface", "static", "byte", "long", "char", "final", "native", "synchronized", "float", "package", "throws", "goto", "private", "transient", "implements", "protected", "volatile", "double", "public", // IE methods // (http://msdn.microsoft.com/en-us/library/ms535873(VS.85).aspx#) "attachEvent", "clientInformation", "clipboardData", "createPopup", "dialogHeight", "dialogLeft", "dialogTop", "dialogWidth", "onafterprint", "onbeforedeactivate", "onbeforeprint", "oncontrolselect", "ondeactivate", "onhelp", "onresizeend", // Common browser-defined identifiers not defined in ECMAScript "event", "external", "Debug", "Enumerator", "Global", "Image", "ActiveXObject", "VBArray", "Components", // Functions commonly defined on Object "toString", "getClass", "constructor", "prototype", "valueOf", // Client-side JavaScript identifiers, which are needed for linkers // that don't ensure GWT's window != $wnd, document != $doc, etc. // Taken from the Rhino book, pg 715 "Anchor", "Applet", "Attr", "Canvas", "CanvasGradient", "CanvasPattern", "CanvasRenderingContext2D", "CDATASection", "CharacterData", "Comment", "CSS2Properties", "CSSRule", "CSSStyleSheet", "Document", "DocumentFragment", "DocumentType", "DOMException", "DOMImplementation", "DOMParser", "Element", "Event", "ExternalInterface", "FlashPlayer", "Form", "Frame", "History", "HTMLCollection", "HTMLDocument", "HTMLElement", "IFrame", "Image", "Input", "JSObject", "KeyEvent", "Link", "Location", "MimeType", "MouseEvent", "Navigator", "Node", "NodeList", "Option", "Plugin", "ProcessingInstruction", "Range", "RangeException", "Screen", "Select", "Table", "TableCell", "TableRow", "TableSelection", "Text", "TextArea", "UIEvent", "Window", "XMLHttpRequest", "XMLSerializer", "XPathException", "XPathResult", "XSLTProcessor", // These keywords trigger the loading of the java-plugin. For the // next-generation plugin, this results in starting a new Java process. "java", "Packages", "netscape", "sun", "JavaObject", "JavaClass", "JavaArray", "JavaMember", // GWT-defined identifiers "$wnd", "$doc", "$entry", "$moduleName", "$moduleBase", "$gwt_version", "$sessionId", // Identifiers used by JsStackEmulator; later set to obfuscatable "$stack", "$stackDepth", "$location", }; reservedGlobalSymbols = new ObjectOpenHashSet<>(commonBuiltins.length); Collections.addAll(reservedGlobalSymbols, commonBuiltins); } private JsReservedIdentifiers() { } }
False
1,840
5
1,878
5
1,973
5
1,878
5
2,189
5
false
false
false
false
false
true
3,663
154253_3
package state2vec; import java.util.ArrayList; import java.util.List; import org.deeplearning4j.models.sequencevectors.SequenceVectors; import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import data.StateImpl; import state2vec.KDTree.SearchResult; import util.HelpFunctions; public class KNNLookupTable<T extends SequenceElement> { private static final Logger logger = LoggerFactory.getLogger(KNNLookupTable.class); /** * Use this class to feed in the data to the RNN! */ private SequenceVectors<StateImpl> vectors; private int nearestNeighbours; private List<Double> weights; private INDArray columnMeans; private INDArray columnStds; private KDTree<INDArray> labelTree = null; private KDTree<String> vectorTree = null; public KNNLookupTable(SequenceVectors<StateImpl> vectors, int nearestNeighbours) { this.vectors = vectors; this.nearestNeighbours = nearestNeighbours; this.weights = calculateWeights(); calculateMeanStd(); } private void calculateMeanStd() { INDArray wordLabels = null; boolean first = true; int rowNb = 0; for(String word: vectors.getVocab().words()) { double[] label = HelpFunctions.parse(word); if(first) { wordLabels = Nd4j.create(vectors.getVocab().numWords(), label.length); first = false; } wordLabels.putRow(rowNb, Nd4j.create(label)); rowNb++; } this.columnMeans = wordLabels.mean(0); this.columnStds = wordLabels.std(0).addi(Nd4j.scalar(Nd4j.EPS_THRESHOLD)); } private List<Double> calculateWeights() { List<Double> weights = new ArrayList<Double>(); double i = nearestNeighbours; while(i != 0) { weights.add(i / nearestNeighbours); i--; } double sum = 0; for(double toSum: weights) { sum = sum + toSum; } List<Double> toReturn = new ArrayList<Double>(); for(double weight: weights) { double newWeight = weight / sum; toReturn.add(newWeight); } return toReturn; } public INDArray addSequenceElementVector(StateImpl sequenceElement) { String label = sequenceElement.getLabel(); INDArray result = null; if(!vectors.hasWord(label)) { //logger.debug("Didn't find word in vocab!"); List<SearchResult<INDArray>> kNearestNeighbours = nearestNeighboursLabel(sequenceElement); // KNN lookup //System.out.println("KNN NEAREST"); //System.out.println(kNearestNeighbours.toString()); //logger.debug(Integer.toString(kNearestNeighbours.size())); List<INDArray> wordVectors = new ArrayList<INDArray>(); for(SearchResult<INDArray> neighbour: kNearestNeighbours) { INDArray point = neighbour.payload; List<Double> labelList = new ArrayList<Double>(); int i = 0; while(i < point.columns()) { double toAdd = point.getDouble(i); labelList.add(toAdd); i++; } String neighbourLabel = labelList.toString(); wordVectors.add(vectors.getWordVectorMatrix(neighbourLabel)); } // gewogen gemiddelde van de arrays = 0.8 * array1 + 0.2 * array2 int i = 0; while(i < wordVectors.size()) { if(result == null) { result = wordVectors.get(i).mul(weights.get(i)); } else { result = result.add(wordVectors.get(i).mul(weights.get(i))); } i++; } // word met vector in lookuptable steken! return result; } else { //logger.debug("Found word in vocab!"); //result = vectors.getLookupTable().vector(label); } return null; } public SequenceVectors<StateImpl> getSequenceVectors() { return this.vectors; } private List<SearchResult<INDArray>> nearestNeighboursLabel(StateImpl label) { if(labelTree == null) { // Tree hasn't been build yet. labelTree = new KDTree.Euclidean<INDArray>(label.getState2vecLabel().size()); for(StateImpl state: vectors.getVocab().vocabWords()) { INDArray ndarray = state.getState2vecLabelNormalized(columnMeans, columnStds); labelTree.addPoint(ndarray.data().asDouble(), ndarray); } } List<SearchResult<INDArray>> results = labelTree.nearestNeighbours(label.getState2vecLabelNormalized(columnMeans, columnStds).data().asDouble(), nearestNeighbours); return results; } public List<SearchResult<String>> nearestNeighboursVector(INDArray vector, int k) { if(vectorTree == null) { // Tree hasn't been build yet. vectorTree = new KDTree.Euclidean<String>(vectors.lookupTable().layerSize()); for(StateImpl state: vectors.getVocab().vocabWords()) { INDArray ndarray = vectors.getWordVectorMatrix(state.getLabel()); vectorTree.addPoint(ndarray.data().asDouble(), state.getLabel()); } } List<SearchResult<String>> results = vectorTree.nearestNeighbours(vector.data().asDouble(), k); return results; } }
milanvdm/MedicalLSTM
src/main/java/state2vec/KNNLookupTable.java
1,637
// gewogen gemiddelde van de arrays = 0.8 * array1 + 0.2 * array2
line_comment
nl
package state2vec; import java.util.ArrayList; import java.util.List; import org.deeplearning4j.models.sequencevectors.SequenceVectors; import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import data.StateImpl; import state2vec.KDTree.SearchResult; import util.HelpFunctions; public class KNNLookupTable<T extends SequenceElement> { private static final Logger logger = LoggerFactory.getLogger(KNNLookupTable.class); /** * Use this class to feed in the data to the RNN! */ private SequenceVectors<StateImpl> vectors; private int nearestNeighbours; private List<Double> weights; private INDArray columnMeans; private INDArray columnStds; private KDTree<INDArray> labelTree = null; private KDTree<String> vectorTree = null; public KNNLookupTable(SequenceVectors<StateImpl> vectors, int nearestNeighbours) { this.vectors = vectors; this.nearestNeighbours = nearestNeighbours; this.weights = calculateWeights(); calculateMeanStd(); } private void calculateMeanStd() { INDArray wordLabels = null; boolean first = true; int rowNb = 0; for(String word: vectors.getVocab().words()) { double[] label = HelpFunctions.parse(word); if(first) { wordLabels = Nd4j.create(vectors.getVocab().numWords(), label.length); first = false; } wordLabels.putRow(rowNb, Nd4j.create(label)); rowNb++; } this.columnMeans = wordLabels.mean(0); this.columnStds = wordLabels.std(0).addi(Nd4j.scalar(Nd4j.EPS_THRESHOLD)); } private List<Double> calculateWeights() { List<Double> weights = new ArrayList<Double>(); double i = nearestNeighbours; while(i != 0) { weights.add(i / nearestNeighbours); i--; } double sum = 0; for(double toSum: weights) { sum = sum + toSum; } List<Double> toReturn = new ArrayList<Double>(); for(double weight: weights) { double newWeight = weight / sum; toReturn.add(newWeight); } return toReturn; } public INDArray addSequenceElementVector(StateImpl sequenceElement) { String label = sequenceElement.getLabel(); INDArray result = null; if(!vectors.hasWord(label)) { //logger.debug("Didn't find word in vocab!"); List<SearchResult<INDArray>> kNearestNeighbours = nearestNeighboursLabel(sequenceElement); // KNN lookup //System.out.println("KNN NEAREST"); //System.out.println(kNearestNeighbours.toString()); //logger.debug(Integer.toString(kNearestNeighbours.size())); List<INDArray> wordVectors = new ArrayList<INDArray>(); for(SearchResult<INDArray> neighbour: kNearestNeighbours) { INDArray point = neighbour.payload; List<Double> labelList = new ArrayList<Double>(); int i = 0; while(i < point.columns()) { double toAdd = point.getDouble(i); labelList.add(toAdd); i++; } String neighbourLabel = labelList.toString(); wordVectors.add(vectors.getWordVectorMatrix(neighbourLabel)); } // gewogen gemiddelde<SUF> int i = 0; while(i < wordVectors.size()) { if(result == null) { result = wordVectors.get(i).mul(weights.get(i)); } else { result = result.add(wordVectors.get(i).mul(weights.get(i))); } i++; } // word met vector in lookuptable steken! return result; } else { //logger.debug("Found word in vocab!"); //result = vectors.getLookupTable().vector(label); } return null; } public SequenceVectors<StateImpl> getSequenceVectors() { return this.vectors; } private List<SearchResult<INDArray>> nearestNeighboursLabel(StateImpl label) { if(labelTree == null) { // Tree hasn't been build yet. labelTree = new KDTree.Euclidean<INDArray>(label.getState2vecLabel().size()); for(StateImpl state: vectors.getVocab().vocabWords()) { INDArray ndarray = state.getState2vecLabelNormalized(columnMeans, columnStds); labelTree.addPoint(ndarray.data().asDouble(), ndarray); } } List<SearchResult<INDArray>> results = labelTree.nearestNeighbours(label.getState2vecLabelNormalized(columnMeans, columnStds).data().asDouble(), nearestNeighbours); return results; } public List<SearchResult<String>> nearestNeighboursVector(INDArray vector, int k) { if(vectorTree == null) { // Tree hasn't been build yet. vectorTree = new KDTree.Euclidean<String>(vectors.lookupTable().layerSize()); for(StateImpl state: vectors.getVocab().vocabWords()) { INDArray ndarray = vectors.getWordVectorMatrix(state.getLabel()); vectorTree.addPoint(ndarray.data().asDouble(), state.getLabel()); } } List<SearchResult<String>> results = vectorTree.nearestNeighbours(vector.data().asDouble(), k); return results; } }
True
1,219
26
1,467
27
1,438
25
1,467
27
1,881
25
false
false
false
false
false
true
1,044
42928_1
public class Game { public void playGame() { // Beide spelers hebben een stok Stok deckP1 = new Stok(); Stok deckP2 = new Stok(); // Beide spelers hebben puntentelling int scoreP1 = 0; int scoreP2 = 0; while (deckP1.getLength() != 0) { // Spelers pakken kaart Kaart cardP1 = deckP1.drawCard(); Kaart cardP2 = deckP2.drawCard(); if (cardP1.getScore() > cardP2.getScore()) { scoreP1 += 1; System.out.println("Player 1 won this round"); System.out.println(String.format("Score player1, player2: %d:%d", scoreP1, scoreP2)); continue; } if (cardP1.getScore() < cardP2.getScore()) { scoreP2 += 1; System.out.println("Player 2 won this round"); System.out.println(String.format("Score player1, player2: %d:%d", scoreP1, scoreP2)); continue; } } if (scoreP1 == scoreP2) { System.out.println("The game ended in a draw"); return; } if (scoreP1 > scoreP2) { System.out.println("Winner of the cardgame is PLAYER 1!"); return; } System.out.println("Winner of the cardgame is PLAYER 2!"); } }
MaartjeGubb/simple-card-game
Game.java
421
// Beide spelers hebben puntentelling
line_comment
nl
public class Game { public void playGame() { // Beide spelers hebben een stok Stok deckP1 = new Stok(); Stok deckP2 = new Stok(); // Beide spelers<SUF> int scoreP1 = 0; int scoreP2 = 0; while (deckP1.getLength() != 0) { // Spelers pakken kaart Kaart cardP1 = deckP1.drawCard(); Kaart cardP2 = deckP2.drawCard(); if (cardP1.getScore() > cardP2.getScore()) { scoreP1 += 1; System.out.println("Player 1 won this round"); System.out.println(String.format("Score player1, player2: %d:%d", scoreP1, scoreP2)); continue; } if (cardP1.getScore() < cardP2.getScore()) { scoreP2 += 1; System.out.println("Player 2 won this round"); System.out.println(String.format("Score player1, player2: %d:%d", scoreP1, scoreP2)); continue; } } if (scoreP1 == scoreP2) { System.out.println("The game ended in a draw"); return; } if (scoreP1 > scoreP2) { System.out.println("Winner of the cardgame is PLAYER 1!"); return; } System.out.println("Winner of the cardgame is PLAYER 2!"); } }
True
341
9
376
13
386
7
376
13
413
9
false
false
false
false
false
true
3,782
151091_7
/*=========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * */ package ngs; /** * Represents an alignment between a Fragment and Reference sub-sequence * provides a path to Read and mate Alignment */ public interface Alignment extends Fragment { /** * Retrieve an identifying String that can be used for later access. * The id will be unique within ReadCollection. * @return alignment id * @throws ErrorMsg if the property cannot be retrieved */ String getAlignmentId () throws ErrorMsg; /*------------------------------------------------------------------ * Reference */ /** * getReferenceSpec * @return the name of the reference * @throws ErrorMsg if the property cannot be retrieved */ String getReferenceSpec () throws ErrorMsg; /** * getMappingQuality * @return mapping quality * @throws ErrorMsg if the property cannot be retrieved */ int getMappingQuality () throws ErrorMsg; /** * getReferenceBases * @return reference bases * @throws ErrorMsg if the property cannot be retrieved */ String getReferenceBases () throws ErrorMsg; /*------------------------------------------------------------------ * Fragment */ /** * getReadGroup * @return the name of the read-group * @throws ErrorMsg if the property cannot be retrieved */ String getReadGroup () throws ErrorMsg; /** * getReadId * @return the unique name of the read * @throws ErrorMsg if the property cannot be retrieved */ String getReadId () throws ErrorMsg; /** * getClippedFragmentBases * @return clipped fragment bases * @throws ErrorMsg if the property cannot be retrieved */ String getClippedFragmentBases () throws ErrorMsg; /** * getClippedFragmentQualities * @return clipped fragment phred quality values using ASCII offset of 33 * @throws ErrorMsg if the property cannot be retrieved */ String getClippedFragmentQualities () throws ErrorMsg; /** * getAlignedFragmentBases * @return fragment bases in their aligned orientation * @throws ErrorMsg if the property cannot be retrieved */ String getAlignedFragmentBases () throws ErrorMsg; /*------------------------------------------------------------------ * details of this alignment */ /* AlignmentFilter * values should be or'd together to produce filter bits */ static int passFailed = 1; // reads rejected due to platform/vendor quality criteria static int passDuplicates = 2; // either a PCR or optical duplicate static int minMapQuality = 4; // pass alignments with mappingQuality >= param static int maxMapQuality = 8; // pass alignments with mappingQuality <= param static int noWraparound = 16; // do not include leading wrapped around alignments to circular references static int startWithinSlice = 32; // change slice intersection criteria so that start pos is within slice /* AlignmentCategory */ static int primaryAlignment = 1; static int secondaryAlignment = 2; static int all = primaryAlignment | secondaryAlignment; /** * Alignments are categorized as primary or secondary (alternate). * @return either Alignment.primaryAlignment or Alignment.secondaryAlignment * @throws ErrorMsg if the property cannot be retrieved */ int getAlignmentCategory () throws ErrorMsg; /** * Retrieve the Alignment's starting position on the Reference * @return unsigned 0-based offset from start of Reference * @throws ErrorMsg if the property cannot be retrieved */ long getAlignmentPosition () throws ErrorMsg; /** * Retrieve the projected length of an Alignment projected upon Reference. * @return unsigned length of projection * @throws ErrorMsg if the property cannot be retrieved */ long getAlignmentLength () throws ErrorMsg; /** * Test if orientation is reversed with respect to the Reference sequence. * @return true if reversed * @throws ErrorMsg if the property cannot be retrieved */ boolean getIsReversedOrientation () throws ErrorMsg; /* ClipEdge */ static int clipLeft = 0; static int clipRight = 1; /** * getSoftClip * @return the position of the clipping * @param edge which edge * @throws ErrorMsg if the property cannot be retrieved */ int getSoftClip ( int edge ) throws ErrorMsg; /** * getTemplateLength * @return the lenght of the template * @throws ErrorMsg if the property cannot be retrieved */ long getTemplateLength () throws ErrorMsg; /** * getShortCigar * @param clipped selects if clipping has to be applied * @return a text string describing alignment details * @throws ErrorMsg if the property cannot be retrieved */ String getShortCigar ( boolean clipped ) throws ErrorMsg; /** * getLongCigar * @param clipped selects if clipping has to be applied * @return a text string describing alignment details * @throws ErrorMsg if the property cannot be retrieved */ String getLongCigar ( boolean clipped ) throws ErrorMsg; /** * getRNAOrientation * @return '+' if positive strand is transcribed; * '-' if negative strand is transcribed; * '?' if unknown * @throws ErrorMsg if the property cannot be retrieved */ char getRNAOrientation () throws ErrorMsg; /*------------------------------------------------------------------ * details of mate alignment */ /** * hasMate * @return if the alignment has a mate */ boolean hasMate (); /** * getMateAlignmentId * @return unique ID of th alignment * @throws ErrorMsg if the property cannot be retrieved */ String getMateAlignmentId () throws ErrorMsg; /** * getMateAlignment * @return the mate as alignment * @throws ErrorMsg if the property cannot be retrieved */ Alignment getMateAlignment () throws ErrorMsg; /** * getMateReferenceSpec * @return the name of the reference the mate is aligned at * @throws ErrorMsg if the property cannot be retrieved */ String getMateReferenceSpec () throws ErrorMsg; /** * getMateIsReversedOrientation * @return the orientation of the mate * @throws ErrorMsg if the property cannot be retrieved */ boolean getMateIsReversedOrientation () throws ErrorMsg; }
ncbi/sra-tools
ngs/ngs-java/ngs/Alignment.java
1,976
/*------------------------------------------------------------------ * Fragment */
block_comment
nl
/*=========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * */ package ngs; /** * Represents an alignment between a Fragment and Reference sub-sequence * provides a path to Read and mate Alignment */ public interface Alignment extends Fragment { /** * Retrieve an identifying String that can be used for later access. * The id will be unique within ReadCollection. * @return alignment id * @throws ErrorMsg if the property cannot be retrieved */ String getAlignmentId () throws ErrorMsg; /*------------------------------------------------------------------ * Reference */ /** * getReferenceSpec * @return the name of the reference * @throws ErrorMsg if the property cannot be retrieved */ String getReferenceSpec () throws ErrorMsg; /** * getMappingQuality * @return mapping quality * @throws ErrorMsg if the property cannot be retrieved */ int getMappingQuality () throws ErrorMsg; /** * getReferenceBases * @return reference bases * @throws ErrorMsg if the property cannot be retrieved */ String getReferenceBases () throws ErrorMsg; /*------------------------------------------------------------------ <SUF>*/ /** * getReadGroup * @return the name of the read-group * @throws ErrorMsg if the property cannot be retrieved */ String getReadGroup () throws ErrorMsg; /** * getReadId * @return the unique name of the read * @throws ErrorMsg if the property cannot be retrieved */ String getReadId () throws ErrorMsg; /** * getClippedFragmentBases * @return clipped fragment bases * @throws ErrorMsg if the property cannot be retrieved */ String getClippedFragmentBases () throws ErrorMsg; /** * getClippedFragmentQualities * @return clipped fragment phred quality values using ASCII offset of 33 * @throws ErrorMsg if the property cannot be retrieved */ String getClippedFragmentQualities () throws ErrorMsg; /** * getAlignedFragmentBases * @return fragment bases in their aligned orientation * @throws ErrorMsg if the property cannot be retrieved */ String getAlignedFragmentBases () throws ErrorMsg; /*------------------------------------------------------------------ * details of this alignment */ /* AlignmentFilter * values should be or'd together to produce filter bits */ static int passFailed = 1; // reads rejected due to platform/vendor quality criteria static int passDuplicates = 2; // either a PCR or optical duplicate static int minMapQuality = 4; // pass alignments with mappingQuality >= param static int maxMapQuality = 8; // pass alignments with mappingQuality <= param static int noWraparound = 16; // do not include leading wrapped around alignments to circular references static int startWithinSlice = 32; // change slice intersection criteria so that start pos is within slice /* AlignmentCategory */ static int primaryAlignment = 1; static int secondaryAlignment = 2; static int all = primaryAlignment | secondaryAlignment; /** * Alignments are categorized as primary or secondary (alternate). * @return either Alignment.primaryAlignment or Alignment.secondaryAlignment * @throws ErrorMsg if the property cannot be retrieved */ int getAlignmentCategory () throws ErrorMsg; /** * Retrieve the Alignment's starting position on the Reference * @return unsigned 0-based offset from start of Reference * @throws ErrorMsg if the property cannot be retrieved */ long getAlignmentPosition () throws ErrorMsg; /** * Retrieve the projected length of an Alignment projected upon Reference. * @return unsigned length of projection * @throws ErrorMsg if the property cannot be retrieved */ long getAlignmentLength () throws ErrorMsg; /** * Test if orientation is reversed with respect to the Reference sequence. * @return true if reversed * @throws ErrorMsg if the property cannot be retrieved */ boolean getIsReversedOrientation () throws ErrorMsg; /* ClipEdge */ static int clipLeft = 0; static int clipRight = 1; /** * getSoftClip * @return the position of the clipping * @param edge which edge * @throws ErrorMsg if the property cannot be retrieved */ int getSoftClip ( int edge ) throws ErrorMsg; /** * getTemplateLength * @return the lenght of the template * @throws ErrorMsg if the property cannot be retrieved */ long getTemplateLength () throws ErrorMsg; /** * getShortCigar * @param clipped selects if clipping has to be applied * @return a text string describing alignment details * @throws ErrorMsg if the property cannot be retrieved */ String getShortCigar ( boolean clipped ) throws ErrorMsg; /** * getLongCigar * @param clipped selects if clipping has to be applied * @return a text string describing alignment details * @throws ErrorMsg if the property cannot be retrieved */ String getLongCigar ( boolean clipped ) throws ErrorMsg; /** * getRNAOrientation * @return '+' if positive strand is transcribed; * '-' if negative strand is transcribed; * '?' if unknown * @throws ErrorMsg if the property cannot be retrieved */ char getRNAOrientation () throws ErrorMsg; /*------------------------------------------------------------------ * details of mate alignment */ /** * hasMate * @return if the alignment has a mate */ boolean hasMate (); /** * getMateAlignmentId * @return unique ID of th alignment * @throws ErrorMsg if the property cannot be retrieved */ String getMateAlignmentId () throws ErrorMsg; /** * getMateAlignment * @return the mate as alignment * @throws ErrorMsg if the property cannot be retrieved */ Alignment getMateAlignment () throws ErrorMsg; /** * getMateReferenceSpec * @return the name of the reference the mate is aligned at * @throws ErrorMsg if the property cannot be retrieved */ String getMateReferenceSpec () throws ErrorMsg; /** * getMateIsReversedOrientation * @return the orientation of the mate * @throws ErrorMsg if the property cannot be retrieved */ boolean getMateIsReversedOrientation () throws ErrorMsg; }
False
1,680
8
1,672
7
1,841
13
1,672
7
2,020
13
false
false
false
false
false
true
285
201795_0
package cz.metacentrum.perun.core.api; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import java.util.UUID; /** * Vo entity. */ public class Vo extends Auditable implements Comparable<PerunBean>, HasUuid { private String name; private String shortName; private UUID uuid; public Vo() { } public Vo(int id, String name, String shortName) { super(id); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } @Deprecated public Vo(int id, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, null, null); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } public Vo(int id, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy, Integer createdByUid, Integer modifiedByUid) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } public Vo(int id, UUID uuid, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy, Integer createdByUid, Integer modifiedByUid) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; this.uuid = uuid; } @Override public int compareTo(PerunBean perunBean) { if (perunBean == null) { throw new NullPointerException("PerunBean to compare with is null."); } if (perunBean instanceof Vo) { Vo vo = (Vo) perunBean; if (this.getName() == null && vo.getName() != null) { return -1; } if (vo.getName() == null && this.getName() != null) { return 1; } if (this.getName() == null && vo.getName() == null) { return 0; } return this.getName().compareToIgnoreCase(vo.getName()); } else { return (this.getId() - perunBean.getId()); } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Vo other = (Vo) obj; if (this.getId() != other.getId()) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.shortName == null) ? (other.shortName != null) : !this.shortName.equals(other.shortName)) { return false; } return true; } public String getName() { return name; } public void setName(String name) { if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } this.name = name; } public String getShortName() { return shortName; } public void setShortName(String shortName) { if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.shortName = shortName; } @Override public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } @Override public int hashCode() { int hash = 7; hash = 53 * hash + this.getId(); hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 53 * hash + (this.shortName != null ? this.shortName.hashCode() : 0); return hash; } @Override public String serializeToString() { StringBuilder str = new StringBuilder(); return str.append(this.getClass().getSimpleName()).append(":[").append("id=<").append(getId()).append(">") .append(", uuid=<").append(getUuid()).append(">").append(", name=<") .append(getName() == null ? "\\0" : BeansUtils.createEscaping(getName())).append(">").append(", shortName=<") .append(getShortName() == null ? "\\0" : BeansUtils.createEscaping(getShortName())).append(">").append(']') .toString(); } @Override public String toString() { StringBuilder str = new StringBuilder(); return str.append(this.getClass().getSimpleName()).append(":[").append("id='").append(this.getId()).append('\'') .append(", uuid='").append(uuid).append('\'').append(", name='").append(name).append('\'') .append(", shortName='").append(shortName).append('\'').append(']').toString(); } }
CESNET/perun
perun-base/src/main/java/cz/metacentrum/perun/core/api/Vo.java
1,673
/** * Vo entity. */
block_comment
nl
package cz.metacentrum.perun.core.api; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import java.util.UUID; /** * Vo entity. <SUF>*/ public class Vo extends Auditable implements Comparable<PerunBean>, HasUuid { private String name; private String shortName; private UUID uuid; public Vo() { } public Vo(int id, String name, String shortName) { super(id); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } @Deprecated public Vo(int id, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, null, null); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } public Vo(int id, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy, Integer createdByUid, Integer modifiedByUid) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; } public Vo(int id, UUID uuid, String name, String shortName, String createdAt, String createdBy, String modifiedAt, String modifiedBy, Integer createdByUid, Integer modifiedByUid) { super(id, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid); if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.name = name; this.shortName = shortName; this.uuid = uuid; } @Override public int compareTo(PerunBean perunBean) { if (perunBean == null) { throw new NullPointerException("PerunBean to compare with is null."); } if (perunBean instanceof Vo) { Vo vo = (Vo) perunBean; if (this.getName() == null && vo.getName() != null) { return -1; } if (vo.getName() == null && this.getName() != null) { return 1; } if (this.getName() == null && vo.getName() == null) { return 0; } return this.getName().compareToIgnoreCase(vo.getName()); } else { return (this.getId() - perunBean.getId()); } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Vo other = (Vo) obj; if (this.getId() != other.getId()) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if ((this.shortName == null) ? (other.shortName != null) : !this.shortName.equals(other.shortName)) { return false; } return true; } public String getName() { return name; } public void setName(String name) { if (name == null) { throw new InternalErrorException(new NullPointerException("name is null")); } this.name = name; } public String getShortName() { return shortName; } public void setShortName(String shortName) { if (shortName == null) { throw new InternalErrorException(new NullPointerException("shortName is null")); } this.shortName = shortName; } @Override public UUID getUuid() { return uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } @Override public int hashCode() { int hash = 7; hash = 53 * hash + this.getId(); hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0); hash = 53 * hash + (this.shortName != null ? this.shortName.hashCode() : 0); return hash; } @Override public String serializeToString() { StringBuilder str = new StringBuilder(); return str.append(this.getClass().getSimpleName()).append(":[").append("id=<").append(getId()).append(">") .append(", uuid=<").append(getUuid()).append(">").append(", name=<") .append(getName() == null ? "\\0" : BeansUtils.createEscaping(getName())).append(">").append(", shortName=<") .append(getShortName() == null ? "\\0" : BeansUtils.createEscaping(getShortName())).append(">").append(']') .toString(); } @Override public String toString() { StringBuilder str = new StringBuilder(); return str.append(this.getClass().getSimpleName()).append(":[").append("id='").append(this.getId()).append('\'') .append(", uuid='").append(uuid).append('\'').append(", name='").append(name).append('\'') .append(", shortName='").append(shortName).append('\'').append(']').toString(); } }
False
1,266
6
1,375
8
1,487
8
1,375
8
1,659
8
false
false
false
false
false
true
2,800
83519_3
package com.in28minutes.rest.webservices.restfulwebservices.helloworld; import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloWorldController { private MessageSource messageSource; public HelloWorldController(MessageSource messageSource) { this.messageSource = messageSource; } @GetMapping(path = "/hello-world") public String helloWorld() { return "Hello World"; } @GetMapping(path = "/hello-world-bean") public HelloWorldBean helloWorldBean() { return new HelloWorldBean("Hello World"); } // Path Parameters // /users/{id}/todos/{id} => /users/2/todos/200 // /hello-world/path-variable/{name} // /hello-world/path-variable/Ranga @GetMapping(path = "/hello-world/path-variable/{name}") public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { return new HelloWorldBean(String.format("Hello World, %s", name)); } @GetMapping(path = "/hello-world-internationalized") public String helloWorldInternationalized() { Locale locale = LocaleContextHolder.getLocale(); return messageSource.getMessage("good.morning.message", null, "Default Message", locale); //return "Hello World V2"; //1: //2: // - Example: `en` - English (Good Morning) // - Example: `nl` - Dutch (Goedemorgen) // - Example: `fr` - French (Bonjour) // - Example: `de` - Deutsch (Guten Morgen) } }
gil-son/spring-ecosystem
spring-boot/mini-projects/in28minutes-spring-microservices-v2/src/main/java/com/in28minutes/rest/webservices/restfulwebservices/helloworld/HelloWorldController.java
511
// - Example: `nl` - Dutch (Goedemorgen)
line_comment
nl
package com.in28minutes.rest.webservices.restfulwebservices.helloworld; import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloWorldController { private MessageSource messageSource; public HelloWorldController(MessageSource messageSource) { this.messageSource = messageSource; } @GetMapping(path = "/hello-world") public String helloWorld() { return "Hello World"; } @GetMapping(path = "/hello-world-bean") public HelloWorldBean helloWorldBean() { return new HelloWorldBean("Hello World"); } // Path Parameters // /users/{id}/todos/{id} => /users/2/todos/200 // /hello-world/path-variable/{name} // /hello-world/path-variable/Ranga @GetMapping(path = "/hello-world/path-variable/{name}") public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { return new HelloWorldBean(String.format("Hello World, %s", name)); } @GetMapping(path = "/hello-world-internationalized") public String helloWorldInternationalized() { Locale locale = LocaleContextHolder.getLocale(); return messageSource.getMessage("good.morning.message", null, "Default Message", locale); //return "Hello World V2"; //1: //2: // - Example: `en` - English (Good Morning) // - Example:<SUF> // - Example: `fr` - French (Bonjour) // - Example: `de` - Deutsch (Guten Morgen) } }
False
380
17
487
19
475
16
487
19
533
17
false
false
false
false
false
true
552
28744_0
package nl.han.ica.killthememe; import java.net.URL; import nl.han.ica.OOPDProcessingEngineHAN.alarm.Alarm; import nl.han.ica.OOPDProcessingEngineHAN.alarm.IAlarmListener; import nl.han.ica.OOPDProcessingEngineHAN.objects.AnimatedSpriteObject; import nl.han.ica.OOPDProcessingEngineHAN.objects.Sprite; import nl.han.ica.OOPDProcessingEngineHAN.objects.SpriteObject; public class Vogel extends AnimatedSpriteObject implements IAlarmListener { private boolean inAnimatie; private MainGame mainGame; private int totalFramez = 0; private static URL vogel = Vogel.class.getResource( "/twitter-bird-sprite.png"); /** * Vogel constructor * * @param mainGame de wereld */ public Vogel(MainGame mainGame) { this(new Sprite(vogel.toString())); this.mainGame = mainGame; setCurrentFrameIndex(totalFramez); } /** * * @param sprite Vogel Sprite */ private Vogel(Sprite sprite) { super(sprite, 4); setxSpeed(-1); } /** * functie voor de alarm voor de animatie. */ public void startAlarm() { Alarm alarm = new Alarm("Animatie", 1 / 0.99f); alarm.addTarget(this); alarm.start(); } /** * Zodra de alarm afgaat, wordt deze functie uitgevoerd en wisselt hij een * boolean voor de animatie en maakt hij magAanvallen false. * */ public void triggerAlarm(String alarmName) { inAnimatie = false; } /** * Functie die kijkt of de vogel uit het scherm gaat, zodra hij dat doet komt * hij weer vanuit een random X positie weer terug aan de rechterkant van de * spelers scherm. Bevat ook een functie voor de animatie van de vogel. */ @Override public void update() { if (getX() + getWidth() <= 0) { setX(mainGame.getWidth()); setY(mainGame.random(0, mainGame.getHeight())); } if (!inAnimatie) { if (totalFramez == 4) { totalFramez = 0; } if (totalFramez < 4) { setCurrentFrameIndex(totalFramez); totalFramez++; inAnimatie = true; startAlarm(); } } } }
GGWPs/Kill-The-Meme
src/main/java/nl/han/ica/killthememe/Vogel.java
727
/** * Vogel constructor * * @param mainGame de wereld */
block_comment
nl
package nl.han.ica.killthememe; import java.net.URL; import nl.han.ica.OOPDProcessingEngineHAN.alarm.Alarm; import nl.han.ica.OOPDProcessingEngineHAN.alarm.IAlarmListener; import nl.han.ica.OOPDProcessingEngineHAN.objects.AnimatedSpriteObject; import nl.han.ica.OOPDProcessingEngineHAN.objects.Sprite; import nl.han.ica.OOPDProcessingEngineHAN.objects.SpriteObject; public class Vogel extends AnimatedSpriteObject implements IAlarmListener { private boolean inAnimatie; private MainGame mainGame; private int totalFramez = 0; private static URL vogel = Vogel.class.getResource( "/twitter-bird-sprite.png"); /** * Vogel constructor <SUF>*/ public Vogel(MainGame mainGame) { this(new Sprite(vogel.toString())); this.mainGame = mainGame; setCurrentFrameIndex(totalFramez); } /** * * @param sprite Vogel Sprite */ private Vogel(Sprite sprite) { super(sprite, 4); setxSpeed(-1); } /** * functie voor de alarm voor de animatie. */ public void startAlarm() { Alarm alarm = new Alarm("Animatie", 1 / 0.99f); alarm.addTarget(this); alarm.start(); } /** * Zodra de alarm afgaat, wordt deze functie uitgevoerd en wisselt hij een * boolean voor de animatie en maakt hij magAanvallen false. * */ public void triggerAlarm(String alarmName) { inAnimatie = false; } /** * Functie die kijkt of de vogel uit het scherm gaat, zodra hij dat doet komt * hij weer vanuit een random X positie weer terug aan de rechterkant van de * spelers scherm. Bevat ook een functie voor de animatie van de vogel. */ @Override public void update() { if (getX() + getWidth() <= 0) { setX(mainGame.getWidth()); setY(mainGame.random(0, mainGame.getHeight())); } if (!inAnimatie) { if (totalFramez == 4) { totalFramez = 0; } if (totalFramez < 4) { setCurrentFrameIndex(totalFramez); totalFramez++; inAnimatie = true; startAlarm(); } } } }
True
576
21
673
19
633
22
673
19
781
23
false
false
false
false
false
true
4,020
24904_2
package quiz.datastorage; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import quiz.domein.QuizVraag; /** * * @author Gregor */ public class QuizVraagDAO { Connection connection; Statement statement; ResultSet resultSet; public QuizVraagDAO() { try { //Connectie innitializeren. connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/quiz", "root", ""); //Statement object aanmaken. statement = connection.createStatement(); } catch (SQLException ex) { System.out.println("Er kon geen connectie gemaakt worden met de database"); } } public ArrayList<QuizVraag> getQuizVragen() { ArrayList<QuizVraag> quizVragen = new ArrayList<>(); try { resultSet = statement.executeQuery("SELECT Spelnaam, Hoofdcaracter FROM Vragen"); while (resultSet.next()) { QuizVraag vraag = new QuizVraag("Shakugan no Shana", "Shana"); quizVragen.add(vraag); } return quizVragen; } catch (SQLException ex) { Logger.getLogger(QuizVraagDAO.class.getName()).log(Level.SEVERE, null, ex); return null; } } }
polyanos/VH5
workspace/Henk/src/quiz/datastorage/QuizVraagDAO.java
458
//Statement object aanmaken.
line_comment
nl
package quiz.datastorage; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import quiz.domein.QuizVraag; /** * * @author Gregor */ public class QuizVraagDAO { Connection connection; Statement statement; ResultSet resultSet; public QuizVraagDAO() { try { //Connectie innitializeren. connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/quiz", "root", ""); //Statement object<SUF> statement = connection.createStatement(); } catch (SQLException ex) { System.out.println("Er kon geen connectie gemaakt worden met de database"); } } public ArrayList<QuizVraag> getQuizVragen() { ArrayList<QuizVraag> quizVragen = new ArrayList<>(); try { resultSet = statement.executeQuery("SELECT Spelnaam, Hoofdcaracter FROM Vragen"); while (resultSet.next()) { QuizVraag vraag = new QuizVraag("Shakugan no Shana", "Shana"); quizVragen.add(vraag); } return quizVragen; } catch (SQLException ex) { Logger.getLogger(QuizVraagDAO.class.getName()).log(Level.SEVERE, null, ex); return null; } } }
True
326
7
390
7
383
6
390
7
459
7
false
false
false
false
false
true
1,724
102008_1
package nl.thijswijnen.geojob.Model; import android.content.Context; import com.google.android.gms.maps.model.LatLng; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import nl.thijswijnen.geojob.R; import nl.thijswijnen.geojob.Util.CoordinateConverter; /** * Created by thijs_000 on 05-Dec-17. */ public class HistorischeKilometer extends Route implements Serializable { public void load(Context context) { setRouteTitle(context.getString(R.string.historischeKilometer)); setDescriptionEN("The Historical Kilometer is a route that goes through the historical city of Breda "); setDescriptionNL("De Historische Kilometer is een route die door de historische binnenstad van Breda loopt"); List<PointOfInterest> pointOfInterests = new ArrayList<>(); List<PointOfInterest> HKpointOfInterests = new ArrayList<>(); try{ JSONArray array = new JSONArray(loadJSONFromAsset(context)); for (int i = 0; i < array.length(); i++){ JSONObject monument = array.getJSONObject(i); String latitude = monument.getString("latitude"); String longitude = monument.getString("longitude"); LatLng location = CoordinateConverter.degreeToDecimal(latitude, longitude); String title = monument.getString("VVV"); JSONObject description = monument.getJSONObject("Verhaal"); String descriptionNL = description.getString("NL"); String descriptionEN = description.getString("ENG"); //images ArrayList<String> listDataImages = new ArrayList<String>(); JSONArray images = monument.getJSONArray("Image"); for (int j = 0; j < images.length(); j++){ String image = images.getString(j); listDataImages.add(image); } List<String> imagesList = listDataImages; //videos ArrayList<String> listDataVideos = new ArrayList<String>(); JSONArray videos = monument.getJSONArray("Video"); for (int v = 0; v < videos.length(); v++){ String video = videos.getString(v); listDataVideos.add(video); } List<String> videosList = listDataVideos; PointOfInterest poi = new Monument(title, descriptionNL, descriptionEN, location); poi.setAllImages(imagesList); poi.setAllVideos(videosList); if(!poi.getTitle().equals("")){ HKpointOfInterests.add(poi); System.out.println(poi.getTitle()); } pointOfInterests.add(poi); } } catch (JSONException e){ e.printStackTrace(); } if(!HKpointOfInterests.isEmpty()){ setHKPointsOfInterests(HKpointOfInterests); } setAllPointOfInterests(pointOfInterests); } private String loadJSONFromAsset(Context context) { String json = null; try{ InputStream is = context.getAssets().open("HistorischeKilometer.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex){ ex.printStackTrace(); return null; } return json; } } /** * [ { "1": "2", "latitude": "51°35.5967’", "longitude": "4°46.7633’", "VVV": "Liefdeszuster", "Beginpunt": "", "Verhaal": { "Default": "Symbolisch beeld voor het religieus verleden van Breda. De Liefdezuster geeft de dienstverlening weer, zoals de Gasthuiszusters die eeuwenlang in de praktijk brachten.", "NL": "Symbolisch beeld voor het religieus verleden van Breda. De Liefdezuster geeft de dienstverlening weer, zoals de Gasthuiszusters die eeuwenlang in de praktijk brachten.", "ENG": "Symbolic image for the religious past of Breda. De Liefdezuster shows the service, as the Gasthuiszusters put into practice for centuries" }, "Image": [ { "0": "liefdeszuster.jpg" } ], "Audio": [ { "0": "liefdeszustergeluid.mp3" } ], "Video": [ { "0": "liefdeszusterfilm.mp4" } ] } ] */
Thijs0x57/GeoJob
app/src/main/java/nl/thijswijnen/geojob/Model/HistorischeKilometer.java
1,357
/** * [ { "1": "2", "latitude": "51°35.5967’", "longitude": "4°46.7633’", "VVV": "Liefdeszuster", "Beginpunt": "", "Verhaal": { "Default": "Symbolisch beeld voor het religieus verleden van Breda. De Liefdezuster geeft de dienstverlening weer, zoals de Gasthuiszusters die eeuwenlang in de praktijk brachten.", "NL": "Symbolisch beeld voor het religieus verleden van Breda. De Liefdezuster geeft de dienstverlening weer, zoals de Gasthuiszusters die eeuwenlang in de praktijk brachten.", "ENG": "Symbolic image for the religious past of Breda. De Liefdezuster shows the service, as the Gasthuiszusters put into practice for centuries" }, "Image": [ { "0": "liefdeszuster.jpg" } ], "Audio": [ { "0": "liefdeszustergeluid.mp3" } ], "Video": [ { "0": "liefdeszusterfilm.mp4" } ] } ] */
block_comment
nl
package nl.thijswijnen.geojob.Model; import android.content.Context; import com.google.android.gms.maps.model.LatLng; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import nl.thijswijnen.geojob.R; import nl.thijswijnen.geojob.Util.CoordinateConverter; /** * Created by thijs_000 on 05-Dec-17. */ public class HistorischeKilometer extends Route implements Serializable { public void load(Context context) { setRouteTitle(context.getString(R.string.historischeKilometer)); setDescriptionEN("The Historical Kilometer is a route that goes through the historical city of Breda "); setDescriptionNL("De Historische Kilometer is een route die door de historische binnenstad van Breda loopt"); List<PointOfInterest> pointOfInterests = new ArrayList<>(); List<PointOfInterest> HKpointOfInterests = new ArrayList<>(); try{ JSONArray array = new JSONArray(loadJSONFromAsset(context)); for (int i = 0; i < array.length(); i++){ JSONObject monument = array.getJSONObject(i); String latitude = monument.getString("latitude"); String longitude = monument.getString("longitude"); LatLng location = CoordinateConverter.degreeToDecimal(latitude, longitude); String title = monument.getString("VVV"); JSONObject description = monument.getJSONObject("Verhaal"); String descriptionNL = description.getString("NL"); String descriptionEN = description.getString("ENG"); //images ArrayList<String> listDataImages = new ArrayList<String>(); JSONArray images = monument.getJSONArray("Image"); for (int j = 0; j < images.length(); j++){ String image = images.getString(j); listDataImages.add(image); } List<String> imagesList = listDataImages; //videos ArrayList<String> listDataVideos = new ArrayList<String>(); JSONArray videos = monument.getJSONArray("Video"); for (int v = 0; v < videos.length(); v++){ String video = videos.getString(v); listDataVideos.add(video); } List<String> videosList = listDataVideos; PointOfInterest poi = new Monument(title, descriptionNL, descriptionEN, location); poi.setAllImages(imagesList); poi.setAllVideos(videosList); if(!poi.getTitle().equals("")){ HKpointOfInterests.add(poi); System.out.println(poi.getTitle()); } pointOfInterests.add(poi); } } catch (JSONException e){ e.printStackTrace(); } if(!HKpointOfInterests.isEmpty()){ setHKPointsOfInterests(HKpointOfInterests); } setAllPointOfInterests(pointOfInterests); } private String loadJSONFromAsset(Context context) { String json = null; try{ InputStream is = context.getAssets().open("HistorischeKilometer.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex){ ex.printStackTrace(); return null; } return json; } } /** * [ <SUF>*/
False
1,010
310
1,178
328
1,166
318
1,178
328
1,324
355
true
true
true
true
true
false
1,687
204556_2
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package views; import controller.Controller; import models.Task; import models.Thought; import net.miginfocom.swing.MigLayout; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.net.URL; import java.util.List; import models.Task.Sort; /** * * @author tim */ public class MainWindow extends JFrame { private FilterPanel navpane; private ContentPanel contentpane; public MainWindow(Controller controller) { super("miniGTD"); setLayout(null); setBounds(0, 0, 950, 700); setLocationRelativeTo(null); setMinimumSize(new Dimension(1000, 700)); setIconImage( new ImageIcon(getClass().getResource("/resources/icons/to_do_list_cheked_1.png")).getImage()); setLayout(new MigLayout("ins 0, fill, gap 0", "[][grow]", "[grow]")); navpane = new FilterPanel(controller); JScrollPane scroller = new JScrollPane(navpane); scroller.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.black)); scroller.setMinimumSize(new Dimension(200, 400)); add(scroller, "growy"); navpane.setMinimumSize(new Dimension(200, 400)); contentpane = new ContentPanel(controller); JScrollPane contentScroller = new JScrollPane(contentpane); contentScroller.setBorder(BorderFactory.createEmptyBorder()); add(contentScroller, "span, grow"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void showConnectionError() { //TODO: omgaan met SQL problemen contentpane.setBackground(Color.RED); } public void showThoughts(List<Thought> thoughts) { contentpane.showThoughts(thoughts); } public void updateThoughts(List<Thought> all) { contentpane.updateThoughts(all); } public void showTasks(List<Task> tasks, Task.Sort currentSort, boolean asc, boolean formVisible) { contentpane.showTasks(tasks, currentSort, asc, formVisible); } public void updateTasks(List<Task> tasks, Task.Sort currentSort, boolean asc, boolean formVisible) { contentpane.updateTasks(tasks, currentSort, asc); } public void updateFilters() { navpane.updateFilters(); } @Override public void setTitle(String title) { if (!title.isEmpty()) title += " - "; super.setTitle(title + "miniGTD"); } }
Tasky/miniGTD
src/views/MainWindow.java
772
//TODO: omgaan met SQL problemen
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package views; import controller.Controller; import models.Task; import models.Thought; import net.miginfocom.swing.MigLayout; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.net.URL; import java.util.List; import models.Task.Sort; /** * * @author tim */ public class MainWindow extends JFrame { private FilterPanel navpane; private ContentPanel contentpane; public MainWindow(Controller controller) { super("miniGTD"); setLayout(null); setBounds(0, 0, 950, 700); setLocationRelativeTo(null); setMinimumSize(new Dimension(1000, 700)); setIconImage( new ImageIcon(getClass().getResource("/resources/icons/to_do_list_cheked_1.png")).getImage()); setLayout(new MigLayout("ins 0, fill, gap 0", "[][grow]", "[grow]")); navpane = new FilterPanel(controller); JScrollPane scroller = new JScrollPane(navpane); scroller.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.black)); scroller.setMinimumSize(new Dimension(200, 400)); add(scroller, "growy"); navpane.setMinimumSize(new Dimension(200, 400)); contentpane = new ContentPanel(controller); JScrollPane contentScroller = new JScrollPane(contentpane); contentScroller.setBorder(BorderFactory.createEmptyBorder()); add(contentScroller, "span, grow"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void showConnectionError() { //TODO: omgaan<SUF> contentpane.setBackground(Color.RED); } public void showThoughts(List<Thought> thoughts) { contentpane.showThoughts(thoughts); } public void updateThoughts(List<Thought> all) { contentpane.updateThoughts(all); } public void showTasks(List<Task> tasks, Task.Sort currentSort, boolean asc, boolean formVisible) { contentpane.showTasks(tasks, currentSort, asc, formVisible); } public void updateTasks(List<Task> tasks, Task.Sort currentSort, boolean asc, boolean formVisible) { contentpane.updateTasks(tasks, currentSort, asc); } public void updateFilters() { navpane.updateFilters(); } @Override public void setTitle(String title) { if (!title.isEmpty()) title += " - "; super.setTitle(title + "miniGTD"); } }
True
570
10
679
10
684
8
679
10
796
11
false
false
false
false
false
true
1,113
20849_1
import java.util.Arrays; import static generic.CommandLine.*; public class Week4{ public static void main(String[] args){ int lucas = askForInt("geef een natuurlijk getal: "); printLucasRow(lucas); System.out.println("Java".substring(0,1)); /* int a = 5; int b = 2; System.out.println(exponent(a,b)); System.out.println(isOdd(b)); System.out.println(isOdd(a)); int[] test = new int[]{1, 2, 3, 4, 5}; System.out.println(Arrays.toString(test)); int[] test2 = invert(test); System.out.println(Arrays.toString(test));*/ } private static void printLucasRow(int nrOfNumbers){ int[] lucasRow = getLucasRow(nrOfNumbers); if(lucasRow == null)return; System.out.printf("De eerst %d Lucas-getallen:%n", lucasRow.length); for(int i: lucasRow){ System.out.print(i + " "); } System.out.println(); } private static int[] getLucasRow(int nrOfNumbers){ if(nrOfNumbers < 0){ System.out.println("Getal negatief, fout"); return null; } if(nrOfNumbers == 0) return new int[]{}; if(nrOfNumbers < 3) return new int[]{nrOfNumbers == 1? 2 : 2, 1}; int[] totalRow = new int[nrOfNumbers]; totalRow[0] = 2; totalRow[1] = 1; for(int i = 2; i < totalRow.length; i++){ totalRow[i] = totalRow[i-1] + totalRow[i-2]; if(((long)totalRow[i] + totalRow[i-1]) > Integer.MAX_VALUE){ System.out.println("Getal te groot, past niet"); return null; } } return totalRow; } private static int exponent(int base, int exp){ return (int)Math.pow(base, exp); } private static boolean isOdd(int number){ return number%2 != 0; } public static int[] invert(int[] array) { for(int i = 0; i < array.length; i++) { array[i] *= -1; } return array; } } /* 2 1 3 4 7 11 18 …​ Het eerste Lucas-getal is 2, het tweede is 1. Daarna krijg je het volgende getal telkens door de twee voorgaande getallen bij elkaar op te tellen. In je programma moet je testen of het door de gebruiker ingetypte getal wel positief is. Verder kunnen de getallen van de Lucas-reeks zo groot worden dat ze niet meer passen in een int. ​ Bouw in je programma een test in, zodat bij een te grote waarde van n niets geprint wordt. ​ ​*/
Michelvdm83/OpdrachtenIT
Week4.java
853
/* 2 1 3 4 7 11 18 …​ Het eerste Lucas-getal is 2, het tweede is 1. Daarna krijg je het volgende getal telkens door de twee voorgaande getallen bij elkaar op te tellen. In je programma moet je testen of het door de gebruiker ingetypte getal wel positief is. Verder kunnen de getallen van de Lucas-reeks zo groot worden dat ze niet meer passen in een int. ​ Bouw in je programma een test in, zodat bij een te grote waarde van n niets geprint wordt. ​ ​*/
block_comment
nl
import java.util.Arrays; import static generic.CommandLine.*; public class Week4{ public static void main(String[] args){ int lucas = askForInt("geef een natuurlijk getal: "); printLucasRow(lucas); System.out.println("Java".substring(0,1)); /* int a = 5; int b = 2; System.out.println(exponent(a,b)); System.out.println(isOdd(b)); System.out.println(isOdd(a)); int[] test = new int[]{1, 2, 3, 4, 5}; System.out.println(Arrays.toString(test)); int[] test2 = invert(test); System.out.println(Arrays.toString(test));*/ } private static void printLucasRow(int nrOfNumbers){ int[] lucasRow = getLucasRow(nrOfNumbers); if(lucasRow == null)return; System.out.printf("De eerst %d Lucas-getallen:%n", lucasRow.length); for(int i: lucasRow){ System.out.print(i + " "); } System.out.println(); } private static int[] getLucasRow(int nrOfNumbers){ if(nrOfNumbers < 0){ System.out.println("Getal negatief, fout"); return null; } if(nrOfNumbers == 0) return new int[]{}; if(nrOfNumbers < 3) return new int[]{nrOfNumbers == 1? 2 : 2, 1}; int[] totalRow = new int[nrOfNumbers]; totalRow[0] = 2; totalRow[1] = 1; for(int i = 2; i < totalRow.length; i++){ totalRow[i] = totalRow[i-1] + totalRow[i-2]; if(((long)totalRow[i] + totalRow[i-1]) > Integer.MAX_VALUE){ System.out.println("Getal te groot, past niet"); return null; } } return totalRow; } private static int exponent(int base, int exp){ return (int)Math.pow(base, exp); } private static boolean isOdd(int number){ return number%2 != 0; } public static int[] invert(int[] array) { for(int i = 0; i < array.length; i++) { array[i] *= -1; } return array; } } /* 2 1 3<SUF>*/
True
680
146
836
170
794
137
836
170
904
159
false
false
false
false
false
true
4,580
7893_4
package teun.demo.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import teun.demo.domain.Exercise; import teun.demo.domain.ExerciseFact; import teun.demo.domain.User; import teun.demo.repository.ExerciseFactRepository; import teun.demo.repository.ExerciseRepository; import teun.demo.repository.UserRepository; import java.util.*; @Slf4j @SessionAttributes({"selectedUser", "selectedCategory", "selectedSubCategory", "selectedExercise"}) @Controller @RequestMapping("/exercise") public class ExerciseFactController { private ExerciseFactRepository exerciseFactRepository; private ExerciseRepository exerciseRepository; private UserRepository userRepository; @Autowired public ExerciseFactController(ExerciseFactRepository exerciseFactRepo, ExerciseRepository exerciseRepo, UserRepository userRepo) { this.exerciseFactRepository = exerciseFactRepo; this.exerciseRepository = exerciseRepo; this.userRepository = userRepo; } @GetMapping("/{id}/categories") public String showCat(@PathVariable long id, Model model) { log.info("/{id}/categories"); log.info("changed selectedUser to PathVariable"); model.addAttribute("selectedUser", this.userRepository.findById(id).get()); printModelContent(model.asMap()); return "showCategories"; } @GetMapping("/{id}/{category}") public String showSubcat(@PathVariable long id, @PathVariable String category, Model model) { log.info("/{id}/{category}"); log.info(category); Collection<String> subCategories = this.exerciseRepository.findSubCategoriesByCategory(category); log.info(subCategories.toString()); model.addAttribute("subCategories", subCategories); log.info("changed subCategories to PathVariable"); printModelContent(model.asMap()); return "showSubcategories"; } @GetMapping("/{id}/{category}/{subCat}") public String showExercise1(@PathVariable long id, @PathVariable String category, @PathVariable String subCat, Model model) { log.info("/{id}/{category}/{subCat}"); log.info("dit is je geselecteerde category: " + category); log.info("dit is je geselecteerde subcat: " + subCat); List<Exercise> exercises = this.exerciseRepository.findExercisesBySubCategory(subCat); log.info("dit zijn je exercises: " + exercises.toString()); model.addAttribute("category", category); model.addAttribute("exercises", exercises); log.info("changed category to PathVariable"); log.info("changed exercises to PathVariable"); printModelContent(model.asMap()); System.out.println("hello"); return "showExercises"; } @GetMapping("/{exerciseId}") public String exerciseFormInput(@PathVariable long exerciseId, Model model) { log.info("/{exerciseId}/{userId}"); //log.info("id of user " +userId); //User selectedUser = this.userRepository.findById(userId).get(); Exercise exercise = this.exerciseRepository.findById(exerciseId).get(); log.info("gekozen exercise: " + exercise.toString() + " met id: " + exercise.getId()); //model.addAttribute("selectedUser",selectedUser); model.addAttribute("selectedExercise", exercise); printModelContent(model.asMap()); return "exerciseForm"; } @PostMapping("/newFact") public String ProcessNewFact(@ModelAttribute ExerciseFact exerciseFact, Model model) { // deze user wordt niet goed geset. Kan blijkbaar niet op basis van transient dingen? // waarom wordt date ook niet goed gebruikt? // exercise gaat ook niet naar het goede // en waarom is de id nog niet gegenerate? log.info("/newFact"); log.info("class van exerciseFact is " + exerciseFact.getClass()); exerciseFact.setUser((User) model.getAttribute("selectedUser")); exerciseFact.setExercise((Exercise) model.getAttribute("selectedExercise")); exerciseFactRepository.insertNewExerciseFactUserIdExerciseIdScore( exerciseFact.getUser().getId(), exerciseFact.getExercise().getId(), exerciseFact.getScore()); printModelContent(model.asMap()); log.info(exerciseFact.toString()); return "exerciseForm"; } // ModelAttributes @ModelAttribute(name = "exercise") public Exercise findExercise() { return new Exercise(); } @ModelAttribute(name = "categories") public Set<String> showCategories() { log.info("Put categories in Model"); Set<String> categories = new HashSet<>(); this.exerciseRepository.findAll().forEach(x -> categories.add(x.getCategory().toLowerCase())); return categories; } @ModelAttribute("selectedUser") public User findSelectedUser() { log.info("created new object selectedUser"); return new User(); } @ModelAttribute("selectedExercise") public Exercise findSelectedExercise() { log.info("created new object selectedUser"); return new Exercise(); } @ModelAttribute("exerciseFact") public ExerciseFact newExerciseFact() { return new ExerciseFact(); } public void printModelContent(Map model) { log.info("OBJECTS IN MODEL:"); for (Object modelObject : model.keySet()) { log.info(modelObject + " " + model.get(modelObject)); } log.info("EINDE"); } }
tvcstseng/FitnessApp3
src/main/java/teun/demo/controller/ExerciseFactController.java
1,590
// exercise gaat ook niet naar het goede
line_comment
nl
package teun.demo.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import teun.demo.domain.Exercise; import teun.demo.domain.ExerciseFact; import teun.demo.domain.User; import teun.demo.repository.ExerciseFactRepository; import teun.demo.repository.ExerciseRepository; import teun.demo.repository.UserRepository; import java.util.*; @Slf4j @SessionAttributes({"selectedUser", "selectedCategory", "selectedSubCategory", "selectedExercise"}) @Controller @RequestMapping("/exercise") public class ExerciseFactController { private ExerciseFactRepository exerciseFactRepository; private ExerciseRepository exerciseRepository; private UserRepository userRepository; @Autowired public ExerciseFactController(ExerciseFactRepository exerciseFactRepo, ExerciseRepository exerciseRepo, UserRepository userRepo) { this.exerciseFactRepository = exerciseFactRepo; this.exerciseRepository = exerciseRepo; this.userRepository = userRepo; } @GetMapping("/{id}/categories") public String showCat(@PathVariable long id, Model model) { log.info("/{id}/categories"); log.info("changed selectedUser to PathVariable"); model.addAttribute("selectedUser", this.userRepository.findById(id).get()); printModelContent(model.asMap()); return "showCategories"; } @GetMapping("/{id}/{category}") public String showSubcat(@PathVariable long id, @PathVariable String category, Model model) { log.info("/{id}/{category}"); log.info(category); Collection<String> subCategories = this.exerciseRepository.findSubCategoriesByCategory(category); log.info(subCategories.toString()); model.addAttribute("subCategories", subCategories); log.info("changed subCategories to PathVariable"); printModelContent(model.asMap()); return "showSubcategories"; } @GetMapping("/{id}/{category}/{subCat}") public String showExercise1(@PathVariable long id, @PathVariable String category, @PathVariable String subCat, Model model) { log.info("/{id}/{category}/{subCat}"); log.info("dit is je geselecteerde category: " + category); log.info("dit is je geselecteerde subcat: " + subCat); List<Exercise> exercises = this.exerciseRepository.findExercisesBySubCategory(subCat); log.info("dit zijn je exercises: " + exercises.toString()); model.addAttribute("category", category); model.addAttribute("exercises", exercises); log.info("changed category to PathVariable"); log.info("changed exercises to PathVariable"); printModelContent(model.asMap()); System.out.println("hello"); return "showExercises"; } @GetMapping("/{exerciseId}") public String exerciseFormInput(@PathVariable long exerciseId, Model model) { log.info("/{exerciseId}/{userId}"); //log.info("id of user " +userId); //User selectedUser = this.userRepository.findById(userId).get(); Exercise exercise = this.exerciseRepository.findById(exerciseId).get(); log.info("gekozen exercise: " + exercise.toString() + " met id: " + exercise.getId()); //model.addAttribute("selectedUser",selectedUser); model.addAttribute("selectedExercise", exercise); printModelContent(model.asMap()); return "exerciseForm"; } @PostMapping("/newFact") public String ProcessNewFact(@ModelAttribute ExerciseFact exerciseFact, Model model) { // deze user wordt niet goed geset. Kan blijkbaar niet op basis van transient dingen? // waarom wordt date ook niet goed gebruikt? // exercise gaat<SUF> // en waarom is de id nog niet gegenerate? log.info("/newFact"); log.info("class van exerciseFact is " + exerciseFact.getClass()); exerciseFact.setUser((User) model.getAttribute("selectedUser")); exerciseFact.setExercise((Exercise) model.getAttribute("selectedExercise")); exerciseFactRepository.insertNewExerciseFactUserIdExerciseIdScore( exerciseFact.getUser().getId(), exerciseFact.getExercise().getId(), exerciseFact.getScore()); printModelContent(model.asMap()); log.info(exerciseFact.toString()); return "exerciseForm"; } // ModelAttributes @ModelAttribute(name = "exercise") public Exercise findExercise() { return new Exercise(); } @ModelAttribute(name = "categories") public Set<String> showCategories() { log.info("Put categories in Model"); Set<String> categories = new HashSet<>(); this.exerciseRepository.findAll().forEach(x -> categories.add(x.getCategory().toLowerCase())); return categories; } @ModelAttribute("selectedUser") public User findSelectedUser() { log.info("created new object selectedUser"); return new User(); } @ModelAttribute("selectedExercise") public Exercise findSelectedExercise() { log.info("created new object selectedUser"); return new Exercise(); } @ModelAttribute("exerciseFact") public ExerciseFact newExerciseFact() { return new ExerciseFact(); } public void printModelContent(Map model) { log.info("OBJECTS IN MODEL:"); for (Object modelObject : model.keySet()) { log.info(modelObject + " " + model.get(modelObject)); } log.info("EINDE"); } }
True
1,126
8
1,289
11
1,362
8
1,289
11
1,616
10
false
false
false
false
false
true
1,626
10861_36
/**************************************************************************/ /* GodotLib.java */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ package org.godotengine.godot; import org.godotengine.godot.gl.GodotRenderer; import org.godotengine.godot.io.directory.DirectoryAccessHandler; import org.godotengine.godot.io.file.FileAccessHandler; import org.godotengine.godot.tts.GodotTTS; import org.godotengine.godot.utils.GodotNetUtils; import android.app.Activity; import android.content.res.AssetManager; import android.hardware.SensorEvent; import android.view.Surface; import javax.microedition.khronos.opengles.GL10; /** * Wrapper for native library */ public class GodotLib { static { System.loadLibrary("godot_android"); } /** * Invoked on the main thread to initialize Godot native layer. */ public static native boolean initialize(Activity activity, Godot p_instance, AssetManager p_asset_manager, GodotIO godotIO, GodotNetUtils netUtils, DirectoryAccessHandler directoryAccessHandler, FileAccessHandler fileAccessHandler, boolean use_apk_expansion); /** * Invoked on the main thread to clean up Godot native layer. * @see androidx.fragment.app.Fragment#onDestroy() */ public static native void ondestroy(); /** * Invoked on the GL thread to complete setup for the Godot native layer logic. * @param p_cmdline Command line arguments used to configure Godot native layer components. */ public static native boolean setup(String[] p_cmdline, GodotTTS tts); /** * Invoked on the GL thread when the underlying Android surface has changed size. * @param p_surface * @param p_width * @param p_height * @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onSurfaceChanged(GL10, int, int) */ public static native void resize(Surface p_surface, int p_width, int p_height); /** * Invoked on the render thread when the underlying Android surface is created or recreated. * @param p_surface */ public static native void newcontext(Surface p_surface); /** * Forward {@link Activity#onBackPressed()} event. */ public static native void back(); /** * Invoked on the GL thread to draw the current frame. * @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onDrawFrame(GL10) */ public static native boolean step(); /** * TTS callback. */ public static native void ttsCallback(int event, int id, int pos); /** * Forward touch events. */ public static native void dispatchTouchEvent(int event, int pointer, int pointerCount, float[] positions, boolean doubleTap); /** * Dispatch mouse events */ public static native void dispatchMouseEvent(int event, int buttonMask, float x, float y, float deltaX, float deltaY, boolean doubleClick, boolean sourceMouseRelative, float pressure, float tiltX, float tiltY); public static native void magnify(float x, float y, float factor); public static native void pan(float x, float y, float deltaX, float deltaY); /** * Forward accelerometer sensor events. * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent) */ public static native void accelerometer(float x, float y, float z); /** * Forward gravity sensor events. * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent) */ public static native void gravity(float x, float y, float z); /** * Forward magnetometer sensor events. * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent) */ public static native void magnetometer(float x, float y, float z); /** * Forward gyroscope sensor events. * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent) */ public static native void gyroscope(float x, float y, float z); /** * Forward regular key events. */ public static native void key(int p_physical_keycode, int p_unicode, int p_key_label, boolean p_pressed, boolean p_echo); /** * Forward game device's key events. */ public static native void joybutton(int p_device, int p_but, boolean p_pressed); /** * Forward joystick devices axis motion events. */ public static native void joyaxis(int p_device, int p_axis, float p_value); /** * Forward joystick devices hat motion events. */ public static native void joyhat(int p_device, int p_hat_x, int p_hat_y); /** * Fires when a joystick device is added or removed. */ public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name); /** * Invoked when the Android app resumes. * @see androidx.fragment.app.Fragment#onResume() */ public static native void focusin(); /** * Invoked when the Android app pauses. * @see androidx.fragment.app.Fragment#onPause() */ public static native void focusout(); /** * Used to access Godot global properties. * @param p_key Property key * @return String value of the property */ public static native String getGlobal(String p_key); /** * Used to access Godot's editor settings. * @param settingKey Setting key * @return String value of the setting */ public static native String getEditorSetting(String settingKey); /** * Invoke method |p_method| on the Godot object specified by |p_id| * @param p_id Id of the Godot object to invoke * @param p_method Name of the method to invoke * @param p_params Parameters to use for method invocation */ public static native void callobject(long p_id, String p_method, Object[] p_params); /** * Invoke method |p_method| on the Godot object specified by |p_id| during idle time. * @param p_id Id of the Godot object to invoke * @param p_method Name of the method to invoke * @param p_params Parameters to use for method invocation */ public static native void calldeferred(long p_id, String p_method, Object[] p_params); /** * Forward the results from a permission request. * @see Activity#onRequestPermissionsResult(int, String[], int[]) * @param p_permission Request permission * @param p_result True if the permission was granted, false otherwise */ public static native void requestPermissionResult(String p_permission, boolean p_result); /** * Invoked on the GL thread to configure the height of the virtual keyboard. */ public static native void setVirtualKeyboardHeight(int p_height); /** * Invoked on the GL thread when the {@link GodotRenderer} has been resumed. * @see GodotRenderer#onActivityResumed() */ public static native void onRendererResumed(); /** * Invoked on the GL thread when the {@link GodotRenderer} has been paused. * @see GodotRenderer#onActivityPaused() */ public static native void onRendererPaused(); }
SonicMastr/godot-vita
platform/android/java/lib/src/org/godotengine/godot/GodotLib.java
2,425
/** * Forward gyroscope sensor events. * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent) */
block_comment
nl
/**************************************************************************/ /* GodotLib.java */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ package org.godotengine.godot; import org.godotengine.godot.gl.GodotRenderer; import org.godotengine.godot.io.directory.DirectoryAccessHandler; import org.godotengine.godot.io.file.FileAccessHandler; import org.godotengine.godot.tts.GodotTTS; import org.godotengine.godot.utils.GodotNetUtils; import android.app.Activity; import android.content.res.AssetManager; import android.hardware.SensorEvent; import android.view.Surface; import javax.microedition.khronos.opengles.GL10; /** * Wrapper for native library */ public class GodotLib { static { System.loadLibrary("godot_android"); } /** * Invoked on the main thread to initialize Godot native layer. */ public static native boolean initialize(Activity activity, Godot p_instance, AssetManager p_asset_manager, GodotIO godotIO, GodotNetUtils netUtils, DirectoryAccessHandler directoryAccessHandler, FileAccessHandler fileAccessHandler, boolean use_apk_expansion); /** * Invoked on the main thread to clean up Godot native layer. * @see androidx.fragment.app.Fragment#onDestroy() */ public static native void ondestroy(); /** * Invoked on the GL thread to complete setup for the Godot native layer logic. * @param p_cmdline Command line arguments used to configure Godot native layer components. */ public static native boolean setup(String[] p_cmdline, GodotTTS tts); /** * Invoked on the GL thread when the underlying Android surface has changed size. * @param p_surface * @param p_width * @param p_height * @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onSurfaceChanged(GL10, int, int) */ public static native void resize(Surface p_surface, int p_width, int p_height); /** * Invoked on the render thread when the underlying Android surface is created or recreated. * @param p_surface */ public static native void newcontext(Surface p_surface); /** * Forward {@link Activity#onBackPressed()} event. */ public static native void back(); /** * Invoked on the GL thread to draw the current frame. * @see org.godotengine.godot.gl.GLSurfaceView.Renderer#onDrawFrame(GL10) */ public static native boolean step(); /** * TTS callback. */ public static native void ttsCallback(int event, int id, int pos); /** * Forward touch events. */ public static native void dispatchTouchEvent(int event, int pointer, int pointerCount, float[] positions, boolean doubleTap); /** * Dispatch mouse events */ public static native void dispatchMouseEvent(int event, int buttonMask, float x, float y, float deltaX, float deltaY, boolean doubleClick, boolean sourceMouseRelative, float pressure, float tiltX, float tiltY); public static native void magnify(float x, float y, float factor); public static native void pan(float x, float y, float deltaX, float deltaY); /** * Forward accelerometer sensor events. * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent) */ public static native void accelerometer(float x, float y, float z); /** * Forward gravity sensor events. * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent) */ public static native void gravity(float x, float y, float z); /** * Forward magnetometer sensor events. * @see android.hardware.SensorEventListener#onSensorChanged(SensorEvent) */ public static native void magnetometer(float x, float y, float z); /** * Forward gyroscope sensor<SUF>*/ public static native void gyroscope(float x, float y, float z); /** * Forward regular key events. */ public static native void key(int p_physical_keycode, int p_unicode, int p_key_label, boolean p_pressed, boolean p_echo); /** * Forward game device's key events. */ public static native void joybutton(int p_device, int p_but, boolean p_pressed); /** * Forward joystick devices axis motion events. */ public static native void joyaxis(int p_device, int p_axis, float p_value); /** * Forward joystick devices hat motion events. */ public static native void joyhat(int p_device, int p_hat_x, int p_hat_y); /** * Fires when a joystick device is added or removed. */ public static native void joyconnectionchanged(int p_device, boolean p_connected, String p_name); /** * Invoked when the Android app resumes. * @see androidx.fragment.app.Fragment#onResume() */ public static native void focusin(); /** * Invoked when the Android app pauses. * @see androidx.fragment.app.Fragment#onPause() */ public static native void focusout(); /** * Used to access Godot global properties. * @param p_key Property key * @return String value of the property */ public static native String getGlobal(String p_key); /** * Used to access Godot's editor settings. * @param settingKey Setting key * @return String value of the setting */ public static native String getEditorSetting(String settingKey); /** * Invoke method |p_method| on the Godot object specified by |p_id| * @param p_id Id of the Godot object to invoke * @param p_method Name of the method to invoke * @param p_params Parameters to use for method invocation */ public static native void callobject(long p_id, String p_method, Object[] p_params); /** * Invoke method |p_method| on the Godot object specified by |p_id| during idle time. * @param p_id Id of the Godot object to invoke * @param p_method Name of the method to invoke * @param p_params Parameters to use for method invocation */ public static native void calldeferred(long p_id, String p_method, Object[] p_params); /** * Forward the results from a permission request. * @see Activity#onRequestPermissionsResult(int, String[], int[]) * @param p_permission Request permission * @param p_result True if the permission was granted, false otherwise */ public static native void requestPermissionResult(String p_permission, boolean p_result); /** * Invoked on the GL thread to configure the height of the virtual keyboard. */ public static native void setVirtualKeyboardHeight(int p_height); /** * Invoked on the GL thread when the {@link GodotRenderer} has been resumed. * @see GodotRenderer#onActivityResumed() */ public static native void onRendererResumed(); /** * Invoked on the GL thread when the {@link GodotRenderer} has been paused. * @see GodotRenderer#onActivityPaused() */ public static native void onRendererPaused(); }
False
1,886
28
2,145
29
2,243
32
2,145
29
2,537
38
false
false
false
false
false
true
2,772
207454_0
package io.geekidea.boot.util; import io.geekidea.boot.framework.bean.IpRegion; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.lionsoul.ip2region.xdb.Searcher; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import org.springframework.util.FileCopyUtils; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; import java.io.InputStream; /** * IP归属地信息工具类 * * @author geekidea * @date 2023/6/23 **/ @Slf4j @Component public class IpRegionUtil { private static final String CHINA = "中国"; private static final String PROVINCE = "省"; private static final String CITY = "市"; private static final String INTRANET = "内网IP"; private static Searcher searcher; /** * 程序启动时,将ip2region.xdb一次性加载到内存中 * 并发场景下可安全使用 */ @PostConstruct private static void init() { InputStream inputStream = null; try { inputStream = new ClassPathResource("/ip2region.xdb").getInputStream(); byte[] buff = FileCopyUtils.copyToByteArray(inputStream); searcher = Searcher.newWithBuffer(buff); log.info("加载ip2region.xdb成功"); } catch (IOException e) { log.error("加载ip2region.xdb异常"); e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 根据IP获取区域信息 * * @param ip * @return */ public static IpRegion getIpRegion(String ip) { try { String region = searcher.search(ip); if (StringUtils.isBlank(region)) { return null; } String[] array = region.split("\\|"); String country = array[0]; String province = null; String city = null; String isp = null; String areaDesc; if (CHINA.equals(country)) { province = array[2]; city = array[3]; isp = array[4]; if (province.endsWith(PROVINCE)) { province = province.substring(0, province.length() - 1); } if (city.endsWith(CITY)) { city = city.substring(0, city.length() - 1); } if (province.equals(city)) { areaDesc = province; } else { areaDesc = province + " " + city; } } else if (region.contains(INTRANET)) { areaDesc = INTRANET; } else { province = array[2]; isp = array[4]; if (StringUtils.isBlank(province)) { areaDesc = country; } else { areaDesc = country + " " + province; } } IpRegion ipRegion = new IpRegion(); ipRegion.setCountry(country); ipRegion.setProvince(province); ipRegion.setCity(city); ipRegion.setAreaDesc(areaDesc); ipRegion.setIsp(isp); return ipRegion; } catch (Exception e) { log.error("解析IP归属地信息异常:" + ip); e.printStackTrace(); } return null; } /** * 通过IP获取区域描述 * * @param ip * @return */ public static String getIpAreaDesc(String ip) { IpRegion ipRegion = getIpRegion(ip); if (ipRegion != null) { return ipRegion.getAreaDesc(); } return null; } @PreDestroy public static void destroy() { try { if (searcher != null) { searcher.close(); } } catch (IOException e) { e.printStackTrace(); } } }
geekidea/spring-boot-plus
src/main/java/io/geekidea/boot/util/IpRegionUtil.java
1,161
/** * IP归属地信息工具类 * * @author geekidea * @date 2023/6/23 **/
block_comment
nl
package io.geekidea.boot.util; import io.geekidea.boot.framework.bean.IpRegion; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.lionsoul.ip2region.xdb.Searcher; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import org.springframework.util.FileCopyUtils; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; import java.io.InputStream; /** * IP归属地信息工具类 *<SUF>*/ @Slf4j @Component public class IpRegionUtil { private static final String CHINA = "中国"; private static final String PROVINCE = "省"; private static final String CITY = "市"; private static final String INTRANET = "内网IP"; private static Searcher searcher; /** * 程序启动时,将ip2region.xdb一次性加载到内存中 * 并发场景下可安全使用 */ @PostConstruct private static void init() { InputStream inputStream = null; try { inputStream = new ClassPathResource("/ip2region.xdb").getInputStream(); byte[] buff = FileCopyUtils.copyToByteArray(inputStream); searcher = Searcher.newWithBuffer(buff); log.info("加载ip2region.xdb成功"); } catch (IOException e) { log.error("加载ip2region.xdb异常"); e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 根据IP获取区域信息 * * @param ip * @return */ public static IpRegion getIpRegion(String ip) { try { String region = searcher.search(ip); if (StringUtils.isBlank(region)) { return null; } String[] array = region.split("\\|"); String country = array[0]; String province = null; String city = null; String isp = null; String areaDesc; if (CHINA.equals(country)) { province = array[2]; city = array[3]; isp = array[4]; if (province.endsWith(PROVINCE)) { province = province.substring(0, province.length() - 1); } if (city.endsWith(CITY)) { city = city.substring(0, city.length() - 1); } if (province.equals(city)) { areaDesc = province; } else { areaDesc = province + " " + city; } } else if (region.contains(INTRANET)) { areaDesc = INTRANET; } else { province = array[2]; isp = array[4]; if (StringUtils.isBlank(province)) { areaDesc = country; } else { areaDesc = country + " " + province; } } IpRegion ipRegion = new IpRegion(); ipRegion.setCountry(country); ipRegion.setProvince(province); ipRegion.setCity(city); ipRegion.setAreaDesc(areaDesc); ipRegion.setIsp(isp); return ipRegion; } catch (Exception e) { log.error("解析IP归属地信息异常:" + ip); e.printStackTrace(); } return null; } /** * 通过IP获取区域描述 * * @param ip * @return */ public static String getIpAreaDesc(String ip) { IpRegion ipRegion = getIpRegion(ip); if (ipRegion != null) { return ipRegion.getAreaDesc(); } return null; } @PreDestroy public static void destroy() { try { if (searcher != null) { searcher.close(); } } catch (IOException e) { e.printStackTrace(); } } }
False
867
32
966
35
1,048
33
966
35
1,198
42
false
false
false
false
false
true
2,612
64781_3
package nl.ealse.ccnl.ledenadministratie.dd; import java.time.LocalDate; import nl.ealse.ccnl.ledenadministratie.dd.model.AccountIdentification4Choice; import nl.ealse.ccnl.ledenadministratie.dd.model.ActiveOrHistoricCurrencyAndAmount; import nl.ealse.ccnl.ledenadministratie.dd.model.BranchAndFinancialInstitutionIdentification4; import nl.ealse.ccnl.ledenadministratie.dd.model.CashAccount16; import nl.ealse.ccnl.ledenadministratie.dd.model.ChargeBearerType1Code; import nl.ealse.ccnl.ledenadministratie.dd.model.DirectDebitTransaction6; import nl.ealse.ccnl.ledenadministratie.dd.model.DirectDebitTransactionInformation9; import nl.ealse.ccnl.ledenadministratie.dd.model.FinancialInstitutionIdentification7; import nl.ealse.ccnl.ledenadministratie.dd.model.MandateRelatedInformation6; import nl.ealse.ccnl.ledenadministratie.dd.model.PartyIdentification32; import nl.ealse.ccnl.ledenadministratie.dd.model.PaymentIdentification1; import nl.ealse.ccnl.ledenadministratie.dd.model.RemittanceInformation5; import nl.ealse.ccnl.ledenadministratie.excel.dd.BicResolver; import org.apache.commons.validator.routines.checkdigit.IBANCheckDigit; /** * Debiteur informatie deel opbouwen. * * @author Ealse * */ public class DirectDebitTransactionInformationBuilder { /** * Utility om te checken of het IBAN-nummer geldig is. */ private static final IBANCheckDigit IBAN_CHECK = new IBANCheckDigit(); private static final LocalDate START_MANDATE = LocalDate.of(2009, 11, 01); /** * Het op te bouwen object. */ private DirectDebitTransactionInformation9 transactie = new DirectDebitTransactionInformation9(); public DirectDebitTransactionInformationBuilder() { init(); } /** * Naam van de debiteur toevoegen. * * @param naam - debiteurnaam * @return builder */ public DirectDebitTransactionInformationBuilder metDibiteurNaam(String naam) { PartyIdentification32 debiteur = new PartyIdentification32(); debiteur.setNm(naam); transactie.setDbtr(debiteur); return this; } /** * IBAN-nummer van de debiteur toevoegen. DE BIC-code wordt erbij gezocht en toegevoegd. * * @param iban - toe te voegen IBAN-nummer * @return builder * @throws InvalidIbanException */ public DirectDebitTransactionInformationBuilder metDibiteurIBAN(String iban, String bicCode) throws InvalidIbanException { if (!IBAN_CHECK.isValid(iban)) { throw new InvalidIbanException(String.format("IBAN is ongeldig '%s'", iban)); } CashAccount16 ibanRekening = new CashAccount16(); AccountIdentification4Choice ibanNummer = new AccountIdentification4Choice(); ibanNummer.setIBAN(iban); ibanRekening.setId(ibanNummer); transactie.setDbtrAcct(ibanRekening); BranchAndFinancialInstitutionIdentification4 bic = new BranchAndFinancialInstitutionIdentification4(); FinancialInstitutionIdentification7 finId = new FinancialInstitutionIdentification7(); bic.setFinInstnId(finId); if (bicCode != null && !bicCode.isBlank()) { finId.setBIC(bicCode.trim()); } else { finId.setBIC(BicResolver.getBicCode(iban)); } transactie.setDbtrAgt(bic); return this; } /** * Incasso omschrijving toevoegen. * * @param lidnummer - toe te voegen nummer CCNL-lid * @return builder */ public DirectDebitTransactionInformationBuilder metLidnummer(Integer lidnummer) { PaymentIdentification1 reden = new PaymentIdentification1(); reden.setEndToEndId("lid " + lidnummer.toString()); transactie.setPmtId(reden); RemittanceInformation5 referentie = new RemittanceInformation5(); referentie.getUstrd().add(IncassoProperties.getIncassoReden()); transactie.setRmtInf(referentie); transactie.setDrctDbtTx(getMandaat(lidnummer)); return this; } /** * Mandaat gegevens invoegen voor IBAN-mandaat * * @param lidnummer - nummer waarvoor mandaat wordt toegevoegd * @return builder */ private DirectDebitTransaction6 getMandaat(Integer lidnummer) { DirectDebitTransaction6 ddtx = new DirectDebitTransaction6(); MandateRelatedInformation6 mandaat = new MandateRelatedInformation6(); mandaat.setMndtId(String.format(IncassoProperties.getMachtigingReferentie(), lidnummer)); mandaat.setDtOfSgntr(DateUtil.toXMLDate(START_MANDATE)); ddtx.setMndtRltdInf(mandaat); return ddtx; } /** * Object object opvragen. * * @return gebouwde object */ public DirectDebitTransactionInformation9 build() { return transactie; } /** * Initialisatie van vaste gegevens. */ private void init() { ActiveOrHistoricCurrencyAndAmount bedraginfo = new ActiveOrHistoricCurrencyAndAmount(); bedraginfo.setCcy("EUR"); bedraginfo.setValue(IncassoProperties.getIncassoBedrag()); transactie.setInstdAmt(bedraginfo); RemittanceInformation5 referentie = new RemittanceInformation5(); referentie.getUstrd().add(IncassoProperties.getIncassoReden()); transactie.setRmtInf(referentie); transactie.setChrgBr(ChargeBearerType1Code.SLEV); } }
ealsedewilde/ledenadministratieCCNL
annual-ccnl/src/main/java/nl/ealse/ccnl/ledenadministratie/dd/DirectDebitTransactionInformationBuilder.java
1,727
/** * Naam van de debiteur toevoegen. * * @param naam - debiteurnaam * @return builder */
block_comment
nl
package nl.ealse.ccnl.ledenadministratie.dd; import java.time.LocalDate; import nl.ealse.ccnl.ledenadministratie.dd.model.AccountIdentification4Choice; import nl.ealse.ccnl.ledenadministratie.dd.model.ActiveOrHistoricCurrencyAndAmount; import nl.ealse.ccnl.ledenadministratie.dd.model.BranchAndFinancialInstitutionIdentification4; import nl.ealse.ccnl.ledenadministratie.dd.model.CashAccount16; import nl.ealse.ccnl.ledenadministratie.dd.model.ChargeBearerType1Code; import nl.ealse.ccnl.ledenadministratie.dd.model.DirectDebitTransaction6; import nl.ealse.ccnl.ledenadministratie.dd.model.DirectDebitTransactionInformation9; import nl.ealse.ccnl.ledenadministratie.dd.model.FinancialInstitutionIdentification7; import nl.ealse.ccnl.ledenadministratie.dd.model.MandateRelatedInformation6; import nl.ealse.ccnl.ledenadministratie.dd.model.PartyIdentification32; import nl.ealse.ccnl.ledenadministratie.dd.model.PaymentIdentification1; import nl.ealse.ccnl.ledenadministratie.dd.model.RemittanceInformation5; import nl.ealse.ccnl.ledenadministratie.excel.dd.BicResolver; import org.apache.commons.validator.routines.checkdigit.IBANCheckDigit; /** * Debiteur informatie deel opbouwen. * * @author Ealse * */ public class DirectDebitTransactionInformationBuilder { /** * Utility om te checken of het IBAN-nummer geldig is. */ private static final IBANCheckDigit IBAN_CHECK = new IBANCheckDigit(); private static final LocalDate START_MANDATE = LocalDate.of(2009, 11, 01); /** * Het op te bouwen object. */ private DirectDebitTransactionInformation9 transactie = new DirectDebitTransactionInformation9(); public DirectDebitTransactionInformationBuilder() { init(); } /** * Naam van de<SUF>*/ public DirectDebitTransactionInformationBuilder metDibiteurNaam(String naam) { PartyIdentification32 debiteur = new PartyIdentification32(); debiteur.setNm(naam); transactie.setDbtr(debiteur); return this; } /** * IBAN-nummer van de debiteur toevoegen. DE BIC-code wordt erbij gezocht en toegevoegd. * * @param iban - toe te voegen IBAN-nummer * @return builder * @throws InvalidIbanException */ public DirectDebitTransactionInformationBuilder metDibiteurIBAN(String iban, String bicCode) throws InvalidIbanException { if (!IBAN_CHECK.isValid(iban)) { throw new InvalidIbanException(String.format("IBAN is ongeldig '%s'", iban)); } CashAccount16 ibanRekening = new CashAccount16(); AccountIdentification4Choice ibanNummer = new AccountIdentification4Choice(); ibanNummer.setIBAN(iban); ibanRekening.setId(ibanNummer); transactie.setDbtrAcct(ibanRekening); BranchAndFinancialInstitutionIdentification4 bic = new BranchAndFinancialInstitutionIdentification4(); FinancialInstitutionIdentification7 finId = new FinancialInstitutionIdentification7(); bic.setFinInstnId(finId); if (bicCode != null && !bicCode.isBlank()) { finId.setBIC(bicCode.trim()); } else { finId.setBIC(BicResolver.getBicCode(iban)); } transactie.setDbtrAgt(bic); return this; } /** * Incasso omschrijving toevoegen. * * @param lidnummer - toe te voegen nummer CCNL-lid * @return builder */ public DirectDebitTransactionInformationBuilder metLidnummer(Integer lidnummer) { PaymentIdentification1 reden = new PaymentIdentification1(); reden.setEndToEndId("lid " + lidnummer.toString()); transactie.setPmtId(reden); RemittanceInformation5 referentie = new RemittanceInformation5(); referentie.getUstrd().add(IncassoProperties.getIncassoReden()); transactie.setRmtInf(referentie); transactie.setDrctDbtTx(getMandaat(lidnummer)); return this; } /** * Mandaat gegevens invoegen voor IBAN-mandaat * * @param lidnummer - nummer waarvoor mandaat wordt toegevoegd * @return builder */ private DirectDebitTransaction6 getMandaat(Integer lidnummer) { DirectDebitTransaction6 ddtx = new DirectDebitTransaction6(); MandateRelatedInformation6 mandaat = new MandateRelatedInformation6(); mandaat.setMndtId(String.format(IncassoProperties.getMachtigingReferentie(), lidnummer)); mandaat.setDtOfSgntr(DateUtil.toXMLDate(START_MANDATE)); ddtx.setMndtRltdInf(mandaat); return ddtx; } /** * Object object opvragen. * * @return gebouwde object */ public DirectDebitTransactionInformation9 build() { return transactie; } /** * Initialisatie van vaste gegevens. */ private void init() { ActiveOrHistoricCurrencyAndAmount bedraginfo = new ActiveOrHistoricCurrencyAndAmount(); bedraginfo.setCcy("EUR"); bedraginfo.setValue(IncassoProperties.getIncassoBedrag()); transactie.setInstdAmt(bedraginfo); RemittanceInformation5 referentie = new RemittanceInformation5(); referentie.getUstrd().add(IncassoProperties.getIncassoReden()); transactie.setRmtInf(referentie); transactie.setChrgBr(ChargeBearerType1Code.SLEV); } }
True
1,373
35
1,523
36
1,473
35
1,523
36
1,774
39
false
false
false
false
false
true
895
8383_0
package nl.kb.core.scheduledjobs; import com.google.common.util.concurrent.AbstractScheduledService; import nl.kb.core.model.RunState; import nl.kb.core.model.repository.HarvestSchedule; import nl.kb.core.model.repository.Repository; import nl.kb.core.model.repository.RepositoryDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.concurrent.TimeUnit; /** * ScheduledRepositoryHarvester, conform spec: * Trigger * Elke dag wordt er gekeken welke harvests moeten draaien op basis van hun harvest schema, * wanneer er voor het laatst gedraaid is (startdatum laatste harvest) en of de harvest actief is. */ public class DailyIdentifierHarvestScheduler extends AbstractScheduledService { private static final Logger LOG = LoggerFactory.getLogger(DailyIdentifierHarvestScheduler.class); private final RepositoryDao repositoryDao; private final IdentifierHarvestSchedulerDaemon harvestRunner; public DailyIdentifierHarvestScheduler(RepositoryDao repositoryDao, IdentifierHarvestSchedulerDaemon harvestRunner) { this.repositoryDao = repositoryDao; this.harvestRunner = harvestRunner; } @Override protected void runOneIteration() throws Exception { try { repositoryDao.list().stream() .filter(this::harvestShouldRun) .map(Repository::getId) .forEach(harvestRunner::startHarvest); } catch (Exception e) { LOG.warn("Failed to start scheduled harvests, probably caused by missing schema", e); } } /** * Slaagt wanneer een harvest gestart mag en moet worden * 1) Staat de repository aan (getEnabled) EN * 2) Is de harvest voor deze repository niet al aan het draaien (getRunState) EN * 3a) Is er nog niet eerder geharvest? OF * 3b) Is het schema dagelijks? OF * 3c) Is het schema wekelijks en is het vandaag >= 7 sinds laatste harvest? OF * 3d) Is het schema maandelijks en is het vandaag >= 1 maand sinds laatste harvest? * * @param repository de te toetsen repository * @return of de harvest voor deze repository mag en zou moeten draaien */ private boolean harvestShouldRun(Repository repository) { return repository.getEnabled() && harvestRunner.getHarvesterRunstate(repository.getId()) == RunState.WAITING && ( repository.getSchedule() == HarvestSchedule.DAILY || repository.getLastHarvest() == null || (repository.getSchedule() == HarvestSchedule.WEEKLY && ChronoUnit.DAYS.between(repository.getLastHarvest(), LocalDate.now()) >= 7) || (repository.getSchedule() == HarvestSchedule.MONTHLY && ChronoUnit.MONTHS.between(repository.getLastHarvest(), LocalDate.now()) >= 1) ); } @Override protected Scheduler scheduler() { return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.DAYS); } }
KBNLresearch/oai-pmh-bulk-downloader
src/main/java/nl/kb/core/scheduledjobs/DailyIdentifierHarvestScheduler.java
886
/** * ScheduledRepositoryHarvester, conform spec: * Trigger * Elke dag wordt er gekeken welke harvests moeten draaien op basis van hun harvest schema, * wanneer er voor het laatst gedraaid is (startdatum laatste harvest) en of de harvest actief is. */
block_comment
nl
package nl.kb.core.scheduledjobs; import com.google.common.util.concurrent.AbstractScheduledService; import nl.kb.core.model.RunState; import nl.kb.core.model.repository.HarvestSchedule; import nl.kb.core.model.repository.Repository; import nl.kb.core.model.repository.RepositoryDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.concurrent.TimeUnit; /** * ScheduledRepositoryHarvester, conform spec:<SUF>*/ public class DailyIdentifierHarvestScheduler extends AbstractScheduledService { private static final Logger LOG = LoggerFactory.getLogger(DailyIdentifierHarvestScheduler.class); private final RepositoryDao repositoryDao; private final IdentifierHarvestSchedulerDaemon harvestRunner; public DailyIdentifierHarvestScheduler(RepositoryDao repositoryDao, IdentifierHarvestSchedulerDaemon harvestRunner) { this.repositoryDao = repositoryDao; this.harvestRunner = harvestRunner; } @Override protected void runOneIteration() throws Exception { try { repositoryDao.list().stream() .filter(this::harvestShouldRun) .map(Repository::getId) .forEach(harvestRunner::startHarvest); } catch (Exception e) { LOG.warn("Failed to start scheduled harvests, probably caused by missing schema", e); } } /** * Slaagt wanneer een harvest gestart mag en moet worden * 1) Staat de repository aan (getEnabled) EN * 2) Is de harvest voor deze repository niet al aan het draaien (getRunState) EN * 3a) Is er nog niet eerder geharvest? OF * 3b) Is het schema dagelijks? OF * 3c) Is het schema wekelijks en is het vandaag >= 7 sinds laatste harvest? OF * 3d) Is het schema maandelijks en is het vandaag >= 1 maand sinds laatste harvest? * * @param repository de te toetsen repository * @return of de harvest voor deze repository mag en zou moeten draaien */ private boolean harvestShouldRun(Repository repository) { return repository.getEnabled() && harvestRunner.getHarvesterRunstate(repository.getId()) == RunState.WAITING && ( repository.getSchedule() == HarvestSchedule.DAILY || repository.getLastHarvest() == null || (repository.getSchedule() == HarvestSchedule.WEEKLY && ChronoUnit.DAYS.between(repository.getLastHarvest(), LocalDate.now()) >= 7) || (repository.getSchedule() == HarvestSchedule.MONTHLY && ChronoUnit.MONTHS.between(repository.getLastHarvest(), LocalDate.now()) >= 1) ); } @Override protected Scheduler scheduler() { return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.DAYS); } }
True
675
65
782
81
737
62
782
81
890
80
false
false
false
false
false
true
359
23598_1
_x000D_ /**_x000D_ * This class contains the main method which allows the project to be run outside of bluej_x000D_ * _x000D_ * @author Dennis Vrieling_x000D_ * @version 0.1_x000D_ */_x000D_ _x000D_ /**_x000D_ * Dit is een tekst om te kijken of ik kan pushen._x000D_ * @author Dennis_x000D_ *_x000D_ */_x000D_ public class CarparkMain_x000D_ {_x000D_ /**_x000D_ * The starting point for the car park simulation_x000D_ * @param arg Program Arguments_x000D_ */ _x000D_ public static void main(String[] args)_x000D_ {_x000D_ Simulator simulator = new Simulator();_x000D_ simulator.run();_x000D_ } _x000D_ }_x000D_
D0pe69/Project-car-park-simulation
CarparkMain.java
163
/**_x000D_ * Dit is een tekst om te kijken of ik kan pushen._x000D_ * @author Dennis_x000D_ *_x000D_ */
block_comment
nl
_x000D_ /**_x000D_ * This class contains the main method which allows the project to be run outside of bluej_x000D_ * _x000D_ * @author Dennis Vrieling_x000D_ * @version 0.1_x000D_ */_x000D_ _x000D_ /**_x000D_ * Dit is een<SUF>*/_x000D_ public class CarparkMain_x000D_ {_x000D_ /**_x000D_ * The starting point for the car park simulation_x000D_ * @param arg Program Arguments_x000D_ */ _x000D_ public static void main(String[] args)_x000D_ {_x000D_ Simulator simulator = new Simulator();_x000D_ simulator.run();_x000D_ } _x000D_ }_x000D_
True
270
46
307
57
305
51
307
57
317
55
false
false
false
false
false
true
3,547
112983_3
package com.tierep.twitterlists.ui; import android.os.AsyncTask; import android.os.Bundle; import com.tierep.twitterlists.R; import com.tierep.twitterlists.Session; import com.tierep.twitterlists.adapters.ListNonMembersAdapter; import com.tierep.twitterlists.twitter4jcache.TwitterCache; import java.util.Collections; import java.util.LinkedList; import java.util.List; import twitter4j.PagableResponseList; import twitter4j.TwitterException; import twitter4j.User; import twitter4j.UserList; /** * A fragment representing a single TwitterList detail screen. * This fragment is either contained in a {@link ListActivity} * in two-pane mode (on tablets) or a {@link ListDetailActivity} * on handsets. * * Created by pieter on 02/02/15. */ public class ListDetailNonMembersFragment extends ListDetailFragment { @Override protected void initializeList() { new AsyncTask<Void, Void, PagableResponseList<User>>() { @Override protected PagableResponseList<User> doInBackground(Void... params) { TwitterCache twitter = Session.getInstance().getTwitterCacheInstance(); List<User> listMembers = new LinkedList<>(); try { PagableResponseList<User> response = null; do { if (response == null) { response = twitter.getUserListMembers(userList.getId(), -1); listMembers.addAll(response); } else { response = twitter.getUserListMembers(userList.getId(), response.getNextCursor()); listMembers.addAll(response); } } while (response.hasNext()); } catch (TwitterException e) { e.printStackTrace(); } // The friend list is paged, the next response is fetched in the adapter. try { PagableResponseList<User> response = twitter.getFriendsList(Session.getInstance().getUserId(), -1); for (User user : listMembers) { response.remove(user); } return response; } catch (TwitterException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(PagableResponseList<User> users) { if (users != null) { makeListAdapter(users, new LinkedList<>(Collections.nCopies(users.size(), R.drawable.member_add_touch))); } // TODO hier nog de case afhandelen dat userLists null is. // TODO ook speciaal geval afhandelen dat de user geen lijsten heeft (count = 0). } }.execute(); } @Override protected void makeListAdapter(PagableResponseList<User> users, LinkedList<Integer> actions) { setListAdapter(new ListNonMembersAdapter(getActivity(), userList.getId(), users, actions)); } public static ListDetailNonMembersFragment newInstance(UserList userList) { Bundle arguments = new Bundle(); arguments.putSerializable(ListDetailFragment.ARG_USERLIST, userList); ListDetailNonMembersFragment frag = new ListDetailNonMembersFragment(); frag.setArguments(arguments); return frag; } }
maniacs-m/TwitterLists
app/src/main/java/com/tierep/twitterlists/ui/ListDetailNonMembersFragment.java
901
// TODO ook speciaal geval afhandelen dat de user geen lijsten heeft (count = 0).
line_comment
nl
package com.tierep.twitterlists.ui; import android.os.AsyncTask; import android.os.Bundle; import com.tierep.twitterlists.R; import com.tierep.twitterlists.Session; import com.tierep.twitterlists.adapters.ListNonMembersAdapter; import com.tierep.twitterlists.twitter4jcache.TwitterCache; import java.util.Collections; import java.util.LinkedList; import java.util.List; import twitter4j.PagableResponseList; import twitter4j.TwitterException; import twitter4j.User; import twitter4j.UserList; /** * A fragment representing a single TwitterList detail screen. * This fragment is either contained in a {@link ListActivity} * in two-pane mode (on tablets) or a {@link ListDetailActivity} * on handsets. * * Created by pieter on 02/02/15. */ public class ListDetailNonMembersFragment extends ListDetailFragment { @Override protected void initializeList() { new AsyncTask<Void, Void, PagableResponseList<User>>() { @Override protected PagableResponseList<User> doInBackground(Void... params) { TwitterCache twitter = Session.getInstance().getTwitterCacheInstance(); List<User> listMembers = new LinkedList<>(); try { PagableResponseList<User> response = null; do { if (response == null) { response = twitter.getUserListMembers(userList.getId(), -1); listMembers.addAll(response); } else { response = twitter.getUserListMembers(userList.getId(), response.getNextCursor()); listMembers.addAll(response); } } while (response.hasNext()); } catch (TwitterException e) { e.printStackTrace(); } // The friend list is paged, the next response is fetched in the adapter. try { PagableResponseList<User> response = twitter.getFriendsList(Session.getInstance().getUserId(), -1); for (User user : listMembers) { response.remove(user); } return response; } catch (TwitterException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(PagableResponseList<User> users) { if (users != null) { makeListAdapter(users, new LinkedList<>(Collections.nCopies(users.size(), R.drawable.member_add_touch))); } // TODO hier nog de case afhandelen dat userLists null is. // TODO ook<SUF> } }.execute(); } @Override protected void makeListAdapter(PagableResponseList<User> users, LinkedList<Integer> actions) { setListAdapter(new ListNonMembersAdapter(getActivity(), userList.getId(), users, actions)); } public static ListDetailNonMembersFragment newInstance(UserList userList) { Bundle arguments = new Bundle(); arguments.putSerializable(ListDetailFragment.ARG_USERLIST, userList); ListDetailNonMembersFragment frag = new ListDetailNonMembersFragment(); frag.setArguments(arguments); return frag; } }
True
637
24
753
29
772
22
753
29
888
24
false
false
false
false
false
true
1,404
70578_17
import greenfoot.*; import java.util.List; /** * * @author R. Springer */ public class TileEngine { public static int TILE_WIDTH; public static int TILE_HEIGHT; public static int SCREEN_HEIGHT; public static int SCREEN_WIDTH; public static int MAP_WIDTH; public static int MAP_HEIGHT; private World world; private int[][] map; private Tile[][] generateMap; private TileFactory tileFactory; /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations */ public TileEngine(World world, int tileWidth, int tileHeight) { this.world = world; TILE_WIDTH = tileWidth; TILE_HEIGHT = tileHeight; SCREEN_WIDTH = world.getWidth(); SCREEN_HEIGHT = world.getHeight(); this.tileFactory = new TileFactory(); } /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations * @param map A tilemap with numbers */ public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) { this(world, tileWidth, tileHeight); this.setMap(map); } /** * The setMap method used to set a map. This method also clears the previous * map and generates a new one. * * @param map */ public void setMap(int[][] map) { this.clearTilesWorld(); this.map = map; MAP_HEIGHT = this.map.length; MAP_WIDTH = this.map[0].length; this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH]; this.generateWorld(); } /** * The setTileFactory sets a tilefactory. You can use this if you want to * create you own tilefacory and use it in the class. * * @param tf A Tilefactory or extend of it. */ public void setTileFactory(TileFactory tf) { this.tileFactory = tf; } /** * Removes al the tiles from the world. */ public void clearTilesWorld() { List<Tile> removeObjects = this.world.getObjects(Tile.class); this.world.removeObjects(removeObjects); this.map = null; this.generateMap = null; MAP_HEIGHT = 0; MAP_WIDTH = 0; } /** * Creates the tile world based on the TileFactory and the map icons. */ public void generateWorld() { int mapID = 0; for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { // Nummer ophalen in de int array mapID++; int mapIcon = this.map[y][x]; if (mapIcon == -1) { continue; } // Als de mapIcon -1 is dan wordt de code hieronder overgeslagen // Dus er wordt geen tile aangemaakt. -1 is dus geen tile; Tile createdTile = this.tileFactory.createTile(mapIcon); createdTile.setMapID(mapID); createdTile.setMapIcon(mapIcon); addTileAt(createdTile, x, y); } } } /** * Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and * TILE_HEIGHT * * @param tile The Tile * @param colom The colom where the tile exist in the map * @param row The row where the tile exist in the map */ public void addTileAt(Tile tile, int colom, int row) { // De X en Y positie zitten het midden van de Actor. // De tilemap genereerd een wereld gebaseerd op dat de X en Y // positie links boven in zitten. Vandaar de we de helft van de // breedte en hoogte optellen zodat de X en Y links boven zit voor // het toevoegen van het object. this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2); // Toevoegen aan onze lokale array. Makkelijk om de tile op te halen // op basis van een x en y positie van de map this.generateMap[row][colom] = tile; tile.setColom(colom); tile.setRow(row); } /** * Retrieves a tile at the location based on colom and row in the map * * @param colom * @param row * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return null; } return this.generateMap[row][colom]; } /** * Retrieves a tile based on a x and y position in the world * * @param x X-position in the world * @param y Y-position in the world * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); Tile tile = getTileAt(col, row); return tile; } /** * Removes tile at the given colom and row * * @param colom * @param row * @return true if the tile has successfully been removed */ public boolean removeTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return false; } Tile tile = this.generateMap[row][colom]; if (tile != null) { this.world.removeObject(tile); this.generateMap[row][colom] = null; return true; } return false; } /** * Removes tile at the given x and y position * * @param x X-position in the world * @param y Y-position in the world * @return true if the tile has successfully been removed */ public boolean removeTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); return removeTileAt(col, row); } /** * Removes the tile based on a tile * * @param tile Tile from the tilemap * @return true if the tile has successfully been removed */ public boolean removeTile(Tile tile) { int colom = tile.getColom(); int row = tile.getRow(); if (colom != -1 && row != -1) { return this.removeTileAt(colom, row); } return false; } /** * This methode checks if a tile on a x and y position in the world is solid * or not. * * @param x X-position in the world * @param y Y-position in the world * @return Tile at location is solid */ public boolean checkTileSolid(int x, int y) { Tile tile = getTileAtXY(x, y); if (tile != null && tile.isSolid) { return true; } return false; } /** * This methode returns a colom based on a x position. * * @param x * @return the colom */ public int getColumn(int x) { return (int) Math.floor(x / TILE_WIDTH); } /** * This methode returns a row based on a y position. * * @param y * @return the row */ public int getRow(int y) { return (int) Math.floor(y / TILE_HEIGHT); } /** * This methode returns a x position based on the colom * * @param col * @return The x position */ public int getX(int col) { return col * TILE_WIDTH; } /** * This methode returns a y position based on the row * * @param row * @return The y position */ public int getY(int row) { return row * TILE_HEIGHT; } }
ROCMondriaanTIN/project-greenfoot-game-VitoKloots
TileEngine.java
2,422
// op basis van een x en y positie van de map
line_comment
nl
import greenfoot.*; import java.util.List; /** * * @author R. Springer */ public class TileEngine { public static int TILE_WIDTH; public static int TILE_HEIGHT; public static int SCREEN_HEIGHT; public static int SCREEN_WIDTH; public static int MAP_WIDTH; public static int MAP_HEIGHT; private World world; private int[][] map; private Tile[][] generateMap; private TileFactory tileFactory; /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations */ public TileEngine(World world, int tileWidth, int tileHeight) { this.world = world; TILE_WIDTH = tileWidth; TILE_HEIGHT = tileHeight; SCREEN_WIDTH = world.getWidth(); SCREEN_HEIGHT = world.getHeight(); this.tileFactory = new TileFactory(); } /** * Constuctor of the TileEngine * * @param world A World class or a extend of it. * @param tileWidth The width of the tile used in the TileFactory and * calculations * @param tileHeight The heigth of the tile used in the TileFactory and * calculations * @param map A tilemap with numbers */ public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) { this(world, tileWidth, tileHeight); this.setMap(map); } /** * The setMap method used to set a map. This method also clears the previous * map and generates a new one. * * @param map */ public void setMap(int[][] map) { this.clearTilesWorld(); this.map = map; MAP_HEIGHT = this.map.length; MAP_WIDTH = this.map[0].length; this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH]; this.generateWorld(); } /** * The setTileFactory sets a tilefactory. You can use this if you want to * create you own tilefacory and use it in the class. * * @param tf A Tilefactory or extend of it. */ public void setTileFactory(TileFactory tf) { this.tileFactory = tf; } /** * Removes al the tiles from the world. */ public void clearTilesWorld() { List<Tile> removeObjects = this.world.getObjects(Tile.class); this.world.removeObjects(removeObjects); this.map = null; this.generateMap = null; MAP_HEIGHT = 0; MAP_WIDTH = 0; } /** * Creates the tile world based on the TileFactory and the map icons. */ public void generateWorld() { int mapID = 0; for (int y = 0; y < MAP_HEIGHT; y++) { for (int x = 0; x < MAP_WIDTH; x++) { // Nummer ophalen in de int array mapID++; int mapIcon = this.map[y][x]; if (mapIcon == -1) { continue; } // Als de mapIcon -1 is dan wordt de code hieronder overgeslagen // Dus er wordt geen tile aangemaakt. -1 is dus geen tile; Tile createdTile = this.tileFactory.createTile(mapIcon); createdTile.setMapID(mapID); createdTile.setMapIcon(mapIcon); addTileAt(createdTile, x, y); } } } /** * Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and * TILE_HEIGHT * * @param tile The Tile * @param colom The colom where the tile exist in the map * @param row The row where the tile exist in the map */ public void addTileAt(Tile tile, int colom, int row) { // De X en Y positie zitten het midden van de Actor. // De tilemap genereerd een wereld gebaseerd op dat de X en Y // positie links boven in zitten. Vandaar de we de helft van de // breedte en hoogte optellen zodat de X en Y links boven zit voor // het toevoegen van het object. this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2); // Toevoegen aan onze lokale array. Makkelijk om de tile op te halen // op basis<SUF> this.generateMap[row][colom] = tile; tile.setColom(colom); tile.setRow(row); } /** * Retrieves a tile at the location based on colom and row in the map * * @param colom * @param row * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return null; } return this.generateMap[row][colom]; } /** * Retrieves a tile based on a x and y position in the world * * @param x X-position in the world * @param y Y-position in the world * @return The tile at the location colom and row. Returns null if it cannot * find a tile. */ public Tile getTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); Tile tile = getTileAt(col, row); return tile; } /** * Removes tile at the given colom and row * * @param colom * @param row * @return true if the tile has successfully been removed */ public boolean removeTileAt(int colom, int row) { if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) { return false; } Tile tile = this.generateMap[row][colom]; if (tile != null) { this.world.removeObject(tile); this.generateMap[row][colom] = null; return true; } return false; } /** * Removes tile at the given x and y position * * @param x X-position in the world * @param y Y-position in the world * @return true if the tile has successfully been removed */ public boolean removeTileAtXY(int x, int y) { int col = getColumn(x); int row = getRow(y); return removeTileAt(col, row); } /** * Removes the tile based on a tile * * @param tile Tile from the tilemap * @return true if the tile has successfully been removed */ public boolean removeTile(Tile tile) { int colom = tile.getColom(); int row = tile.getRow(); if (colom != -1 && row != -1) { return this.removeTileAt(colom, row); } return false; } /** * This methode checks if a tile on a x and y position in the world is solid * or not. * * @param x X-position in the world * @param y Y-position in the world * @return Tile at location is solid */ public boolean checkTileSolid(int x, int y) { Tile tile = getTileAtXY(x, y); if (tile != null && tile.isSolid) { return true; } return false; } /** * This methode returns a colom based on a x position. * * @param x * @return the colom */ public int getColumn(int x) { return (int) Math.floor(x / TILE_WIDTH); } /** * This methode returns a row based on a y position. * * @param y * @return the row */ public int getRow(int y) { return (int) Math.floor(y / TILE_HEIGHT); } /** * This methode returns a x position based on the colom * * @param col * @return The x position */ public int getX(int col) { return col * TILE_WIDTH; } /** * This methode returns a y position based on the row * * @param row * @return The y position */ public int getY(int row) { return row * TILE_HEIGHT; } }
True
1,976
13
2,077
13
2,265
13
2,091
13
2,483
13
false
false
false
false
false
true
1,742
19825_5
package apps.myapplication; /** * Created by Boning on 21-8-2015. */ public class ThreeRow { private static int Block1; private static int Block2; public ThreeRow(int B1, int B2) { this.Block1 = B1; this.Block2 = B2; } public int[] calcOptions() { int[] res = new int[2]; int option1; int option2; // Block1 ligt rechts van block2 if((Block1 - Block2) == 1) { option1 = Block1 + 1; option2 = Block2 - 1; res[0] = option1; res[1] = option2; return res; } // Block1 ligt boven Block2 else if((Block1 - Block2) == 10) { option1 = Block1 + 10; option2 = Block2 - 10; res[0] = option1; res[1] = option2; return res; } // Block1 ligt rechtsonder Block2 else if((Block1 - Block2) == 11) { option1 = Block1 + 11; option2 = Block2 - 11; res[0] = option1; res[1] = option2; return res; } // Block1 ligt linksonder Block2 else if((Block1 - Block2) == 9) { option1 = Block1 + 9; option2 = Block2 - 9; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd naast elkaar met 1 block ertussen in else if((Block1 - Block2) == 2) { option1 = Block1 - 1; option2 = Block2 + 1; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd boven elkaar met 1 block ertussen in else if((Block1 - Block2 == 20)) { option1 = Block1 - 10; option2 = Block2 + 10; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd rechts schuinonder elkaar met 1 block ertussen in else if((Block1 - Block2 == 22)) { option1 = Block1 - 11; option2 = Block2 + 11; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd links schuinonder elkaar met 1 block ertussen in else if((Block1 - Block2 == 18)) { option1 = Block1 - 9; option2 = Block2 + 9; res[0] = option1; res[1] = option2; return res; } return null; } public int getBlock1() { return Block1; } public int getBlock2() { return Block2; } public void setBlock1(int B1) { Block1 = B1; } public void setBlock2(int B2) { Block2 = B2; } }
TimBuckers/AndroidApp
app/src/main/java/apps/myapplication/ThreeRow.java
915
// Block1 en Block2 liggen 1 verwijderd naast elkaar met 1 block ertussen in
line_comment
nl
package apps.myapplication; /** * Created by Boning on 21-8-2015. */ public class ThreeRow { private static int Block1; private static int Block2; public ThreeRow(int B1, int B2) { this.Block1 = B1; this.Block2 = B2; } public int[] calcOptions() { int[] res = new int[2]; int option1; int option2; // Block1 ligt rechts van block2 if((Block1 - Block2) == 1) { option1 = Block1 + 1; option2 = Block2 - 1; res[0] = option1; res[1] = option2; return res; } // Block1 ligt boven Block2 else if((Block1 - Block2) == 10) { option1 = Block1 + 10; option2 = Block2 - 10; res[0] = option1; res[1] = option2; return res; } // Block1 ligt rechtsonder Block2 else if((Block1 - Block2) == 11) { option1 = Block1 + 11; option2 = Block2 - 11; res[0] = option1; res[1] = option2; return res; } // Block1 ligt linksonder Block2 else if((Block1 - Block2) == 9) { option1 = Block1 + 9; option2 = Block2 - 9; res[0] = option1; res[1] = option2; return res; } // Block1 en<SUF> else if((Block1 - Block2) == 2) { option1 = Block1 - 1; option2 = Block2 + 1; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd boven elkaar met 1 block ertussen in else if((Block1 - Block2 == 20)) { option1 = Block1 - 10; option2 = Block2 + 10; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd rechts schuinonder elkaar met 1 block ertussen in else if((Block1 - Block2 == 22)) { option1 = Block1 - 11; option2 = Block2 + 11; res[0] = option1; res[1] = option2; return res; } // Block1 en Block2 liggen 1 verwijderd links schuinonder elkaar met 1 block ertussen in else if((Block1 - Block2 == 18)) { option1 = Block1 - 9; option2 = Block2 + 9; res[0] = option1; res[1] = option2; return res; } return null; } public int getBlock1() { return Block1; } public int getBlock2() { return Block2; } public void setBlock1(int B1) { Block1 = B1; } public void setBlock2(int B2) { Block2 = B2; } }
True
833
25
859
28
912
20
859
28
962
27
false
false
false
false
false
true
181
8391_11
/* * Copyright (C) 2011-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.config.services; import java.util.*; import javax.persistence.*; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.opengis.filter.Filter; import org.stripesstuff.stripersist.Stripersist; /** * * @author Matthijs Laan */ @Entity @Table(name="feature_type") @org.hibernate.annotations.Entity(dynamicUpdate = true) public class SimpleFeatureType { private static final Log log = LogFactory.getLog(SimpleFeatureType.class); public static final int MAX_FEATURES_DEFAULT = 250; public static final int MAX_FEATURES_UNBOUNDED = -1; @Id private Long id; @ManyToOne(cascade=CascadeType.PERSIST) private FeatureSource featureSource; private String typeName; private String description; private boolean writeable; private String geometryAttribute; @OneToMany (cascade=CascadeType.ALL, mappedBy="featureType") private List<FeatureTypeRelation> relations = new ArrayList<FeatureTypeRelation>(); @ManyToMany(cascade=CascadeType.ALL) // Actually @OneToMany, workaround for HHH-1268 @JoinTable(inverseJoinColumns=@JoinColumn(name="attribute_descriptor")) @OrderColumn(name="list_index") private List<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>(); //<editor-fold defaultstate="collapsed" desc="getters en setters"> public List<AttributeDescriptor> getAttributes() { return attributes; } public void setAttributes(List<AttributeDescriptor> attributes) { this.attributes = attributes; } public FeatureSource getFeatureSource() { return featureSource; } public void setFeatureSource(FeatureSource featureSource) { this.featureSource = featureSource; } public String getGeometryAttribute() { return geometryAttribute; } public void setGeometryAttribute(String geometryAttribute) { this.geometryAttribute = geometryAttribute; } public boolean isWriteable() { return writeable; } public void setWriteable(boolean writeable) { this.writeable = writeable; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<FeatureTypeRelation> getRelations() { return relations; } public void setRelations(List<FeatureTypeRelation> relations) { this.relations = relations; } //</editor-fold> public Object getMaxValue ( String attributeName, Filter f )throws Exception { return featureSource.getMaxValue(this, attributeName, MAX_FEATURES_DEFAULT, f); } public Object getMaxValue ( String attributeName, int maxFeatures )throws Exception { return featureSource.getMaxValue(this, attributeName, maxFeatures,null); } public Object getMinValue ( String attributeName, Filter f )throws Exception { return featureSource.getMinValue(this, attributeName, MAX_FEATURES_DEFAULT, f); } public Object getMinValue ( String attributeName, int maxFeatures )throws Exception { return featureSource.getMinValue(this, attributeName, maxFeatures, null); } public List<String> calculateUniqueValues(String attributeName) throws Exception { return featureSource.calculateUniqueValues(this, attributeName, MAX_FEATURES_DEFAULT,null); } public List<String> calculateUniqueValues(String attributeName, int maxFeatures) throws Exception { return featureSource.calculateUniqueValues(this, attributeName, maxFeatures, null); } public List<String> calculateUniqueValues(String attributeName, int maxFeatures, Filter filter) throws Exception { return featureSource.calculateUniqueValues(this, attributeName, maxFeatures, filter); } public Map<String, String> getKeysValues(String key, String label, int maxFeatures) throws Exception { return featureSource.getKeyValuePairs(this, key, label, maxFeatures); } public Map<String, String> getKeysValues(String key, String label) throws Exception { return featureSource.getKeyValuePairs(this, key, label, MAX_FEATURES_DEFAULT); } public org.geotools.data.FeatureSource openGeoToolsFeatureSource() throws Exception { return featureSource.openGeoToolsFeatureSource(this); } public org.geotools.data.FeatureSource openGeoToolsFeatureSource(int timeout) throws Exception { return featureSource.openGeoToolsFeatureSource(this, timeout); } public boolean update(SimpleFeatureType update) { if(!getTypeName().equals(update.getTypeName())) { throw new IllegalArgumentException("Cannot update feature type with properties from feature type with different type name!"); } description = update.description; writeable = update.writeable; geometryAttribute = update.geometryAttribute; boolean changed = false; // Retain user set aliases for attributes // Does not work correctly for Arc* feature sources which set attribute // title in alias... Needs other field to differentiate user set title Map<String,String> aliasesByAttributeName = new HashMap(); for(AttributeDescriptor ad: attributes) { if(StringUtils.isNotBlank(ad.getAlias())) { aliasesByAttributeName.put(ad.getName(), ad.getAlias()); } } //loop over oude attributes // voor iedere oude attr kijk of er een attib ib de update.attributes zit // zo ja kijk of type gelijk is // als type niet gelijk dan oude attr verwijderen en vervangen door nieuwe, evt met alias kopieren // zo niet dan toevoegen nieuw attr aan oude set // loop over nieuwe attributen om te kijken of er oude verwijderd moeten worden // todo: Het is handiger om deze check op basis van 2 hashmaps uittevoeren if(!attributes.equals(update.attributes)) { changed = true; for(int i = 0; i < attributes.size();i++){ boolean notFound = true; for(AttributeDescriptor newAttribute: update.attributes){ if(attributes.get(i).getName().equals(newAttribute.getName())){ notFound = false; AttributeDescriptor oldAttr = attributes.get(i); if(Objects.equals(oldAttr.getType(), newAttribute.getType())){ // ! expression didnt work(???) so dummy if-else (else is only used) }else{ attributes.remove(i); attributes.add(i, newAttribute); } break; } } if(notFound){ attributes.remove(i); } } //nieuwe attributen worden hier toegevoegd aan de oude attributen lijst for(int i = 0; i < update.attributes.size();i++){ boolean notFound = true; for(AttributeDescriptor oldAttribute: attributes){ if(update.attributes.get(i).getName().equals(oldAttribute.getName())){ notFound = false; break; } } if(notFound){ attributes.add(update.attributes.get(i)); } } } //update.attributes ID = NULL so the attributes list is getting NULL aswell //if(!attributes.equals(update.attributes)) { //attributes.clear(); //attributes.addAll(update.attributes); //changed = true; //} for(AttributeDescriptor ad: attributes) { String alias = aliasesByAttributeName.get(ad.getName()); if(alias != null) { ad.setAlias(alias); } } return changed; } public static void clearReferences(Collection<SimpleFeatureType> typesToRemove) { // Clear references int removed = Stripersist.getEntityManager().createQuery("update Layer set featureType = null where featureType in (:types)") .setParameter("types", typesToRemove) .executeUpdate(); if(removed > 0) { log.warn("Cleared " + removed + " references to " + typesToRemove.size() + " type names which are to be removed"); } // Ignore Layar references } public AttributeDescriptor getAttribute(String attributeName) { for(AttributeDescriptor ad: attributes) { if(ad.getName().equals(attributeName)) { return ad; } } return null; } public JSONObject toJSONObject() throws JSONException { JSONObject o = new JSONObject(); o.put("id", id); o.put("typeName", typeName); o.put("writeable", writeable); o.put("geometryAttribute", geometryAttribute); JSONArray atts = new JSONArray(); o.put("attributes", atts); for(AttributeDescriptor a: attributes) { JSONObject ja = new JSONObject(); ja.put("id", a.getId()); ja.put("name", a.getName()); ja.put("alias", a.getAlias()); ja.put("type", a.getType()); atts.put(ja); } return o; } public boolean hasRelations() { return this.relations!=null && this.relations.size()>0; } }
B3Partners/tailormap
viewer-config-persistence/src/main/java/nl/b3p/viewer/config/services/SimpleFeatureType.java
2,881
// zo niet dan toevoegen nieuw attr aan oude set
line_comment
nl
/* * Copyright (C) 2011-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.config.services; import java.util.*; import javax.persistence.*; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.opengis.filter.Filter; import org.stripesstuff.stripersist.Stripersist; /** * * @author Matthijs Laan */ @Entity @Table(name="feature_type") @org.hibernate.annotations.Entity(dynamicUpdate = true) public class SimpleFeatureType { private static final Log log = LogFactory.getLog(SimpleFeatureType.class); public static final int MAX_FEATURES_DEFAULT = 250; public static final int MAX_FEATURES_UNBOUNDED = -1; @Id private Long id; @ManyToOne(cascade=CascadeType.PERSIST) private FeatureSource featureSource; private String typeName; private String description; private boolean writeable; private String geometryAttribute; @OneToMany (cascade=CascadeType.ALL, mappedBy="featureType") private List<FeatureTypeRelation> relations = new ArrayList<FeatureTypeRelation>(); @ManyToMany(cascade=CascadeType.ALL) // Actually @OneToMany, workaround for HHH-1268 @JoinTable(inverseJoinColumns=@JoinColumn(name="attribute_descriptor")) @OrderColumn(name="list_index") private List<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>(); //<editor-fold defaultstate="collapsed" desc="getters en setters"> public List<AttributeDescriptor> getAttributes() { return attributes; } public void setAttributes(List<AttributeDescriptor> attributes) { this.attributes = attributes; } public FeatureSource getFeatureSource() { return featureSource; } public void setFeatureSource(FeatureSource featureSource) { this.featureSource = featureSource; } public String getGeometryAttribute() { return geometryAttribute; } public void setGeometryAttribute(String geometryAttribute) { this.geometryAttribute = geometryAttribute; } public boolean isWriteable() { return writeable; } public void setWriteable(boolean writeable) { this.writeable = writeable; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<FeatureTypeRelation> getRelations() { return relations; } public void setRelations(List<FeatureTypeRelation> relations) { this.relations = relations; } //</editor-fold> public Object getMaxValue ( String attributeName, Filter f )throws Exception { return featureSource.getMaxValue(this, attributeName, MAX_FEATURES_DEFAULT, f); } public Object getMaxValue ( String attributeName, int maxFeatures )throws Exception { return featureSource.getMaxValue(this, attributeName, maxFeatures,null); } public Object getMinValue ( String attributeName, Filter f )throws Exception { return featureSource.getMinValue(this, attributeName, MAX_FEATURES_DEFAULT, f); } public Object getMinValue ( String attributeName, int maxFeatures )throws Exception { return featureSource.getMinValue(this, attributeName, maxFeatures, null); } public List<String> calculateUniqueValues(String attributeName) throws Exception { return featureSource.calculateUniqueValues(this, attributeName, MAX_FEATURES_DEFAULT,null); } public List<String> calculateUniqueValues(String attributeName, int maxFeatures) throws Exception { return featureSource.calculateUniqueValues(this, attributeName, maxFeatures, null); } public List<String> calculateUniqueValues(String attributeName, int maxFeatures, Filter filter) throws Exception { return featureSource.calculateUniqueValues(this, attributeName, maxFeatures, filter); } public Map<String, String> getKeysValues(String key, String label, int maxFeatures) throws Exception { return featureSource.getKeyValuePairs(this, key, label, maxFeatures); } public Map<String, String> getKeysValues(String key, String label) throws Exception { return featureSource.getKeyValuePairs(this, key, label, MAX_FEATURES_DEFAULT); } public org.geotools.data.FeatureSource openGeoToolsFeatureSource() throws Exception { return featureSource.openGeoToolsFeatureSource(this); } public org.geotools.data.FeatureSource openGeoToolsFeatureSource(int timeout) throws Exception { return featureSource.openGeoToolsFeatureSource(this, timeout); } public boolean update(SimpleFeatureType update) { if(!getTypeName().equals(update.getTypeName())) { throw new IllegalArgumentException("Cannot update feature type with properties from feature type with different type name!"); } description = update.description; writeable = update.writeable; geometryAttribute = update.geometryAttribute; boolean changed = false; // Retain user set aliases for attributes // Does not work correctly for Arc* feature sources which set attribute // title in alias... Needs other field to differentiate user set title Map<String,String> aliasesByAttributeName = new HashMap(); for(AttributeDescriptor ad: attributes) { if(StringUtils.isNotBlank(ad.getAlias())) { aliasesByAttributeName.put(ad.getName(), ad.getAlias()); } } //loop over oude attributes // voor iedere oude attr kijk of er een attib ib de update.attributes zit // zo ja kijk of type gelijk is // als type niet gelijk dan oude attr verwijderen en vervangen door nieuwe, evt met alias kopieren // zo niet<SUF> // loop over nieuwe attributen om te kijken of er oude verwijderd moeten worden // todo: Het is handiger om deze check op basis van 2 hashmaps uittevoeren if(!attributes.equals(update.attributes)) { changed = true; for(int i = 0; i < attributes.size();i++){ boolean notFound = true; for(AttributeDescriptor newAttribute: update.attributes){ if(attributes.get(i).getName().equals(newAttribute.getName())){ notFound = false; AttributeDescriptor oldAttr = attributes.get(i); if(Objects.equals(oldAttr.getType(), newAttribute.getType())){ // ! expression didnt work(???) so dummy if-else (else is only used) }else{ attributes.remove(i); attributes.add(i, newAttribute); } break; } } if(notFound){ attributes.remove(i); } } //nieuwe attributen worden hier toegevoegd aan de oude attributen lijst for(int i = 0; i < update.attributes.size();i++){ boolean notFound = true; for(AttributeDescriptor oldAttribute: attributes){ if(update.attributes.get(i).getName().equals(oldAttribute.getName())){ notFound = false; break; } } if(notFound){ attributes.add(update.attributes.get(i)); } } } //update.attributes ID = NULL so the attributes list is getting NULL aswell //if(!attributes.equals(update.attributes)) { //attributes.clear(); //attributes.addAll(update.attributes); //changed = true; //} for(AttributeDescriptor ad: attributes) { String alias = aliasesByAttributeName.get(ad.getName()); if(alias != null) { ad.setAlias(alias); } } return changed; } public static void clearReferences(Collection<SimpleFeatureType> typesToRemove) { // Clear references int removed = Stripersist.getEntityManager().createQuery("update Layer set featureType = null where featureType in (:types)") .setParameter("types", typesToRemove) .executeUpdate(); if(removed > 0) { log.warn("Cleared " + removed + " references to " + typesToRemove.size() + " type names which are to be removed"); } // Ignore Layar references } public AttributeDescriptor getAttribute(String attributeName) { for(AttributeDescriptor ad: attributes) { if(ad.getName().equals(attributeName)) { return ad; } } return null; } public JSONObject toJSONObject() throws JSONException { JSONObject o = new JSONObject(); o.put("id", id); o.put("typeName", typeName); o.put("writeable", writeable); o.put("geometryAttribute", geometryAttribute); JSONArray atts = new JSONArray(); o.put("attributes", atts); for(AttributeDescriptor a: attributes) { JSONObject ja = new JSONObject(); ja.put("id", a.getId()); ja.put("name", a.getName()); ja.put("alias", a.getAlias()); ja.put("type", a.getType()); atts.put(ja); } return o; } public boolean hasRelations() { return this.relations!=null && this.relations.size()>0; } }
True
2,137
14
2,364
15
2,587
11
2,364
15
2,898
14
false
false
false
false
false
true
4,738
149318_0
import lejos.nxt.*; public class Lego { public static void main(String[] args) { int bedrag = 10; int tijdelijk; int motora =9; int motorb =19; int motorc = 49; int groot = 1; int normaal = 0; int klein = 0; //normaal biljetten if(groot==1){ while(bedrag>0) { while(bedrag>motorc) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>motorb) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>motora) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } //als je meer twintigjes wilt if(normaal==1) { while(bedrag >0) { while(bedrag>139) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>19) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>9) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } if(klein ==1) { while(bedrag >0) { while(bedrag>99) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>60) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>9) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } } }
wvanderp/project-3-4
web/Lego.java
1,715
//als je meer twintigjes wilt
line_comment
nl
import lejos.nxt.*; public class Lego { public static void main(String[] args) { int bedrag = 10; int tijdelijk; int motora =9; int motorb =19; int motorc = 49; int groot = 1; int normaal = 0; int klein = 0; //normaal biljetten if(groot==1){ while(bedrag>0) { while(bedrag>motorc) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>motorb) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>motora) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } //als je<SUF> if(normaal==1) { while(bedrag >0) { while(bedrag>139) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>19) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>9) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } if(klein ==1) { while(bedrag >0) { while(bedrag>99) { Motor.C.setSpeed(750); Motor.C.backward(); Motor.C.rotate(-375); Motor.C.stop(); Motor.C.forward(); Motor.C.rotate(135); Motor.C.stop(); tijdelijk = 50; bedrag = bedrag -tijdelijk; System.out.println("50 gepint"); } while(bedrag>60) { Motor.B .setSpeed(750); Motor.B.backward(); Motor.B.rotate(-375); Motor.B.stop(); Motor.B.forward(); Motor.B.rotate(135); Motor.B.stop(); tijdelijk = 20; bedrag = bedrag-tijdelijk; System.out.println("20 gepint"); } while(bedrag>9) { Motor.A.setSpeed(750); Motor.A.backward(); Motor.A.rotate(-375); Motor.A.stop(); Motor.A.forward(); Motor.A.rotate(135); Motor.A.stop(); tijdelijk = 10; bedrag =bedrag -tijdelijk; System.out.println("10 gepint"); } System.out.println("bedrag is kleiner als 10"); break; } } } }
True
1,248
9
1,483
10
1,611
8
1,483
10
1,877
10
false
false
false
false
false
true
1,297
17930_4
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import com.ctre.phoenix.motorcontrol.TalonFXInvertType; import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; import edu.wpi.first.math.util.Units; /** * The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean * constants. This class should not be used for any other purpose. All constants should be declared * globally (i.e. public static). Do not put anything functional in this class. * * <p>It is advised to statically import this class (or one of its inner classes) wherever the * constants are needed, to reduce verbosity. */ public final class Constants { public static final int TIMEOUT = 30; public static final class DrivetrainConstants { public static final double kS = 0.18579; // Volts public static final double kV = 3.2961; // Volt Seconds per Meter public static final double kA = 0.42341; // Volt Seconds Squared per Meter public static final double kPVel = 4.134; // Volt Seconds per Meter public static final double TRACK_WIDTH = Units.inchesToMeters(22.5); // Meters public static final DifferentialDriveKinematics KINEMATICS = new DifferentialDriveKinematics(TRACK_WIDTH); public static final double WHEEL_DIAMETER = Units.inchesToMeters(4.0); //Meters public static final double DISTANCE_PER_REVOLUTION = WHEEL_DIAMETER * Math.PI; public static final double PULSES_PER_REVOLUTION = 42 * 5.6; public static final double DISTANCE_PER_PULSE = DISTANCE_PER_REVOLUTION / PULSES_PER_REVOLUTION; public static final double SECONDS_PER_MINUTE = 60.0d; public static final double GEAR_REDUCTION = 13.8; public static final double MAX_VELOCITY = 3.6; public static final double MAX_ACCEL = 3; public static final double kRamseteB = 2; public static final double kRamseteZeta = 0.7; public static final double GEAR_RATIO = 1800d / 216d; //Hello World! // Hey Stem Savvy public static final double WHEEL_CIRCUMFRENCE = 2 * Math.PI * (WHEEL_DIAMETER/2); public static final int FRONT_RIGHT_MOTOR = 20; public static final int BACK_RIGHT_MOTOR = 21; public static final int FRONT_LEFT_MOTOR = 18; public static final int BACK_LEFT_MOTOR = 19; } public static final class ClimberConstants { // public static final int LEFT_SOLENOID = 2; //2 // public static final int RIGHT_SOLENOID = 1; //1 public static final int LEFT_LIFT_MOTOR = 25; public static final int RIGHT_LIFT_MOTOR = 26; public static final int LEFT_FOR_SOLENOID = 3; public static final int LEFT_REV_SOLENOID = 2; public static final int RIGHT_FOR_SOLENOID = 6; public static final int RIGHT_REV_SOLENOID = 7; public static final int LEFT_FIRST_EXTEND = 164904; //169000 public static final int LEFT_EXTEND = -169000; public static final int LEFT_MID = -157000; //-157000 public static final int LEFT_CLIMB = -11000; public static final int RIGHT_FIRST_EXTEND = 164904; //169000 public static final int RIGHT_EXTEND = 169000; //169000 public static final int RIGHT_MID = 157000; public static final int RIGHT_CLIMB = 11000; public static boolean kLeftSensorPhase = true; public static boolean kLeftMotorInvert = false; public static boolean kRightSensorPhase = true; public static boolean kRightMotorInvert = false; public static final int kPIDLoopIdx = 0; public static final int kSlotIdx = 0; public static final double kP = 30d / 2048; public static final double FEXTEND = 40 * 2048 * 15 / 9d; public static final double EXTEND = 50 * 2048 * 15 / 9d; public static final double MID = 21 * 2048 * 15 / 9d; } public static final class TransportConstants { public static final int TOP_TRANSPORT_MOTOR = 23; public static final int BOT_TRANSPORT_MOTOR = 22; public static final int BETER_TRANSPORT_MOTOR = 32; } public static final class IntakeConstants { public static final int INTAKE_RIGHT_MOTOR = 24; public static final int INTAKE_LEFT_MOTOR = 33; public static final int INTAKE_FOR_SOLENOID = 5; public static final int INTAKE_REV_SOLENOID = 4; } public static final class ShooterConstants { public static final int LEFT_SHOOTER = 31; public static final int RIGHT_SHOOTER = 30; public static final double MAXPERCENT = 0.4; public static final double ShooterAdjust = 1.125; //1.165 public static final double kS = 0.69004; //0.69004 0.84535 public static final double kV = 0.10758; //0.11811 public static final double kP = 0.02; //0.04257 and 0.0307 } public static int kTimeoutMs = 200; }
Pearadox/CompRobot2022
src/main/java/frc/robot/Constants.java
1,644
// Volt Seconds per Meter
line_comment
nl
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import com.ctre.phoenix.motorcontrol.TalonFXInvertType; import edu.wpi.first.math.kinematics.DifferentialDriveKinematics; import edu.wpi.first.math.util.Units; /** * The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean * constants. This class should not be used for any other purpose. All constants should be declared * globally (i.e. public static). Do not put anything functional in this class. * * <p>It is advised to statically import this class (or one of its inner classes) wherever the * constants are needed, to reduce verbosity. */ public final class Constants { public static final int TIMEOUT = 30; public static final class DrivetrainConstants { public static final double kS = 0.18579; // Volts public static final double kV = 3.2961; // Volt Seconds<SUF> public static final double kA = 0.42341; // Volt Seconds Squared per Meter public static final double kPVel = 4.134; // Volt Seconds per Meter public static final double TRACK_WIDTH = Units.inchesToMeters(22.5); // Meters public static final DifferentialDriveKinematics KINEMATICS = new DifferentialDriveKinematics(TRACK_WIDTH); public static final double WHEEL_DIAMETER = Units.inchesToMeters(4.0); //Meters public static final double DISTANCE_PER_REVOLUTION = WHEEL_DIAMETER * Math.PI; public static final double PULSES_PER_REVOLUTION = 42 * 5.6; public static final double DISTANCE_PER_PULSE = DISTANCE_PER_REVOLUTION / PULSES_PER_REVOLUTION; public static final double SECONDS_PER_MINUTE = 60.0d; public static final double GEAR_REDUCTION = 13.8; public static final double MAX_VELOCITY = 3.6; public static final double MAX_ACCEL = 3; public static final double kRamseteB = 2; public static final double kRamseteZeta = 0.7; public static final double GEAR_RATIO = 1800d / 216d; //Hello World! // Hey Stem Savvy public static final double WHEEL_CIRCUMFRENCE = 2 * Math.PI * (WHEEL_DIAMETER/2); public static final int FRONT_RIGHT_MOTOR = 20; public static final int BACK_RIGHT_MOTOR = 21; public static final int FRONT_LEFT_MOTOR = 18; public static final int BACK_LEFT_MOTOR = 19; } public static final class ClimberConstants { // public static final int LEFT_SOLENOID = 2; //2 // public static final int RIGHT_SOLENOID = 1; //1 public static final int LEFT_LIFT_MOTOR = 25; public static final int RIGHT_LIFT_MOTOR = 26; public static final int LEFT_FOR_SOLENOID = 3; public static final int LEFT_REV_SOLENOID = 2; public static final int RIGHT_FOR_SOLENOID = 6; public static final int RIGHT_REV_SOLENOID = 7; public static final int LEFT_FIRST_EXTEND = 164904; //169000 public static final int LEFT_EXTEND = -169000; public static final int LEFT_MID = -157000; //-157000 public static final int LEFT_CLIMB = -11000; public static final int RIGHT_FIRST_EXTEND = 164904; //169000 public static final int RIGHT_EXTEND = 169000; //169000 public static final int RIGHT_MID = 157000; public static final int RIGHT_CLIMB = 11000; public static boolean kLeftSensorPhase = true; public static boolean kLeftMotorInvert = false; public static boolean kRightSensorPhase = true; public static boolean kRightMotorInvert = false; public static final int kPIDLoopIdx = 0; public static final int kSlotIdx = 0; public static final double kP = 30d / 2048; public static final double FEXTEND = 40 * 2048 * 15 / 9d; public static final double EXTEND = 50 * 2048 * 15 / 9d; public static final double MID = 21 * 2048 * 15 / 9d; } public static final class TransportConstants { public static final int TOP_TRANSPORT_MOTOR = 23; public static final int BOT_TRANSPORT_MOTOR = 22; public static final int BETER_TRANSPORT_MOTOR = 32; } public static final class IntakeConstants { public static final int INTAKE_RIGHT_MOTOR = 24; public static final int INTAKE_LEFT_MOTOR = 33; public static final int INTAKE_FOR_SOLENOID = 5; public static final int INTAKE_REV_SOLENOID = 4; } public static final class ShooterConstants { public static final int LEFT_SHOOTER = 31; public static final int RIGHT_SHOOTER = 30; public static final double MAXPERCENT = 0.4; public static final double ShooterAdjust = 1.125; //1.165 public static final double kS = 0.69004; //0.69004 0.84535 public static final double kV = 0.10758; //0.11811 public static final double kP = 0.02; //0.04257 and 0.0307 } public static int kTimeoutMs = 200; }
True
1,436
5
1,528
7
1,541
5
1,528
7
1,770
7
false
false
false
false
false
true
108
30162_19
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.exceptions.RecordNotFoundException; import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController // @RequestMapping("/persons") // Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen public class TelevisionsController { // De lijst is static, omdat er maar 1 lijst kan zijn. // De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan. private static final List<String> televisionDatabase = new ArrayList<>(); // Show all televisions @GetMapping("/televisions") public ResponseEntity<Object> getAllTelevisions() { // Of ResponseEntity<String> // return "Televisions"; werkt ook // return ResponseEntity.ok(televisionDatabase); return new ResponseEntity<>(televisionDatabase, HttpStatus.OK); // 200 OK } // Show 1 television @GetMapping("televisions/{id}") public ResponseEntity<Object> getTelevision(@PathVariable("id") int id) { // Verschil met: @PathVariable int id? // return ResponseEntity.ok("television with id: " + id); // Return de waarde die op index(id) staat en een 200 status // Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items. // Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje. return new ResponseEntity<>(televisionDatabase.get(id), HttpStatus.OK); } // Post/create 1 television @PostMapping("/televisions") public ResponseEntity<String> addTelevision(@RequestBody String television) { // Of ResponseEntity<Object> // return ResponseEntity.created(null).body("television"); - Oude manier van noteren? // Bonus bonus: check voor 20 letters: if (television.length() > 20) { throw new TelevisionNameTooLongException("Televisienaam is te lang"); } else { // Voeg de televisie uit de parameter toe aan de lijst televisionDatabase.add(television); // Return de televisie uit de parameter met een 201 status // return ResponseEntity.created(null).body(television); return new ResponseEntity<>("Television: " + television + " added.", HttpStatus.CREATED); // 201 } } // Update television @PutMapping("/televisions/{id}") public ResponseEntity<Object> updateTelevision(@PathVariable int id, @RequestBody String television) { // In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst. // In deze methode checken we daar expliciet voor en gooien we een custom exception op. if (televisionDatabase.isEmpty() || id > televisionDatabase.size()) { throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database."); } else { // Vervang de waarde op index(id) met de television uit de parameter televisionDatabase.set(id, television); // Return een 204 status // return ResponseEntity.noContent().build(); return new ResponseEntity<>(television + " with id#" + id + " updated!", HttpStatus.OK); } } @DeleteMapping("/televisions/{id}") public ResponseEntity<Object> deleteTelevision(@PathVariable int id) { // Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen. televisionDatabase.set(id, null); // Ipv remove()? Geeft een entry met null in de ArrayList // televisionDatabase.remove(id); // return new ResponseEntity<>("deleted", HttpStatus.NO_CONTENT); // Met 204 No Content kun je geen bericht mee sturen return new ResponseEntity<>("Television: " + id + " deleted.", HttpStatus.GONE); // 410 Gone } }
Aphelion-im/Les-10-uitwerking-opdracht-backend-spring-boot-tech-it-easy-controller
src/main/java/nl/novi/techiteasy/controllers/TelevisionsController.java
1,170
// Return een 204 status
line_comment
nl
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.exceptions.RecordNotFoundException; import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController // @RequestMapping("/persons") // Alle paden (In Postman) beginnen met /persons - Change base URL to: http://localhost:8080/persons - Optioneel: Onder @RestController plaatsen public class TelevisionsController { // De lijst is static, omdat er maar 1 lijst kan zijn. // De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan. private static final List<String> televisionDatabase = new ArrayList<>(); // Show all televisions @GetMapping("/televisions") public ResponseEntity<Object> getAllTelevisions() { // Of ResponseEntity<String> // return "Televisions"; werkt ook // return ResponseEntity.ok(televisionDatabase); return new ResponseEntity<>(televisionDatabase, HttpStatus.OK); // 200 OK } // Show 1 television @GetMapping("televisions/{id}") public ResponseEntity<Object> getTelevision(@PathVariable("id") int id) { // Verschil met: @PathVariable int id? // return ResponseEntity.ok("television with id: " + id); // Return de waarde die op index(id) staat en een 200 status // Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items. // Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje. return new ResponseEntity<>(televisionDatabase.get(id), HttpStatus.OK); } // Post/create 1 television @PostMapping("/televisions") public ResponseEntity<String> addTelevision(@RequestBody String television) { // Of ResponseEntity<Object> // return ResponseEntity.created(null).body("television"); - Oude manier van noteren? // Bonus bonus: check voor 20 letters: if (television.length() > 20) { throw new TelevisionNameTooLongException("Televisienaam is te lang"); } else { // Voeg de televisie uit de parameter toe aan de lijst televisionDatabase.add(television); // Return de televisie uit de parameter met een 201 status // return ResponseEntity.created(null).body(television); return new ResponseEntity<>("Television: " + television + " added.", HttpStatus.CREATED); // 201 } } // Update television @PutMapping("/televisions/{id}") public ResponseEntity<Object> updateTelevision(@PathVariable int id, @RequestBody String television) { // In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst. // In deze methode checken we daar expliciet voor en gooien we een custom exception op. if (televisionDatabase.isEmpty() || id > televisionDatabase.size()) { throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database."); } else { // Vervang de waarde op index(id) met de television uit de parameter televisionDatabase.set(id, television); // Return een<SUF> // return ResponseEntity.noContent().build(); return new ResponseEntity<>(television + " with id#" + id + " updated!", HttpStatus.OK); } } @DeleteMapping("/televisions/{id}") public ResponseEntity<Object> deleteTelevision(@PathVariable int id) { // Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen. televisionDatabase.set(id, null); // Ipv remove()? Geeft een entry met null in de ArrayList // televisionDatabase.remove(id); // return new ResponseEntity<>("deleted", HttpStatus.NO_CONTENT); // Met 204 No Content kun je geen bericht mee sturen return new ResponseEntity<>("Television: " + id + " deleted.", HttpStatus.GONE); // 410 Gone } }
True
954
8
1,077
8
1,010
8
1,077
8
1,185
8
false
false
false
false
false
true
1,513
159109_0
package com.ugent.pidgeon.postgre.models; import java.io.Serializable; // Hulpklasse zodat de repository correct met meerdere primary keys kan werken. public class GroupUserId implements Serializable { private long groupId; private long userId; public GroupUserId(long groupId, long userId) { this.groupId = groupId; this.userId = userId; } public GroupUserId() { } public long getGroupId() { return groupId; } public void setGroupId(long groupId) { this.groupId = groupId; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } }
SELab-2/UGent-6
backend/app/src/main/java/com/ugent/pidgeon/postgre/models/GroupUserId.java
207
// Hulpklasse zodat de repository correct met meerdere primary keys kan werken.
line_comment
nl
package com.ugent.pidgeon.postgre.models; import java.io.Serializable; // Hulpklasse zodat<SUF> public class GroupUserId implements Serializable { private long groupId; private long userId; public GroupUserId(long groupId, long userId) { this.groupId = groupId; this.userId = userId; } public GroupUserId() { } public long getGroupId() { return groupId; } public void setGroupId(long groupId) { this.groupId = groupId; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } }
True
150
21
166
20
178
15
166
20
215
21
false
false
false
false
false
true
3,450
198500_1
public class Main { public static void main(String[] args) { String string_voorbeeld = "Dit is een voorbeeld"; String string_hello_world = "hello world"; boolean boolean_true = true; int int_four = 4; short short_minus_eight = -8; float float_six_point_five = 6.5f; double double_minus_two_point_three = 2.3d; // Wijzig niets aan onderstaande System.out.println statements System.out.println(string_voorbeeld); // String Dit is een voorbeeld System.out.println(string_hello_world); // String hello world System.out.println(boolean_true); // boolean true System.out.println(int_four); // int 4 System.out.println(short_minus_eight); // short -8 System.out.println(float_six_point_five); // float 6.5 System.out.println(double_minus_two_point_three); // double -2.3 // Bonus: Wijs een nieuwe waarde toe aan een bestaande variabele string_voorbeeld = "Dit is een aangepast voorbeeld"; System.out.println(string_voorbeeld); // String Dit is een aangepast voorbeeld } }
lcryan/lostVariables
src/main/java/Main.java
334
// String Dit is een voorbeeld
line_comment
nl
public class Main { public static void main(String[] args) { String string_voorbeeld = "Dit is een voorbeeld"; String string_hello_world = "hello world"; boolean boolean_true = true; int int_four = 4; short short_minus_eight = -8; float float_six_point_five = 6.5f; double double_minus_two_point_three = 2.3d; // Wijzig niets aan onderstaande System.out.println statements System.out.println(string_voorbeeld); // String Dit<SUF> System.out.println(string_hello_world); // String hello world System.out.println(boolean_true); // boolean true System.out.println(int_four); // int 4 System.out.println(short_minus_eight); // short -8 System.out.println(float_six_point_five); // float 6.5 System.out.println(double_minus_two_point_three); // double -2.3 // Bonus: Wijs een nieuwe waarde toe aan een bestaande variabele string_voorbeeld = "Dit is een aangepast voorbeeld"; System.out.println(string_voorbeeld); // String Dit is een aangepast voorbeeld } }
True
269
7
324
9
310
6
324
9
342
7
false
false
false
false
false
true
2,929
62352_0
package be.kuleuven.jchr.runtime.primitive;_x000D_ _x000D_ import java.util.Iterator;_x000D_ _x000D_ import be.kuleuven.jchr.runtime.Constraint;_x000D_ import be.kuleuven.jchr.runtime.FailureException;_x000D_ _x000D_ _x000D_ public class IntEqualitySolverImpl implements IntEqualitySolver {_x000D_ _x000D_ public void tellEqual(LogicalInt X, int value) {_x000D_ final LogicalInt Xrepr = X.find();_x000D_ final boolean oldHasValue = Xrepr.hasValue;_x000D_ _x000D_ if (oldHasValue) {_x000D_ if (Xrepr.value != value)_x000D_ throw new FailureException("Cannot make equal " + Xrepr.value + " != " + value);_x000D_ }_x000D_ else {_x000D_ Xrepr.value = value;_x000D_ Xrepr.hasValue = true;_x000D_ _x000D_ Xrepr.rehashAll();_x000D_ _x000D_ final Iterator<Constraint> observers = Xrepr.variableObservers.iterator();_x000D_ while (observers.hasNext()) _x000D_ observers.next().reactivate(); /* notify */_x000D_ }_x000D_ }_x000D_ _x000D_ // TODO :: deze extra indirectie kan uiteraard weg in uiteindelijk versie..._x000D_ public void tellEqual(int val, LogicalInt X) {_x000D_ tellEqual(X, val);_x000D_ }_x000D_ _x000D_ public void tellEqual(LogicalInt X, LogicalInt Y) {_x000D_ final LogicalInt Xrepr = X.find();_x000D_ final LogicalInt Yrepr = Y.find();_x000D_ _x000D_ if (Xrepr != Yrepr) {_x000D_ final boolean _x000D_ XhasValue = Xrepr.hasValue, _x000D_ YhasValue = Yrepr.hasValue;_x000D_ _x000D_ final int Xrank = Xrepr.rank;_x000D_ int Yrank = Yrepr.rank;_x000D_ _x000D_ if (Xrank >= Yrank) {_x000D_ Yrepr.parent = Xrepr;_x000D_ if (Xrank == Yrank) Xrepr.rank++;_x000D_ _x000D_ if (! XhasValue) {_x000D_ if (YhasValue) {_x000D_ Xrepr.value = Yrepr.value;_x000D_ Xrepr.hasValue = true;_x000D_ Xrepr.rehashAll();_x000D_ }_x000D_ } else /* XhasValue */ {_x000D_ if (YhasValue && Xrepr.value != Yrepr.value)_x000D_ throw new FailureException("Cannot make equal " _x000D_ + Xrepr.value + " != " + Yrepr.value);_x000D_ }_x000D_ _x000D_ if (Yrepr.hashObservers != null) {_x000D_ Xrepr.mergeHashObservers(Yrepr.hashObservers);_x000D_ Yrepr.hashObservers = null;_x000D_ }_x000D_ _x000D_ Xrepr.variableObservers.mergeWith(Yrepr.variableObservers);_x000D_ Yrepr.variableObservers = null;_x000D_ _x000D_ final Iterator<Constraint> observers = Xrepr.variableObservers.iterator();_x000D_ while (observers.hasNext()) _x000D_ observers.next().reactivate(); /* notify */_x000D_ }_x000D_ else {_x000D_ Xrepr.parent = Yrepr;_x000D_ _x000D_ if (! YhasValue) {_x000D_ if (XhasValue) {_x000D_ Yrepr.value = Xrepr.value;_x000D_ Yrepr.hasValue = true;_x000D_ _x000D_ Yrepr.rehashAll();_x000D_ }_x000D_ } else /* YhasValue */ {_x000D_ if (XhasValue & Xrepr.value != Yrepr.value)_x000D_ throw new FailureException("Cannot make equal " _x000D_ + Xrepr.value + " != " + Yrepr.value);_x000D_ }_x000D_ _x000D_ if (Xrepr.hashObservers != null) {_x000D_ Yrepr.mergeHashObservers(Xrepr.hashObservers);_x000D_ Xrepr.hashObservers = null;_x000D_ }_x000D_ _x000D_ Yrepr.variableObservers.mergeWith(Xrepr.variableObservers); _x000D_ Xrepr.variableObservers = null;_x000D_ _x000D_ final Iterator<Constraint> observers = Yrepr.variableObservers.iterator();_x000D_ while (observers.hasNext()) _x000D_ observers.next().reactivate(); /* notify */_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ public boolean askEqual(LogicalInt X, int value) {_x000D_ final LogicalInt representative = X.find();_x000D_ return representative.hasValue && representative.value == value;_x000D_ }_x000D_ _x000D_ public boolean askEqual(int value, LogicalInt X) {_x000D_ final LogicalInt representative = X.find();_x000D_ return representative.hasValue && representative.value == value;_x000D_ }_x000D_ _x000D_ public boolean askEqual(LogicalInt X, LogicalInt Y) {_x000D_ final LogicalInt Xrepr = X.find();_x000D_ final LogicalInt Yrepr = Y.find();_x000D_ _x000D_ return (Xrepr == Yrepr) _x000D_ || (Xrepr.hasValue && Yrepr.hasValue && Xrepr.value == Yrepr.value);_x000D_ }_x000D_ }
hendrikvanantwerpen/jchr
src/be/kuleuven/jchr/runtime/primitive/IntEqualitySolverImpl.java
1,333
// TODO :: deze extra indirectie kan uiteraard weg in uiteindelijk versie..._x000D_
line_comment
nl
package be.kuleuven.jchr.runtime.primitive;_x000D_ _x000D_ import java.util.Iterator;_x000D_ _x000D_ import be.kuleuven.jchr.runtime.Constraint;_x000D_ import be.kuleuven.jchr.runtime.FailureException;_x000D_ _x000D_ _x000D_ public class IntEqualitySolverImpl implements IntEqualitySolver {_x000D_ _x000D_ public void tellEqual(LogicalInt X, int value) {_x000D_ final LogicalInt Xrepr = X.find();_x000D_ final boolean oldHasValue = Xrepr.hasValue;_x000D_ _x000D_ if (oldHasValue) {_x000D_ if (Xrepr.value != value)_x000D_ throw new FailureException("Cannot make equal " + Xrepr.value + " != " + value);_x000D_ }_x000D_ else {_x000D_ Xrepr.value = value;_x000D_ Xrepr.hasValue = true;_x000D_ _x000D_ Xrepr.rehashAll();_x000D_ _x000D_ final Iterator<Constraint> observers = Xrepr.variableObservers.iterator();_x000D_ while (observers.hasNext()) _x000D_ observers.next().reactivate(); /* notify */_x000D_ }_x000D_ }_x000D_ _x000D_ // TODO ::<SUF> public void tellEqual(int val, LogicalInt X) {_x000D_ tellEqual(X, val);_x000D_ }_x000D_ _x000D_ public void tellEqual(LogicalInt X, LogicalInt Y) {_x000D_ final LogicalInt Xrepr = X.find();_x000D_ final LogicalInt Yrepr = Y.find();_x000D_ _x000D_ if (Xrepr != Yrepr) {_x000D_ final boolean _x000D_ XhasValue = Xrepr.hasValue, _x000D_ YhasValue = Yrepr.hasValue;_x000D_ _x000D_ final int Xrank = Xrepr.rank;_x000D_ int Yrank = Yrepr.rank;_x000D_ _x000D_ if (Xrank >= Yrank) {_x000D_ Yrepr.parent = Xrepr;_x000D_ if (Xrank == Yrank) Xrepr.rank++;_x000D_ _x000D_ if (! XhasValue) {_x000D_ if (YhasValue) {_x000D_ Xrepr.value = Yrepr.value;_x000D_ Xrepr.hasValue = true;_x000D_ Xrepr.rehashAll();_x000D_ }_x000D_ } else /* XhasValue */ {_x000D_ if (YhasValue && Xrepr.value != Yrepr.value)_x000D_ throw new FailureException("Cannot make equal " _x000D_ + Xrepr.value + " != " + Yrepr.value);_x000D_ }_x000D_ _x000D_ if (Yrepr.hashObservers != null) {_x000D_ Xrepr.mergeHashObservers(Yrepr.hashObservers);_x000D_ Yrepr.hashObservers = null;_x000D_ }_x000D_ _x000D_ Xrepr.variableObservers.mergeWith(Yrepr.variableObservers);_x000D_ Yrepr.variableObservers = null;_x000D_ _x000D_ final Iterator<Constraint> observers = Xrepr.variableObservers.iterator();_x000D_ while (observers.hasNext()) _x000D_ observers.next().reactivate(); /* notify */_x000D_ }_x000D_ else {_x000D_ Xrepr.parent = Yrepr;_x000D_ _x000D_ if (! YhasValue) {_x000D_ if (XhasValue) {_x000D_ Yrepr.value = Xrepr.value;_x000D_ Yrepr.hasValue = true;_x000D_ _x000D_ Yrepr.rehashAll();_x000D_ }_x000D_ } else /* YhasValue */ {_x000D_ if (XhasValue & Xrepr.value != Yrepr.value)_x000D_ throw new FailureException("Cannot make equal " _x000D_ + Xrepr.value + " != " + Yrepr.value);_x000D_ }_x000D_ _x000D_ if (Xrepr.hashObservers != null) {_x000D_ Yrepr.mergeHashObservers(Xrepr.hashObservers);_x000D_ Xrepr.hashObservers = null;_x000D_ }_x000D_ _x000D_ Yrepr.variableObservers.mergeWith(Xrepr.variableObservers); _x000D_ Xrepr.variableObservers = null;_x000D_ _x000D_ final Iterator<Constraint> observers = Yrepr.variableObservers.iterator();_x000D_ while (observers.hasNext()) _x000D_ observers.next().reactivate(); /* notify */_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ public boolean askEqual(LogicalInt X, int value) {_x000D_ final LogicalInt representative = X.find();_x000D_ return representative.hasValue && representative.value == value;_x000D_ }_x000D_ _x000D_ public boolean askEqual(int value, LogicalInt X) {_x000D_ final LogicalInt representative = X.find();_x000D_ return representative.hasValue && representative.value == value;_x000D_ }_x000D_ _x000D_ public boolean askEqual(LogicalInt X, LogicalInt Y) {_x000D_ final LogicalInt Xrepr = X.find();_x000D_ final LogicalInt Yrepr = Y.find();_x000D_ _x000D_ return (Xrepr == Yrepr) _x000D_ || (Xrepr.hasValue && Yrepr.hasValue && Xrepr.value == Yrepr.value);_x000D_ }_x000D_ }
True
1,707
28
1,803
30
1,903
23
1,803
30
2,112
28
false
false
false
false
false
true
1,038
34549_0
/** * Deze klassen is een Java programma * @author Jan Willem Cornelis * @version 1.0 */ package Oef8; import java.lang.*; public class PartTimeWerknemer extends Werknemer { public int urenGewerkt; public PartTimeWerknemer(String voornaam, String achternaam, int wNummer, float salaris, int urenGewerkt){ super(voornaam, achternaam, wNummer, salaris); this.urenGewerkt = urenGewerkt; } public float getWeekLoon(){ return this.salaris + this.urenGewerkt; } @Override public void salarisVerhogen(int percentage){ if(percentage > 5){ percentage = 5; } float verhogingsfactor = (float) percentage/100; salaris += salaris * verhogingsfactor; } }
MTA-Digital-Broadcast-2/U-Cornelis-Jan-van-Ruiten-Oscar-Alexander-Project-MHP
Jan Cornelis/blz31/Oef8/PartTimeWerknemer.java
255
/** * Deze klassen is een Java programma * @author Jan Willem Cornelis * @version 1.0 */
block_comment
nl
/** * Deze klassen is<SUF>*/ package Oef8; import java.lang.*; public class PartTimeWerknemer extends Werknemer { public int urenGewerkt; public PartTimeWerknemer(String voornaam, String achternaam, int wNummer, float salaris, int urenGewerkt){ super(voornaam, achternaam, wNummer, salaris); this.urenGewerkt = urenGewerkt; } public float getWeekLoon(){ return this.salaris + this.urenGewerkt; } @Override public void salarisVerhogen(int percentage){ if(percentage > 5){ percentage = 5; } float verhogingsfactor = (float) percentage/100; salaris += salaris * verhogingsfactor; } }
True
221
28
238
33
228
28
238
33
254
30
false
false
false
false
false
true
324
7818_1
public class Customer { String name; String lastName; int customerNumber; CreditCard creditCard; //A constructor //? Waarom 4 argumente as maar 3 parameters? Waarom gebruik 'this' sonder 'n punt? public Customer(String name, String lastName, CreditCard creditCard) { this(name, lastName, (int)(Math.random() * 100), creditCard); } //A constructor public Customer(String name, String lastName, int customerNumber, CreditCard creditCard) { this.name = name; this.lastName = lastName; this.customerNumber = customerNumber; this.creditCard = creditCard; } public void printName() { System.out.println("Customer " + name); } //? Waarom word metode hier gedeclareerd en niet in Creditcard zelf? public CreditCard getCreditCard() { return creditCard; } }
Chrisbuildit/Java-CreditCard-Class-inheritance
src/main/java/Customer.java
247
//? Waarom word metode hier gedeclareerd en niet in Creditcard zelf?
line_comment
nl
public class Customer { String name; String lastName; int customerNumber; CreditCard creditCard; //A constructor //? Waarom 4 argumente as maar 3 parameters? Waarom gebruik 'this' sonder 'n punt? public Customer(String name, String lastName, CreditCard creditCard) { this(name, lastName, (int)(Math.random() * 100), creditCard); } //A constructor public Customer(String name, String lastName, int customerNumber, CreditCard creditCard) { this.name = name; this.lastName = lastName; this.customerNumber = customerNumber; this.creditCard = creditCard; } public void printName() { System.out.println("Customer " + name); } //? Waarom<SUF> public CreditCard getCreditCard() { return creditCard; } }
True
206
20
217
20
228
16
217
20
259
21
false
false
false
false
false
true
1,552
46305_6
package com.wordflip.api.controllers; import com.wordflip.api.SqlCreator; import com.wordflip.api.models.*; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.joda.time.Days; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import static java.lang.StrictMath.ceil; /** * Created by robvangastel on 27/05/16. */ @RestController @RequestMapping("/{userId}/tip") public class TipController { private SqlCreator creator = new SqlCreator(); @RequestMapping(value = "/practice", method = RequestMethod.GET) public ResponseEntity<List<Practice>> allPractices(@PathVariable String userId) { creator = new SqlCreator(); validateUser(userId); List<Practice> practices = creator.getPractices(userId); return new ResponseEntity<List<Practice>>(practices, HttpStatus.OK); } @RequestMapping(value = "/rating", method = RequestMethod.GET) public int getToetsRating(@PathVariable String userId, @RequestParam(value="course", defaultValue="Engels") String course) { creator = new SqlCreator(); validateUser(userId); int correctie = 0; int toetsId = creator.getToetsId(course, Integer.parseInt(userId)); List<Practice> practices = creator.getToetsPractices(toetsId); for(int i = 0; i < practices.size(); i++) { correctie += practices.get(i).compareCorrectToets(); } double rating = correctie/practices.size(); return (int) ceil(rating); } @RequestMapping( method = RequestMethod.GET) public TipVanDeDag tip(@PathVariable String userId) { creator = new SqlCreator(); validateUser(userId); List<Practice> practices = creator.getPractices(userId); List<Practice> practicesOther = creator.getOtherPractices(userId); int speed = 0; // int speedOther = 1; int correctie = 0; // int correctieOther = 1; int consistent = 0; int consistent_dayParts = 0; // for(int i = 0; i < practicesOther.size(); i++) { // speedOther += practicesOther.get(i).compareSpeed(); // correctieOther += practicesOther.get(i).compareCorrect(); // } for(int i = 0; i < practices.size(); i++) { speed += practices.get(i).compareSpeed(); correctie += practices.get(i).compareCorrect(); if(i+1 >= practices.size()) { break; } if(practices.get(i).compareDates(practices.get(i+1)) > 2) { consistent++; } consistent_dayParts += practices.get(i).compareDayParts(practices.get(i+1)); } return new Tip().getTip((speed/practices.size()), (correctie/practices.size()), consistent, (consistent_dayParts/practices.size()), practices.size()); //(speedOther/practicesOther.size()), (correctieOther/practices.size()) } @RequestMapping(method = RequestMethod.POST) public void addPractice(@PathVariable String userId, @RequestParam(value="toets_id", defaultValue="1") String toets_id, @RequestParam(value="amount", defaultValue="8") int amount, @RequestParam(value="mistakes", defaultValue="0") int mistakes, @RequestParam(value="duration", defaultValue="120") int duration, @RequestParam(value="planned", defaultValue="false") boolean planned) throws ParseException { creator = new SqlCreator(); validateUser(userId); creator.addPractice(new Practice(duration, amount, mistakes, planned), userId, toets_id); } //welke dag van de tijd geleerd en aantal @RequestMapping(value = "/times", method = RequestMethod.GET) public ResponseEntity<List<DayPart>> getMoments(@PathVariable String userId) throws ParseException { creator = new SqlCreator(); validateUser(userId); List<DayPart> dayParts = getDayParts(creator.getPractices(userId)); return new ResponseEntity<>(dayParts, HttpStatus.OK); } //momenten geleerd volgens de de app met aantal wel en niet @RequestMapping(value = "/moments", method = RequestMethod.GET) public Moment getTimes(@PathVariable String userId) throws ParseException { creator = new SqlCreator(); validateUser(userId); List<Practice> practices = creator.getPractices(userId); Moment m = new Moment(practices.size(), 0); for(Practice p: practices) { if(p.isPlanned()) { m.appendPlanned(1); } } return m; } //Snelheid van de geleerde woordjes met aantal binnen welke snelheid @RequestMapping(value = "/speed", method = RequestMethod.GET) public ResponseEntity<List<Word>> getSubjects(@PathVariable String userId) throws ParseException { creator = new SqlCreator(); validateUser(userId); List<Word> Speed = getAmountWords(creator.getPractices(userId)); return new ResponseEntity<>(Speed, HttpStatus.OK); } //Aantal leermomenten voor elke woorden met aantal @RequestMapping(value = "/subject", method = RequestMethod.GET) public ResponseEntity<List<Subject>> getSpeed(@PathVariable String userId) throws ParseException { creator = new SqlCreator(); validateUser(userId); List<Subject> subjects = creator.getSubjectCount(userId); return new ResponseEntity<>(subjects, HttpStatus.OK); } private void validateUser(String userId) { creator = new SqlCreator(); if(!creator.validateUser(userId)) { throw new UserNotFoundException(userId); } } public List<DayPart> getDayParts(List<Practice> practices) { List<DayPart> dayParts = new ArrayList<DayPart>(); DayPart ochtend = new DayPart(0,"'s ochtends"); DayPart middag = new DayPart(0,"'s middags"); DayPart avond = new DayPart(0,"'s avonds"); DayPart nacht = new DayPart(0,"'s nachts"); for (Practice p : practices) { if (p.getHourOfDay() >= 5 && p.getHourOfDay() <= 12) { ochtend.appendAmount(1); } else if (p.getHourOfDay() >= 12 && p.getHourOfDay() <= 18) { middag.appendAmount(1); } else if (p.getHourOfDay() >= 18 && p.getHourOfDay() <= 24) { avond.appendAmount(1); } else if (p.getHourOfDay() >= 0 && p.getHourOfDay() <= 5) { nacht.appendAmount(1); } } dayParts.add(ochtend); dayParts.add(middag); dayParts.add(avond); dayParts.add(nacht); return dayParts; } public List<Word> getAmountWords(List<Practice> practices) { List<Word> speed = new ArrayList<Word>(); Word sloom = new Word(0,"< 1 minuut"); Word matig = new Word(0,"> 1 minuut"); Word snel = new Word(0,"> 2 minuten"); for (Practice p : practices) { if (p.compareSpeed() == -1) { snel.appendAmount(1); } else if (p.compareSpeed() == 0) { matig.appendAmount(1); } else if (p.compareSpeed() == 1) { sloom.appendAmount(1); } } speed.add(sloom); speed.add(matig); speed.add(snel); return speed; } } @ResponseStatus(HttpStatus.NOT_FOUND) class UserNotFoundException extends RuntimeException { public UserNotFoundException(String userId) { super("could not find user '" + userId + "'."); } }
SanderEveraers/SMPT32
Application/api/src/main/java/com/wordflip/api/controllers/TipController.java
2,320
//welke dag van de tijd geleerd en aantal
line_comment
nl
package com.wordflip.api.controllers; import com.wordflip.api.SqlCreator; import com.wordflip.api.models.*; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.joda.time.Days; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import static java.lang.StrictMath.ceil; /** * Created by robvangastel on 27/05/16. */ @RestController @RequestMapping("/{userId}/tip") public class TipController { private SqlCreator creator = new SqlCreator(); @RequestMapping(value = "/practice", method = RequestMethod.GET) public ResponseEntity<List<Practice>> allPractices(@PathVariable String userId) { creator = new SqlCreator(); validateUser(userId); List<Practice> practices = creator.getPractices(userId); return new ResponseEntity<List<Practice>>(practices, HttpStatus.OK); } @RequestMapping(value = "/rating", method = RequestMethod.GET) public int getToetsRating(@PathVariable String userId, @RequestParam(value="course", defaultValue="Engels") String course) { creator = new SqlCreator(); validateUser(userId); int correctie = 0; int toetsId = creator.getToetsId(course, Integer.parseInt(userId)); List<Practice> practices = creator.getToetsPractices(toetsId); for(int i = 0; i < practices.size(); i++) { correctie += practices.get(i).compareCorrectToets(); } double rating = correctie/practices.size(); return (int) ceil(rating); } @RequestMapping( method = RequestMethod.GET) public TipVanDeDag tip(@PathVariable String userId) { creator = new SqlCreator(); validateUser(userId); List<Practice> practices = creator.getPractices(userId); List<Practice> practicesOther = creator.getOtherPractices(userId); int speed = 0; // int speedOther = 1; int correctie = 0; // int correctieOther = 1; int consistent = 0; int consistent_dayParts = 0; // for(int i = 0; i < practicesOther.size(); i++) { // speedOther += practicesOther.get(i).compareSpeed(); // correctieOther += practicesOther.get(i).compareCorrect(); // } for(int i = 0; i < practices.size(); i++) { speed += practices.get(i).compareSpeed(); correctie += practices.get(i).compareCorrect(); if(i+1 >= practices.size()) { break; } if(practices.get(i).compareDates(practices.get(i+1)) > 2) { consistent++; } consistent_dayParts += practices.get(i).compareDayParts(practices.get(i+1)); } return new Tip().getTip((speed/practices.size()), (correctie/practices.size()), consistent, (consistent_dayParts/practices.size()), practices.size()); //(speedOther/practicesOther.size()), (correctieOther/practices.size()) } @RequestMapping(method = RequestMethod.POST) public void addPractice(@PathVariable String userId, @RequestParam(value="toets_id", defaultValue="1") String toets_id, @RequestParam(value="amount", defaultValue="8") int amount, @RequestParam(value="mistakes", defaultValue="0") int mistakes, @RequestParam(value="duration", defaultValue="120") int duration, @RequestParam(value="planned", defaultValue="false") boolean planned) throws ParseException { creator = new SqlCreator(); validateUser(userId); creator.addPractice(new Practice(duration, amount, mistakes, planned), userId, toets_id); } //welke dag<SUF> @RequestMapping(value = "/times", method = RequestMethod.GET) public ResponseEntity<List<DayPart>> getMoments(@PathVariable String userId) throws ParseException { creator = new SqlCreator(); validateUser(userId); List<DayPart> dayParts = getDayParts(creator.getPractices(userId)); return new ResponseEntity<>(dayParts, HttpStatus.OK); } //momenten geleerd volgens de de app met aantal wel en niet @RequestMapping(value = "/moments", method = RequestMethod.GET) public Moment getTimes(@PathVariable String userId) throws ParseException { creator = new SqlCreator(); validateUser(userId); List<Practice> practices = creator.getPractices(userId); Moment m = new Moment(practices.size(), 0); for(Practice p: practices) { if(p.isPlanned()) { m.appendPlanned(1); } } return m; } //Snelheid van de geleerde woordjes met aantal binnen welke snelheid @RequestMapping(value = "/speed", method = RequestMethod.GET) public ResponseEntity<List<Word>> getSubjects(@PathVariable String userId) throws ParseException { creator = new SqlCreator(); validateUser(userId); List<Word> Speed = getAmountWords(creator.getPractices(userId)); return new ResponseEntity<>(Speed, HttpStatus.OK); } //Aantal leermomenten voor elke woorden met aantal @RequestMapping(value = "/subject", method = RequestMethod.GET) public ResponseEntity<List<Subject>> getSpeed(@PathVariable String userId) throws ParseException { creator = new SqlCreator(); validateUser(userId); List<Subject> subjects = creator.getSubjectCount(userId); return new ResponseEntity<>(subjects, HttpStatus.OK); } private void validateUser(String userId) { creator = new SqlCreator(); if(!creator.validateUser(userId)) { throw new UserNotFoundException(userId); } } public List<DayPart> getDayParts(List<Practice> practices) { List<DayPart> dayParts = new ArrayList<DayPart>(); DayPart ochtend = new DayPart(0,"'s ochtends"); DayPart middag = new DayPart(0,"'s middags"); DayPart avond = new DayPart(0,"'s avonds"); DayPart nacht = new DayPart(0,"'s nachts"); for (Practice p : practices) { if (p.getHourOfDay() >= 5 && p.getHourOfDay() <= 12) { ochtend.appendAmount(1); } else if (p.getHourOfDay() >= 12 && p.getHourOfDay() <= 18) { middag.appendAmount(1); } else if (p.getHourOfDay() >= 18 && p.getHourOfDay() <= 24) { avond.appendAmount(1); } else if (p.getHourOfDay() >= 0 && p.getHourOfDay() <= 5) { nacht.appendAmount(1); } } dayParts.add(ochtend); dayParts.add(middag); dayParts.add(avond); dayParts.add(nacht); return dayParts; } public List<Word> getAmountWords(List<Practice> practices) { List<Word> speed = new ArrayList<Word>(); Word sloom = new Word(0,"< 1 minuut"); Word matig = new Word(0,"> 1 minuut"); Word snel = new Word(0,"> 2 minuten"); for (Practice p : practices) { if (p.compareSpeed() == -1) { snel.appendAmount(1); } else if (p.compareSpeed() == 0) { matig.appendAmount(1); } else if (p.compareSpeed() == 1) { sloom.appendAmount(1); } } speed.add(sloom); speed.add(matig); speed.add(snel); return speed; } } @ResponseStatus(HttpStatus.NOT_FOUND) class UserNotFoundException extends RuntimeException { public UserNotFoundException(String userId) { super("could not find user '" + userId + "'."); } }
True
1,713
11
2,038
16
2,011
11
2,038
16
2,452
12
false
false
false
false
false
true
1,625
8337_0
package be.swsb.fiazard.ordering.orderplacement; import be.swsb.fiazard.eventstore.AggregateRepository; public class PlaceOrderCommandHandler { private OrderFactory orderFactory; private AggregateRepository aggregateRepository; // TODO jozef+bktid: Bij CommandHandlers die eerst een aggregate moeten reconstrueren from eventstore // gaan we een fail fast inbouwen die de versie van het readmodel (zie state op command) checkt tov de versie op de aggregate public PlaceOrderCommandHandler(OrderFactory orderFactory, AggregateRepository aggregateRepository) { this.orderFactory = orderFactory; this.aggregateRepository = aggregateRepository; } public void handleCommand(PlaceOrderCommand command) { Order newOrder = orderFactory.makeANewOrder(command); aggregateRepository.saveAggregate(newOrder); } }
SoftwareSandbox/Fiazard
src/main/java/be/swsb/fiazard/ordering/orderplacement/PlaceOrderCommandHandler.java
219
// TODO jozef+bktid: Bij CommandHandlers die eerst een aggregate moeten reconstrueren from eventstore
line_comment
nl
package be.swsb.fiazard.ordering.orderplacement; import be.swsb.fiazard.eventstore.AggregateRepository; public class PlaceOrderCommandHandler { private OrderFactory orderFactory; private AggregateRepository aggregateRepository; // TODO jozef+bktid:<SUF> // gaan we een fail fast inbouwen die de versie van het readmodel (zie state op command) checkt tov de versie op de aggregate public PlaceOrderCommandHandler(OrderFactory orderFactory, AggregateRepository aggregateRepository) { this.orderFactory = orderFactory; this.aggregateRepository = aggregateRepository; } public void handleCommand(PlaceOrderCommand command) { Order newOrder = orderFactory.makeANewOrder(command); aggregateRepository.saveAggregate(newOrder); } }
True
182
25
210
29
200
21
210
29
233
25
false
false
false
false
false
true
1,660
64550_1
package com.svenwesterlaken.gemeentebreda.data.api; /** * Created by lukab on 4-6-2017. */ import android.content.Context; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; public class ReportRequestQueue { private static ReportRequestQueue mInstance; private RequestQueue mRequestQueue; private static Context mCtx; private ReportRequestQueue(Context context) { mCtx = context.getApplicationContext(); mRequestQueue = getRequestQueue(); } /** * Static methode die één enkele instantie van deze class beheert. * * @param context * @return */ public static synchronized ReportRequestQueue getInstance(Context context) { if (mInstance == null) { mInstance = new ReportRequestQueue(context); } return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024); Network network = new BasicNetwork(new HurlStack()); mRequestQueue = new RequestQueue(cache, network); mRequestQueue.start(); } return mRequestQueue; } public <T> void addToRequestQueue(Request<T> req) { getRequestQueue().add(req); } }
SvenWesterlaken/gemeente-breda
app/src/main/java/com/svenwesterlaken/gemeentebreda/data/api/ReportRequestQueue.java
446
/** * Static methode die één enkele instantie van deze class beheert. * * @param context * @return */
block_comment
nl
package com.svenwesterlaken.gemeentebreda.data.api; /** * Created by lukab on 4-6-2017. */ import android.content.Context; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; public class ReportRequestQueue { private static ReportRequestQueue mInstance; private RequestQueue mRequestQueue; private static Context mCtx; private ReportRequestQueue(Context context) { mCtx = context.getApplicationContext(); mRequestQueue = getRequestQueue(); } /** * Static methode die<SUF>*/ public static synchronized ReportRequestQueue getInstance(Context context) { if (mInstance == null) { mInstance = new ReportRequestQueue(context); } return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024); Network network = new BasicNetwork(new HurlStack()); mRequestQueue = new RequestQueue(cache, network); mRequestQueue.start(); } return mRequestQueue; } public <T> void addToRequestQueue(Request<T> req) { getRequestQueue().add(req); } }
True
342
35
403
34
407
34
403
34
462
40
false
false
false
false
false
true
1,060
178432_2
package database; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AccountRegistratie { @Autowired private AccountDao accountDao; @SuppressWarnings("unused") @Autowired private PlayerDao playerDao; /** * Toon een overzicht van alle accounts */ @RequestMapping("/") public String overzicht(Model model) { model.addAttribute("accounts", accountDao.allAccounts()); return "frontpage"; } /** * Toon een detail-view van een enkele account */ @RequestMapping(value="/account/{id}") public String detailView(@PathVariable String id, Model model){ Long key; try{ key = Long.valueOf(id); } catch(NumberFormatException e){ // id is geen getal? error 404 return null; } Account account = accountDao.findAccount(key); if(account == null){ // geen account met gegeven id? error 404 return null; } else { model.addAttribute("account", account); return "detail"; } } /** * Verwijdert gegeven account -- zonder om bevestiging te vragen ;) */ @RequestMapping(value="/delete/{id}") public String deleteView(@PathVariable String id){ Long key; try{ key = Long.valueOf(id); } catch(NumberFormatException e){ // id is geen getal? error 404 return null; } accountDao.remove(key); return "redirect:/"; } /*@RequestMapping(value="/register", method=RequestMethod.POST) public String nieuw(String username, String password){ AccountDao.create(username, password); return "redirect:/charactercreation"; }*/ }
Mallechai/DarkFantasy2
src/database/AccountRegistratie.java
556
// id is geen getal? error 404
line_comment
nl
package database; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AccountRegistratie { @Autowired private AccountDao accountDao; @SuppressWarnings("unused") @Autowired private PlayerDao playerDao; /** * Toon een overzicht van alle accounts */ @RequestMapping("/") public String overzicht(Model model) { model.addAttribute("accounts", accountDao.allAccounts()); return "frontpage"; } /** * Toon een detail-view van een enkele account */ @RequestMapping(value="/account/{id}") public String detailView(@PathVariable String id, Model model){ Long key; try{ key = Long.valueOf(id); } catch(NumberFormatException e){ // id is<SUF> return null; } Account account = accountDao.findAccount(key); if(account == null){ // geen account met gegeven id? error 404 return null; } else { model.addAttribute("account", account); return "detail"; } } /** * Verwijdert gegeven account -- zonder om bevestiging te vragen ;) */ @RequestMapping(value="/delete/{id}") public String deleteView(@PathVariable String id){ Long key; try{ key = Long.valueOf(id); } catch(NumberFormatException e){ // id is geen getal? error 404 return null; } accountDao.remove(key); return "redirect:/"; } /*@RequestMapping(value="/register", method=RequestMethod.POST) public String nieuw(String username, String password){ AccountDao.create(username, password); return "redirect:/charactercreation"; }*/ }
True
410
12
511
13
506
12
511
13
603
12
false
false
false
false
false
true
943
69615_0
package com.molvenolakeresort.restaurant.order; import com.molvenolakeresort.restaurant.menu.MenuItem; public class OrderItem { // MenuItem // Quantity // dictionary zou hier al voldoen, maar met oog op de toekomst is dit beter }
KuroPSPiso/molveno
src/main/java/com/molvenolakeresort/restaurant/order/OrderItem.java
81
// dictionary zou hier al voldoen, maar met oog op de toekomst is dit beter
line_comment
nl
package com.molvenolakeresort.restaurant.order; import com.molvenolakeresort.restaurant.menu.MenuItem; public class OrderItem { // MenuItem // Quantity // dictionary zou<SUF> }
True
64
24
78
26
65
18
78
26
85
25
false
false
false
false
false
true
4,819
10249_4
package be.kdg.tic_tac_toe.model; import java.util.Objects; public class Piece { // vars aanmaken private final Sort SORT; private final int X; private final int Y; //constructor van de var Piece(Sort sort, int y, int x) { this.X = x; this.Y = y; this.SORT = sort; } public boolean equalsSort(Sort sort) { //zorgt ervoor om te checken of dat teken het teken is dat ze zeggen wat het is // als het null is is het zowiezo false if (sort == null) { //het kan nooit null zijn anders was der niks om mee te vergelijken daarom altijd false return false; } else { //dikke sort is wat je bent en dat vergelijk je met de kleine sort wat er gevraagd word of je dat bent //ben je die sort geef je true en dan kan het doorgaan //ben je het niet dan stopt ie en gaat het spel verder --> false return this.getSORT().equals(sort); } } Sort getSORT() { //de sort returnen die je bent return SORT; } @Override public int hashCode() { //returned de uitgerekende hashcode return Objects.hash(SORT, X, Y); } @Override public boolean equals(Object o) { //het is hetzelfde dus gelijk --> true if (this == o) return true; //als o null is is het zwz false en of als de klasse van o niet gelijk is aan de klasse van het opgegeven var if (o == null || getClass() != o.getClass()) return false; //nieuwe var en we weten dat het o is omdat we dat ervoor hebben gecheckt Piece piece = (Piece) o; // als de hashcode gelijk is dan zijn alle var ook gelijk aan elkaar if (this.hashCode() == o.hashCode()) { return X == piece.X && Y == piece.Y && SORT == piece.SORT; } return false; } @Override public String toString() { //een string van da gecheckte var teruggeven return String.format("%s", this.getSORT()); } }
zouffke/TicTacToeFX
src/main/java/be/kdg/tic_tac_toe/model/Piece.java
603
//dikke sort is wat je bent en dat vergelijk je met de kleine sort wat er gevraagd word of je dat bent
line_comment
nl
package be.kdg.tic_tac_toe.model; import java.util.Objects; public class Piece { // vars aanmaken private final Sort SORT; private final int X; private final int Y; //constructor van de var Piece(Sort sort, int y, int x) { this.X = x; this.Y = y; this.SORT = sort; } public boolean equalsSort(Sort sort) { //zorgt ervoor om te checken of dat teken het teken is dat ze zeggen wat het is // als het null is is het zowiezo false if (sort == null) { //het kan nooit null zijn anders was der niks om mee te vergelijken daarom altijd false return false; } else { //dikke sort<SUF> //ben je die sort geef je true en dan kan het doorgaan //ben je het niet dan stopt ie en gaat het spel verder --> false return this.getSORT().equals(sort); } } Sort getSORT() { //de sort returnen die je bent return SORT; } @Override public int hashCode() { //returned de uitgerekende hashcode return Objects.hash(SORT, X, Y); } @Override public boolean equals(Object o) { //het is hetzelfde dus gelijk --> true if (this == o) return true; //als o null is is het zwz false en of als de klasse van o niet gelijk is aan de klasse van het opgegeven var if (o == null || getClass() != o.getClass()) return false; //nieuwe var en we weten dat het o is omdat we dat ervoor hebben gecheckt Piece piece = (Piece) o; // als de hashcode gelijk is dan zijn alle var ook gelijk aan elkaar if (this.hashCode() == o.hashCode()) { return X == piece.X && Y == piece.Y && SORT == piece.SORT; } return false; } @Override public String toString() { //een string van da gecheckte var teruggeven return String.format("%s", this.getSORT()); } }
True
526
29
564
37
550
26
564
37
623
29
false
false
false
false
false
true
3,671
203255_0
/* * Copyright (c) 2020 De Staat der Nederlanden, Ministerie van Volksgezondheid, Welzijn en Sport. * Licensed under the EUROPEAN UNION PUBLIC LICENCE v. 1.2 * * SPDX-License-Identifier: EUPL-1.2 * */ package nl.rijksoverheid.dbco.util; import android.util.Base64; import java.nio.charset.StandardCharsets; public class Obfuscator { private static final byte OFFSET = -17; /** * Obfuscates the input into an unidentifiable text. * * @param input The string to hide the content of. * @return The obfuscated string. */ public static String obfuscate(String input) { // create bytes from the string byte[] bytes = input.getBytes(StandardCharsets.UTF_8); // offset byte[] offsetted = new byte[bytes.length]; for (int i = 0; i < bytes.length; ++i) { byte current = bytes[i]; if (current + OFFSET < 0) { offsetted[i] = (byte) (0xff + (current + OFFSET)); } else { offsetted[i] = (byte) (current + OFFSET); } } // byte value and order invert byte[] unordered = new byte[offsetted.length]; for (int i = 0; i < offsetted.length; ++i) { unordered[unordered.length - i - 1] = (byte) (~offsetted[i] & 0xff); } // base64 encode byte[] result = Base64.encode(unordered, Base64.DEFAULT); return new String(result, StandardCharsets.UTF_8); } /** * Deobfuscates the string using our own methods * * @param input The string to deobfuscate. * @return The result, which should equal with the input string of the obfuscation method. */ public static String deObfuscate(String input) { // Input should be first Base64 decoded. byte[] base64Decoded = Base64.decode(input, Base64.DEFAULT); // Bytes are inverted in value and also order byte[] ordered = new byte[base64Decoded.length]; for (int i = 0; i < base64Decoded.length; ++i) { ordered[ordered.length - i - 1] = (byte) (~base64Decoded[i] & 0xff); } // they also have an offset byte[] result = new byte[ordered.length]; for (int i = 0; i < ordered.length; ++i) { byte current = ordered[i]; if (current - OFFSET > 0xff) { result[i] = (byte) (current - OFFSET - 0xff); } else { result[i] = (byte) (current - OFFSET); } } return new String(result, StandardCharsets.UTF_8); } /** * With this method you can test if the obfuscator truly works on any string. * * @param input The string to test. * @return True if the obfuscator works. */ public static boolean test(String input) { String probe = deObfuscate(obfuscate(input)); return input.equals(probe); } }
minvws/nl-covid19-dbco-app-android
app/src/main/java/nl/rijksoverheid/dbco/util/Obfuscator.java
901
/* * Copyright (c) 2020 De Staat der Nederlanden, Ministerie van Volksgezondheid, Welzijn en Sport. * Licensed under the EUROPEAN UNION PUBLIC LICENCE v. 1.2 * * SPDX-License-Identifier: EUPL-1.2 * */
block_comment
nl
/* * Copyright (c) 2020<SUF>*/ package nl.rijksoverheid.dbco.util; import android.util.Base64; import java.nio.charset.StandardCharsets; public class Obfuscator { private static final byte OFFSET = -17; /** * Obfuscates the input into an unidentifiable text. * * @param input The string to hide the content of. * @return The obfuscated string. */ public static String obfuscate(String input) { // create bytes from the string byte[] bytes = input.getBytes(StandardCharsets.UTF_8); // offset byte[] offsetted = new byte[bytes.length]; for (int i = 0; i < bytes.length; ++i) { byte current = bytes[i]; if (current + OFFSET < 0) { offsetted[i] = (byte) (0xff + (current + OFFSET)); } else { offsetted[i] = (byte) (current + OFFSET); } } // byte value and order invert byte[] unordered = new byte[offsetted.length]; for (int i = 0; i < offsetted.length; ++i) { unordered[unordered.length - i - 1] = (byte) (~offsetted[i] & 0xff); } // base64 encode byte[] result = Base64.encode(unordered, Base64.DEFAULT); return new String(result, StandardCharsets.UTF_8); } /** * Deobfuscates the string using our own methods * * @param input The string to deobfuscate. * @return The result, which should equal with the input string of the obfuscation method. */ public static String deObfuscate(String input) { // Input should be first Base64 decoded. byte[] base64Decoded = Base64.decode(input, Base64.DEFAULT); // Bytes are inverted in value and also order byte[] ordered = new byte[base64Decoded.length]; for (int i = 0; i < base64Decoded.length; ++i) { ordered[ordered.length - i - 1] = (byte) (~base64Decoded[i] & 0xff); } // they also have an offset byte[] result = new byte[ordered.length]; for (int i = 0; i < ordered.length; ++i) { byte current = ordered[i]; if (current - OFFSET > 0xff) { result[i] = (byte) (current - OFFSET - 0xff); } else { result[i] = (byte) (current - OFFSET); } } return new String(result, StandardCharsets.UTF_8); } /** * With this method you can test if the obfuscator truly works on any string. * * @param input The string to test. * @return True if the obfuscator works. */ public static boolean test(String input) { String probe = deObfuscate(obfuscate(input)); return input.equals(probe); } }
True
743
70
800
84
839
71
800
84
924
86
false
false
false
false
false
true
2,977
11119_2
import java.util.*; // Deze klasse dient als naslagwerk en dient uiteindelijk verwijderd te worden voor je het huiswerk inlevert. // In deze klasse staan de aanval methodes die je kunt gebruiken. public class Methodes { /*deze methode komt op meerdere plaatsen terug*/ List<String> getAttacks() { return attacks; } /*De volgende 16 methodes zijn aanvallen*/ void surf(Pokemon name, Pokemon enemy); void fireLash(Pokemon name, Pokemon enemy); public void leafStorm(Pokemon name, Pokemon enemy); void hydroPump(Pokemon name, Pokemon enemy); void thunderPunch(Pokemon name, Pokemon enemy); void electroBall(Pokemon name, Pokemon enemy); public void solarBeam(Pokemon name, Pokemon enemy); void flameThrower(Pokemon name, Pokemon enemy); void hydroCanon(Pokemon name, Pokemon enemy); void pyroBall(Pokemon name, Pokemon enemy); void thunder(Pokemon name, Pokemon enemy); void rainDance(Pokemon name, Pokemon enemy); public void leechSeed(Pokemon name, Pokemon enemy); public void leaveBlade(Pokemon name, Pokemon enemy); void inferno(Pokemon name, Pokemon enemy); void voltTackle(Pokemon name, Pokemon enemy); }
hogeschoolnovi/backend-java-pokemon-interface
src/Methodes.java
379
/*deze methode komt op meerdere plaatsen terug*/
block_comment
nl
import java.util.*; // Deze klasse dient als naslagwerk en dient uiteindelijk verwijderd te worden voor je het huiswerk inlevert. // In deze klasse staan de aanval methodes die je kunt gebruiken. public class Methodes { /*deze methode komt<SUF>*/ List<String> getAttacks() { return attacks; } /*De volgende 16 methodes zijn aanvallen*/ void surf(Pokemon name, Pokemon enemy); void fireLash(Pokemon name, Pokemon enemy); public void leafStorm(Pokemon name, Pokemon enemy); void hydroPump(Pokemon name, Pokemon enemy); void thunderPunch(Pokemon name, Pokemon enemy); void electroBall(Pokemon name, Pokemon enemy); public void solarBeam(Pokemon name, Pokemon enemy); void flameThrower(Pokemon name, Pokemon enemy); void hydroCanon(Pokemon name, Pokemon enemy); void pyroBall(Pokemon name, Pokemon enemy); void thunder(Pokemon name, Pokemon enemy); void rainDance(Pokemon name, Pokemon enemy); public void leechSeed(Pokemon name, Pokemon enemy); public void leaveBlade(Pokemon name, Pokemon enemy); void inferno(Pokemon name, Pokemon enemy); void voltTackle(Pokemon name, Pokemon enemy); }
True
292
14
316
17
295
10
316
17
405
15
false
false
false
false
false
true
2,965
25145_0
package nl.novi.jp.methods.junior; /** * Uitdagende opdracht! * Een stuk van de code is uitgecommentarieerd, omdat deze pas gaat werken, wanneer de methode doTransaction afgemaakt * is. * * Maak doTransaction af. Deze moet twee waardes accepteren als input (bepaal zelf welke datatypes daarvoor logisch zijn). * - Één waarde is het banksaldo voor de transactie, * - de andere waarde is de waarde van de transactie. * * De andere methodes (main(), deposit() en withdraw()) hoeven niet aangepast te worden. * * Gebruik een if-statement om de logica van de methode op te schrijven: * - Wanneer de waarde van de transactie negatief is, gaat het om het opnemen (withdraw) van geld. Dan dient de withdraw * methode aangeroepen te worden. * - Wanneer de waarde van de transactie positief is, gaat het om geld storten (deposit). Dan dient de deposit methode * aangeroepen te worden. */ public class JuniorFour { public static void main(String[] args) { //doTransaction(1000, -200); //doTransaction(123, 3445); } public static void doTransaction() { } public static void deposit(int bankAccountBalance, int amount) { int updatedBalance = bankAccountBalance + amount; System.out.println("The user deposits: " + amount + " euro."); System.out.println("The new balance is: " + updatedBalance); } public static void withdraw(int bankAccountBalance, int amount) { int updatedBalance = bankAccountBalance + amount; System.out.println("The user withdraws " + amount + " euro."); System.out.println("The new balance is: " + updatedBalance); } }
hogeschoolnovi/SD-BE-JP-methods
src/nl/novi/jp/methods/junior/JuniorFour.java
485
/** * Uitdagende opdracht! * Een stuk van de code is uitgecommentarieerd, omdat deze pas gaat werken, wanneer de methode doTransaction afgemaakt * is. * * Maak doTransaction af. Deze moet twee waardes accepteren als input (bepaal zelf welke datatypes daarvoor logisch zijn). * - Één waarde is het banksaldo voor de transactie, * - de andere waarde is de waarde van de transactie. * * De andere methodes (main(), deposit() en withdraw()) hoeven niet aangepast te worden. * * Gebruik een if-statement om de logica van de methode op te schrijven: * - Wanneer de waarde van de transactie negatief is, gaat het om het opnemen (withdraw) van geld. Dan dient de withdraw * methode aangeroepen te worden. * - Wanneer de waarde van de transactie positief is, gaat het om geld storten (deposit). Dan dient de deposit methode * aangeroepen te worden. */
block_comment
nl
package nl.novi.jp.methods.junior; /** * Uitdagende opdracht! <SUF>*/ public class JuniorFour { public static void main(String[] args) { //doTransaction(1000, -200); //doTransaction(123, 3445); } public static void doTransaction() { } public static void deposit(int bankAccountBalance, int amount) { int updatedBalance = bankAccountBalance + amount; System.out.println("The user deposits: " + amount + " euro."); System.out.println("The new balance is: " + updatedBalance); } public static void withdraw(int bankAccountBalance, int amount) { int updatedBalance = bankAccountBalance + amount; System.out.println("The user withdraws " + amount + " euro."); System.out.println("The new balance is: " + updatedBalance); } }
True
431
247
489
280
433
218
489
280
521
280
true
true
true
true
true
false
102
169967_1
package com.nhlstenden.amazonsimulatie.views; import com.nhlstenden.amazonsimulatie.base.Command; import org.springframework.web.socket.BinaryMessage; import org.springframework.web.socket.WebSocketSession; /* * Deze class is de standaard websocketview. De class is een andere variant * van een gewone view. Een "normale" view is meestal een schermpje op de PC, * maar in dit geval is het wat de gebruiker ziet in de browser. Het behandelen * van een webpagina als view zie je vaker wanneer je te maken hebt met * serversystemen. In deze class wordt de WebSocketSession van de client opgeslagen, * waarmee de view class kan communiceren met de browser. */ public class WebAppView implements View { private WebSocketSession sesion; private Command onClose; public WebAppView(WebSocketSession sesion) { this.sesion = sesion; } /* * Deze methode wordt aangroepen vanuit de controller wanneer er een update voor * de views is. Op elke view wordt dan de update methode aangroepen, welke een * JSON pakketje maakt van de informatie die verstuurd moet worden. Deze JSON * wordt naar de browser verstuurd, welke de informatie weer afhandeld. */ @Override public void update(BinaryMessage bin) { try { if (this.sesion.isOpen()) { this.sesion.sendMessage(bin); } else { this.onClose.execute(); } } catch (Exception e) { this.onClose.execute(); } } @Override public void onViewClose(Command command) { onClose = command; } }
AnotherFoxGuy/AzwSimulatie
src/main/java/com/nhlstenden/amazonsimulatie/views/WebAppView.java
449
/* * Deze methode wordt aangroepen vanuit de controller wanneer er een update voor * de views is. Op elke view wordt dan de update methode aangroepen, welke een * JSON pakketje maakt van de informatie die verstuurd moet worden. Deze JSON * wordt naar de browser verstuurd, welke de informatie weer afhandeld. */
block_comment
nl
package com.nhlstenden.amazonsimulatie.views; import com.nhlstenden.amazonsimulatie.base.Command; import org.springframework.web.socket.BinaryMessage; import org.springframework.web.socket.WebSocketSession; /* * Deze class is de standaard websocketview. De class is een andere variant * van een gewone view. Een "normale" view is meestal een schermpje op de PC, * maar in dit geval is het wat de gebruiker ziet in de browser. Het behandelen * van een webpagina als view zie je vaker wanneer je te maken hebt met * serversystemen. In deze class wordt de WebSocketSession van de client opgeslagen, * waarmee de view class kan communiceren met de browser. */ public class WebAppView implements View { private WebSocketSession sesion; private Command onClose; public WebAppView(WebSocketSession sesion) { this.sesion = sesion; } /* * Deze methode wordt<SUF>*/ @Override public void update(BinaryMessage bin) { try { if (this.sesion.isOpen()) { this.sesion.sendMessage(bin); } else { this.onClose.execute(); } } catch (Exception e) { this.onClose.execute(); } } @Override public void onViewClose(Command command) { onClose = command; } }
True
383
91
433
95
409
80
433
95
471
99
false
false
false
false
false
true
910
123475_1
public class Punt { // implement UML notation private double x; private double y; // constructor public Punt(double xCoordinaat, double yCoordinaat) { x = xCoordinaat; y = yCoordinaat; } // getters,setters public double getX() {return x;} public void setX(double x) {this.x = x;} public double getY() {return y;} public void setY(double y) {this.y = y;} public String toString() // override { return "<Punt("+x+","+y+")>"; } public void transleer(double dx, double dy) { x += dx; y += dy; } // Euclidean distance between 2 points (kortste weg) public double afstand(Punt p) { // sqrt( (x2-x1)^2 + (y2-y1)^2 ) return Math.sqrt(Math.pow(p.x - this.x,2) + Math.pow(p.y - this.y,2)); } public boolean equals(Object obj) // override { if (obj instanceof Punt) // check if obj is more specifically, a Punt object { Punt p = (Punt) obj; // temp Punt object return this.x==p.x && this.y==p.y; } return false; // obj is not Punt type } }
Ketho/misc
edu/TUD/TI1206 OOP/Opdracht 2/Punt.java
407
// Euclidean distance between 2 points (kortste weg)
line_comment
nl
public class Punt { // implement UML notation private double x; private double y; // constructor public Punt(double xCoordinaat, double yCoordinaat) { x = xCoordinaat; y = yCoordinaat; } // getters,setters public double getX() {return x;} public void setX(double x) {this.x = x;} public double getY() {return y;} public void setY(double y) {this.y = y;} public String toString() // override { return "<Punt("+x+","+y+")>"; } public void transleer(double dx, double dy) { x += dx; y += dy; } // Euclidean distance<SUF> public double afstand(Punt p) { // sqrt( (x2-x1)^2 + (y2-y1)^2 ) return Math.sqrt(Math.pow(p.x - this.x,2) + Math.pow(p.y - this.y,2)); } public boolean equals(Object obj) // override { if (obj instanceof Punt) // check if obj is more specifically, a Punt object { Punt p = (Punt) obj; // temp Punt object return this.x==p.x && this.y==p.y; } return false; // obj is not Punt type } }
True
321
14
386
15
380
13
386
15
425
14
false
false
false
false
false
true
1,942
149734_1
package oose.dea.dao; import oose.dea.domain.Lightsaber; import javax.enterprise.inject.Default; // Dit is de default implementatie. // Deze gebruikt een zogenaamde Database implementatie. // In de webapp/WEB-INF/beans.xml heb ik aangegeven dat ik een Alternative implementatie wil gaan gebruiken. @Default public class LightsaberDAO implements ILightsaberDAO { @Override public Lightsaber getLightsaber() { //ToDo: Get data from database Lightsaber lightsaber = new Lightsaber(); lightsaber.setColor("red"); lightsaber.setSides(2); return lightsaber; } }
aaron5670/OOSE-Course
JEE-Demo/src/main/java/oose/dea/dao/LightsaberDAO.java
182
// Deze gebruikt een zogenaamde Database implementatie.
line_comment
nl
package oose.dea.dao; import oose.dea.domain.Lightsaber; import javax.enterprise.inject.Default; // Dit is de default implementatie. // Deze gebruikt<SUF> // In de webapp/WEB-INF/beans.xml heb ik aangegeven dat ik een Alternative implementatie wil gaan gebruiken. @Default public class LightsaberDAO implements ILightsaberDAO { @Override public Lightsaber getLightsaber() { //ToDo: Get data from database Lightsaber lightsaber = new Lightsaber(); lightsaber.setColor("red"); lightsaber.setSides(2); return lightsaber; } }
True
143
14
170
14
157
11
170
14
199
13
false
false
false
false
false
true
1,081
33045_5
package data;_x000D_ _x000D_ import java.util.ArrayList;_x000D_ import java.util.Calendar;_x000D_ import java.util.Random;_x000D_ _x000D_ import model.lessenrooster.Dag;_x000D_ import model.lessenrooster.Student;_x000D_ import model.locatie.Locatie;_x000D_ _x000D_ public class DataGenerator {_x000D_ _x000D_ private static final int aantal_dagen = 42;_x000D_ private static int aantal_studenten = 50;_x000D_ private static final int aantal_lessen = 10;_x000D_ private static final int aantal_locaties = 50;_x000D_ private static final boolean weekends = false;_x000D_ _x000D_ static Random random = new Random();_x000D_ _x000D_ _x000D_ private static Calendar getCalendar(int uur, int minuten, Calendar dag) {_x000D_ dag.set(Calendar.HOUR_OF_DAY, uur);_x000D_ dag.set(Calendar.MINUTE, minuten);_x000D_ return dag;_x000D_ }_x000D_ _x000D_ public static ArrayList<Dag> maakRooster() {_x000D_ _x000D_ ArrayList<Dag> rooster = new ArrayList<Dag>();_x000D_ Calendar cal = Calendar.getInstance();_x000D_ for (int i = 0; i <= aantal_dagen; i++) {_x000D_ cal.add(Calendar.DAY_OF_MONTH, 1); // Altijd 1 dag er bij_x000D_ if (!(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && cal_x000D_ .get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) || weekends) { // in weekend geenles_x000D_ if (random.nextInt(5) >2) { // 2op5 kans dat je les hebt_x000D_ Dag dag = new Dag((Calendar)cal.clone());_x000D_ for (int l = 1; l <= aantal_lessen; l++) {_x000D_ if (random.nextInt(5) > 1) { // 3op5 kans dat je op dat uur les hebt_x000D_ dag.voegLesToe(_x000D_ getCalendar(l + 7, 0,(Calendar) dag.getDatum().clone()),_x000D_ getCalendar(l + 8, 0,(Calendar) dag.getDatum().clone()));_x000D_ }_x000D_ }_x000D_ rooster.add(dag);_x000D_ }_x000D_ }_x000D_ }_x000D_ return rooster;_x000D_ _x000D_ }_x000D_ _x000D_ public static ArrayList<Student> maakStudenten() {_x000D_ ArrayList<Student> studenten = new ArrayList<Student>();_x000D_ for (int i = 0; i < aantal_studenten; i++) {_x000D_ Student student = new Student("KdG" + i);_x000D_ student.setLesdagen(maakRooster());_x000D_ studenten.add(student);_x000D_ }_x000D_ return studenten;_x000D_ }_x000D_ _x000D_ public static ArrayList<Locatie> maakLocaties() {_x000D_ ArrayList<Locatie> locaties = new ArrayList<Locatie>();_x000D_ for (int i = 0; i < aantal_locaties; i++) {_x000D_ Locatie locatie = new Locatie("Lokaal", "GR" + i+1,_x000D_ random.nextInt(200) + 20);_x000D_ locatie.setDagen(maakLocatiesSlots());_x000D_ locaties.add(locatie);_x000D_ }_x000D_ return locaties;_x000D_ }_x000D_ _x000D_ public static ArrayList<model.locatie.Dag> maakLocatiesSlots() {_x000D_ _x000D_ ArrayList<model.locatie.Dag> rooster = new ArrayList<model.locatie.Dag>();_x000D_ Calendar cal = Calendar.getInstance();_x000D_ for (int i = 0; i <= aantal_dagen; i++) {_x000D_ cal.add(Calendar.DAY_OF_MONTH, 1); // Altijd 1 dag er bij_x000D_ model.locatie.Dag dag = new model.locatie.Dag((Calendar)cal.clone());_x000D_ //System.out.println(dag.getDatum().getTime());_x000D_ for (int s=0; s<dag.getSlots().size(); s++){ //Hoeveelste slot van de dag_x000D_ //System.out.println("StartSlot:" + s);_x000D_ if (random.nextInt(3) > 0){ //2op3kans dat het lokaal op dat slot bezet is_x000D_ int aantal = random.nextInt(7) + 4; //Minimaal les van 1 uur (4 slots), maximum 2.5 uur);_x000D_ for (int j = 0; j < aantal; j++){_x000D_ try{_x000D_ dag.getSlots().get(s + j).setBezet(true); _x000D_ //System.out.println("Slot:" + (s + j) + " is bezet");_x000D_ } catch (IndexOutOfBoundsException ie){_x000D_ //Einde van slotlijst bereikt_x000D_ }_x000D_ }_x000D_ s += aantal; //Volgend slot om te beginnen in loop is ten vroegste kwartier later dan eind vorige les_x000D_ }_x000D_ }_x000D_ //System.out.println();_x000D_ rooster.add(dag); _x000D_ }_x000D_ return rooster;_x000D_ _x000D_ }_x000D_ _x000D_ }_x000D_
MathiasVandePol/ws-eventmanagementsystem
src/data/DataGenerator.java
1,316
//Hoeveelste slot van de dag_x000D_
line_comment
nl
package data;_x000D_ _x000D_ import java.util.ArrayList;_x000D_ import java.util.Calendar;_x000D_ import java.util.Random;_x000D_ _x000D_ import model.lessenrooster.Dag;_x000D_ import model.lessenrooster.Student;_x000D_ import model.locatie.Locatie;_x000D_ _x000D_ public class DataGenerator {_x000D_ _x000D_ private static final int aantal_dagen = 42;_x000D_ private static int aantal_studenten = 50;_x000D_ private static final int aantal_lessen = 10;_x000D_ private static final int aantal_locaties = 50;_x000D_ private static final boolean weekends = false;_x000D_ _x000D_ static Random random = new Random();_x000D_ _x000D_ _x000D_ private static Calendar getCalendar(int uur, int minuten, Calendar dag) {_x000D_ dag.set(Calendar.HOUR_OF_DAY, uur);_x000D_ dag.set(Calendar.MINUTE, minuten);_x000D_ return dag;_x000D_ }_x000D_ _x000D_ public static ArrayList<Dag> maakRooster() {_x000D_ _x000D_ ArrayList<Dag> rooster = new ArrayList<Dag>();_x000D_ Calendar cal = Calendar.getInstance();_x000D_ for (int i = 0; i <= aantal_dagen; i++) {_x000D_ cal.add(Calendar.DAY_OF_MONTH, 1); // Altijd 1 dag er bij_x000D_ if (!(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && cal_x000D_ .get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) || weekends) { // in weekend geenles_x000D_ if (random.nextInt(5) >2) { // 2op5 kans dat je les hebt_x000D_ Dag dag = new Dag((Calendar)cal.clone());_x000D_ for (int l = 1; l <= aantal_lessen; l++) {_x000D_ if (random.nextInt(5) > 1) { // 3op5 kans dat je op dat uur les hebt_x000D_ dag.voegLesToe(_x000D_ getCalendar(l + 7, 0,(Calendar) dag.getDatum().clone()),_x000D_ getCalendar(l + 8, 0,(Calendar) dag.getDatum().clone()));_x000D_ }_x000D_ }_x000D_ rooster.add(dag);_x000D_ }_x000D_ }_x000D_ }_x000D_ return rooster;_x000D_ _x000D_ }_x000D_ _x000D_ public static ArrayList<Student> maakStudenten() {_x000D_ ArrayList<Student> studenten = new ArrayList<Student>();_x000D_ for (int i = 0; i < aantal_studenten; i++) {_x000D_ Student student = new Student("KdG" + i);_x000D_ student.setLesdagen(maakRooster());_x000D_ studenten.add(student);_x000D_ }_x000D_ return studenten;_x000D_ }_x000D_ _x000D_ public static ArrayList<Locatie> maakLocaties() {_x000D_ ArrayList<Locatie> locaties = new ArrayList<Locatie>();_x000D_ for (int i = 0; i < aantal_locaties; i++) {_x000D_ Locatie locatie = new Locatie("Lokaal", "GR" + i+1,_x000D_ random.nextInt(200) + 20);_x000D_ locatie.setDagen(maakLocatiesSlots());_x000D_ locaties.add(locatie);_x000D_ }_x000D_ return locaties;_x000D_ }_x000D_ _x000D_ public static ArrayList<model.locatie.Dag> maakLocatiesSlots() {_x000D_ _x000D_ ArrayList<model.locatie.Dag> rooster = new ArrayList<model.locatie.Dag>();_x000D_ Calendar cal = Calendar.getInstance();_x000D_ for (int i = 0; i <= aantal_dagen; i++) {_x000D_ cal.add(Calendar.DAY_OF_MONTH, 1); // Altijd 1 dag er bij_x000D_ model.locatie.Dag dag = new model.locatie.Dag((Calendar)cal.clone());_x000D_ //System.out.println(dag.getDatum().getTime());_x000D_ for (int s=0; s<dag.getSlots().size(); s++){ //Hoeveelste slot<SUF> //System.out.println("StartSlot:" + s);_x000D_ if (random.nextInt(3) > 0){ //2op3kans dat het lokaal op dat slot bezet is_x000D_ int aantal = random.nextInt(7) + 4; //Minimaal les van 1 uur (4 slots), maximum 2.5 uur);_x000D_ for (int j = 0; j < aantal; j++){_x000D_ try{_x000D_ dag.getSlots().get(s + j).setBezet(true); _x000D_ //System.out.println("Slot:" + (s + j) + " is bezet");_x000D_ } catch (IndexOutOfBoundsException ie){_x000D_ //Einde van slotlijst bereikt_x000D_ }_x000D_ }_x000D_ s += aantal; //Volgend slot om te beginnen in loop is ten vroegste kwartier later dan eind vorige les_x000D_ }_x000D_ }_x000D_ //System.out.println();_x000D_ rooster.add(dag); _x000D_ }_x000D_ return rooster;_x000D_ _x000D_ }_x000D_ _x000D_ }_x000D_
True
1,667
16
1,884
17
1,818
16
1,885
17
2,100
17
false
false
false
false
false
true
3,105
52903_1
package structures; // https://en.wikipedia.org/wiki/Binary_heap // invariant: heap[parent] <= heap[child] public class BinaryHeapIndexed { int[] heap; int[] pos2Id; int[] id2Pos; public int size; public BinaryHeapIndexed(int n) { heap = new int[n]; pos2Id = new int[n]; id2Pos = new int[n]; } public void add(int id, int value) { heap[size] = value; pos2Id[size] = id; id2Pos[id] = size; up(size++); } public int removeMin() { int removedId = pos2Id[0]; heap[0] = heap[--size]; pos2Id[0] = pos2Id[size]; id2Pos[pos2Id[0]] = 0; down(0); return removedId; } public void remove(int id) { int pos = id2Pos[id]; pos2Id[pos] = pos2Id[--size]; id2Pos[pos2Id[pos]] = pos; changeValue(pos2Id[pos], heap[size]); } public void changeValue(int id, int value) { int pos = id2Pos[id]; if (heap[pos] < value) { heap[pos] = value; down(pos); } else if (heap[pos] > value) { heap[pos] = value; up(pos); } } void up(int pos) { while (pos > 0) { int parent = (pos - 1) / 2; if (heap[pos] >= heap[parent]) break; swap(pos, parent); pos = parent; } } void down(int pos) { while (true) { int child = 2 * pos + 1; if (child >= size) break; if (child + 1 < size && heap[child + 1] < heap[child]) ++child; if (heap[pos] <= heap[child]) break; swap(pos, child); pos = child; } } void swap(int i, int j) { int t = heap[i]; heap[i] = heap[j]; heap[j] = t; int tt = pos2Id[i]; pos2Id[i] = pos2Id[j]; pos2Id[j] = tt; id2Pos[pos2Id[i]] = i; id2Pos[pos2Id[j]] = j; } // Usage example public static void main(String[] args) { BinaryHeapIndexed heap = new BinaryHeapIndexed(10); heap.add(0, 4); heap.add(1, 5); heap.add(2, 2); heap.changeValue(1, 3); heap.changeValue(2, 6); heap.remove(0); // print elements in sorted order while (heap.size != 0) { System.out.println(heap.heap[0] + " " + heap.removeMin()); } } }
indy256/codelibrary
java/structures/BinaryHeapIndexed.java
875
// print elements in sorted order
line_comment
nl
package structures; // https://en.wikipedia.org/wiki/Binary_heap // invariant: heap[parent] <= heap[child] public class BinaryHeapIndexed { int[] heap; int[] pos2Id; int[] id2Pos; public int size; public BinaryHeapIndexed(int n) { heap = new int[n]; pos2Id = new int[n]; id2Pos = new int[n]; } public void add(int id, int value) { heap[size] = value; pos2Id[size] = id; id2Pos[id] = size; up(size++); } public int removeMin() { int removedId = pos2Id[0]; heap[0] = heap[--size]; pos2Id[0] = pos2Id[size]; id2Pos[pos2Id[0]] = 0; down(0); return removedId; } public void remove(int id) { int pos = id2Pos[id]; pos2Id[pos] = pos2Id[--size]; id2Pos[pos2Id[pos]] = pos; changeValue(pos2Id[pos], heap[size]); } public void changeValue(int id, int value) { int pos = id2Pos[id]; if (heap[pos] < value) { heap[pos] = value; down(pos); } else if (heap[pos] > value) { heap[pos] = value; up(pos); } } void up(int pos) { while (pos > 0) { int parent = (pos - 1) / 2; if (heap[pos] >= heap[parent]) break; swap(pos, parent); pos = parent; } } void down(int pos) { while (true) { int child = 2 * pos + 1; if (child >= size) break; if (child + 1 < size && heap[child + 1] < heap[child]) ++child; if (heap[pos] <= heap[child]) break; swap(pos, child); pos = child; } } void swap(int i, int j) { int t = heap[i]; heap[i] = heap[j]; heap[j] = t; int tt = pos2Id[i]; pos2Id[i] = pos2Id[j]; pos2Id[j] = tt; id2Pos[pos2Id[i]] = i; id2Pos[pos2Id[j]] = j; } // Usage example public static void main(String[] args) { BinaryHeapIndexed heap = new BinaryHeapIndexed(10); heap.add(0, 4); heap.add(1, 5); heap.add(2, 2); heap.changeValue(1, 3); heap.changeValue(2, 6); heap.remove(0); // print elements<SUF> while (heap.size != 0) { System.out.println(heap.heap[0] + " " + heap.removeMin()); } } }
678
6
752
6
834
6
752
6
868
6
false
false
false
false
false
true
503
30809_5
package frc.team4481.robot.auto.modes; import frc.team4481.lib.auto.actions.ParallelAction; import frc.team4481.lib.auto.mode.AutoModeBase; import frc.team4481.lib.auto.mode.AutoModeEndedException; import frc.team4481.lib.path.PathNotLoadedException; import frc.team4481.lib.path.TrajectoryHandler; import frc.team4481.lib.subsystems.SubsystemHandler; import frc.team4481.robot.auto.actions.*; import frc.team4481.robot.auto.selector.AutoMode; import frc.team4481.robot.auto.selector.Disabled; import frc.team4481.robot.subsystems.Intake; import frc.team4481.robot.subsystems.IntakeManager; import frc.team4481.robot.subsystems.OuttakeManager; @Disabled @AutoMode(displayName = "[Bottom] 4 note Q90") public class Low_4_note_barker extends AutoModeBase { String path_1 = "LOW_CN1"; String path_2 = "SHOOT_CN12"; String path_3 = "Recover_CN12"; String path_4 = "SHOOT_CN2"; String path_5 = "Recover_CN23"; String path_6 = "CN3_understage"; String path_7 = "SHOOT_CN3"; String path_8 = "FN1_4_note_runner"; private Intake intake; private IntakeManager intakeManager; private final SubsystemHandler subsystemHandler = SubsystemHandler.getInstance(); @Override protected void initialize() throws AutoModeEndedException, PathNotLoadedException { intake = (Intake) subsystemHandler.getSubsystemByClass(Intake.class); intakeManager = intake.getSubsystemManager(); TrajectoryHandler trajectoryHandler = TrajectoryHandler.getInstance(); try { trajectoryHandler.setUnloadedPath(path_1); trajectoryHandler.setUnloadedPath(path_2); trajectoryHandler.setUnloadedPath(path_3); trajectoryHandler.setUnloadedPath(path_4); trajectoryHandler.setUnloadedPath(path_5); trajectoryHandler.setUnloadedPath(path_6); trajectoryHandler.setUnloadedPath(path_7); trajectoryHandler.setUnloadedPath(path_8); } catch (PathNotLoadedException e) { e.printStackTrace(); } } @Override protected void routine() throws AutoModeEndedException { //shoot // runAction(new SetInitalPositionAction(path_1)); // runAction(new DriveAndShootTimedAction(path_1, new double[]{0.92, 4.14, 7.07})); // runAction(new ParallelAction( // new DrivePathAction(path_2), // new ParallelAction( // new AimingManualAction(OuttakeManager.positionState.STOWED)), // new IntakeAction(2.9)) // ); // runAction(new DriveAndShootTimedAction(path_3, new double[]{0.82})); runAction(new SetInitalPositionAction(path_1)); runAction(new DriveAndShootTimedAction(path_1, new double[] {0.7})); if (intakeManager.getControlState() == IntakeManager.controlState.STORE || intakeManager.getControlState() == IntakeManager.controlState.HOLD ) { runAction(new DriveAndShootTimedAction(path_2, new double [] {2})); } else { runAction(new DrivePathAction(path_3)); } // if (intakeManager.getControlState() == IntakeManager.controlState.STORE || intakeManager.getControlState() == IntakeManager.controlState.HOLD) { runAction(new DriveAndShootTimedAction(path_4, new double[] {2.1-0.15})); // runAction(new ParallelAction( // new AimingManualAction(OuttakeManager.positionState.STOWED), // new IntakeAction(2.25), // new DrivePathAction(path_6) ) //// ); // } else { // runAction(new DrivePathAction(path_5)); // runAction(new AimingManualAction(OuttakeManager.positionState.STOWED)); // } // runAction(new DrivePathAction(path_7)); // runAction(new ScoreAutomaticAction()); runAction(new DriveAndShootTimedAction(path_8, new double[]{0.10})); //dit werkt, 0.10 doet eigenlijk niks runAction(new ScoreAutomaticAction()); } }
FRC-4481-Team-Rembrandts/4481-robot-2024-public
src/main/java/frc/team4481/robot/auto/modes/Low_4_note_barker.java
1,274
//dit werkt, 0.10 doet eigenlijk niks
line_comment
nl
package frc.team4481.robot.auto.modes; import frc.team4481.lib.auto.actions.ParallelAction; import frc.team4481.lib.auto.mode.AutoModeBase; import frc.team4481.lib.auto.mode.AutoModeEndedException; import frc.team4481.lib.path.PathNotLoadedException; import frc.team4481.lib.path.TrajectoryHandler; import frc.team4481.lib.subsystems.SubsystemHandler; import frc.team4481.robot.auto.actions.*; import frc.team4481.robot.auto.selector.AutoMode; import frc.team4481.robot.auto.selector.Disabled; import frc.team4481.robot.subsystems.Intake; import frc.team4481.robot.subsystems.IntakeManager; import frc.team4481.robot.subsystems.OuttakeManager; @Disabled @AutoMode(displayName = "[Bottom] 4 note Q90") public class Low_4_note_barker extends AutoModeBase { String path_1 = "LOW_CN1"; String path_2 = "SHOOT_CN12"; String path_3 = "Recover_CN12"; String path_4 = "SHOOT_CN2"; String path_5 = "Recover_CN23"; String path_6 = "CN3_understage"; String path_7 = "SHOOT_CN3"; String path_8 = "FN1_4_note_runner"; private Intake intake; private IntakeManager intakeManager; private final SubsystemHandler subsystemHandler = SubsystemHandler.getInstance(); @Override protected void initialize() throws AutoModeEndedException, PathNotLoadedException { intake = (Intake) subsystemHandler.getSubsystemByClass(Intake.class); intakeManager = intake.getSubsystemManager(); TrajectoryHandler trajectoryHandler = TrajectoryHandler.getInstance(); try { trajectoryHandler.setUnloadedPath(path_1); trajectoryHandler.setUnloadedPath(path_2); trajectoryHandler.setUnloadedPath(path_3); trajectoryHandler.setUnloadedPath(path_4); trajectoryHandler.setUnloadedPath(path_5); trajectoryHandler.setUnloadedPath(path_6); trajectoryHandler.setUnloadedPath(path_7); trajectoryHandler.setUnloadedPath(path_8); } catch (PathNotLoadedException e) { e.printStackTrace(); } } @Override protected void routine() throws AutoModeEndedException { //shoot // runAction(new SetInitalPositionAction(path_1)); // runAction(new DriveAndShootTimedAction(path_1, new double[]{0.92, 4.14, 7.07})); // runAction(new ParallelAction( // new DrivePathAction(path_2), // new ParallelAction( // new AimingManualAction(OuttakeManager.positionState.STOWED)), // new IntakeAction(2.9)) // ); // runAction(new DriveAndShootTimedAction(path_3, new double[]{0.82})); runAction(new SetInitalPositionAction(path_1)); runAction(new DriveAndShootTimedAction(path_1, new double[] {0.7})); if (intakeManager.getControlState() == IntakeManager.controlState.STORE || intakeManager.getControlState() == IntakeManager.controlState.HOLD ) { runAction(new DriveAndShootTimedAction(path_2, new double [] {2})); } else { runAction(new DrivePathAction(path_3)); } // if (intakeManager.getControlState() == IntakeManager.controlState.STORE || intakeManager.getControlState() == IntakeManager.controlState.HOLD) { runAction(new DriveAndShootTimedAction(path_4, new double[] {2.1-0.15})); // runAction(new ParallelAction( // new AimingManualAction(OuttakeManager.positionState.STOWED), // new IntakeAction(2.25), // new DrivePathAction(path_6) ) //// ); // } else { // runAction(new DrivePathAction(path_5)); // runAction(new AimingManualAction(OuttakeManager.positionState.STOWED)); // } // runAction(new DrivePathAction(path_7)); // runAction(new ScoreAutomaticAction()); runAction(new DriveAndShootTimedAction(path_8, new double[]{0.10})); //dit werkt,<SUF> runAction(new ScoreAutomaticAction()); } }
True
995
16
1,159
16
1,169
12
1,159
16
1,307
16
false
false
false
false
false
true
82
26148_16
import org.postgresql.shaded.com.ongres.scram.common.ScramAttributes; import org.w3c.dom.ls.LSOutput; import java.sql.*; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws SQLException{ String url = "jdbc:postgresql://localhost/ovchip?user=postgres&password=rJFQu34u"; Connection conn; conn = DriverManager.getConnection(url); ReizigerDAO reizigerDAOPsql = new ReizigerDAOPsql(conn); AdresDAO adresDAOPsql = new AdresDAOPsql(conn); OVChipkaartDAO ovChipkaartDAOsql = new OVChipkaartDAOPsql(conn); ProductDAO productDAOsql = new ProductDAOPsql(conn); testReizigerDAO(reizigerDAOPsql); testAdresDAO(adresDAOPsql, reizigerDAOPsql); testOVchipkaartDAO(adresDAOPsql, reizigerDAOPsql, ovChipkaartDAOsql); testProductDAO(productDAOsql, ovChipkaartDAOsql); } private static void testReizigerDAO( ReizigerDAO rdao) throws SQLException { System.out.println("\n---------- Test ReizigerDAO -------------"); // Haal alle reizigers op uit de database List<Reiziger> reizigers = rdao.findAll(); System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:"); for (Reiziger r : reizigers) { System.out.println(r); } // Maak een nieuwe reiziger aan en persisteer deze in de database String gbdatum = "1981-03-14"; Reiziger sietske = new Reiziger(77, "S", "", "Boers", gbdatum); System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() "); rdao.save(sietske); reizigers = rdao.findAll(); System.out.println(reizigers.size() + " reizigers\n"); // Voeg aanvullende tests van de ontbrekende CRUD-operaties in. //Hier word een reiziger geruturned op basis van de aangegeven ID. System.out.println("De {TEST} van de functie findById met ID 77" + "\n" + "---------------------------------------"); System.out.println(rdao.findById(77)); System.out.println("De {TEST} van de functie findByGbdatum()" + "\n" + "---------------------------------------"); for (Reiziger r: rdao.findByGbdatum("1981-03-14") ) { System.out.println(r); } // De gegevens van een bestaande reiziger worden aangepast in een database. String geboorteDatum = "1950-04-12"; sietske.setGeboortedatum(geboorteDatum); rdao.update(sietske); System.out.println("Reiziger Sietske is geupdate in de database."); // De verwijder een specifieke reiziger uit de database. System.out.println("De {TEST} van de functie delte() rsultaten" + "\n" + "------------------------------------"); try { rdao.delete(sietske); System.out.println("Reiziger is met succes verwijderd"); } catch (Exception e){ System.out.println("Het is niet gelukt om de reiziger te verwijderen."); e.printStackTrace(); } } private static void testAdresDAO(AdresDAO adresDAO, ReizigerDAO rdao) throws SQLException{ System.out.println("Hier beginnen de test's van de Adres klasse" + "\n" + "------------------------------------------------" ); // Haal alle reizigers op uit de database System.out.println("Hier begint de test van de .save() functie van de adresDAO" + "\n" + "------------------------------------------------" ); List<Adres> adressen = adresDAO.findAll(); System.out.println("[Test] adresDAO.findAll() geeft de volgende Adressen:"); for (Adres a : adressen) { System.out.println(a); } // Hier wordt een nieuw adres aangemaakt en deze word opgeslagen in de database. System.out.println("Hier begint de test van de .save() functie van de adresDAO" + "\n" + "------------------------------------------------" ); String gbDatum = "1997-10-24"; Reiziger reizigerA = new Reiziger(6, "A","", "Ait Si'Mhand", gbDatum ); rdao.save(reizigerA); Adres adresAchraf = new Adres(6, "2964BL", "26", "Irenestraat", "Groot-Ammers"); reizigerA.setAdres(adresAchraf); System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.save()"); adresDAO.save(adresAchraf); List<Adres> adressenNaUpdate = adresDAO.findAll(); System.out.println(adressenNaUpdate.size() + " reizigers\n"); //Hier wordt de update() functie van Adres aangeroepen en getest. System.out.println("Hier begint de test van de update functie van de adres klasse" + "\n" + "------------------------------------------------" ); adresAchraf.setHuisnummer("30"); try{ adresDAO.update(adresAchraf); System.out.println("Het adres is geupdate."); } catch (Exception e){ System.out.println("Het is niet gelukt om het adres te updaten in de database"); e.printStackTrace(); } //Hier wordt de functie .findbyreiziger() getest. System.out.println("Hier begint de test van de .findByReiziger() functie van de adresDAO" + "\n" + "------------------------------------------------" ); try { adresDAO.findByReiziger(reizigerA); System.out.println("Adres is opgehaald."); } catch (Exception e){ System.out.println("Het is niet gelukt om de het adres te vinden bij de reiziger."); e.printStackTrace(); } //Hier word de delete() functie van adres aangeroepen. System.out.println("Hier begint de test van de .delete functie van de adresDAO" + "\n" + "------------------------------------------------" ); System.out.println("Test delete() methode"); System.out.println("Eerst" + adressen.size()); adressenNaUpdate.forEach((value) -> System.out.println(value)); System.out.println("[test] delete() geeft -> "); adresDAO.delete(adresAchraf); //delete adres rdao.delete(reizigerA); List<Adres> adressenNaDelete = new ArrayList<>(adresDAO.findAll()); adressenNaDelete.forEach((value) -> System.out.println(value)); } private static void testOVchipkaartDAO(AdresDAO adresDAO, ReizigerDAO reizigerDAO, OVChipkaartDAO ovChipkaartDAO){ System.out.println("Hier beginnen de test's van de OVchipkaart klasse" + "\n" + "------------------------------------------------" ); // Haal alle kaarten op uit de database System.out.println("Hier begint de test van de OVchipkaart.findall() functie van de OVchipkaartDAO" + "\n" + "------------------------------------------------" ); List<OVChipkaart> ovChipkaarts = ovChipkaartDAO.findAll(); System.out.println("[Test] OVchipkaartDAO.findAll() geeft de volgende ov's:"); for (OVChipkaart ov : ovChipkaarts) { System.out.println(ov); } //Hier wordt er een nieuw OVchipkaart object aangemaakt en gepersisteerd in de datbase. OVChipkaart ovChipkaart = new OVChipkaart(); ovChipkaart.setKaartNummer(12345); ovChipkaart.setGeldigTot("2022-10-24"); ovChipkaart.setKlasse(1); ovChipkaart.setSaldo(350.00); ovChipkaart.setReizigerId(5); // Hier wordt een bepaalde Chipkaart verwijderd uit de database. System.out.println("Hier begint de test van OVChipkaart.delete()" + "\n" + "------------------------------------------------" ); try { ovChipkaartDAO.delete(ovChipkaart); System.out.println("De kaart is met succes verwijderd uit de database."); } catch (Exception e){ System.out.println("Het is niet gelukt om de kaart te verwijderen."); e.printStackTrace(); } ovChipkaarts = ovChipkaartDAO.findAll(); System.out.println("De database bevatte voor het opslaan " + ovChipkaarts.size() + "kaarten" + "\n"); for (OVChipkaart ov : ovChipkaarts) { System.out.println(ov); } try { ovChipkaartDAO.save(ovChipkaart); System.out.println("De nieuwe chipkaart is opgeslagen."); } catch (Exception e){ System.out.println("Het is niet gelukt om het nieuwe opbject op te slaan in de database."); e.printStackTrace(); } ovChipkaarts = ovChipkaartDAO.findAll(); System.out.println("En de databse bevat na het opslaan " + ovChipkaarts.size()); // Hier wordt de update functie de OVchipkaartDAO aangeroepen en getest. try { ovChipkaart.setSaldo(20.00); ovChipkaartDAO.update(ovChipkaart); //Hier halen we de lijst opnieuw op om er zo voor te zorgen dat de lijst klopt en dus hier uitggeprint kan worden ovChipkaarts = ovChipkaartDAO.findAll(); System.out.println("De kaart is met succes geupdate, het saldo is gewzijzigd"); for (OVChipkaart ov : ovChipkaarts){ System.out.println(ov); } } catch (Exception e ){ System.out.println("Het is niet gelukt om de kaart te udpaten."); e.printStackTrace(); } System.out.println("Hier begint de test van OVChipkaart.findByReiziger" + "\n" + "------------------------------------------------" ); Reiziger reiziger = reizigerDAO.findById(5); //Hier wordt de functie getest van OvchipkaartDAO.findByReiziger() getest System.out.println(ovChipkaartDAO.findByReiziger(reiziger)); System.out.println("DONE"); } public static void testProductDAO(ProductDAO productDAO, OVChipkaartDAO ovChipkaartDAO) throws SQLException{ //Hall alle producten op uit de database System.out.println("Hier begint de test van de .save() functie van de productDAO\n" + "------------------------------------------------" ); List<Product> producten = productDAO.findAll(); System.out.println("[Test] productDAO.findAll() geeft de volgende Adressen voor de .save():"); for (Product product: producten) { System.out.println(product); System.out.println("Aantal producten in de database voor de save: " + producten.size()); } //Hier wordt een nieuw product aangemaakt en opgeslagen in de database. Product testProduct = new Product(12345, "SeniorenProduct", "Mobiliteit voor ouderen", 25.00); System.out.println("Producten in de database na de .save()"); try { productDAO.save(testProduct); List<Product> productenNaSave = productDAO.findAll(); for (Product product: productenNaSave){ System.out.println(product); } System.out.println("Aantal" + productenNaSave.size()); } catch (Exception e){ e.printStackTrace(); } //Hier wordt het product geupdate en gepersisteerd in de database. try { testProduct.setPrijs(9999.00); productDAO.update(testProduct); System.out.println(" " +testProduct.getProduct_nummer()); System.out.println("Producten in de databse na de .update()"); List<Product> productenNaUpdate = productDAO.findAll(); for (Product product: productenNaUpdate){ System.out.println(product); } } catch (Exception e){ e.printStackTrace(); } System.out.println("Hier word de delete functie getest"); try { //Hier wordt het product verwijderd. System.out.println("De producten in de database na het verwijderen"); productDAO.delete(testProduct); List<Product> productenNaDelete = productDAO.findAll(); for (Product product :productenNaDelete ){ System.out.println(product); } System.out.println("Aantal producten na delete:" + productenNaDelete.size()); } catch (Exception e){ e.printStackTrace(); } } }
Aitsimhand/DP_OV-Chipkaart
src/Main.java
3,767
//Hier wordt de functie getest van OvchipkaartDAO.findByReiziger() getest
line_comment
nl
import org.postgresql.shaded.com.ongres.scram.common.ScramAttributes; import org.w3c.dom.ls.LSOutput; import java.sql.*; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws SQLException{ String url = "jdbc:postgresql://localhost/ovchip?user=postgres&password=rJFQu34u"; Connection conn; conn = DriverManager.getConnection(url); ReizigerDAO reizigerDAOPsql = new ReizigerDAOPsql(conn); AdresDAO adresDAOPsql = new AdresDAOPsql(conn); OVChipkaartDAO ovChipkaartDAOsql = new OVChipkaartDAOPsql(conn); ProductDAO productDAOsql = new ProductDAOPsql(conn); testReizigerDAO(reizigerDAOPsql); testAdresDAO(adresDAOPsql, reizigerDAOPsql); testOVchipkaartDAO(adresDAOPsql, reizigerDAOPsql, ovChipkaartDAOsql); testProductDAO(productDAOsql, ovChipkaartDAOsql); } private static void testReizigerDAO( ReizigerDAO rdao) throws SQLException { System.out.println("\n---------- Test ReizigerDAO -------------"); // Haal alle reizigers op uit de database List<Reiziger> reizigers = rdao.findAll(); System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:"); for (Reiziger r : reizigers) { System.out.println(r); } // Maak een nieuwe reiziger aan en persisteer deze in de database String gbdatum = "1981-03-14"; Reiziger sietske = new Reiziger(77, "S", "", "Boers", gbdatum); System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() "); rdao.save(sietske); reizigers = rdao.findAll(); System.out.println(reizigers.size() + " reizigers\n"); // Voeg aanvullende tests van de ontbrekende CRUD-operaties in. //Hier word een reiziger geruturned op basis van de aangegeven ID. System.out.println("De {TEST} van de functie findById met ID 77" + "\n" + "---------------------------------------"); System.out.println(rdao.findById(77)); System.out.println("De {TEST} van de functie findByGbdatum()" + "\n" + "---------------------------------------"); for (Reiziger r: rdao.findByGbdatum("1981-03-14") ) { System.out.println(r); } // De gegevens van een bestaande reiziger worden aangepast in een database. String geboorteDatum = "1950-04-12"; sietske.setGeboortedatum(geboorteDatum); rdao.update(sietske); System.out.println("Reiziger Sietske is geupdate in de database."); // De verwijder een specifieke reiziger uit de database. System.out.println("De {TEST} van de functie delte() rsultaten" + "\n" + "------------------------------------"); try { rdao.delete(sietske); System.out.println("Reiziger is met succes verwijderd"); } catch (Exception e){ System.out.println("Het is niet gelukt om de reiziger te verwijderen."); e.printStackTrace(); } } private static void testAdresDAO(AdresDAO adresDAO, ReizigerDAO rdao) throws SQLException{ System.out.println("Hier beginnen de test's van de Adres klasse" + "\n" + "------------------------------------------------" ); // Haal alle reizigers op uit de database System.out.println("Hier begint de test van de .save() functie van de adresDAO" + "\n" + "------------------------------------------------" ); List<Adres> adressen = adresDAO.findAll(); System.out.println("[Test] adresDAO.findAll() geeft de volgende Adressen:"); for (Adres a : adressen) { System.out.println(a); } // Hier wordt een nieuw adres aangemaakt en deze word opgeslagen in de database. System.out.println("Hier begint de test van de .save() functie van de adresDAO" + "\n" + "------------------------------------------------" ); String gbDatum = "1997-10-24"; Reiziger reizigerA = new Reiziger(6, "A","", "Ait Si'Mhand", gbDatum ); rdao.save(reizigerA); Adres adresAchraf = new Adres(6, "2964BL", "26", "Irenestraat", "Groot-Ammers"); reizigerA.setAdres(adresAchraf); System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.save()"); adresDAO.save(adresAchraf); List<Adres> adressenNaUpdate = adresDAO.findAll(); System.out.println(adressenNaUpdate.size() + " reizigers\n"); //Hier wordt de update() functie van Adres aangeroepen en getest. System.out.println("Hier begint de test van de update functie van de adres klasse" + "\n" + "------------------------------------------------" ); adresAchraf.setHuisnummer("30"); try{ adresDAO.update(adresAchraf); System.out.println("Het adres is geupdate."); } catch (Exception e){ System.out.println("Het is niet gelukt om het adres te updaten in de database"); e.printStackTrace(); } //Hier wordt de functie .findbyreiziger() getest. System.out.println("Hier begint de test van de .findByReiziger() functie van de adresDAO" + "\n" + "------------------------------------------------" ); try { adresDAO.findByReiziger(reizigerA); System.out.println("Adres is opgehaald."); } catch (Exception e){ System.out.println("Het is niet gelukt om de het adres te vinden bij de reiziger."); e.printStackTrace(); } //Hier word de delete() functie van adres aangeroepen. System.out.println("Hier begint de test van de .delete functie van de adresDAO" + "\n" + "------------------------------------------------" ); System.out.println("Test delete() methode"); System.out.println("Eerst" + adressen.size()); adressenNaUpdate.forEach((value) -> System.out.println(value)); System.out.println("[test] delete() geeft -> "); adresDAO.delete(adresAchraf); //delete adres rdao.delete(reizigerA); List<Adres> adressenNaDelete = new ArrayList<>(adresDAO.findAll()); adressenNaDelete.forEach((value) -> System.out.println(value)); } private static void testOVchipkaartDAO(AdresDAO adresDAO, ReizigerDAO reizigerDAO, OVChipkaartDAO ovChipkaartDAO){ System.out.println("Hier beginnen de test's van de OVchipkaart klasse" + "\n" + "------------------------------------------------" ); // Haal alle kaarten op uit de database System.out.println("Hier begint de test van de OVchipkaart.findall() functie van de OVchipkaartDAO" + "\n" + "------------------------------------------------" ); List<OVChipkaart> ovChipkaarts = ovChipkaartDAO.findAll(); System.out.println("[Test] OVchipkaartDAO.findAll() geeft de volgende ov's:"); for (OVChipkaart ov : ovChipkaarts) { System.out.println(ov); } //Hier wordt er een nieuw OVchipkaart object aangemaakt en gepersisteerd in de datbase. OVChipkaart ovChipkaart = new OVChipkaart(); ovChipkaart.setKaartNummer(12345); ovChipkaart.setGeldigTot("2022-10-24"); ovChipkaart.setKlasse(1); ovChipkaart.setSaldo(350.00); ovChipkaart.setReizigerId(5); // Hier wordt een bepaalde Chipkaart verwijderd uit de database. System.out.println("Hier begint de test van OVChipkaart.delete()" + "\n" + "------------------------------------------------" ); try { ovChipkaartDAO.delete(ovChipkaart); System.out.println("De kaart is met succes verwijderd uit de database."); } catch (Exception e){ System.out.println("Het is niet gelukt om de kaart te verwijderen."); e.printStackTrace(); } ovChipkaarts = ovChipkaartDAO.findAll(); System.out.println("De database bevatte voor het opslaan " + ovChipkaarts.size() + "kaarten" + "\n"); for (OVChipkaart ov : ovChipkaarts) { System.out.println(ov); } try { ovChipkaartDAO.save(ovChipkaart); System.out.println("De nieuwe chipkaart is opgeslagen."); } catch (Exception e){ System.out.println("Het is niet gelukt om het nieuwe opbject op te slaan in de database."); e.printStackTrace(); } ovChipkaarts = ovChipkaartDAO.findAll(); System.out.println("En de databse bevat na het opslaan " + ovChipkaarts.size()); // Hier wordt de update functie de OVchipkaartDAO aangeroepen en getest. try { ovChipkaart.setSaldo(20.00); ovChipkaartDAO.update(ovChipkaart); //Hier halen we de lijst opnieuw op om er zo voor te zorgen dat de lijst klopt en dus hier uitggeprint kan worden ovChipkaarts = ovChipkaartDAO.findAll(); System.out.println("De kaart is met succes geupdate, het saldo is gewzijzigd"); for (OVChipkaart ov : ovChipkaarts){ System.out.println(ov); } } catch (Exception e ){ System.out.println("Het is niet gelukt om de kaart te udpaten."); e.printStackTrace(); } System.out.println("Hier begint de test van OVChipkaart.findByReiziger" + "\n" + "------------------------------------------------" ); Reiziger reiziger = reizigerDAO.findById(5); //Hier wordt<SUF> System.out.println(ovChipkaartDAO.findByReiziger(reiziger)); System.out.println("DONE"); } public static void testProductDAO(ProductDAO productDAO, OVChipkaartDAO ovChipkaartDAO) throws SQLException{ //Hall alle producten op uit de database System.out.println("Hier begint de test van de .save() functie van de productDAO\n" + "------------------------------------------------" ); List<Product> producten = productDAO.findAll(); System.out.println("[Test] productDAO.findAll() geeft de volgende Adressen voor de .save():"); for (Product product: producten) { System.out.println(product); System.out.println("Aantal producten in de database voor de save: " + producten.size()); } //Hier wordt een nieuw product aangemaakt en opgeslagen in de database. Product testProduct = new Product(12345, "SeniorenProduct", "Mobiliteit voor ouderen", 25.00); System.out.println("Producten in de database na de .save()"); try { productDAO.save(testProduct); List<Product> productenNaSave = productDAO.findAll(); for (Product product: productenNaSave){ System.out.println(product); } System.out.println("Aantal" + productenNaSave.size()); } catch (Exception e){ e.printStackTrace(); } //Hier wordt het product geupdate en gepersisteerd in de database. try { testProduct.setPrijs(9999.00); productDAO.update(testProduct); System.out.println(" " +testProduct.getProduct_nummer()); System.out.println("Producten in de databse na de .update()"); List<Product> productenNaUpdate = productDAO.findAll(); for (Product product: productenNaUpdate){ System.out.println(product); } } catch (Exception e){ e.printStackTrace(); } System.out.println("Hier word de delete functie getest"); try { //Hier wordt het product verwijderd. System.out.println("De producten in de database na het verwijderen"); productDAO.delete(testProduct); List<Product> productenNaDelete = productDAO.findAll(); for (Product product :productenNaDelete ){ System.out.println(product); } System.out.println("Aantal producten na delete:" + productenNaDelete.size()); } catch (Exception e){ e.printStackTrace(); } } }
True
2,984
22
3,346
24
3,244
20
3,345
24
3,889
28
false
false
false
false
false
true
1,373
72779_13
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class MyWorld extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 14, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(), 1170, 410); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } }
ROCMondriaanTIN/project-greenfoot-game-Darnell070
MyWorld.java
3,121
// Toevoegen van de mover instantie of een extentie hiervan
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class MyWorld extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 14, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, }; // Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen TileEngine te = new TileEngine(this, 60, 60, map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); addObject(new Enemy(), 1170, 410); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van<SUF> ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } }
True
3,361
16
3,392
18
3,395
15
3,392
18
3,461
17
false
false
false
false
false
true
190
17508_6
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.CommandHandler.Action; import tillerino.tillerinobot.CommandHandler.Message; import tillerino.tillerinobot.CommandHandler.Response; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { private static final long serialVersionUID = 1L; static final Random rnd = new Random(); @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public Response hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public Response optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(rnd); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!", "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
Banbeucmas/Tillerinobot
tillerinobot/src/main/java/tillerino/tillerinobot/lang/Nederlands.java
2,674
//nl.wikipedia.org/wiki/Special:Random wikipedia] eens zien!",
line_comment
nl
package tillerino.tillerinobot.lang; import java.util.List; import java.util.Random; import org.tillerino.osuApiModel.Mods; import org.tillerino.osuApiModel.OsuApiUser; import tillerino.tillerinobot.CommandHandler.Action; import tillerino.tillerinobot.CommandHandler.Message; import tillerino.tillerinobot.CommandHandler.Response; /** * Dutch language implementation by https://osu.ppy.sh/u/PudiPudi and https://github.com/notadecent and https://osu.ppy.sh/u/2756335 */ public class Nederlands extends AbstractMutableLanguage { private static final long serialVersionUID = 1L; static final Random rnd = new Random(); @Override public String unknownBeatmap() { return "Het spijt me, ik ken die map niet. Hij kan gloednieuw zijn, heel erg moeilijk of hij is niet voor osu standard mode."; } @Override public String internalException(String marker) { return "Ugh... Lijkt er op dat Tillerino een oelewapper is geweest en mijn bedrading kapot heeft gemaakt." + " Als hij het zelf niet merkt, kan je hem dan [https://github.com/Tillerino/Tillerinobot/wiki/Contact op de hoogte stellen]? (reference " + marker + ")"; } @Override public String externalException(String marker) { return "Wat gebeurt er? Ik krijg alleen maar onzin van de osu server. Kan je me vertellen wat dit betekent? 00111010 01011110 00101001" + " De menselijke Tillerino zegt dat we ons er geen zorgen over hoeven te maken en dat we het opnieuw moeten proberen." + " Als je je heel erg zorgen maakt hierover, kan je het aan Tillerino [https://github.com/Tillerino/Tillerinobot/wiki/Contact vertellen]. (reference " + marker + ")"; } @Override public String noInformationForModsShort() { return "Geen informatie beschikbaar voor opgevraagde mods"; } @Override public Response welcomeUser(OsuApiUser apiUser, long inactiveTime) { if(inactiveTime < 60 * 1000) { return new Message("beep boop"); } else if(inactiveTime < 24 * 60 * 60 * 1000) { return new Message("Welkom terug, " + apiUser.getUserName() + "."); } else if(inactiveTime > 7l * 24 * 60 * 60 * 1000) { return new Message(apiUser.getUserName() + "...") .then(new Message("...ben jij dat? Dat is lang geleden!")) .then(new Message("Het is goed om je weer te zien. Kan ik je wellicht een recommandatie geven?")); } else { String[] messages = { "jij ziet er uit alsof je een recommandatie wilt.", "leuk om je te zien! :)", "mijn favoriete mens. (Vertel het niet aan de andere mensen!)", "wat een leuke verrassing! ^.^", "Ik hoopte al dat je op kwam dagen. Al die andere mensen zijn saai, maar vertel ze niet dat ik dat zei! :3", "waar heb je zin in vandaag?", }; Random random = new Random(); String message = messages[random.nextInt(messages.length)]; return new Message(apiUser.getUserName() + ", " + message); } } @Override public String unknownCommand(String command) { return "Ik snap niet helemaal wat je bedoelt met \"" + command + "\". Typ !help als je hulp nodig hebt!"; } @Override public String noInformationForMods() { return "Sorry, ik kan je op het moment geen informatie geven over die mods."; } @Override public String malformattedMods(String mods) { return "Die mods zien er niet goed uit. Mods kunnen elke combinatie zijn van DT HR HD HT EZ NC FL SO NF. Combineer ze zonder spaties of speciale tekens, bijvoorbeeld: '!with HDHR' of '!with DTEZ'"; } @Override public String noLastSongInfo() { return "Ik kan me niet herinneren dat je al een map had opgevraagd..."; } @Override public String tryWithMods() { return "Probeer deze map met wat mods!"; } @Override public String tryWithMods(List<Mods> mods) { return "Probeer deze map eens met " + Mods.toShortNamesContinuous(mods); } @Override public String excuseForError() { return "Het spijt me, een prachtige rij van enen en nullen kwam langs en dat leidde me af. Wat wou je ook al weer?"; } @Override public String complaint() { return "Je klacht is ingediend. Tillerino zal er naar kijken als hij tijd heeft."; } @Override public Response hug(OsuApiUser apiUser) { return new Message("Kom eens hier jij!") .then(new Action("knuffelt " + apiUser.getUserName())); } @Override public String help() { return "Hallo! Ik ben de robot die Tillerino heeft gedood en zijn account heeft overgenomen! Grapje, maar ik gebruik wel zijn account." + " Check https://twitter.com/Tillerinobot voor status en updates!" + " Zie https://github.com/Tillerino/Tillerinobot/wiki voor commandos!"; } @Override public String faq() { return "Zie https://github.com/Tillerino/Tillerinobot/wiki/FAQ voor veelgestelde vragen!"; } @Override public String featureRankRestricted(String feature, int minRank, OsuApiUser user) { return "Sorry, " + feature + " is op het moment alleen beschikbaar voor spelers boven rank " + minRank ; } @Override public String mixedNomodAndMods() { return "Hoe bedoel je, nomod met mods?"; } @Override public String outOfRecommendations() { return "[https://github.com/Tillerino/Tillerinobot/wiki/FAQ#the-bot-says-its-out-of-recommendations-what-do" + " Ik heb je alles wat ik me kan bedenken al aanbevolen]." + " Probeer andere aanbevelingsopties of gebruik !reset. Als je het niet zeker weet, check !help."; } @Override public String notRanked() { return "Lijkt erop dat die beatmap niet ranked is."; } @Override public String invalidAccuracy(String acc) { return "Ongeldige accuracy: \"" + acc + "\""; } @Override public Response optionalCommentOnLanguage(OsuApiUser apiUser) { return new Message("PudiPudi heeft me geleerd Nederlands te spreken."); } @Override public String invalidChoice(String invalid, String choices) { return "Het spijt me, maar \"" + invalid + "\" werkt niet. Probeer deze: " + choices + "!"; } @Override public String setFormat() { return "De syntax om een parameter in te stellen is '!set optie waarde'. Typ !help als je meer aanwijzingen nodig hebt."; } StringShuffler apiTimeoutShuffler = new StringShuffler(rnd); @Override public String apiTimeoutException() { registerModification(); final String message = "De osu! servers zijn nu heel erg traag, dus ik kan op dit moment niets voor je doen. "; return message + apiTimeoutShuffler.get( "Zeg... Wanneer heb je voor het laatst met je oma gesproken?", "Wat dacht je ervan om je kamer eens op te ruimen en dan nog eens te proberen?", "Ik weet zeker dat je vast erg zin hebt in een wandeling. Jeweetwel... daarbuiten?", "Ik weet gewoon zeker dat er een helehoop andere dingen zijn die je nog moet doen. Wat dacht je ervan om ze nu te doen?", "Je ziet eruit alsof je wel wat slaap kan gebruiken...", "Maat moet je deze superinteressante pagina op [https://nl.wikipedia.org/wiki/Special:Random wikipedia]<SUF> "Laten we eens kijken of er een goed iemand aan het [http://www.twitch.tv/directory/game/Osu! streamen] is!", "Kijk, hier is een ander [http://dagobah.net/flash/Cursor_Invisible.swf spel] waar je waarschijnlijk superslecht in bent!", "Dit moet je tijd zat geven om [https://github.com/Tillerino/Tillerinobot/wiki mijn handleiding] te bestuderen.", "Geen zorgen, met deze [https://www.reddit.com/r/osugame dank memes] kun je de tijd dooden.", "Terwijl je je verveelt, probeer [http://gabrielecirulli.github.io/2048/ 2048] eens een keer!", "Leuke vraag: Als je harde schijf op dit moment zou crashen, hoeveel van je persoonlijke gegevens ben je dan voor eeuwig kwijt?", "Dus... Heb je wel eens de [https://www.google.nl/search?q=bring%20sally%20up%20push%20up%20challenge sally up push up challenge] geprobeerd?", "Je kunt wat anders gaan doen of we kunnen elkaar in de ogen gaan staren. In stilte." ); } @Override public String noRecentPlays() { return "Ik heb je de afgelopen tijd niet zien spelen."; } @Override public String isSetId() { return "Dit refereerd naar een beatmap-verzameling in plaats van een beatmap zelf."; } }
True
2,316
14
2,767
20
2,414
17
2,767
20
3,017
22
false
false
false
false
false
true
1,155
89830_3
import java.io.File;_x000D_ import java.io.FileWriter;_x000D_ import java.io.IOException;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Arrays;_x000D_ _x000D_ /**_x000D_ * Dateiname : Mergesort.java_x000D_ * Beschreibung : Einsendeaufgabe 2 für den Kurs Algorithmen_x000D_ *_x000D_ * @author Tobias Wagner (s79080@beuth-hochschule.de)_x000D_ * @version 1.00, 02.12.2019_x000D_ */_x000D_ _x000D_ // Klasse Mergesort zum Sortieren von Arrays und zum Testen der gegebenen Dateien Rand... und Sort..._x000D_ // Jeweils mit Anfangs- und Endzeit_x000D_ public class Mergesort_x000D_ {_x000D_ _x000D_ private static String[] testDaten = {"Rand10_1", "Rand10_2", "Rand20_1", "Rand20_2",_x000D_ "Rand50_1", "Rand50_2", "Rand100_1", "Rand100_2",_x000D_ "Rand200_1", "Rand200_2", "Rand500_1", "Rand500_1",_x000D_ "Rand1000_1", "Rand1000_2", "Rand10000_1", "Rand10000_2",_x000D_ "Rand100000_1", "Rand100000_2", "Sort10_1", "Sort20_1", "Sort50_1", "Sort100_1", "Sort200_1",_x000D_ "Sort500_1", "Sort1000_1", "Sort10000_1", "Sort100000_1"};_x000D_ _x000D_ //Deklaration der main Methode_x000D_ public static void main(String[] args) throws IOException_x000D_ {_x000D_ ArrayList<TestErgebnis> ergebnisListe = new ArrayList<>();_x000D_ _x000D_ for (String testFilename : testDaten) {_x000D_ // Einlesen des zu bearbeitenden Arrays - Auswahl der Datei mit dem Array_x000D_ int[] testDatensatz = FileIntArray.FileToIntArray(testFilename);_x000D_ _x000D_ // Ausgeben des unsortierten Arrays_x000D_ System.out.println(Arrays.toString(testDatensatz));_x000D_ _x000D_ // Erfassen der Anfangszeit_x000D_ double anfangszeit = System.nanoTime();_x000D_ _x000D_ // Ausführen von mergeSort_x000D_ mergeSort(testDatensatz, 0, testDatensatz.length - 1);_x000D_ _x000D_ // Erfassen der Endzeit_x000D_ double endzeit = System.nanoTime();_x000D_ _x000D_ // Ausgabe des sortierten Arrays_x000D_ System.out.println(Arrays.toString(testDatensatz));_x000D_ _x000D_ // Ausgabe der benötigten Dauer für den Durchlauf von mergeSort_x000D_ double dauer = endzeit - anfangszeit;_x000D_ System.out.println("Die benötigte Zeit betraegt: " + dauer + " Nanosekunden");_x000D_ _x000D_ // Speichern des Testergebnisses in unsere ergebnissliste_x000D_ TestErgebnis testErgebnis = new TestErgebnis(testFilename, dauer);_x000D_ ergebnisListe.add(testErgebnis);_x000D_ }_x000D_ _x000D_ File datei = new File("Testlaufergebnis.csv");_x000D_ FileWriter schreiber = new FileWriter(datei);_x000D_ _x000D_ // CSV Kopzeile_x000D_ schreiber.write("Testlauf;Zeit\n");_x000D_ _x000D_ for (TestErgebnis testErg : ergebnisListe) {_x000D_ schreiber.write(testErg.getTestDataname() + ";" + testErg.getTime() + "\n");_x000D_ }_x000D_ schreiber.close();_x000D_ }_x000D_ _x000D_ // Rekursive Funktion Mergesort_x000D_ // Initialisierung Mergesort mit dem eingelesenen Array, dem linken Index, dem rechten Index_x000D_ private static void mergeSort(int[] datensatz, int indexLinks, int indexRechts)_x000D_ {_x000D_ if (indexLinks < indexRechts) {_x000D_ int mitte = (indexLinks + indexRechts) / 2;_x000D_ mergeSort(datensatz, indexLinks, mitte);_x000D_ mergeSort(datensatz, mitte + 1, indexRechts);_x000D_ merge(datensatz, indexLinks, mitte, indexRechts);_x000D_ }_x000D_ }_x000D_ _x000D_ //Merge - Methode, die in Mergesort aufgerufen wird_x000D_ private static void merge(int[] datensatz, int l, int m, int r)_x000D_ {_x000D_ // H = Hilfsarray, zum Zwischenspeichern, mit der Länge des Arrays A_x000D_ int hilfsArray[] = new int[datensatz.length];_x000D_ _x000D_ // definiere i = linker Index, solange i kleiner gleich rechter Index, führe aus und erhöhe i_x000D_ for (int i = l; i <= r; i++) {_x000D_ // Zwischenspeichern von Array datensatz[i] nach hilfsarray[i]_x000D_ hilfsArray[i] = datensatz[i];_x000D_ }_x000D_ // Laufzeitvariablen i, j und k für die while - Schleifendurchläufe_x000D_ int i = l;_x000D_ int j = m + 1;_x000D_ int k = l;_x000D_ // solange i kleiner gleich mittlerer Index UND j kleiner gleich rechter Index,_x000D_ while (i <= m && j <= r) {_x000D_ _x000D_ // Kopiere kleineren aktuellen Wert hilfsArray[j] -> datensatz[k] bzw. hilfsArray[i] -> datensatz[k]_x000D_ // Erhöhe aktuellen Index von Teilarray mit kleinerem Wert_x000D_ // Erhöhe aktuellen Index von H_x000D_ _x000D_ // Wenn H an der Stelle i kleiner gleich H an der Stelle J, dann setze H[i] auf A[k] erhöhe i um eins_x000D_ if (hilfsArray[i] <= hilfsArray[j]) {_x000D_ datensatz[k] = hilfsArray[i];_x000D_ i++;_x000D_ // ansonsten setze H an der Stelle j auf A[k] und erhöhe j um 1_x000D_ } else {_x000D_ datensatz[k] = hilfsArray[j];_x000D_ j++;_x000D_ }_x000D_ // Erhöhe k, die Zählvariable des Arrays A um eins,_x000D_ // um die nächste Position im Array A im kommenden Durchlauf einzufügen_x000D_ k++;_x000D_ }_x000D_ _x000D_ // übertrage Werte des noch nicht vollständig durchlaufenen Teilarrays nach H_x000D_ // Kopiere H nach A (von Index l bis Index r)_x000D_ while (i <= m) {_x000D_ datensatz[k] = hilfsArray[i];_x000D_ k++;_x000D_ i++;_x000D_ }_x000D_ _x000D_ while (j <= r) {_x000D_ datensatz[k] = hilfsArray[j];_x000D_ k++;_x000D_ j++;_x000D_ _x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ // Hilfsklasse zum speichern von Testergebnissen_x000D_ private static class TestErgebnis_x000D_ {_x000D_ private final String testDataname;_x000D_ private final Double time;_x000D_ _x000D_ public TestErgebnis(String testDataname, Double time)_x000D_ {_x000D_ this.testDataname = testDataname;_x000D_ this.time = time;_x000D_ }_x000D_ _x000D_ public String getTestDataname()_x000D_ {_x000D_ return testDataname;_x000D_ }_x000D_ _x000D_ public Double getTime()_x000D_ {_x000D_ return time;_x000D_ }_x000D_ }_x000D_ }_x000D_
MrTobiasWagner/s79080ESA010
Mergesort.java
1,896
//Deklaration der main Methode_x000D_
line_comment
nl
import java.io.File;_x000D_ import java.io.FileWriter;_x000D_ import java.io.IOException;_x000D_ import java.util.ArrayList;_x000D_ import java.util.Arrays;_x000D_ _x000D_ /**_x000D_ * Dateiname : Mergesort.java_x000D_ * Beschreibung : Einsendeaufgabe 2 für den Kurs Algorithmen_x000D_ *_x000D_ * @author Tobias Wagner (s79080@beuth-hochschule.de)_x000D_ * @version 1.00, 02.12.2019_x000D_ */_x000D_ _x000D_ // Klasse Mergesort zum Sortieren von Arrays und zum Testen der gegebenen Dateien Rand... und Sort..._x000D_ // Jeweils mit Anfangs- und Endzeit_x000D_ public class Mergesort_x000D_ {_x000D_ _x000D_ private static String[] testDaten = {"Rand10_1", "Rand10_2", "Rand20_1", "Rand20_2",_x000D_ "Rand50_1", "Rand50_2", "Rand100_1", "Rand100_2",_x000D_ "Rand200_1", "Rand200_2", "Rand500_1", "Rand500_1",_x000D_ "Rand1000_1", "Rand1000_2", "Rand10000_1", "Rand10000_2",_x000D_ "Rand100000_1", "Rand100000_2", "Sort10_1", "Sort20_1", "Sort50_1", "Sort100_1", "Sort200_1",_x000D_ "Sort500_1", "Sort1000_1", "Sort10000_1", "Sort100000_1"};_x000D_ _x000D_ //Deklaration der<SUF> public static void main(String[] args) throws IOException_x000D_ {_x000D_ ArrayList<TestErgebnis> ergebnisListe = new ArrayList<>();_x000D_ _x000D_ for (String testFilename : testDaten) {_x000D_ // Einlesen des zu bearbeitenden Arrays - Auswahl der Datei mit dem Array_x000D_ int[] testDatensatz = FileIntArray.FileToIntArray(testFilename);_x000D_ _x000D_ // Ausgeben des unsortierten Arrays_x000D_ System.out.println(Arrays.toString(testDatensatz));_x000D_ _x000D_ // Erfassen der Anfangszeit_x000D_ double anfangszeit = System.nanoTime();_x000D_ _x000D_ // Ausführen von mergeSort_x000D_ mergeSort(testDatensatz, 0, testDatensatz.length - 1);_x000D_ _x000D_ // Erfassen der Endzeit_x000D_ double endzeit = System.nanoTime();_x000D_ _x000D_ // Ausgabe des sortierten Arrays_x000D_ System.out.println(Arrays.toString(testDatensatz));_x000D_ _x000D_ // Ausgabe der benötigten Dauer für den Durchlauf von mergeSort_x000D_ double dauer = endzeit - anfangszeit;_x000D_ System.out.println("Die benötigte Zeit betraegt: " + dauer + " Nanosekunden");_x000D_ _x000D_ // Speichern des Testergebnisses in unsere ergebnissliste_x000D_ TestErgebnis testErgebnis = new TestErgebnis(testFilename, dauer);_x000D_ ergebnisListe.add(testErgebnis);_x000D_ }_x000D_ _x000D_ File datei = new File("Testlaufergebnis.csv");_x000D_ FileWriter schreiber = new FileWriter(datei);_x000D_ _x000D_ // CSV Kopzeile_x000D_ schreiber.write("Testlauf;Zeit\n");_x000D_ _x000D_ for (TestErgebnis testErg : ergebnisListe) {_x000D_ schreiber.write(testErg.getTestDataname() + ";" + testErg.getTime() + "\n");_x000D_ }_x000D_ schreiber.close();_x000D_ }_x000D_ _x000D_ // Rekursive Funktion Mergesort_x000D_ // Initialisierung Mergesort mit dem eingelesenen Array, dem linken Index, dem rechten Index_x000D_ private static void mergeSort(int[] datensatz, int indexLinks, int indexRechts)_x000D_ {_x000D_ if (indexLinks < indexRechts) {_x000D_ int mitte = (indexLinks + indexRechts) / 2;_x000D_ mergeSort(datensatz, indexLinks, mitte);_x000D_ mergeSort(datensatz, mitte + 1, indexRechts);_x000D_ merge(datensatz, indexLinks, mitte, indexRechts);_x000D_ }_x000D_ }_x000D_ _x000D_ //Merge - Methode, die in Mergesort aufgerufen wird_x000D_ private static void merge(int[] datensatz, int l, int m, int r)_x000D_ {_x000D_ // H = Hilfsarray, zum Zwischenspeichern, mit der Länge des Arrays A_x000D_ int hilfsArray[] = new int[datensatz.length];_x000D_ _x000D_ // definiere i = linker Index, solange i kleiner gleich rechter Index, führe aus und erhöhe i_x000D_ for (int i = l; i <= r; i++) {_x000D_ // Zwischenspeichern von Array datensatz[i] nach hilfsarray[i]_x000D_ hilfsArray[i] = datensatz[i];_x000D_ }_x000D_ // Laufzeitvariablen i, j und k für die while - Schleifendurchläufe_x000D_ int i = l;_x000D_ int j = m + 1;_x000D_ int k = l;_x000D_ // solange i kleiner gleich mittlerer Index UND j kleiner gleich rechter Index,_x000D_ while (i <= m && j <= r) {_x000D_ _x000D_ // Kopiere kleineren aktuellen Wert hilfsArray[j] -> datensatz[k] bzw. hilfsArray[i] -> datensatz[k]_x000D_ // Erhöhe aktuellen Index von Teilarray mit kleinerem Wert_x000D_ // Erhöhe aktuellen Index von H_x000D_ _x000D_ // Wenn H an der Stelle i kleiner gleich H an der Stelle J, dann setze H[i] auf A[k] erhöhe i um eins_x000D_ if (hilfsArray[i] <= hilfsArray[j]) {_x000D_ datensatz[k] = hilfsArray[i];_x000D_ i++;_x000D_ // ansonsten setze H an der Stelle j auf A[k] und erhöhe j um 1_x000D_ } else {_x000D_ datensatz[k] = hilfsArray[j];_x000D_ j++;_x000D_ }_x000D_ // Erhöhe k, die Zählvariable des Arrays A um eins,_x000D_ // um die nächste Position im Array A im kommenden Durchlauf einzufügen_x000D_ k++;_x000D_ }_x000D_ _x000D_ // übertrage Werte des noch nicht vollständig durchlaufenen Teilarrays nach H_x000D_ // Kopiere H nach A (von Index l bis Index r)_x000D_ while (i <= m) {_x000D_ datensatz[k] = hilfsArray[i];_x000D_ k++;_x000D_ i++;_x000D_ }_x000D_ _x000D_ while (j <= r) {_x000D_ datensatz[k] = hilfsArray[j];_x000D_ k++;_x000D_ j++;_x000D_ _x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ // Hilfsklasse zum speichern von Testergebnissen_x000D_ private static class TestErgebnis_x000D_ {_x000D_ private final String testDataname;_x000D_ private final Double time;_x000D_ _x000D_ public TestErgebnis(String testDataname, Double time)_x000D_ {_x000D_ this.testDataname = testDataname;_x000D_ this.time = time;_x000D_ }_x000D_ _x000D_ public String getTestDataname()_x000D_ {_x000D_ return testDataname;_x000D_ }_x000D_ _x000D_ public Double getTime()_x000D_ {_x000D_ return time;_x000D_ }_x000D_ }_x000D_ }_x000D_
False
2,623
15
2,947
16
2,721
13
2,947
16
3,115
16
false
false
false
false
false
true
100
113420_1
package be.annelyse.year2019; import be.annelyse.util.Color; import be.annelyse.util.Coordinate2D; import be.annelyse.util.Direction; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class Day11 { private static LinkedBlockingQueue<Long> inputPaintRobot = new LinkedBlockingQueue<>(); private static LinkedBlockingQueue<Long> outputPaintRobot = new LinkedBlockingQueue<>(); private static List<Pannel> paintedPannels; public static void main(String[] args) { // System.out.println("********************************************************************"); // System.out.println("The testSolution is: " + solveWithoutIntComputer("Day11_test1")); System.out.println("********************************************************************"); System.out.println("The solution with my computer is is: " + solveA("Day11")); } private static int solveWithoutIntComputer(String inputFileName) { List<Long> input = getInput(inputFileName); LinkedBlockingQueue<Long> testInput = new LinkedBlockingQueue<>(input); PaintRobot testPaintRobot = new PaintRobot(new Coordinate2D(0, 0, Direction.UP), testInput, outputPaintRobot); Thread paintRobotThread = new Thread(testPaintRobot); paintRobotThread.start(); try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } testPaintRobot.setActive(false); //todo ... deze komt te laat!!!! deze zou moeten komen voor hij alweer wacht op een nieuwe input. Misschien hier te implementeren als de laatste input wordt genomen ofzo??? try { paintRobotThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return testPaintRobot.getPaintedPannels().size(); } private static int solveA(String inputFileName) { PaintRobot ourPaintRobot = new PaintRobot(new Coordinate2D(0, 0, Direction.UP), inputPaintRobot, outputPaintRobot); IntCodeComputer2 intCodeComputer2 = new IntCodeComputer2(getInput(inputFileName), outputPaintRobot, inputPaintRobot); Thread paintRobotThread = new Thread(ourPaintRobot); paintRobotThread.start(); Thread intComputerThread = new Thread(intCodeComputer2); intComputerThread.start(); try { intComputerThread.join(); paintedPannels = ourPaintRobot.getPaintedPannels(); ourPaintRobot.setActive(false); } catch (InterruptedException e) { e.printStackTrace(); } printPaintedPannels(paintedPannels); return paintedPannels.size(); } static List<Long> getInput(String inputFileName) { String input = null; try { input = Files.readString(Paths.get("src/main/resources/input/year2019", inputFileName)); } catch (IOException e) { e.printStackTrace(); } return Arrays.stream(input.split(",")) .map(Long::parseLong) .collect(Collectors.toList()); } static String[][] printPaintedPannels(List<Pannel> paintedPannels) { int xMin = paintedPannels.stream().map(Coordinate2D::getX).min(Integer::compareTo).get(); int xMax = paintedPannels.stream().map(Coordinate2D::getX).max(Integer::compareTo).get(); int yMin = paintedPannels.stream().map(Coordinate2D::getY).min(Integer::compareTo).get(); int yMax = paintedPannels.stream().map(Coordinate2D::getY).max(Integer::compareTo).get(); System.out.println("xMin: " + xMin + " xMax: " + xMax + " yMin: " + yMin + " yMax: " + yMax); int columnCount = xMax - xMin + 1; int rowCount = yMax - yMin + 1; String[][] print = new String[columnCount][rowCount]; for (int y = rowCount-1; y >= 0; y--){ System.out.println(); for (int x = 0; x < columnCount; x++){ int indexOfPannel = paintedPannels.indexOf(new Pannel(x+xMin,y+yMin)); if(indexOfPannel < 0){ print[x][y] = " "; } else { Color pannelColor = paintedPannels.get(indexOfPannel).getColor(); print[x][y] = pannelColor.toString(); } System.out.print(print[x][y]); } } return print; } }
AnnelyseBe/AdventOfCode2019
src/main/java/be/annelyse/year2019/Day11.java
1,352
//todo ... deze komt te laat!!!! deze zou moeten komen voor hij alweer wacht op een nieuwe input. Misschien hier te implementeren als de laatste input wordt genomen ofzo???
line_comment
nl
package be.annelyse.year2019; import be.annelyse.util.Color; import be.annelyse.util.Coordinate2D; import be.annelyse.util.Direction; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class Day11 { private static LinkedBlockingQueue<Long> inputPaintRobot = new LinkedBlockingQueue<>(); private static LinkedBlockingQueue<Long> outputPaintRobot = new LinkedBlockingQueue<>(); private static List<Pannel> paintedPannels; public static void main(String[] args) { // System.out.println("********************************************************************"); // System.out.println("The testSolution is: " + solveWithoutIntComputer("Day11_test1")); System.out.println("********************************************************************"); System.out.println("The solution with my computer is is: " + solveA("Day11")); } private static int solveWithoutIntComputer(String inputFileName) { List<Long> input = getInput(inputFileName); LinkedBlockingQueue<Long> testInput = new LinkedBlockingQueue<>(input); PaintRobot testPaintRobot = new PaintRobot(new Coordinate2D(0, 0, Direction.UP), testInput, outputPaintRobot); Thread paintRobotThread = new Thread(testPaintRobot); paintRobotThread.start(); try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } testPaintRobot.setActive(false); //todo ...<SUF> try { paintRobotThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return testPaintRobot.getPaintedPannels().size(); } private static int solveA(String inputFileName) { PaintRobot ourPaintRobot = new PaintRobot(new Coordinate2D(0, 0, Direction.UP), inputPaintRobot, outputPaintRobot); IntCodeComputer2 intCodeComputer2 = new IntCodeComputer2(getInput(inputFileName), outputPaintRobot, inputPaintRobot); Thread paintRobotThread = new Thread(ourPaintRobot); paintRobotThread.start(); Thread intComputerThread = new Thread(intCodeComputer2); intComputerThread.start(); try { intComputerThread.join(); paintedPannels = ourPaintRobot.getPaintedPannels(); ourPaintRobot.setActive(false); } catch (InterruptedException e) { e.printStackTrace(); } printPaintedPannels(paintedPannels); return paintedPannels.size(); } static List<Long> getInput(String inputFileName) { String input = null; try { input = Files.readString(Paths.get("src/main/resources/input/year2019", inputFileName)); } catch (IOException e) { e.printStackTrace(); } return Arrays.stream(input.split(",")) .map(Long::parseLong) .collect(Collectors.toList()); } static String[][] printPaintedPannels(List<Pannel> paintedPannels) { int xMin = paintedPannels.stream().map(Coordinate2D::getX).min(Integer::compareTo).get(); int xMax = paintedPannels.stream().map(Coordinate2D::getX).max(Integer::compareTo).get(); int yMin = paintedPannels.stream().map(Coordinate2D::getY).min(Integer::compareTo).get(); int yMax = paintedPannels.stream().map(Coordinate2D::getY).max(Integer::compareTo).get(); System.out.println("xMin: " + xMin + " xMax: " + xMax + " yMin: " + yMin + " yMax: " + yMax); int columnCount = xMax - xMin + 1; int rowCount = yMax - yMin + 1; String[][] print = new String[columnCount][rowCount]; for (int y = rowCount-1; y >= 0; y--){ System.out.println(); for (int x = 0; x < columnCount; x++){ int indexOfPannel = paintedPannels.indexOf(new Pannel(x+xMin,y+yMin)); if(indexOfPannel < 0){ print[x][y] = " "; } else { Color pannelColor = paintedPannels.get(indexOfPannel).getColor(); print[x][y] = pannelColor.toString(); } System.out.print(print[x][y]); } } return print; } }
True
1,008
42
1,167
52
1,195
37
1,167
52
1,355
46
false
false
false
false
false
true
366
143931_2
package Opties; import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class OptieLijst { Optie Navigatiesysteem = new Optie(true, "Navigatiesysteem", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); Optie Motor = new Optie(true, "Motor", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, true); Optie Roer = new Optie(true, "Roer", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); public Optie Brandstoftank = new Optie(true, "Brandstoftank", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, true); public Optie Anker = new Optie(true, "Anker", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); Optie Airconditioning = new Optie(false, "Airconditioning", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); Optie Sonar = new Optie(false, "Sonar", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); Optie ExtraPKs = new Optie(false, "ExtraPKs", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); //public List<Opties.Optie> optielijst = List.of(optie1, optie2, optie3, optie4, optie5, optie6, optie7, optie8); // is voor List // is handig om te houden in het geval je de List optielijst veranderd naar ArrayList public ArrayList<Optie> optielijst = new ArrayList<Optie>(); private String Path = "ShipFlexcode" + File.separator + "src" + File.separator + "CSV_Files" + File.separator + "opties.csv"; //Bovenstaande path is een relatief path naar de juiste plek voor het bestand. Dit betekent dat de code op elk andere computer hoort te werken. public void writeToCSV() throws FileNotFoundException { //readFromCSV(); //Vul de arraylist eerst in zodat het csv bestand overschreven kan worden. StringBuilder builder = new StringBuilder(); File csv = new File(Path); PrintWriter pw = new PrintWriter(csv); try { for (int i = 0; i < optielijst.size(); i++) { builder.append(optielijst.get(i).getIsEssentieel()); builder.append(","); builder.append(optielijst.get(i).getNaam()); builder.append(","); builder.append(optielijst.get(i).getBeschrijving()); builder.append(","); builder.append(optielijst.get(i).getPrijs()); builder.append(","); builder.append(optielijst.get(i).getMiliuekorting()); builder.append("\n"); } pw.write(String.valueOf(builder)); pw.flush(); pw.close(); //System.out.println(builder); } catch (Exception e) { e.printStackTrace(); } } //Deze methode leest dingen uit een csv bestand en maakt hiermee objecten van het type Opties.Optie aan. public void readFromCSV() { BufferedReader reader = null; String line = ""; try { reader = new BufferedReader(new FileReader(Path)); optielijst.clear(); while ((line = reader.readLine()) != null) { String[] row = line.split(","); optielijst.add(new Optie(row[0], row[1], row[2], row[3], row[4])); } } catch (Exception e) { } } public void voegAlleOptiesToeAanLijst(OptieLijst optielijst) { optielijst.optielijst.add(Navigatiesysteem); optielijst.optielijst.add(Motor); optielijst.optielijst.add(Roer); optielijst.optielijst.add(Brandstoftank); optielijst.optielijst.add(Anker); optielijst.optielijst.add(Airconditioning); optielijst.optielijst.add(Sonar); optielijst.optielijst.add(ExtraPKs); } // tot hier public void printOptieLijst() { readFromCSV(); for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); System.out.printf("|%-15s| %-20s| %-20s| %-100s| %-10s| %-25s|%n", "Optie nr.", "Essentiele optie", "Naam", "Beschrijving", "Prijs", "Milieukorting" ); for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); for (int i = 1; i < optielijst.size(); i++) { String prijs = String.valueOf(optielijst.get(i).getPrijs()); //Dit was eerst 'doubleprijs' //String prijs = "\u20ac" + doubleprijs; //De bedoeling hiervan was om een eurosymbool te printen, maar dat lijkt niet te werken met printf if (optielijst.get(i).getIsEssentieel()) { System.out.printf("|%-15d| %-20s| %-20s| %-100s| %-10s| %-25s|%n", optielijst.indexOf(optielijst.get(i)), optielijst.get(i).getIsEssentieel(), optielijst.get(i).getNaam(), optielijst.get(i).getBeschrijving(), optielijst.get(i).getPrijs(), optielijst.get(i).getMiliuekorting() ); } } for (int i = 1; i < optielijst.size(); i++) { if (!optielijst.get(i).getIsEssentieel()) { System.out.printf("|%-15d| %-20s| %-20s| %-100s| %-10s| %-25s|%n", optielijst.indexOf(optielijst.get(i)), optielijst.get(i).getIsEssentieel(), optielijst.get(i).getNaam(), optielijst.get(i).getBeschrijving(), optielijst.get(i).getPrijs(), optielijst.get(i).getMiliuekorting() ); } } for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); } public void nieuweOptie(String isEssentieel, String naam, String beschrijving, String prijs, String milieukorting) throws FileNotFoundException { Optie nieuweOptie = new Optie(isEssentieel, naam, beschrijving, prijs, milieukorting); readFromCSV(); optielijst.add(nieuweOptie); writeToCSV(); } public void nieuweOptie(boolean isEssentieel, String naam, String beschrijving, double prijs, boolean milieukorting) throws FileNotFoundException { readFromCSV(); Optie nieuweOptie = new Optie(isEssentieel, naam, beschrijving, prijs, milieukorting); optielijst.add(nieuweOptie); writeToCSV(); } }
DKnightAnon/OPT-project-1
ShipFlexcode/src/Opties/OptieLijst.java
2,291
//Bovenstaande path is een relatief path naar de juiste plek voor het bestand. Dit betekent dat de code op elk andere computer hoort te werken.
line_comment
nl
package Opties; import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class OptieLijst { Optie Navigatiesysteem = new Optie(true, "Navigatiesysteem", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); Optie Motor = new Optie(true, "Motor", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, true); Optie Roer = new Optie(true, "Roer", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); public Optie Brandstoftank = new Optie(true, "Brandstoftank", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, true); public Optie Anker = new Optie(true, "Anker", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 50, false); Optie Airconditioning = new Optie(false, "Airconditioning", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); Optie Sonar = new Optie(false, "Sonar", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); Optie ExtraPKs = new Optie(false, "ExtraPKs", "Dit is een test beschrijving om te kijken hoe het reageert op meerdere characters", 20, false); //public List<Opties.Optie> optielijst = List.of(optie1, optie2, optie3, optie4, optie5, optie6, optie7, optie8); // is voor List // is handig om te houden in het geval je de List optielijst veranderd naar ArrayList public ArrayList<Optie> optielijst = new ArrayList<Optie>(); private String Path = "ShipFlexcode" + File.separator + "src" + File.separator + "CSV_Files" + File.separator + "opties.csv"; //Bovenstaande path<SUF> public void writeToCSV() throws FileNotFoundException { //readFromCSV(); //Vul de arraylist eerst in zodat het csv bestand overschreven kan worden. StringBuilder builder = new StringBuilder(); File csv = new File(Path); PrintWriter pw = new PrintWriter(csv); try { for (int i = 0; i < optielijst.size(); i++) { builder.append(optielijst.get(i).getIsEssentieel()); builder.append(","); builder.append(optielijst.get(i).getNaam()); builder.append(","); builder.append(optielijst.get(i).getBeschrijving()); builder.append(","); builder.append(optielijst.get(i).getPrijs()); builder.append(","); builder.append(optielijst.get(i).getMiliuekorting()); builder.append("\n"); } pw.write(String.valueOf(builder)); pw.flush(); pw.close(); //System.out.println(builder); } catch (Exception e) { e.printStackTrace(); } } //Deze methode leest dingen uit een csv bestand en maakt hiermee objecten van het type Opties.Optie aan. public void readFromCSV() { BufferedReader reader = null; String line = ""; try { reader = new BufferedReader(new FileReader(Path)); optielijst.clear(); while ((line = reader.readLine()) != null) { String[] row = line.split(","); optielijst.add(new Optie(row[0], row[1], row[2], row[3], row[4])); } } catch (Exception e) { } } public void voegAlleOptiesToeAanLijst(OptieLijst optielijst) { optielijst.optielijst.add(Navigatiesysteem); optielijst.optielijst.add(Motor); optielijst.optielijst.add(Roer); optielijst.optielijst.add(Brandstoftank); optielijst.optielijst.add(Anker); optielijst.optielijst.add(Airconditioning); optielijst.optielijst.add(Sonar); optielijst.optielijst.add(ExtraPKs); } // tot hier public void printOptieLijst() { readFromCSV(); for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); System.out.printf("|%-15s| %-20s| %-20s| %-100s| %-10s| %-25s|%n", "Optie nr.", "Essentiele optie", "Naam", "Beschrijving", "Prijs", "Milieukorting" ); for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); for (int i = 1; i < optielijst.size(); i++) { String prijs = String.valueOf(optielijst.get(i).getPrijs()); //Dit was eerst 'doubleprijs' //String prijs = "\u20ac" + doubleprijs; //De bedoeling hiervan was om een eurosymbool te printen, maar dat lijkt niet te werken met printf if (optielijst.get(i).getIsEssentieel()) { System.out.printf("|%-15d| %-20s| %-20s| %-100s| %-10s| %-25s|%n", optielijst.indexOf(optielijst.get(i)), optielijst.get(i).getIsEssentieel(), optielijst.get(i).getNaam(), optielijst.get(i).getBeschrijving(), optielijst.get(i).getPrijs(), optielijst.get(i).getMiliuekorting() ); } } for (int i = 1; i < optielijst.size(); i++) { if (!optielijst.get(i).getIsEssentieel()) { System.out.printf("|%-15d| %-20s| %-20s| %-100s| %-10s| %-25s|%n", optielijst.indexOf(optielijst.get(i)), optielijst.get(i).getIsEssentieel(), optielijst.get(i).getNaam(), optielijst.get(i).getBeschrijving(), optielijst.get(i).getPrijs(), optielijst.get(i).getMiliuekorting() ); } } for (int i = 0; i < 202; i++) { System.out.print("-"); } System.out.println(); } public void nieuweOptie(String isEssentieel, String naam, String beschrijving, String prijs, String milieukorting) throws FileNotFoundException { Optie nieuweOptie = new Optie(isEssentieel, naam, beschrijving, prijs, milieukorting); readFromCSV(); optielijst.add(nieuweOptie); writeToCSV(); } public void nieuweOptie(boolean isEssentieel, String naam, String beschrijving, double prijs, boolean milieukorting) throws FileNotFoundException { readFromCSV(); Optie nieuweOptie = new Optie(isEssentieel, naam, beschrijving, prijs, milieukorting); optielijst.add(nieuweOptie); writeToCSV(); } }
True
1,859
39
2,047
43
1,971
31
2,047
43
2,269
41
false
false
false
false
false
true
4,493
54922_2
package vb.week2.tabular; /** * VB prac week2: LaTeX tabular -> HTML symbolicName. * Token class. * @author Theo Ruys, Arend Rensink * @version 2012.04.28 */ public class Token { public enum Kind { IDENTIFIER("<IDENTIFIER>"), NUM("<NUM>"), BEGIN("begin"), END("end"), TABULAR("tabular"), BSLASH("<BSLASH>"), DOUBLE_BSLASH("<DOUBLE_BSLASH>"), BAR("<BAR>"), AMPERSAND("<AMPERSAND>"), LCURLY("<LCURLY>"), RCURLY("<RCURLY>"), EOT("<EOT>"); private Kind(String spelling) { this.spelling = spelling; } /** Returns the exact spelling of the keyword tokens. */ public String getSpelling() { return this.spelling; } final private String spelling; } private Kind kind; private String repr; /** * Construeert een Token-object gegeven de "kind" van het Token * en zijn representatie. Als het een IDENTIFIER Token is wordt * gecontroleerd of het geen "keyword" is. * @param kind soort Token * @param repr String representatie van het Token */ public Token(Kind kind, String repr) { this.kind = kind; this.repr = repr; // Recognize keywords if (this.kind == Kind.IDENTIFIER) { for (Kind k: Kind.values()) { if (repr.equals(k.getSpelling())) { this.kind = k; break; } } } } /** Levert het soort Token. */ public Kind getKind() { return this.kind; } /** Levert de String-representatie van dit Token. */ public String getRepr() { return this.repr; } }
thomasbrus/vertalerbouw
vb/week2/tabular/Token.java
535
/** * Construeert een Token-object gegeven de "kind" van het Token * en zijn representatie. Als het een IDENTIFIER Token is wordt * gecontroleerd of het geen "keyword" is. * @param kind soort Token * @param repr String representatie van het Token */
block_comment
nl
package vb.week2.tabular; /** * VB prac week2: LaTeX tabular -> HTML symbolicName. * Token class. * @author Theo Ruys, Arend Rensink * @version 2012.04.28 */ public class Token { public enum Kind { IDENTIFIER("<IDENTIFIER>"), NUM("<NUM>"), BEGIN("begin"), END("end"), TABULAR("tabular"), BSLASH("<BSLASH>"), DOUBLE_BSLASH("<DOUBLE_BSLASH>"), BAR("<BAR>"), AMPERSAND("<AMPERSAND>"), LCURLY("<LCURLY>"), RCURLY("<RCURLY>"), EOT("<EOT>"); private Kind(String spelling) { this.spelling = spelling; } /** Returns the exact spelling of the keyword tokens. */ public String getSpelling() { return this.spelling; } final private String spelling; } private Kind kind; private String repr; /** * Construeert een Token-object<SUF>*/ public Token(Kind kind, String repr) { this.kind = kind; this.repr = repr; // Recognize keywords if (this.kind == Kind.IDENTIFIER) { for (Kind k: Kind.values()) { if (repr.equals(k.getSpelling())) { this.kind = k; break; } } } } /** Levert het soort Token. */ public Kind getKind() { return this.kind; } /** Levert de String-representatie van dit Token. */ public String getRepr() { return this.repr; } }
True
432
73
450
71
483
73
450
71
540
78
false
false
false
false
false
true
3,868
200395_4
import javax.swing.*; import java.awt.*; /** * @author Oscar Baume & Dorain Gillioz */ public class Digital extends Clock{ // label qui affiche l'heure JLabel label; /** * Constructeur de l'horloge digital * @param subject = sujet de l'horloge */ Digital(Chrono subject) { // on appele le constructeur d'horloge super(subject); // on mets le background en gris setBackground(Color.gray); // on crée un Jlabel label = new JLabel(); // on utilise un gridbaglayout pour que le label soit centré sans faire + de manip this.setLayout(new GridBagLayout()); // on ajoute le label au JPanel add(label); } @Override public void update(){ super.update(); // on met à jour le contenu du label label.setText(subject.name() + " : " + hour +"h "+ minute +"m "+ second +"s"); } }
obaume/MCR_Labo1
code/Horloge/src/Digital.java
276
// on mets le background en gris
line_comment
nl
import javax.swing.*; import java.awt.*; /** * @author Oscar Baume & Dorain Gillioz */ public class Digital extends Clock{ // label qui affiche l'heure JLabel label; /** * Constructeur de l'horloge digital * @param subject = sujet de l'horloge */ Digital(Chrono subject) { // on appele le constructeur d'horloge super(subject); // on mets<SUF> setBackground(Color.gray); // on crée un Jlabel label = new JLabel(); // on utilise un gridbaglayout pour que le label soit centré sans faire + de manip this.setLayout(new GridBagLayout()); // on ajoute le label au JPanel add(label); } @Override public void update(){ super.update(); // on met à jour le contenu du label label.setText(subject.name() + " : " + hour +"h "+ minute +"m "+ second +"s"); } }
False
224
8
243
9
242
7
243
9
272
9
false
false
false
false
false
true
3,323
86654_0
/* * Copyright (c) 2016 Kaede Akatsuki (kidhaibara@gmail.com) */ package moe.studio.frontia; import android.util.Log; import moe.studio.frontia.BuildConfig; class Logger { static final boolean DEBUG = BuildConfig.DEBUG; static void v(String TAG, String msg) { if (!DEBUG) return; Log.v(TAG, msg); } static void d(String TAG, String msg) { if (!DEBUG) return; Log.d(TAG, msg); } static void i(String TAG, String msg) { if (!DEBUG) return; Log.i(TAG, msg); } static void w(String TAG, String msg) { Log.w(TAG, msg); } static void w(String TAG, Throwable throwable) { Log.w(TAG, throwable); } }
kaedea/android-dynamical-loading
android-frontia/frontia/src/main/java/moe/studio/frontia/Logger.java
241
/* * Copyright (c) 2016 Kaede Akatsuki (kidhaibara@gmail.com) */
block_comment
nl
/* * Copyright (c) 2016<SUF>*/ package moe.studio.frontia; import android.util.Log; import moe.studio.frontia.BuildConfig; class Logger { static final boolean DEBUG = BuildConfig.DEBUG; static void v(String TAG, String msg) { if (!DEBUG) return; Log.v(TAG, msg); } static void d(String TAG, String msg) { if (!DEBUG) return; Log.d(TAG, msg); } static void i(String TAG, String msg) { if (!DEBUG) return; Log.i(TAG, msg); } static void w(String TAG, String msg) { Log.w(TAG, msg); } static void w(String TAG, Throwable throwable) { Log.w(TAG, throwable); } }
False
183
25
219
30
230
29
219
30
254
31
false
false
false
false
false
true
219
10823_2
package testRetroFit; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; import retrofit.mime.TypedByteArray; import static android.content.Context.MODE_PRIVATE; public class LogInFragment extends Fragment { public EditText txtName; private EditText txtPwd; private EditText txtLogIn; private Button btnSignIn; private Button btnFbSignIn; private Button btnGplusSignIn; private boolean alreadyLoggedIn; /* @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_sign_in_screen, container, false); Typeface opensans = Typeface.createFromAsset(getActivity().getAssets(), "fonts/OpenSans-Regular.ttf"); Typeface roboto = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Bold.ttf"); txtName = (EditText) rootView.findViewById(R.id.signInUsername); txtPwd = (EditText) rootView.findViewById(R.id.signInPassword); txtLogIn = (EditText) rootView.findViewById(R.id.register); btnSignIn = (Button) rootView.findViewById(R.id.signInBtn); btnFbSignIn = (Button)rootView.findViewById(R.id.btnSingInFacebook); btnGplusSignIn = (Button)rootView.findViewById(R.id.btnSingInGoogle); btnSignIn.setTypeface(opensans); btnGplusSignIn.setTypeface(opensans); btnFbSignIn.setTypeface(opensans); txtName.setTypeface(opensans); txtPwd.setTypeface(opensans); txtLogIn.setTypeface(roboto); initListeners(); initUsernameAndPassWordFields(); return rootView; } */ public void initUsernameAndPassWordFields() { SharedPreferences userDetails = getActivity().getSharedPreferences("Logindetails", Context.MODE_PRIVATE); String email = userDetails.getString("email", ""); String password = userDetails.getString("password", ""); //Haalt in de SP het email & PW op zodat deze gegevens al ingevuld kunnen worden op beide textFields in het inlogscherm. if (!email.isEmpty()) { txtName.setText(email); } if (!password.isEmpty()) { txtPwd.setText(password); } } /* public void initListeners() { btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Bij het klikken op de knop wordt er gekeken of de email en pw van de gebruiker nog in de Sharedprefence zit. Staat hier niets in, dan is de gebruiker niet aangelogd. ==> We controleren dan elke veld om te zien of deze een waarde bevat. Zoja probeer dan in te loggen. Staat in de Sharedpref wel een waarde dan is de gebruiker al inglogd. Probeert hij opnieuw in te loggen met de gegevens die al in de sharedpref staan dan krijgt hij een melding dat hij al aangmeld is Probeert hij in te loggen met andere gegevens dan in de sharedpref staan dan probeert het systeem gewoon in te loggen. Zijn de inlog gegevens verkeerd dan wordt er een melding weergegeven. SharedPreferences userDetails = getActivity().getSharedPreferences("Logindetails", Context.MODE_PRIVATE); String email = userDetails.getString("email", ""); // email uit de SP ophalen String password = userDetails.getString("password", ""); //pw uit de SP ophalen if (txtName.getText().length() == 0) { txtName.setError(getString(R.string.EmptyTextFieldCannotBeEmpty)); } if (txtPwd.getText().length() == 0) { txtPwd.setError(getString(R.string.EmptyTextFieldCannotBeEmpty)); } if (email.equalsIgnoreCase(txtName.getText().toString()) && password.equals(txtPwd.getText().toString())) { // Email uit de SP zijn hetzelfde als ingegeven email? ==> Al ingelogd alreadyLoggedIn = true; } else { alreadyLoggedIn = false; } if (email.isEmpty() || password.isEmpty()) { // is de sharedpref leeg? Dan kan er niemand ingelogd zijn. alreadyLoggedIn = false; } if (alreadyLoggedIn) { //melding geven als de gebruiker al ingelogd is en nog eens probeert in te loggen met dezelfde gegevens AppMsg.makeText(getActivity(), getResources().getString(R.string.already_logged_in_as) + " " + email, AppMsg.STYLE_ALERT).show(); } else { if (!(txtName.getText().length() == 0 || txtPwd.getText().length() == 0)) { // Als beide velden een waarde bevatten mag er een inlog poging gebeuren. signIn(); } } } }); } */ /* private void signIn() { // Haal OAuth token op getJppService().getToken("password", txtName.getText().toString() + 1, txtPwd.getText().toString(), this); } */ /* @Override public void success(Token token, Response response) { //Als de login succes vol is, zet dan de token, email en password in een sharedPrefence zodat deze gegevens later kunnen worden opgehaald. SharedPreferences.Editor editor = getActivity().getSharedPreferences("Logindetails", MODE_PRIVATE).edit(); editor.putString("token", token.getAccess_token()); editor.putString("email", txtName.getText().toString()); editor.putString("password", txtPwd.getText().toString()); editor.apply(); AppMsg.makeText(getActivity(), getResources().getString(R.string.successfullLogin) + " " + txtName.getText().toString(), AppMsg.STYLE_INFO).show(); //Als het inloggen succesvol is gebeurd wissel dan naar het Home scherm (lijst met vragen) Fragment frag = new AmsHomeFragment(); FragmentManager fragMan = getFragmentManager(); FragmentTransaction fragTran = fragMan.beginTransaction(); fragTran.replace(R.id.frame_container, frag); fragTran.addToBackStack(null); fragTran.commit(); } */ /* @Override public void failure(RetrofitError error) { //Gaat het inloggen verkeerd, vang dan de json error code die retrofit teruggeeft. Match de json code aan gekende errors en geef gepaste feedback. String json = new String(((TypedByteArray) error.getResponse().getBody()).getBytes()); if (json.equals(getResources().getString(R.string.retrofit_username_or_password_wrong_json))) { AppMsg.makeText(getActivity(), getResources().getString(R.string.username_or_password_wrong), AppMsg.STYLE_ALERT).show(); } else { AppMsg.makeText(getActivity(), getResources().getString(R.string.something_went_wrong) + error, AppMsg.STYLE_ALERT).show(); } } */ }
Blaperile/kandoe-android
app/src/main/java/testRetroFit/LogInFragment.java
2,159
/* public void initListeners() { btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Bij het klikken op de knop wordt er gekeken of de email en pw van de gebruiker nog in de Sharedprefence zit. Staat hier niets in, dan is de gebruiker niet aangelogd. ==> We controleren dan elke veld om te zien of deze een waarde bevat. Zoja probeer dan in te loggen. Staat in de Sharedpref wel een waarde dan is de gebruiker al inglogd. Probeert hij opnieuw in te loggen met de gegevens die al in de sharedpref staan dan krijgt hij een melding dat hij al aangmeld is Probeert hij in te loggen met andere gegevens dan in de sharedpref staan dan probeert het systeem gewoon in te loggen. Zijn de inlog gegevens verkeerd dan wordt er een melding weergegeven. SharedPreferences userDetails = getActivity().getSharedPreferences("Logindetails", Context.MODE_PRIVATE); String email = userDetails.getString("email", ""); // email uit de SP ophalen String password = userDetails.getString("password", ""); //pw uit de SP ophalen if (txtName.getText().length() == 0) { txtName.setError(getString(R.string.EmptyTextFieldCannotBeEmpty)); } if (txtPwd.getText().length() == 0) { txtPwd.setError(getString(R.string.EmptyTextFieldCannotBeEmpty)); } if (email.equalsIgnoreCase(txtName.getText().toString()) && password.equals(txtPwd.getText().toString())) { // Email uit de SP zijn hetzelfde als ingegeven email? ==> Al ingelogd alreadyLoggedIn = true; } else { alreadyLoggedIn = false; } if (email.isEmpty() || password.isEmpty()) { // is de sharedpref leeg? Dan kan er niemand ingelogd zijn. alreadyLoggedIn = false; } if (alreadyLoggedIn) { //melding geven als de gebruiker al ingelogd is en nog eens probeert in te loggen met dezelfde gegevens AppMsg.makeText(getActivity(), getResources().getString(R.string.already_logged_in_as) + " " + email, AppMsg.STYLE_ALERT).show(); } else { if (!(txtName.getText().length() == 0 || txtPwd.getText().length() == 0)) { // Als beide velden een waarde bevatten mag er een inlog poging gebeuren. signIn(); } } } }); } */
block_comment
nl
package testRetroFit; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; import retrofit.mime.TypedByteArray; import static android.content.Context.MODE_PRIVATE; public class LogInFragment extends Fragment { public EditText txtName; private EditText txtPwd; private EditText txtLogIn; private Button btnSignIn; private Button btnFbSignIn; private Button btnGplusSignIn; private boolean alreadyLoggedIn; /* @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_sign_in_screen, container, false); Typeface opensans = Typeface.createFromAsset(getActivity().getAssets(), "fonts/OpenSans-Regular.ttf"); Typeface roboto = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Bold.ttf"); txtName = (EditText) rootView.findViewById(R.id.signInUsername); txtPwd = (EditText) rootView.findViewById(R.id.signInPassword); txtLogIn = (EditText) rootView.findViewById(R.id.register); btnSignIn = (Button) rootView.findViewById(R.id.signInBtn); btnFbSignIn = (Button)rootView.findViewById(R.id.btnSingInFacebook); btnGplusSignIn = (Button)rootView.findViewById(R.id.btnSingInGoogle); btnSignIn.setTypeface(opensans); btnGplusSignIn.setTypeface(opensans); btnFbSignIn.setTypeface(opensans); txtName.setTypeface(opensans); txtPwd.setTypeface(opensans); txtLogIn.setTypeface(roboto); initListeners(); initUsernameAndPassWordFields(); return rootView; } */ public void initUsernameAndPassWordFields() { SharedPreferences userDetails = getActivity().getSharedPreferences("Logindetails", Context.MODE_PRIVATE); String email = userDetails.getString("email", ""); String password = userDetails.getString("password", ""); //Haalt in de SP het email & PW op zodat deze gegevens al ingevuld kunnen worden op beide textFields in het inlogscherm. if (!email.isEmpty()) { txtName.setText(email); } if (!password.isEmpty()) { txtPwd.setText(password); } } /* public void initListeners()<SUF>*/ /* private void signIn() { // Haal OAuth token op getJppService().getToken("password", txtName.getText().toString() + 1, txtPwd.getText().toString(), this); } */ /* @Override public void success(Token token, Response response) { //Als de login succes vol is, zet dan de token, email en password in een sharedPrefence zodat deze gegevens later kunnen worden opgehaald. SharedPreferences.Editor editor = getActivity().getSharedPreferences("Logindetails", MODE_PRIVATE).edit(); editor.putString("token", token.getAccess_token()); editor.putString("email", txtName.getText().toString()); editor.putString("password", txtPwd.getText().toString()); editor.apply(); AppMsg.makeText(getActivity(), getResources().getString(R.string.successfullLogin) + " " + txtName.getText().toString(), AppMsg.STYLE_INFO).show(); //Als het inloggen succesvol is gebeurd wissel dan naar het Home scherm (lijst met vragen) Fragment frag = new AmsHomeFragment(); FragmentManager fragMan = getFragmentManager(); FragmentTransaction fragTran = fragMan.beginTransaction(); fragTran.replace(R.id.frame_container, frag); fragTran.addToBackStack(null); fragTran.commit(); } */ /* @Override public void failure(RetrofitError error) { //Gaat het inloggen verkeerd, vang dan de json error code die retrofit teruggeeft. Match de json code aan gekende errors en geef gepaste feedback. String json = new String(((TypedByteArray) error.getResponse().getBody()).getBytes()); if (json.equals(getResources().getString(R.string.retrofit_username_or_password_wrong_json))) { AppMsg.makeText(getActivity(), getResources().getString(R.string.username_or_password_wrong), AppMsg.STYLE_ALERT).show(); } else { AppMsg.makeText(getActivity(), getResources().getString(R.string.something_went_wrong) + error, AppMsg.STYLE_ALERT).show(); } } */ }
False
1,535
571
1,772
627
1,752
594
1,772
627
2,097
725
true
true
true
true
true
false
4,054
109369_14
package Logic; import java.awt.geom.Point2D; import Main.Houston; import Main.Map; import Main.Movable; import Main.Player; import Main.Quest; import Main.Story; /** enthaelt die Logic vom Spiel */ public class GameLogic { private Houston houston; private Player player; private Map map; private EnemyLogic enemyLogic; private PlayerLogic playerLogic; private MagicLogic magicLogic; private ItemLogic itemLogic; private Story story; private Quest quest; private Point2D topLeft, topRight, bottomLeft, bottomRight; double tlX, tlY; // Temporaere Character Ecke private long delta; private double dX, dY; /** Wert einer Kachel */ public int value; public int npcv; /** * Initialisiert die anderen Logiken und die Eckpunkte des Charakters * @param houston */ public GameLogic(Houston houston) { this.houston = houston; this.player = houston.player; this.map = houston.map; this.story = houston.story; this.quest = houston.quest; this.playerLogic = houston.playerLogic = new PlayerLogic(houston); this.enemyLogic = houston.enemyLogic = new EnemyLogic(houston); this.magicLogic = houston.magicLogic = new MagicLogic(houston); this.itemLogic = houston.itemLogic = new ItemLogic(houston); // 4 Punkte fuer die 4 Ecken des Character topLeft = new Point2D.Double(); topRight = new Point2D.Double(); bottomLeft = new Point2D.Double(); bottomRight = new Point2D.Double(); } /** * Startet ein neues Spiel * @param levelNumber * @param mapNumber */ public void setupNewGame(int levelNumber, int mapNumber) { player.resetPlayerStats(100, 100, 120, 100, 3, 1, 0); houston.inventory.clear(); changeLevel(levelNumber, mapNumber); } // Springt zum angegebenen Level. public void changeLevel(int levelNumber, int mapNumber) { map.renewMap(levelNumber, mapNumber); story.renewStory(mapNumber); quest.renewQuest(mapNumber); playerLogic.onLevelChange(); enemyLogic.onLevelChange(); magicLogic.onLevelChange(); itemLogic.onLevelChange(); } /** * Berechnet z.B. alle Bewegungen und Kollisionen im Spiel * @param delta */ public void doGameUpdates(long delta) { this.delta = delta; if (houston.multiPlayer.ready) houston.multiPlayer.doGameUpdates(); playerLogic.doGameUpdates(); enemyLogic.doGameUpdates(); itemLogic.doGameUpdates(); magicLogic.doGameUpdates(); } // Regelt den Wechsel zur naechsten Karte private void nextMap() { if(enemyLogic.bossIsAlive){ return; } player.stop(); if (map.getMapNumber() < (map.getCountOfMapsByLevel() - 1)) { // Naechste Karte changeLevel(map.getLevelNumber(), (map.getMapNumber() + 1)); } else { if (map.getLevelNumber() < (map.getCountOfLevel() - 1)) { // Naechstes Level changeLevel((map.getLevelNumber() + 1), 0); } else { // Spiel gewonnen if (houston.multiPlayer.isOver == false) houston.multiPlayer.exitGame(Houston.WON); else houston.changeAppearance(true, false, Houston.WON); } } } /** * Setzt die Tastendruecke um in die Bewegung des Charakter * @param character */ public void controlCharacterMovement(Movable character) { dX = dY = 0; getCharacterCorners(character); // Bewegung nach Links if (character.getLeft() > 0 && character.getRight() == 0) { dX = character.getDX(-1, delta); if (isValidXMovement(topLeft, bottomLeft, dX, 1) == 1) { dX = 0; character.onWallHit(); } else if (isValidXMovement(topLeft, bottomLeft, dX, 3) == 3) { dX = 0; npcv = 1; character.onWallHit(); } else if (isValidXMovement(topLeft, bottomLeft, dX, 4) == 4){ dX = 0; npcv = 2; character.onWallHit(); } // Bewegung nach Rechts } else if (character.getRight() > 0 && character.getLeft() == 0) { dX = character.getDX(1, delta); if (isValidXMovement(topRight, bottomRight, dX, 1) == 1) { dX = 0; character.onWallHit(); } else if (isValidXMovement(topRight, bottomRight, dX, 3) == 3) { dX = 0; npcv = 1; character.onWallHit(); } else if (isValidXMovement(topRight, bottomRight, dX, 4) == 4) { dX = 0; npcv = 2; character.onWallHit(); } } // Bewegung nach Oben if (character.getUp() > 0 && character.getDown() == 0) { dY = character.getDY(-1, delta); if (isValidYMovement(topLeft, topRight, dY, 1) == 1) { dY = 0; character.onWallHit(); } else if (isValidYMovement(topLeft, topRight, dY, 3) == 3) { dY = 0; npcv = 1; character.onWallHit(); } else if (isValidYMovement(topLeft, topRight, dY, 4) == 4) { dY = 0; npcv = 2; character.onWallHit(); } // Bewegung nach Unten } else if (character.getDown() > 0 && character.getUp() == 0) { dY = character.getDY(1, delta); if (isValidYMovement(bottomLeft, bottomRight, dY, 1) == 1) { dY = 0; character.onWallHit(); } else if (isValidYMovement(bottomLeft, bottomRight, dY, 3) == 3) { dY = 0; npcv = 1; character.onWallHit(); } else if (isValidYMovement(bottomLeft, bottomRight, dY, 4) == 4) { dY = 0; npcv = 2; character.onWallHit(); } } // Bewegt den Charakter falls notwendig if (dX != 0 || dY != 0) character.move(dX, dY); } /** Ermittelt, ob sich der Player auf einer Speziellen Kachel befindet, und leitet entsprechende Massnahmen ein */ public void detectSpecialTiles() { if (player.isMoving()) { try { value = (map.mapArray[(int) Math.floor(player.getCenterPosition().getY())/32][(int) Math.floor((player.getCenterPosition().getX())/32)]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ungueltige Position x:"+player.getX()+" y:"+player.getY()); die(); } // entsprechende Massnahmen if (value == 7) { backToLastCheckpoint(); player.decreaseHealth(25); } else if (value == 9) { nextMap(); } } } // Ermittelt die Koordinaten der 4 Eckpunkte des Charakter private void getCharacterCorners(Movable character) { double tlX = character.getX(); double tlY = character.getY(); topLeft.setLocation(tlX, tlY); topRight.setLocation(tlX + character.getWidth(), tlY); bottomLeft.setLocation(tlX, tlY + character.getHeight()); bottomRight.setLocation(tlX + character.getWidth(), tlY + character.getHeight()); } // Ermittelt, ob die, durch horizontale Bewegung dX, errechnete neue Position (des Spielers) in einer Wand liegt oder nicht private int isValidXMovement(Point2D pointTop, Point2D pointBottom, double dX, int checkValue) { try { if ((map.mapArray[(int) Math.floor(pointTop.getY()/32)][(int) Math.floor((pointTop.getX()+dX)/32)] == checkValue)) return checkValue; else if ((map.mapArray[(int) Math.floor(pointBottom.getY()/32)][(int) Math.floor((pointBottom.getX()+dX)/32)] == checkValue)) return checkValue; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ungueltige x Bewegung pT:"+pointTop+" pB:"+pointBottom); die(); } return 0; } // Ermittelt, ob die, durch vertikale Bewegung dY, errechnete neue Position (des Spielers) in einer Wand liegt oder nicht private int isValidYMovement(Point2D pointLeft, Point2D pointRight, double dY2, int checkValue) { try { if ((map.mapArray[(int) Math.floor(pointLeft.getY()+dY)/32][(int) Math.floor(pointLeft.getX()/32)] == checkValue)) return checkValue; else if ((map.mapArray[(int) Math.floor(pointRight.getY()+dY)/32][(int) Math.floor(pointRight.getX()/32)] == checkValue)) return checkValue; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ungueltige y Bewegung pL:"+pointLeft+" pR:"+pointRight); die(); } return 0; } private void backToLastCheckpoint() { // Zurueck zur ersten Karte des aktuellen Level changeLevel(map.getLevelNumber(), 0); player.setArmor(100); } private void die() { houston.changeAppearance(true, false, Houston.STARTMENU); } }
propra13-orga/gruppe44
src/Logic/GameLogic.java
3,014
// Bewegt den Charakter falls notwendig
line_comment
nl
package Logic; import java.awt.geom.Point2D; import Main.Houston; import Main.Map; import Main.Movable; import Main.Player; import Main.Quest; import Main.Story; /** enthaelt die Logic vom Spiel */ public class GameLogic { private Houston houston; private Player player; private Map map; private EnemyLogic enemyLogic; private PlayerLogic playerLogic; private MagicLogic magicLogic; private ItemLogic itemLogic; private Story story; private Quest quest; private Point2D topLeft, topRight, bottomLeft, bottomRight; double tlX, tlY; // Temporaere Character Ecke private long delta; private double dX, dY; /** Wert einer Kachel */ public int value; public int npcv; /** * Initialisiert die anderen Logiken und die Eckpunkte des Charakters * @param houston */ public GameLogic(Houston houston) { this.houston = houston; this.player = houston.player; this.map = houston.map; this.story = houston.story; this.quest = houston.quest; this.playerLogic = houston.playerLogic = new PlayerLogic(houston); this.enemyLogic = houston.enemyLogic = new EnemyLogic(houston); this.magicLogic = houston.magicLogic = new MagicLogic(houston); this.itemLogic = houston.itemLogic = new ItemLogic(houston); // 4 Punkte fuer die 4 Ecken des Character topLeft = new Point2D.Double(); topRight = new Point2D.Double(); bottomLeft = new Point2D.Double(); bottomRight = new Point2D.Double(); } /** * Startet ein neues Spiel * @param levelNumber * @param mapNumber */ public void setupNewGame(int levelNumber, int mapNumber) { player.resetPlayerStats(100, 100, 120, 100, 3, 1, 0); houston.inventory.clear(); changeLevel(levelNumber, mapNumber); } // Springt zum angegebenen Level. public void changeLevel(int levelNumber, int mapNumber) { map.renewMap(levelNumber, mapNumber); story.renewStory(mapNumber); quest.renewQuest(mapNumber); playerLogic.onLevelChange(); enemyLogic.onLevelChange(); magicLogic.onLevelChange(); itemLogic.onLevelChange(); } /** * Berechnet z.B. alle Bewegungen und Kollisionen im Spiel * @param delta */ public void doGameUpdates(long delta) { this.delta = delta; if (houston.multiPlayer.ready) houston.multiPlayer.doGameUpdates(); playerLogic.doGameUpdates(); enemyLogic.doGameUpdates(); itemLogic.doGameUpdates(); magicLogic.doGameUpdates(); } // Regelt den Wechsel zur naechsten Karte private void nextMap() { if(enemyLogic.bossIsAlive){ return; } player.stop(); if (map.getMapNumber() < (map.getCountOfMapsByLevel() - 1)) { // Naechste Karte changeLevel(map.getLevelNumber(), (map.getMapNumber() + 1)); } else { if (map.getLevelNumber() < (map.getCountOfLevel() - 1)) { // Naechstes Level changeLevel((map.getLevelNumber() + 1), 0); } else { // Spiel gewonnen if (houston.multiPlayer.isOver == false) houston.multiPlayer.exitGame(Houston.WON); else houston.changeAppearance(true, false, Houston.WON); } } } /** * Setzt die Tastendruecke um in die Bewegung des Charakter * @param character */ public void controlCharacterMovement(Movable character) { dX = dY = 0; getCharacterCorners(character); // Bewegung nach Links if (character.getLeft() > 0 && character.getRight() == 0) { dX = character.getDX(-1, delta); if (isValidXMovement(topLeft, bottomLeft, dX, 1) == 1) { dX = 0; character.onWallHit(); } else if (isValidXMovement(topLeft, bottomLeft, dX, 3) == 3) { dX = 0; npcv = 1; character.onWallHit(); } else if (isValidXMovement(topLeft, bottomLeft, dX, 4) == 4){ dX = 0; npcv = 2; character.onWallHit(); } // Bewegung nach Rechts } else if (character.getRight() > 0 && character.getLeft() == 0) { dX = character.getDX(1, delta); if (isValidXMovement(topRight, bottomRight, dX, 1) == 1) { dX = 0; character.onWallHit(); } else if (isValidXMovement(topRight, bottomRight, dX, 3) == 3) { dX = 0; npcv = 1; character.onWallHit(); } else if (isValidXMovement(topRight, bottomRight, dX, 4) == 4) { dX = 0; npcv = 2; character.onWallHit(); } } // Bewegung nach Oben if (character.getUp() > 0 && character.getDown() == 0) { dY = character.getDY(-1, delta); if (isValidYMovement(topLeft, topRight, dY, 1) == 1) { dY = 0; character.onWallHit(); } else if (isValidYMovement(topLeft, topRight, dY, 3) == 3) { dY = 0; npcv = 1; character.onWallHit(); } else if (isValidYMovement(topLeft, topRight, dY, 4) == 4) { dY = 0; npcv = 2; character.onWallHit(); } // Bewegung nach Unten } else if (character.getDown() > 0 && character.getUp() == 0) { dY = character.getDY(1, delta); if (isValidYMovement(bottomLeft, bottomRight, dY, 1) == 1) { dY = 0; character.onWallHit(); } else if (isValidYMovement(bottomLeft, bottomRight, dY, 3) == 3) { dY = 0; npcv = 1; character.onWallHit(); } else if (isValidYMovement(bottomLeft, bottomRight, dY, 4) == 4) { dY = 0; npcv = 2; character.onWallHit(); } } // Bewegt den<SUF> if (dX != 0 || dY != 0) character.move(dX, dY); } /** Ermittelt, ob sich der Player auf einer Speziellen Kachel befindet, und leitet entsprechende Massnahmen ein */ public void detectSpecialTiles() { if (player.isMoving()) { try { value = (map.mapArray[(int) Math.floor(player.getCenterPosition().getY())/32][(int) Math.floor((player.getCenterPosition().getX())/32)]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ungueltige Position x:"+player.getX()+" y:"+player.getY()); die(); } // entsprechende Massnahmen if (value == 7) { backToLastCheckpoint(); player.decreaseHealth(25); } else if (value == 9) { nextMap(); } } } // Ermittelt die Koordinaten der 4 Eckpunkte des Charakter private void getCharacterCorners(Movable character) { double tlX = character.getX(); double tlY = character.getY(); topLeft.setLocation(tlX, tlY); topRight.setLocation(tlX + character.getWidth(), tlY); bottomLeft.setLocation(tlX, tlY + character.getHeight()); bottomRight.setLocation(tlX + character.getWidth(), tlY + character.getHeight()); } // Ermittelt, ob die, durch horizontale Bewegung dX, errechnete neue Position (des Spielers) in einer Wand liegt oder nicht private int isValidXMovement(Point2D pointTop, Point2D pointBottom, double dX, int checkValue) { try { if ((map.mapArray[(int) Math.floor(pointTop.getY()/32)][(int) Math.floor((pointTop.getX()+dX)/32)] == checkValue)) return checkValue; else if ((map.mapArray[(int) Math.floor(pointBottom.getY()/32)][(int) Math.floor((pointBottom.getX()+dX)/32)] == checkValue)) return checkValue; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ungueltige x Bewegung pT:"+pointTop+" pB:"+pointBottom); die(); } return 0; } // Ermittelt, ob die, durch vertikale Bewegung dY, errechnete neue Position (des Spielers) in einer Wand liegt oder nicht private int isValidYMovement(Point2D pointLeft, Point2D pointRight, double dY2, int checkValue) { try { if ((map.mapArray[(int) Math.floor(pointLeft.getY()+dY)/32][(int) Math.floor(pointLeft.getX()/32)] == checkValue)) return checkValue; else if ((map.mapArray[(int) Math.floor(pointRight.getY()+dY)/32][(int) Math.floor(pointRight.getX()/32)] == checkValue)) return checkValue; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ungueltige y Bewegung pL:"+pointLeft+" pR:"+pointRight); die(); } return 0; } private void backToLastCheckpoint() { // Zurueck zur ersten Karte des aktuellen Level changeLevel(map.getLevelNumber(), 0); player.setArmor(100); } private void die() { houston.changeAppearance(true, false, Houston.STARTMENU); } }
False
2,422
10
2,831
13
2,646
8
2,830
13
3,345
11
false
false
false
false
false
true
1,361
15318_8
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class BeginScherm extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public BeginScherm() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("startScreen.jpg"); //startScreen(); TileEngine te = new TileEngine(this, 60, 60); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); prepare(); } public void act() { ce.update(); } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { StartPlay startPlay = new StartPlay(); addObject(startPlay,414,314); } }
ROCMondriaanTIN/project-greenfoot-game-302443235
BeginScherm.java
539
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class BeginScherm extends World { private CollisionEngine ce; /** * Constructor for objects of class MyWorld. * */ public BeginScherm() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("startScreen.jpg"); //startScreen(); TileEngine te = new TileEngine(this, 60, 60); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(); // Laat de<SUF> camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); prepare(); } public void act() { ce.update(); } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { StartPlay startPlay = new StartPlay(); addObject(startPlay,414,314); } }
True
481
26
514
25
507
23
514
25
573
26
false
false
false
false
false
true
250
30836_0
package game.spawner; import java.util.ArrayList; import java.util.List; import java.util.Random; import game.movement.Direction; import game.objects.background.BackgroundObject; import game.objects.enemies.Enemy; import VisualAndAudioData.DataClass; import game.objects.enemies.enums.EnemyEnums; import javax.xml.crypto.Data; public class SpawningCoordinator { private static SpawningCoordinator instance = new SpawningCoordinator(); private Random random = new Random(); // Al deze ranges moeten eigenlijk dynamisch berekend worden, want nu is het // niet resizable private int maximumBGOWidthRange = DataClass.getInstance().getWindowWidth() + 200; private int minimumBGOWidthRange = -200; private int maximumBGOHeightRange = DataClass.getInstance().getWindowHeight(); private int minimumBGOHeightRange = 0; private int maximumBombEnemyHeightDownRange = 0; private int minimumBombEnemyHeightDownRange = -200; //Left Spawning block private int leftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int leftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); private int leftEnemyMaxWidthRange = 500; private int leftEnemyMinWidthRange = 100; private int bottomLeftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int bottomLeftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private int topLeftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); private int topLeftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; //Right Spawning block private int rightEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() + 200; private int rightEnemyMinWidthRange = DataClass.getInstance().getWindowWidth(); private int rightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int rightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; private int bottomRightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int bottomRightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private int topRightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; private int topRightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 200; //Up spawning block private int upEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() - 50; private int upEnemyMinWidthRange = 100; private int upEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 150; private int upEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); //Down spawning block private int downEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() - 50; private int downEnemyMinWidthRange = 50; private int downEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 200; private int downEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private SpawningCoordinator () { } public static SpawningCoordinator getInstance () { return instance; } //Function used to prevent enemies of the same type of stacking on top of each other when being spawned in public boolean checkValidEnemyXCoordinate (Enemy enemyType, List<Enemy> listToCheck, int xCoordinate, int minimumRange) { for (Enemy enemy : listToCheck) { if (!enemy.getEnemyType().equals(EnemyEnums.Alien_Bomb)) { if (Math.abs(enemy.getXCoordinate() - xCoordinate) < minimumRange) { return false; } } } return true; } //Function used to prevent enemies of the same type of stacking on top of each other when being spawned in public boolean checkValidEnemyYCoordinate (Enemy enemyType, List<Enemy> listToCheck, int yCoordinate, int minimumRange) { for (Enemy enemy : listToCheck) { if (!enemy.getEnemyType().equals(EnemyEnums.Alien_Bomb)) { if (Math.abs(enemy.getYCoordinate() - yCoordinate) < minimumRange) { return false; } } } return true; } public int getRightBlockXCoordinate () { return random.nextInt((rightEnemyMaxWidthRange - rightEnemyMinWidthRange) + 1) + rightEnemyMinWidthRange; } public int getRightBlockYCoordinate () { return random.nextInt((rightEnemyMaxHeightRange - rightEnemyMinHeightRange) + 1) + rightEnemyMinHeightRange; } public int getBottomRightBlockYCoordinate () { return random.nextInt((bottomRightEnemyMaxHeightRange - bottomRightEnemyMinHeightRange) + 1) + bottomRightEnemyMinHeightRange; } public int getTopRightBlockYCoordinate () { return 0 - random.nextInt((topRightEnemyMaxHeightRange - topRightEnemyMinHeightRange) + 1) + topRightEnemyMinHeightRange; } public int getLeftBlockXCoordinate () { return 0 - random.nextInt((leftEnemyMaxWidthRange - leftEnemyMinWidthRange) + 1) + leftEnemyMinWidthRange; } public int getLeftBlockYCoordinate () { return random.nextInt((leftEnemyMaxHeightRange - leftEnemyMinHeightRange) + 1) + leftEnemyMinHeightRange; } public int getBottomLeftBlockYCoordinate () { return random.nextInt((bottomLeftEnemyMaxHeightRange - bottomLeftEnemyMinHeightRange) + 1) + bottomLeftEnemyMinHeightRange; } public int getTopLeftBlockYCoordinate () { return 0 - random.nextInt((topLeftEnemyMaxHeightRange - topLeftEnemyMinHeightRange) + 1) + topLeftEnemyMinHeightRange; } public int getUpBlockXCoordinate () { return random.nextInt((upEnemyMaxWidthRange - upEnemyMinWidthRange) + 1) + upEnemyMinWidthRange; } public int getUpBlockYCoordinate () { return 0 - random.nextInt((upEnemyMaxHeightRange - upEnemyMinHeightRange) + 1) + upEnemyMinHeightRange; } public int getDownBlockXCoordinate () { return random.nextInt((downEnemyMaxWidthRange - downEnemyMinWidthRange) + 1) + downEnemyMinWidthRange; } public int getDownBlockYCoordinate () { return random.nextInt((downEnemyMaxHeightRange - downEnemyMinHeightRange) + 1) + downEnemyMinHeightRange; } public int getRandomXBombEnemyCoordinate () { return random.nextInt((downEnemyMaxWidthRange - downEnemyMinWidthRange) + 1) + downEnemyMinWidthRange; } //Recently swapped public int getRandomYDownBombEnemyCoordinate () { return random.nextInt((downEnemyMaxHeightRange - downEnemyMinHeightRange) + 1) + downEnemyMinHeightRange; } public int getRandomYUpBombEnemyCoordinate () { return 0 - random.nextInt((upEnemyMaxHeightRange - upEnemyMinHeightRange) + 1) + upEnemyMinHeightRange; } public Direction upOrDown () { int randInt = random.nextInt((1 - 0) + 1) + 0; switch (randInt) { case (0): return Direction.DOWN; case (1): return Direction.UP; } return Direction.UP; } // Random functions used for Background objects // public boolean checkValidBGOXCoordinate (List<BackgroundObject> listToCheck, int xCoordinate, int size) { for (BackgroundObject bgObject : listToCheck) { if (Math.abs(bgObject.getXCoordinate() - xCoordinate) < size) { return false; } } return true; } public boolean checkValidBGOYCoordinate (List<BackgroundObject> listToCheck, int yCoordinate, int size) { for (BackgroundObject bgObject : listToCheck) { if (Math.abs(bgObject.getYCoordinate() - yCoordinate) < size) { return false; } } return true; } public int getRandomXBGOCoordinate () { return random.nextInt((maximumBGOWidthRange - minimumBGOWidthRange) + 1) + minimumBGOWidthRange; } public int getRandomYBGOCoordinate () { return random.nextInt((maximumBGOHeightRange - minimumBGOHeightRange) + 1) + minimumBGOHeightRange; } public List<Integer> getSpawnCoordinatesByDirection (Direction direction) { List<Integer> coordinatesList = new ArrayList<Integer>(); if (direction.equals(Direction.LEFT)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getRightBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getLeftBlockYCoordinate()); } else if (direction.equals(Direction.DOWN)) { coordinatesList.add(getUpBlockXCoordinate()); coordinatesList.add(getUpBlockYCoordinate()); } else if (direction.equals(Direction.UP)) { coordinatesList.add(getDownBlockXCoordinate()); coordinatesList.add(getDownBlockYCoordinate()); } else if (direction.equals(Direction.LEFT_UP)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getBottomRightBlockYCoordinate()); } else if (direction.equals(Direction.LEFT_DOWN)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getTopRightBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT_UP)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getBottomLeftBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT_DOWN)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getTopLeftBlockYCoordinate()); } return coordinatesList; } }
Broozer29/Game
src/main/java/game/spawner/SpawningCoordinator.java
2,825
// Al deze ranges moeten eigenlijk dynamisch berekend worden, want nu is het
line_comment
nl
package game.spawner; import java.util.ArrayList; import java.util.List; import java.util.Random; import game.movement.Direction; import game.objects.background.BackgroundObject; import game.objects.enemies.Enemy; import VisualAndAudioData.DataClass; import game.objects.enemies.enums.EnemyEnums; import javax.xml.crypto.Data; public class SpawningCoordinator { private static SpawningCoordinator instance = new SpawningCoordinator(); private Random random = new Random(); // Al deze<SUF> // niet resizable private int maximumBGOWidthRange = DataClass.getInstance().getWindowWidth() + 200; private int minimumBGOWidthRange = -200; private int maximumBGOHeightRange = DataClass.getInstance().getWindowHeight(); private int minimumBGOHeightRange = 0; private int maximumBombEnemyHeightDownRange = 0; private int minimumBombEnemyHeightDownRange = -200; //Left Spawning block private int leftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int leftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); private int leftEnemyMaxWidthRange = 500; private int leftEnemyMinWidthRange = 100; private int bottomLeftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int bottomLeftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private int topLeftEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); private int topLeftEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; //Right Spawning block private int rightEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() + 200; private int rightEnemyMinWidthRange = DataClass.getInstance().getWindowWidth(); private int rightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int rightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; private int bottomRightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() - 100; private int bottomRightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private int topRightEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 100; private int topRightEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 200; //Up spawning block private int upEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() - 50; private int upEnemyMinWidthRange = 100; private int upEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMinHeight() + 150; private int upEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMinHeight(); //Down spawning block private int downEnemyMaxWidthRange = DataClass.getInstance().getWindowWidth() - 50; private int downEnemyMinWidthRange = 50; private int downEnemyMaxHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 200; private int downEnemyMinHeightRange = DataClass.getInstance().getPlayableWindowMaxHeight() + 50; private SpawningCoordinator () { } public static SpawningCoordinator getInstance () { return instance; } //Function used to prevent enemies of the same type of stacking on top of each other when being spawned in public boolean checkValidEnemyXCoordinate (Enemy enemyType, List<Enemy> listToCheck, int xCoordinate, int minimumRange) { for (Enemy enemy : listToCheck) { if (!enemy.getEnemyType().equals(EnemyEnums.Alien_Bomb)) { if (Math.abs(enemy.getXCoordinate() - xCoordinate) < minimumRange) { return false; } } } return true; } //Function used to prevent enemies of the same type of stacking on top of each other when being spawned in public boolean checkValidEnemyYCoordinate (Enemy enemyType, List<Enemy> listToCheck, int yCoordinate, int minimumRange) { for (Enemy enemy : listToCheck) { if (!enemy.getEnemyType().equals(EnemyEnums.Alien_Bomb)) { if (Math.abs(enemy.getYCoordinate() - yCoordinate) < minimumRange) { return false; } } } return true; } public int getRightBlockXCoordinate () { return random.nextInt((rightEnemyMaxWidthRange - rightEnemyMinWidthRange) + 1) + rightEnemyMinWidthRange; } public int getRightBlockYCoordinate () { return random.nextInt((rightEnemyMaxHeightRange - rightEnemyMinHeightRange) + 1) + rightEnemyMinHeightRange; } public int getBottomRightBlockYCoordinate () { return random.nextInt((bottomRightEnemyMaxHeightRange - bottomRightEnemyMinHeightRange) + 1) + bottomRightEnemyMinHeightRange; } public int getTopRightBlockYCoordinate () { return 0 - random.nextInt((topRightEnemyMaxHeightRange - topRightEnemyMinHeightRange) + 1) + topRightEnemyMinHeightRange; } public int getLeftBlockXCoordinate () { return 0 - random.nextInt((leftEnemyMaxWidthRange - leftEnemyMinWidthRange) + 1) + leftEnemyMinWidthRange; } public int getLeftBlockYCoordinate () { return random.nextInt((leftEnemyMaxHeightRange - leftEnemyMinHeightRange) + 1) + leftEnemyMinHeightRange; } public int getBottomLeftBlockYCoordinate () { return random.nextInt((bottomLeftEnemyMaxHeightRange - bottomLeftEnemyMinHeightRange) + 1) + bottomLeftEnemyMinHeightRange; } public int getTopLeftBlockYCoordinate () { return 0 - random.nextInt((topLeftEnemyMaxHeightRange - topLeftEnemyMinHeightRange) + 1) + topLeftEnemyMinHeightRange; } public int getUpBlockXCoordinate () { return random.nextInt((upEnemyMaxWidthRange - upEnemyMinWidthRange) + 1) + upEnemyMinWidthRange; } public int getUpBlockYCoordinate () { return 0 - random.nextInt((upEnemyMaxHeightRange - upEnemyMinHeightRange) + 1) + upEnemyMinHeightRange; } public int getDownBlockXCoordinate () { return random.nextInt((downEnemyMaxWidthRange - downEnemyMinWidthRange) + 1) + downEnemyMinWidthRange; } public int getDownBlockYCoordinate () { return random.nextInt((downEnemyMaxHeightRange - downEnemyMinHeightRange) + 1) + downEnemyMinHeightRange; } public int getRandomXBombEnemyCoordinate () { return random.nextInt((downEnemyMaxWidthRange - downEnemyMinWidthRange) + 1) + downEnemyMinWidthRange; } //Recently swapped public int getRandomYDownBombEnemyCoordinate () { return random.nextInt((downEnemyMaxHeightRange - downEnemyMinHeightRange) + 1) + downEnemyMinHeightRange; } public int getRandomYUpBombEnemyCoordinate () { return 0 - random.nextInt((upEnemyMaxHeightRange - upEnemyMinHeightRange) + 1) + upEnemyMinHeightRange; } public Direction upOrDown () { int randInt = random.nextInt((1 - 0) + 1) + 0; switch (randInt) { case (0): return Direction.DOWN; case (1): return Direction.UP; } return Direction.UP; } // Random functions used for Background objects // public boolean checkValidBGOXCoordinate (List<BackgroundObject> listToCheck, int xCoordinate, int size) { for (BackgroundObject bgObject : listToCheck) { if (Math.abs(bgObject.getXCoordinate() - xCoordinate) < size) { return false; } } return true; } public boolean checkValidBGOYCoordinate (List<BackgroundObject> listToCheck, int yCoordinate, int size) { for (BackgroundObject bgObject : listToCheck) { if (Math.abs(bgObject.getYCoordinate() - yCoordinate) < size) { return false; } } return true; } public int getRandomXBGOCoordinate () { return random.nextInt((maximumBGOWidthRange - minimumBGOWidthRange) + 1) + minimumBGOWidthRange; } public int getRandomYBGOCoordinate () { return random.nextInt((maximumBGOHeightRange - minimumBGOHeightRange) + 1) + minimumBGOHeightRange; } public List<Integer> getSpawnCoordinatesByDirection (Direction direction) { List<Integer> coordinatesList = new ArrayList<Integer>(); if (direction.equals(Direction.LEFT)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getRightBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getLeftBlockYCoordinate()); } else if (direction.equals(Direction.DOWN)) { coordinatesList.add(getUpBlockXCoordinate()); coordinatesList.add(getUpBlockYCoordinate()); } else if (direction.equals(Direction.UP)) { coordinatesList.add(getDownBlockXCoordinate()); coordinatesList.add(getDownBlockYCoordinate()); } else if (direction.equals(Direction.LEFT_UP)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getBottomRightBlockYCoordinate()); } else if (direction.equals(Direction.LEFT_DOWN)) { coordinatesList.add(getRightBlockXCoordinate()); coordinatesList.add(getTopRightBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT_UP)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getBottomLeftBlockYCoordinate()); } else if (direction.equals(Direction.RIGHT_DOWN)) { coordinatesList.add(getLeftBlockXCoordinate()); coordinatesList.add(getTopLeftBlockYCoordinate()); } return coordinatesList; } }
True
2,234
18
2,421
20
2,520
16
2,421
20
2,860
19
false
false
false
false
false
true
2,046
161403_3
import java.util.Scanner; /** * Developed by András Ács (acsandras@gmail.com) * Zealand / www.zealand.dk * Licensed under the MIT License * 30/09/2019 */ public class SteenSaksPapir { public static void startSpillet() { SteenSaksPapir runde1 = new SteenSaksPapir(); int count = 1; while (count>=1) { // Indlæse spillerns hånd Scanner scanner = new Scanner(System.in); System.out.print("Runde " + count + " - hvad slår du (sten, saks, papir)? "); Haand spillerensHaand = null; String spillerenString = scanner.next(); if (spillerenString.equalsIgnoreCase("sten")) { spillerensHaand = Haand.STEN; } if (spillerenString.equalsIgnoreCase("saks")) { spillerensHaand = Haand.SAKS; } if (spillerenString.equalsIgnoreCase("papir")) { spillerensHaand = Haand.PAPIR; } if (spillerenString.equalsIgnoreCase("afslut")) { break; } System.out.println("Spiller slår " + spillerensHaand); // Computer generere en hånd Haand computerensHaand = null; int haandInt =(int) (Math.random()*3+1); // Korte nørklet kode computersHaand = Haand.values()[haandInt]; if (haandInt == 1) { computerensHaand = Haand.STEN; } if (haandInt == 2) { computerensHaand = Haand.SAKS; } if (haandInt == 3) { computerensHaand = Haand.PAPIR; } System.out.println("Computer slår " + computerensHaand); // Sammenligne med slaa() metoden int resultat = runde1.slaa(spillerensHaand, computerensHaand); // Udråbe en vinder if (resultat==1) { System.out.println("Du har vundet!"); } if (resultat==2) { System.out.println("Du har tabt!"); } if (resultat==0) { System.out.println("Uafgjort :)"); } if (resultat==-1) { System.out.println("Der er sket en funky fejl, prøv igen!"); } count++; } } /** Hvis den første hånd vinder, returneres 1 * Hvis den anden hånd vinder, returneres 2 * Hvis uafgjort, returneres 0 * Hvis der er en fejl, så returnerer den -1 */ int slaa(Haand a, Haand b) { int resultat = -1; // TODO refaktorer, så det bliver kortere med f.eks. // if(a == Haand.STEN && b== Haand.STEN) { resultat = 0;} // if(a == Haand.STEN && b== Haand.SAKS) { resultat = 1;} // første hånd sten if(a == Haand.STEN) { // anden hånd er sten if (b== Haand.STEN) { resultat = 0; } // anden hånd er saks if (b== Haand.SAKS) { resultat = 1; } // anden hånd er papir if (b== Haand.PAPIR) { resultat = 2; } } // første hånd saks if(a == Haand.SAKS) { // anden hånd er sten if (b== Haand.STEN) { resultat = 2; } // anden hånd er saks if (b== Haand.SAKS) { resultat = 0; } // anden hånd er papir if (b== Haand.PAPIR) { resultat = 1; } } // første hånd papir if(a == Haand.PAPIR) { // anden hånd er sten if (b== Haand.STEN) { resultat = 1; } // anden hånd er saks if (b== Haand.SAKS) { resultat = 2; } // anden hånd er papir if (b== Haand.PAPIR) { resultat = 0; } } return resultat; } }
andracs/StenSaksPapiro
src/SteenSaksPapir.java
1,217
// Korte nørklet kode computersHaand = Haand.values()[haandInt];
line_comment
nl
import java.util.Scanner; /** * Developed by András Ács (acsandras@gmail.com) * Zealand / www.zealand.dk * Licensed under the MIT License * 30/09/2019 */ public class SteenSaksPapir { public static void startSpillet() { SteenSaksPapir runde1 = new SteenSaksPapir(); int count = 1; while (count>=1) { // Indlæse spillerns hånd Scanner scanner = new Scanner(System.in); System.out.print("Runde " + count + " - hvad slår du (sten, saks, papir)? "); Haand spillerensHaand = null; String spillerenString = scanner.next(); if (spillerenString.equalsIgnoreCase("sten")) { spillerensHaand = Haand.STEN; } if (spillerenString.equalsIgnoreCase("saks")) { spillerensHaand = Haand.SAKS; } if (spillerenString.equalsIgnoreCase("papir")) { spillerensHaand = Haand.PAPIR; } if (spillerenString.equalsIgnoreCase("afslut")) { break; } System.out.println("Spiller slår " + spillerensHaand); // Computer generere en hånd Haand computerensHaand = null; int haandInt =(int) (Math.random()*3+1); // Korte nørklet<SUF> if (haandInt == 1) { computerensHaand = Haand.STEN; } if (haandInt == 2) { computerensHaand = Haand.SAKS; } if (haandInt == 3) { computerensHaand = Haand.PAPIR; } System.out.println("Computer slår " + computerensHaand); // Sammenligne med slaa() metoden int resultat = runde1.slaa(spillerensHaand, computerensHaand); // Udråbe en vinder if (resultat==1) { System.out.println("Du har vundet!"); } if (resultat==2) { System.out.println("Du har tabt!"); } if (resultat==0) { System.out.println("Uafgjort :)"); } if (resultat==-1) { System.out.println("Der er sket en funky fejl, prøv igen!"); } count++; } } /** Hvis den første hånd vinder, returneres 1 * Hvis den anden hånd vinder, returneres 2 * Hvis uafgjort, returneres 0 * Hvis der er en fejl, så returnerer den -1 */ int slaa(Haand a, Haand b) { int resultat = -1; // TODO refaktorer, så det bliver kortere med f.eks. // if(a == Haand.STEN && b== Haand.STEN) { resultat = 0;} // if(a == Haand.STEN && b== Haand.SAKS) { resultat = 1;} // første hånd sten if(a == Haand.STEN) { // anden hånd er sten if (b== Haand.STEN) { resultat = 0; } // anden hånd er saks if (b== Haand.SAKS) { resultat = 1; } // anden hånd er papir if (b== Haand.PAPIR) { resultat = 2; } } // første hånd saks if(a == Haand.SAKS) { // anden hånd er sten if (b== Haand.STEN) { resultat = 2; } // anden hånd er saks if (b== Haand.SAKS) { resultat = 0; } // anden hånd er papir if (b== Haand.PAPIR) { resultat = 1; } } // første hånd papir if(a == Haand.PAPIR) { // anden hånd er sten if (b== Haand.STEN) { resultat = 1; } // anden hånd er saks if (b== Haand.SAKS) { resultat = 2; } // anden hånd er papir if (b== Haand.PAPIR) { resultat = 0; } } return resultat; } }
False
1,037
21
1,134
23
1,049
22
1,134
23
1,220
24
false
false
false
false
false
true
358
44640_7
/** * Create all entity EJBs in the uml model and put them in a hashmap * * @param entityEJBs list with all entity EJBs. * @param simpleModel the uml model. * @return HashMap with all UML Entity classes. */ private HashMap createEntityEJBs(ArrayList entityEJBs, SimpleModel simpleModel) { HashMap map = new HashMap(); for (int i = 0; i < entityEJBs.size(); i++) { Entity e = (Entity) entityEJBs.get(i); String documentation = e.getDescription().toString(); String name = e.getName().toString(); String refName = e.getRefName(); String tableName = e.getTableName(); String displayName = e.getDisplayName().toString(); String entityRootPackage = e.getRootPackage().toString(); simpleModel.addSimpleUmlPackage(entityRootPackage); String isCompositeKey = e.getIsComposite(); String isAssocation = e.getIsAssociationEntity(); // "true" or "false" // Use the refName to put all EntityEJBs in a HashMap. // Add the standard definition for the URLS. SimpleUmlClass umlClass = new SimpleUmlClass(name, SimpleModelElement.PUBLIC); // The e should be a UML Class. // Use the stereoType: simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_CLASS_ENTITY, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_DOCUMENTATION, documentation, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_TABLE_NAME, tableName, umlClass); if (!"".equals(displayName)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_DISPLAY_NAME, displayName, umlClass); } if ("true".equals(isCompositeKey)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_COMPOSITE_PRIMARY_KEY, e.getPrimaryKeyType().toString(), umlClass); } if ("true".equals(isAssocation)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_IS_ASSOCIATION, isAssocation, umlClass); } ArrayList fields = (ArrayList) e.getFields(); for (int j = 0; j < fields.size(); j++) { Field field = (Field) fields.get(j); String fieldType = field.getType(); String fieldName = field.getName().toString(); SimpleUmlClass type = (SimpleUmlClass) typeMappings.get(fieldType); if (type == null) { log("Unknown type: " + type + " for field " + fieldType); type = (SimpleUmlClass) typeMappings.get(this.stringType); } SimpleAttribute theAttribute = new SimpleAttribute(fieldName, SimpleModelElement.PUBLIC, type); umlClass.addSimpleAttribute(theAttribute); String foreignKey = field.getForeignKey().toString(); // "true" or "false" if the current field as a foreign key. if (field.isPrimaryKey()) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_PRIMARY_KEY, theAttribute); } else if (field.isNullable() == false) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_REQUIRED, theAttribute); } if (field.isForeignKey()) { // Niet duidelijk of het plaatsen van 2 stereotypes mogelijk is.... String stereoTypeForeignKey = JagUMLProfile.STEREOTYPE_ATTRIBUTE_FOREIGN_KEY; } String jdbcType = field.getJdbcType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_JDBC_TYPE, jdbcType, theAttribute); String sqlType = field.getSqlType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_SQL_TYPE, sqlType, theAttribute); String columnName = field.getColumnName(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_COLUMN_NAME, columnName, theAttribute); boolean autoGeneratedPrimarykey = field.getHasAutoGenPrimaryKey(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_AUTO_PRIMARY_KEY, "" + autoGeneratedPrimarykey, theAttribute); } SimpleUmlPackage pk = simpleModel.addSimpleUmlPackage(entityRootPackage); pk.addSimpleClassifier(umlClass); map.put(refName, umlClass); } return map; }
D-a-r-e-k/Code-Smells-Detection
Preparation/processed-dataset/god-class_2_942/4.java
1,294
// Niet duidelijk of het plaatsen van 2 stereotypes mogelijk is....
line_comment
nl
/** * Create all entity EJBs in the uml model and put them in a hashmap * * @param entityEJBs list with all entity EJBs. * @param simpleModel the uml model. * @return HashMap with all UML Entity classes. */ private HashMap createEntityEJBs(ArrayList entityEJBs, SimpleModel simpleModel) { HashMap map = new HashMap(); for (int i = 0; i < entityEJBs.size(); i++) { Entity e = (Entity) entityEJBs.get(i); String documentation = e.getDescription().toString(); String name = e.getName().toString(); String refName = e.getRefName(); String tableName = e.getTableName(); String displayName = e.getDisplayName().toString(); String entityRootPackage = e.getRootPackage().toString(); simpleModel.addSimpleUmlPackage(entityRootPackage); String isCompositeKey = e.getIsComposite(); String isAssocation = e.getIsAssociationEntity(); // "true" or "false" // Use the refName to put all EntityEJBs in a HashMap. // Add the standard definition for the URLS. SimpleUmlClass umlClass = new SimpleUmlClass(name, SimpleModelElement.PUBLIC); // The e should be a UML Class. // Use the stereoType: simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_CLASS_ENTITY, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_DOCUMENTATION, documentation, umlClass); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_TABLE_NAME, tableName, umlClass); if (!"".equals(displayName)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_DISPLAY_NAME, displayName, umlClass); } if ("true".equals(isCompositeKey)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_COMPOSITE_PRIMARY_KEY, e.getPrimaryKeyType().toString(), umlClass); } if ("true".equals(isAssocation)) { simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_CLASS_IS_ASSOCIATION, isAssocation, umlClass); } ArrayList fields = (ArrayList) e.getFields(); for (int j = 0; j < fields.size(); j++) { Field field = (Field) fields.get(j); String fieldType = field.getType(); String fieldName = field.getName().toString(); SimpleUmlClass type = (SimpleUmlClass) typeMappings.get(fieldType); if (type == null) { log("Unknown type: " + type + " for field " + fieldType); type = (SimpleUmlClass) typeMappings.get(this.stringType); } SimpleAttribute theAttribute = new SimpleAttribute(fieldName, SimpleModelElement.PUBLIC, type); umlClass.addSimpleAttribute(theAttribute); String foreignKey = field.getForeignKey().toString(); // "true" or "false" if the current field as a foreign key. if (field.isPrimaryKey()) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_PRIMARY_KEY, theAttribute); } else if (field.isNullable() == false) { simpleModel.setStereoType(JagUMLProfile.STEREOTYPE_ATTRIBUTE_REQUIRED, theAttribute); } if (field.isForeignKey()) { // Niet duidelijk<SUF> String stereoTypeForeignKey = JagUMLProfile.STEREOTYPE_ATTRIBUTE_FOREIGN_KEY; } String jdbcType = field.getJdbcType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_JDBC_TYPE, jdbcType, theAttribute); String sqlType = field.getSqlType().toString(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_SQL_TYPE, sqlType, theAttribute); String columnName = field.getColumnName(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_COLUMN_NAME, columnName, theAttribute); boolean autoGeneratedPrimarykey = field.getHasAutoGenPrimaryKey(); simpleModel.addTaggedValue(JagUMLProfile.TAGGED_VALUE_ATTRIBUTE_AUTO_PRIMARY_KEY, "" + autoGeneratedPrimarykey, theAttribute); } SimpleUmlPackage pk = simpleModel.addSimpleUmlPackage(entityRootPackage); pk.addSimpleClassifier(umlClass); map.put(refName, umlClass); } return map; }
True
983
17
1,087
24
1,133
14
1,087
24
1,301
22
false
false
false
false
false
true
2,608
56929_7
/* * Commons eID Project. * Copyright (C) 2008-2013 FedICT. * Copyright (C) 2018-2024 e-Contract.be BV. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version * 3.0 as published by the Free Software Foundation. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, see * http://www.gnu.org/licenses/. */ package be.fedict.commons.eid.consumer; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Enumeration for eID Document Type. * * @author Frank Cornelis * @see Identity */ public enum DocumentType implements Serializable { BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD("8"), /** * Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk verblijf */ FOREIGNER_A("11", "33"), /** * Bewijs van inschrijving in het vreemdelingenregister */ FOREIGNER_B("12", "34"), /** * Identiteitskaart voor vreemdeling */ FOREIGNER_C("13"), /** * EG-Langdurig ingezetene */ FOREIGNER_D("14"), /** * (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring van * inschrijving */ FOREIGNER_E("15"), /** * Document ter staving van duurzaam verblijf van een EU onderdaan */ FOREIGNER_E_PLUS("16"), /** * Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg * Verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F("17", "35"), /** * Duurzame verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F_PLUS("18", "36"), /** * H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde * landen. */ EUROPEAN_BLUE_CARD_H("19"), /** * I. New types of foreigner cards (I and J cards) will be issued for employees * that are transferred within their company (EU directive 2014/66/EU) */ FOREIGNER_I("20"), /** * J. New types of foreigner cards (I and J cards) will be issued for employees * that are transferred within their company (EU directive 2014/66/EU) */ FOREIGNER_J("21"), FOREIGNER_M("22"), FOREIGNER_N("23"), /** * ETABLISSEMENT */ FOREIGNER_K("27"), /** * RESIDENT DE LONGUE DUREE – UE */ FOREIGNER_L("28"), FOREIGNER_EU("31"), FOREIGNER_EU_PLUS("32"), FOREIGNER_KIDS_EU("61"), FOREIGNER_KIDS_EU_PLUS("62"), FOREIGNER_KIDS_A("63"), FOREIGNER_KIDS_B("64"), FOREIGNER_KIDS_K("65"), FOREIGNER_KIDS_L("66"), FOREIGNER_KIDS_F("67"), FOREIGNER_KIDS_F_PLUS("68"), FOREIGNER_KIDS_M("69"); private final Set<Integer> keys; DocumentType(final String... valueList) { this.keys = new HashSet<>(); for (String value : valueList) { this.keys.add(toKey(value)); } } private int toKey(final String value) { final char c1 = value.charAt(0); int key = c1 - '0'; if (2 == value.length()) { key *= 10; final char c2 = value.charAt(1); key += c2 - '0'; } return key; } private static int toKey(final byte[] value) { int key = value[0] - '0'; if (2 == value.length) { key *= 10; key += value[1] - '0'; } return key; } private static Map<Integer, DocumentType> documentTypes; static { final Map<Integer, DocumentType> documentTypes = new HashMap<>(); for (DocumentType documentType : DocumentType.values()) { for (Integer key : documentType.keys) { if (documentTypes.containsKey(key)) { throw new RuntimeException("duplicate document type enum: " + key); } documentTypes.put(key, documentType); } } DocumentType.documentTypes = documentTypes; } public static DocumentType toDocumentType(final byte[] value) { final int key = DocumentType.toKey(value); /* * If the key is unknown, we simply return null. */ return DocumentType.documentTypes.get(key); } public static String toString(final byte[] documentTypeValue) { return Integer.toString(DocumentType.toKey(documentTypeValue)); } }
e-Contract/commons-eid
commons-eid-consumer/src/main/java/be/fedict/commons/eid/consumer/DocumentType.java
1,562
/** * Document ter staving van duurzaam verblijf van een EU onderdaan */
block_comment
nl
/* * Commons eID Project. * Copyright (C) 2008-2013 FedICT. * Copyright (C) 2018-2024 e-Contract.be BV. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version * 3.0 as published by the Free Software Foundation. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, see * http://www.gnu.org/licenses/. */ package be.fedict.commons.eid.consumer; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Enumeration for eID Document Type. * * @author Frank Cornelis * @see Identity */ public enum DocumentType implements Serializable { BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD("8"), /** * Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk verblijf */ FOREIGNER_A("11", "33"), /** * Bewijs van inschrijving in het vreemdelingenregister */ FOREIGNER_B("12", "34"), /** * Identiteitskaart voor vreemdeling */ FOREIGNER_C("13"), /** * EG-Langdurig ingezetene */ FOREIGNER_D("14"), /** * (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring van * inschrijving */ FOREIGNER_E("15"), /** * Document ter staving<SUF>*/ FOREIGNER_E_PLUS("16"), /** * Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg * Verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F("17", "35"), /** * Duurzame verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F_PLUS("18", "36"), /** * H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde * landen. */ EUROPEAN_BLUE_CARD_H("19"), /** * I. New types of foreigner cards (I and J cards) will be issued for employees * that are transferred within their company (EU directive 2014/66/EU) */ FOREIGNER_I("20"), /** * J. New types of foreigner cards (I and J cards) will be issued for employees * that are transferred within their company (EU directive 2014/66/EU) */ FOREIGNER_J("21"), FOREIGNER_M("22"), FOREIGNER_N("23"), /** * ETABLISSEMENT */ FOREIGNER_K("27"), /** * RESIDENT DE LONGUE DUREE – UE */ FOREIGNER_L("28"), FOREIGNER_EU("31"), FOREIGNER_EU_PLUS("32"), FOREIGNER_KIDS_EU("61"), FOREIGNER_KIDS_EU_PLUS("62"), FOREIGNER_KIDS_A("63"), FOREIGNER_KIDS_B("64"), FOREIGNER_KIDS_K("65"), FOREIGNER_KIDS_L("66"), FOREIGNER_KIDS_F("67"), FOREIGNER_KIDS_F_PLUS("68"), FOREIGNER_KIDS_M("69"); private final Set<Integer> keys; DocumentType(final String... valueList) { this.keys = new HashSet<>(); for (String value : valueList) { this.keys.add(toKey(value)); } } private int toKey(final String value) { final char c1 = value.charAt(0); int key = c1 - '0'; if (2 == value.length()) { key *= 10; final char c2 = value.charAt(1); key += c2 - '0'; } return key; } private static int toKey(final byte[] value) { int key = value[0] - '0'; if (2 == value.length) { key *= 10; key += value[1] - '0'; } return key; } private static Map<Integer, DocumentType> documentTypes; static { final Map<Integer, DocumentType> documentTypes = new HashMap<>(); for (DocumentType documentType : DocumentType.values()) { for (Integer key : documentType.keys) { if (documentTypes.containsKey(key)) { throw new RuntimeException("duplicate document type enum: " + key); } documentTypes.put(key, documentType); } } DocumentType.documentTypes = documentTypes; } public static DocumentType toDocumentType(final byte[] value) { final int key = DocumentType.toKey(value); /* * If the key is unknown, we simply return null. */ return DocumentType.documentTypes.get(key); } public static String toString(final byte[] documentTypeValue) { return Integer.toString(DocumentType.toKey(documentTypeValue)); } }
True
1,306
24
1,489
23
1,448
21
1,489
23
1,743
25
false
false
false
false
false
true
987
86767_4
package be.pxl.collections.arraylist; import java.util.ArrayList; import java.util.List; public class Theatre { private String theatreName; private List<Seat> seats = new ArrayList<>(); private int seatsPerRow; private int numRows; public Theatre(String theatreName, int numRows, int seatsPerRow) { this.theatreName = theatreName; this.seatsPerRow = seatsPerRow; this.numRows = numRows; // voeg alle stoelen toe in het theater, nummer alle stoelen. // de eerste rij stoelen is genummerd vanaf A1, A2,... // de tweede rij stoelen is genummerd vanaf B1, B2,... } public void displayMap() { int count = 0; for (Seat seat : seats) { System.out.print(seat + " "); count++; if (count % seatsPerRow == 0) { System.out.println(); } } } public boolean reservateSeat(String seatNumber) { // implementeer de reservatie van een stoel, // gebruik hierbij de methode getSeatBySeatNumber } private Seat getSeatBySeatNumber(String seatNumber) { // implementeer het opzoeken van een stoel adhv een stoelnummer // hoelang duurt het om stoel A1 te zoeken // hoelang duurt het om de laatste stoel in het theater te zoeken // probeer dit eens uit het het hoofdprogramma // stel eventueel nog alternatieven voor } private class Seat { private String seatNumber; private boolean reserved = false; public Seat(String seatNumber) { this.seatNumber = seatNumber; } public String getSeatNumber() { return seatNumber; } public boolean reserve() { if (isReserved()) { System.out.println("Seat " + seatNumber + " already reserved."); return false; } reserved = true; return reserved; } public boolean isReserved() { return reserved; } @Override public String toString() { return (reserved ? "*" : "") + seatNumber + (reserved ? "*" : ""); } } }
Lordrin/week6-collections-overview-skelet
src/be/pxl/collections/arraylist/Theatre.java
619
// gebruik hierbij de methode getSeatBySeatNumber
line_comment
nl
package be.pxl.collections.arraylist; import java.util.ArrayList; import java.util.List; public class Theatre { private String theatreName; private List<Seat> seats = new ArrayList<>(); private int seatsPerRow; private int numRows; public Theatre(String theatreName, int numRows, int seatsPerRow) { this.theatreName = theatreName; this.seatsPerRow = seatsPerRow; this.numRows = numRows; // voeg alle stoelen toe in het theater, nummer alle stoelen. // de eerste rij stoelen is genummerd vanaf A1, A2,... // de tweede rij stoelen is genummerd vanaf B1, B2,... } public void displayMap() { int count = 0; for (Seat seat : seats) { System.out.print(seat + " "); count++; if (count % seatsPerRow == 0) { System.out.println(); } } } public boolean reservateSeat(String seatNumber) { // implementeer de reservatie van een stoel, // gebruik hierbij<SUF> } private Seat getSeatBySeatNumber(String seatNumber) { // implementeer het opzoeken van een stoel adhv een stoelnummer // hoelang duurt het om stoel A1 te zoeken // hoelang duurt het om de laatste stoel in het theater te zoeken // probeer dit eens uit het het hoofdprogramma // stel eventueel nog alternatieven voor } private class Seat { private String seatNumber; private boolean reserved = false; public Seat(String seatNumber) { this.seatNumber = seatNumber; } public String getSeatNumber() { return seatNumber; } public boolean reserve() { if (isReserved()) { System.out.println("Seat " + seatNumber + " already reserved."); return false; } reserved = true; return reserved; } public boolean isReserved() { return reserved; } @Override public String toString() { return (reserved ? "*" : "") + seatNumber + (reserved ? "*" : ""); } } }
True
498
12
568
13
561
11
568
13
629
16
false
false
false
false
false
true
1,892
33311_6
package zeppelin;_x000D_ import server.SendToClient;_x000D_ import transfer.Transfer;_x000D_ _x000D_ import com.pi4j.io.gpio.GpioController;_x000D_ import com.pi4j.io.gpio.GpioPinDigitalOutput;_x000D_ import com.pi4j.io.gpio.GpioPinPwmOutput;_x000D_ import com.pi4j.io.gpio.Pin;_x000D_ import com.pi4j.io.gpio.PinState;_x000D_ _x000D_ _x000D_ public class Motor {_x000D_ private GpioPinDigitalOutput forwardPin;_x000D_ private GpioPinDigitalOutput reversePin;_x000D_ private GpioPinPwmOutput pwmPin;_x000D_ _x000D_ //PWM: value tussen 0 en 1024 (volgens WiringPi)_x000D_ //of mss tussen 0 en 100 (dit is bij SoftPWM)_x000D_ //evt een aparte klasse pwm control die gedeeld tussen alle motoren_x000D_ private boolean pwmEnabled;_x000D_ _x000D_ private GpioController gpiocontroller;_x000D_ private Propellor id;_x000D_ _x000D_ //previous mode and direction ==> avoids sending the same transfer twice_x000D_ private Propellor.Mode prevmode = Propellor.Mode.OFF;_x000D_ private Propellor.Direction prevdirection;_x000D_ _x000D_ private SendToClient sender;_x000D_ _x000D_ public Motor(Pin fwPin, Pin rvPin, GpioController gpio,Propellor id, GpioPinPwmOutput pwmPin, SendToClient sender) {_x000D_ gpiocontroller = gpio;_x000D_ forwardPin = gpiocontroller.provisionDigitalOutputPin(fwPin,"forward");_x000D_ reversePin = gpiocontroller.provisionDigitalOutputPin(rvPin,"backward");_x000D_ this.pwmPin = pwmPin; _x000D_ this.id = id;_x000D_ this.sender = sender;_x000D_ _x000D_ //status wanneer de app wordt afgesloten_x000D_ forwardPin.setShutdownOptions(true,PinState.LOW);_x000D_ reversePin.setShutdownOptions(true,PinState.LOW);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Laat deze motor naar voor draaien._x000D_ */_x000D_ public void setForward() {_x000D_ reversePin.setState(PinState.LOW);_x000D_ forwardPin.setState(PinState.HIGH);_x000D_ _x000D_ if(prevdirection != Propellor.Direction.FORWARD || prevmode != Propellor.Mode.ON) {_x000D_ Transfer transfer = new Transfer();_x000D_ transfer.setPropellor(id, Propellor.Mode.ON, Propellor.Direction.FORWARD, 0);_x000D_ sender.sendTransfer(transfer);_x000D_ _x000D_ prevmode = Propellor.Mode.ON;_x000D_ prevdirection = Propellor.Direction.FORWARD;_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Laat deze motor naar voor draaien._x000D_ * Stuurt geen update_x000D_ */_x000D_ private void fw() {_x000D_ reversePin.setState(PinState.LOW);_x000D_ forwardPin.setState(PinState.HIGH);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Laat deze motor naar achter draaien._x000D_ */_x000D_ public void setReverse() {_x000D_ forwardPin.setState(PinState.LOW);_x000D_ reversePin.setState(PinState.HIGH);_x000D_ _x000D_ if(prevdirection != Propellor.Direction.REVERSE || prevmode != Propellor.Mode.ON) {_x000D_ Transfer transfer = new Transfer();_x000D_ transfer.setPropellor(id, Propellor.Mode.ON, Propellor.Direction.REVERSE, 0);_x000D_ sender.sendTransfer(transfer);_x000D_ _x000D_ prevmode = Propellor.Mode.ON;_x000D_ prevdirection = Propellor.Direction.REVERSE;_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Laat deze motor naar achter draaien._x000D_ * Stuurt geen update_x000D_ */_x000D_ private void rv() {_x000D_ forwardPin.setState(PinState.LOW);_x000D_ reversePin.setState(PinState.HIGH);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet deze motor uit._x000D_ */_x000D_ public void setOff() {_x000D_ reversePin.setState(PinState.LOW);_x000D_ forwardPin.setState(PinState.LOW);_x000D_ _x000D_ if(prevmode != Propellor.Mode.OFF) {_x000D_ Transfer transfer = new Transfer();_x000D_ transfer.setPropellor(id, Propellor.Mode.OFF, null, 0);_x000D_ sender.sendTransfer(transfer);_x000D_ _x000D_ prevmode = Propellor.Mode.OFF;_x000D_ prevdirection = null;_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet deze motor uit._x000D_ * Stuurt geen update_x000D_ */_x000D_ public void off() {_x000D_ reversePin.setState(PinState.LOW);_x000D_ forwardPin.setState(PinState.LOW);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Activeert pwm op deze motor_x000D_ */_x000D_ public void PwmOn() {_x000D_ pwmEnabled = true;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deactiveert pwm op deze motor_x000D_ * @param set0_x000D_ * Om aan te geven of de pwm pin op 0 moet worden gezet_x000D_ * Dus indien geen andere motoren hier nog gebruik van aan het maken zijn._x000D_ */_x000D_ public void PwmOff(boolean set0) {_x000D_ pwmEnabled = false;_x000D_ if(set0)_x000D_ pwmPin.setPwm(0);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet de pwm value en laat de motor in de juiste richting draaien_x000D_ * indien pwm geactiveerd is op deze motor_x000D_ * @param value_x000D_ * Getal tussen -1024 (min) en 1024 (max)_x000D_ */_x000D_ public void setPwmValue(int value) {_x000D_ if(pwmEnabled) {_x000D_ if(value > 0){_x000D_ pwmPin.setPwm(1024);_x000D_ fw();_x000D_ off();_x000D_ pwmPin.setPwm(value);_x000D_ fw();_x000D_ }_x000D_ else{_x000D_ pwmPin.setPwm(1024);_x000D_ rv();_x000D_ off();_x000D_ pwmPin.setPwm(Math.abs(value));_x000D_ rv();_x000D_ }_x000D_ _x000D_ _x000D_ // Transfer transfer = new Transfer();_x000D_ // transfer.setPropellor(id, Propellor.Mode.PWM, null, value);_x000D_ // sender.sendTransfer(transfer);_x000D_ prevmode = Propellor.Mode.PWM;_x000D_ _x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Geeft aan of pwm geactiveerd is voor deze motor._x000D_ * @return_x000D_ */_x000D_ public boolean getPwmStatus() {_x000D_ return pwmEnabled;_x000D_ }_x000D_ }_x000D_
WoutV/Indigo
IndigoZeppelin/src/zeppelin/Motor.java
1,827
/**_x000D_ * Laat deze motor naar voor draaien._x000D_ * Stuurt geen update_x000D_ */
block_comment
nl
package zeppelin;_x000D_ import server.SendToClient;_x000D_ import transfer.Transfer;_x000D_ _x000D_ import com.pi4j.io.gpio.GpioController;_x000D_ import com.pi4j.io.gpio.GpioPinDigitalOutput;_x000D_ import com.pi4j.io.gpio.GpioPinPwmOutput;_x000D_ import com.pi4j.io.gpio.Pin;_x000D_ import com.pi4j.io.gpio.PinState;_x000D_ _x000D_ _x000D_ public class Motor {_x000D_ private GpioPinDigitalOutput forwardPin;_x000D_ private GpioPinDigitalOutput reversePin;_x000D_ private GpioPinPwmOutput pwmPin;_x000D_ _x000D_ //PWM: value tussen 0 en 1024 (volgens WiringPi)_x000D_ //of mss tussen 0 en 100 (dit is bij SoftPWM)_x000D_ //evt een aparte klasse pwm control die gedeeld tussen alle motoren_x000D_ private boolean pwmEnabled;_x000D_ _x000D_ private GpioController gpiocontroller;_x000D_ private Propellor id;_x000D_ _x000D_ //previous mode and direction ==> avoids sending the same transfer twice_x000D_ private Propellor.Mode prevmode = Propellor.Mode.OFF;_x000D_ private Propellor.Direction prevdirection;_x000D_ _x000D_ private SendToClient sender;_x000D_ _x000D_ public Motor(Pin fwPin, Pin rvPin, GpioController gpio,Propellor id, GpioPinPwmOutput pwmPin, SendToClient sender) {_x000D_ gpiocontroller = gpio;_x000D_ forwardPin = gpiocontroller.provisionDigitalOutputPin(fwPin,"forward");_x000D_ reversePin = gpiocontroller.provisionDigitalOutputPin(rvPin,"backward");_x000D_ this.pwmPin = pwmPin; _x000D_ this.id = id;_x000D_ this.sender = sender;_x000D_ _x000D_ //status wanneer de app wordt afgesloten_x000D_ forwardPin.setShutdownOptions(true,PinState.LOW);_x000D_ reversePin.setShutdownOptions(true,PinState.LOW);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Laat deze motor naar voor draaien._x000D_ */_x000D_ public void setForward() {_x000D_ reversePin.setState(PinState.LOW);_x000D_ forwardPin.setState(PinState.HIGH);_x000D_ _x000D_ if(prevdirection != Propellor.Direction.FORWARD || prevmode != Propellor.Mode.ON) {_x000D_ Transfer transfer = new Transfer();_x000D_ transfer.setPropellor(id, Propellor.Mode.ON, Propellor.Direction.FORWARD, 0);_x000D_ sender.sendTransfer(transfer);_x000D_ _x000D_ prevmode = Propellor.Mode.ON;_x000D_ prevdirection = Propellor.Direction.FORWARD;_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Laat deze motor<SUF>*/_x000D_ private void fw() {_x000D_ reversePin.setState(PinState.LOW);_x000D_ forwardPin.setState(PinState.HIGH);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Laat deze motor naar achter draaien._x000D_ */_x000D_ public void setReverse() {_x000D_ forwardPin.setState(PinState.LOW);_x000D_ reversePin.setState(PinState.HIGH);_x000D_ _x000D_ if(prevdirection != Propellor.Direction.REVERSE || prevmode != Propellor.Mode.ON) {_x000D_ Transfer transfer = new Transfer();_x000D_ transfer.setPropellor(id, Propellor.Mode.ON, Propellor.Direction.REVERSE, 0);_x000D_ sender.sendTransfer(transfer);_x000D_ _x000D_ prevmode = Propellor.Mode.ON;_x000D_ prevdirection = Propellor.Direction.REVERSE;_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Laat deze motor naar achter draaien._x000D_ * Stuurt geen update_x000D_ */_x000D_ private void rv() {_x000D_ forwardPin.setState(PinState.LOW);_x000D_ reversePin.setState(PinState.HIGH);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet deze motor uit._x000D_ */_x000D_ public void setOff() {_x000D_ reversePin.setState(PinState.LOW);_x000D_ forwardPin.setState(PinState.LOW);_x000D_ _x000D_ if(prevmode != Propellor.Mode.OFF) {_x000D_ Transfer transfer = new Transfer();_x000D_ transfer.setPropellor(id, Propellor.Mode.OFF, null, 0);_x000D_ sender.sendTransfer(transfer);_x000D_ _x000D_ prevmode = Propellor.Mode.OFF;_x000D_ prevdirection = null;_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet deze motor uit._x000D_ * Stuurt geen update_x000D_ */_x000D_ public void off() {_x000D_ reversePin.setState(PinState.LOW);_x000D_ forwardPin.setState(PinState.LOW);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Activeert pwm op deze motor_x000D_ */_x000D_ public void PwmOn() {_x000D_ pwmEnabled = true;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deactiveert pwm op deze motor_x000D_ * @param set0_x000D_ * Om aan te geven of de pwm pin op 0 moet worden gezet_x000D_ * Dus indien geen andere motoren hier nog gebruik van aan het maken zijn._x000D_ */_x000D_ public void PwmOff(boolean set0) {_x000D_ pwmEnabled = false;_x000D_ if(set0)_x000D_ pwmPin.setPwm(0);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Zet de pwm value en laat de motor in de juiste richting draaien_x000D_ * indien pwm geactiveerd is op deze motor_x000D_ * @param value_x000D_ * Getal tussen -1024 (min) en 1024 (max)_x000D_ */_x000D_ public void setPwmValue(int value) {_x000D_ if(pwmEnabled) {_x000D_ if(value > 0){_x000D_ pwmPin.setPwm(1024);_x000D_ fw();_x000D_ off();_x000D_ pwmPin.setPwm(value);_x000D_ fw();_x000D_ }_x000D_ else{_x000D_ pwmPin.setPwm(1024);_x000D_ rv();_x000D_ off();_x000D_ pwmPin.setPwm(Math.abs(value));_x000D_ rv();_x000D_ }_x000D_ _x000D_ _x000D_ // Transfer transfer = new Transfer();_x000D_ // transfer.setPropellor(id, Propellor.Mode.PWM, null, value);_x000D_ // sender.sendTransfer(transfer);_x000D_ prevmode = Propellor.Mode.PWM;_x000D_ _x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Geeft aan of pwm geactiveerd is voor deze motor._x000D_ * @return_x000D_ */_x000D_ public boolean getPwmStatus() {_x000D_ return pwmEnabled;_x000D_ }_x000D_ }_x000D_
True
2,468
41
2,723
44
2,707
42
2,723
44
3,071
44
false
false
false
false
false
true
718
11751_1
package data; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import data.RegionType.ModelType; import data.RegionType.RegionName; /** * This class has the enumerations for the various dimensions in the M-files * that are encountered. It also has an enumeration with the region names in it. * Note that correct behaviour depends on the order of regions in the RegionName * enumeration! This will also not work with the aggegrated regions in files * with 33 dimensions! * * @author Vortech * */ public class RegionControl { static Logger logger = Logger.getLogger(RegionControl.class.getName()); /** * <pre> * In onze huidige datafiles kan je verschillende configuraties tegenkomen * 24 24 Image regios * 25 24 image regios+wereld * 26 26 TIMER/FAIR regios * 27 26 TIMER/FAIR regios+wereld * 28 26 TIMER/FAIR regios+lege regio+wereld * 33 26 TIMER/FAIR regios+aggregaties+wereld * * Dus je kan wel een bestand tegenkomen met 25 + 1 regios. * * De beslisboom wordt dan: * * IF 24, * Report [24 regios, 0 for region 25 en 26] * LOG: missing regions 25 and 26, LOG missing global * If 25, * Report [24 regios, 0 for region 25 en 26, Global(dim25 van data)] * LOG: missing regions 25 and 26 * IF 26, * report [26 regions] * LOG: missing global * IF 27 * report [26 regions, global(dim27 van data)] * LOG: missing global * IF 28 * report [26 regions, global(dim28 van data)] * LOG: missing global * IF 33 * report [26 regions, global(dim33 van data)] * LOG: missing global * * Voor wereldtotaal geld ook * IFNOT 24 of 26 THEN laatste van de array altijd het wereldtotaal. * IF 24 of 25 THEN report N/A, LOG: missing global * </pre> */ protected static void createRegions(int numRegions, HashMap<RegionName, OutputRow> ioRegions, ModelType iModel, OutputRow iTemplateRow, String iScenario) { int i = 0; for (RegionName r : RegionName.values()) { OutputRow aRow = OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, r); ioRegions.put(r, aRow); i++; if (i == numRegions) { break; } } } /** * This function uses a combination of the global/noglobal/regions and * ModelType to determine how many outputrows need to be created for the * current mapping. * * @param iModel The modeltype determines the amount of regions when worldtype is not 'global' * @param iTemplateRow The template row is used to copy some relevant information to the output row, like the variable name and unit. * @param iScenario The scenario is also part of the result row and is already copied into place here. * @param iType If the WorldType is set to global then only a single output row is created. * @return A map that maps regions to output rows, it can contain 1, 24, 25, 26 or 27 entries. * @throws Exception If the ModelType is not recognized and the WorldType is not global. * */ public static Map<RegionName, OutputRow> createOutputList(ModelType iModel, OutputRow iTemplateRow, String iScenario, WorldType iType) throws Exception { HashMap<RegionName, OutputRow> aResult = new HashMap<RegionName, OutputRow>(); if (iType == WorldType.global) { OutputRow aRow = OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World); aResult.put(RegionName.World, aRow); } else { switch (iModel) { case Image: createRegions(24, aResult, iModel, iTemplateRow, iScenario); break; case ImageWorld: createRegions(24, aResult, iModel, iTemplateRow, iScenario); aResult.put(RegionName.World, OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World)); break; case TimerFair: createRegions(26, aResult, iModel, iTemplateRow, iScenario); break; case TimerFairWorld: createRegions(26, aResult, iModel, iTemplateRow, iScenario); aResult.put(RegionName.World, OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World)); break; case TimerFairEmptyWorld: createRegions(26, aResult, iModel, iTemplateRow, iScenario); aResult.put(RegionName.World, OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World)); break; case TimerFairAggWorld: createRegions(33, aResult, iModel, iTemplateRow, iScenario); break; case SingleValue: aResult.put(RegionName.World, OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World)); break; default: throw new Exception("Model not supported"); } } return aResult; } }
IAMconsortium/reporting_workflows
java2iamc/RegionControl.java
1,569
/** * <pre> * In onze huidige datafiles kan je verschillende configuraties tegenkomen * 24 24 Image regios * 25 24 image regios+wereld * 26 26 TIMER/FAIR regios * 27 26 TIMER/FAIR regios+wereld * 28 26 TIMER/FAIR regios+lege regio+wereld * 33 26 TIMER/FAIR regios+aggregaties+wereld * * Dus je kan wel een bestand tegenkomen met 25 + 1 regios. * * De beslisboom wordt dan: * * IF 24, * Report [24 regios, 0 for region 25 en 26] * LOG: missing regions 25 and 26, LOG missing global * If 25, * Report [24 regios, 0 for region 25 en 26, Global(dim25 van data)] * LOG: missing regions 25 and 26 * IF 26, * report [26 regions] * LOG: missing global * IF 27 * report [26 regions, global(dim27 van data)] * LOG: missing global * IF 28 * report [26 regions, global(dim28 van data)] * LOG: missing global * IF 33 * report [26 regions, global(dim33 van data)] * LOG: missing global * * Voor wereldtotaal geld ook * IFNOT 24 of 26 THEN laatste van de array altijd het wereldtotaal. * IF 24 of 25 THEN report N/A, LOG: missing global * </pre> */
block_comment
nl
package data; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import data.RegionType.ModelType; import data.RegionType.RegionName; /** * This class has the enumerations for the various dimensions in the M-files * that are encountered. It also has an enumeration with the region names in it. * Note that correct behaviour depends on the order of regions in the RegionName * enumeration! This will also not work with the aggegrated regions in files * with 33 dimensions! * * @author Vortech * */ public class RegionControl { static Logger logger = Logger.getLogger(RegionControl.class.getName()); /** * <pre> <SUF>*/ protected static void createRegions(int numRegions, HashMap<RegionName, OutputRow> ioRegions, ModelType iModel, OutputRow iTemplateRow, String iScenario) { int i = 0; for (RegionName r : RegionName.values()) { OutputRow aRow = OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, r); ioRegions.put(r, aRow); i++; if (i == numRegions) { break; } } } /** * This function uses a combination of the global/noglobal/regions and * ModelType to determine how many outputrows need to be created for the * current mapping. * * @param iModel The modeltype determines the amount of regions when worldtype is not 'global' * @param iTemplateRow The template row is used to copy some relevant information to the output row, like the variable name and unit. * @param iScenario The scenario is also part of the result row and is already copied into place here. * @param iType If the WorldType is set to global then only a single output row is created. * @return A map that maps regions to output rows, it can contain 1, 24, 25, 26 or 27 entries. * @throws Exception If the ModelType is not recognized and the WorldType is not global. * */ public static Map<RegionName, OutputRow> createOutputList(ModelType iModel, OutputRow iTemplateRow, String iScenario, WorldType iType) throws Exception { HashMap<RegionName, OutputRow> aResult = new HashMap<RegionName, OutputRow>(); if (iType == WorldType.global) { OutputRow aRow = OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World); aResult.put(RegionName.World, aRow); } else { switch (iModel) { case Image: createRegions(24, aResult, iModel, iTemplateRow, iScenario); break; case ImageWorld: createRegions(24, aResult, iModel, iTemplateRow, iScenario); aResult.put(RegionName.World, OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World)); break; case TimerFair: createRegions(26, aResult, iModel, iTemplateRow, iScenario); break; case TimerFairWorld: createRegions(26, aResult, iModel, iTemplateRow, iScenario); aResult.put(RegionName.World, OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World)); break; case TimerFairEmptyWorld: createRegions(26, aResult, iModel, iTemplateRow, iScenario); aResult.put(RegionName.World, OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World)); break; case TimerFairAggWorld: createRegions(33, aResult, iModel, iTemplateRow, iScenario); break; case SingleValue: aResult.put(RegionName.World, OutputRow.createOutputRow(iModel, iTemplateRow, iScenario, RegionName.World)); break; default: throw new Exception("Model not supported"); } } return aResult; } }
True
1,379
476
1,425
458
1,508
472
1,425
458
1,587
496
true
true
true
true
true
false
778
169765_0
package nl.hu.cisq1.lingo.trainer.domain; import nl.hu.cisq1.lingo.trainer.domain.enumerations.Mark; import nl.hu.cisq1.lingo.trainer.domain.enumerations.Round_States; import nl.hu.cisq1.lingo.trainer.domain.exceptions.InvalidFeedbackException; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import static nl.hu.cisq1.lingo.trainer.domain.enumerations.Mark.ABSENT; @Entity public class Round { public static final int max_attempts = 5; @Id @GeneratedValue private Long id; private String wordToGuess; @Enumerated(EnumType.STRING) private Round_States round_status = Round_States.PLAYING; @OneToMany(cascade = CascadeType.ALL) @JoinColumn private final List<Feedback> feedbackHistory = new ArrayList<>(); public Round_States getRound_status() { return round_status; } public void setRound_status(Round_States round_status) { this.round_status = round_status; } public Round(String wordToGuess) { this.wordToGuess = wordToGuess; } public Round() { } public String giveFirstHint(String wordToGuess) { String firstHint = ""; if (wordToGuess.length() > 0) { firstHint += wordToGuess.charAt(0); for (int i = 1; i < wordToGuess.length(); i++) { firstHint += "."; } } return firstHint; } public void guess(String guess) { if (guess.length() != this.wordToGuess.length()) { throw new InvalidFeedbackException("Attempt is too long"); } else if(feedbackHistory.size() > 4) { this.setRound_status(Round_States.ELIMINATED); } Feedback feedback = new Feedback(guess, this.generateMarks(guess)); feedbackHistory.add(feedback); // schrijf nog een test hiervoor + test dit } public List<Character> showFeedback(){ return feedbackHistory.get(feedbackHistory.size()-1).giveHint(); } public List<Mark> generateMarks(String guess) { List<Mark> marks = new ArrayList<>(); List<Character> presentList = new ArrayList<>(); int index = 0; for (char character : wordToGuess.toCharArray()) { if (guess.charAt(index) == character) { marks.add(index, Mark.CORRECT); index++; continue; } else if (!presentList.contains(guess.charAt(index)) && wordToGuess.contains(Character.toString(guess.charAt(index)))) { marks.add(index, Mark.PRESENT); presentList.add(guess.charAt(index)); index++; continue; } marks.add(index, ABSENT); index++; } return marks; } public int calculateScore(){ return 5 * (5-feedbackHistory.size()) + 5; } }
JBaltjes1997/HU_Lingo
cisq1-lingo-v2b-Lobohuargo822-main/src/main/java/nl/hu/cisq1/lingo/trainer/domain/Round.java
906
// schrijf nog een test hiervoor + test dit
line_comment
nl
package nl.hu.cisq1.lingo.trainer.domain; import nl.hu.cisq1.lingo.trainer.domain.enumerations.Mark; import nl.hu.cisq1.lingo.trainer.domain.enumerations.Round_States; import nl.hu.cisq1.lingo.trainer.domain.exceptions.InvalidFeedbackException; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import static nl.hu.cisq1.lingo.trainer.domain.enumerations.Mark.ABSENT; @Entity public class Round { public static final int max_attempts = 5; @Id @GeneratedValue private Long id; private String wordToGuess; @Enumerated(EnumType.STRING) private Round_States round_status = Round_States.PLAYING; @OneToMany(cascade = CascadeType.ALL) @JoinColumn private final List<Feedback> feedbackHistory = new ArrayList<>(); public Round_States getRound_status() { return round_status; } public void setRound_status(Round_States round_status) { this.round_status = round_status; } public Round(String wordToGuess) { this.wordToGuess = wordToGuess; } public Round() { } public String giveFirstHint(String wordToGuess) { String firstHint = ""; if (wordToGuess.length() > 0) { firstHint += wordToGuess.charAt(0); for (int i = 1; i < wordToGuess.length(); i++) { firstHint += "."; } } return firstHint; } public void guess(String guess) { if (guess.length() != this.wordToGuess.length()) { throw new InvalidFeedbackException("Attempt is too long"); } else if(feedbackHistory.size() > 4) { this.setRound_status(Round_States.ELIMINATED); } Feedback feedback = new Feedback(guess, this.generateMarks(guess)); feedbackHistory.add(feedback); // schrijf nog<SUF> } public List<Character> showFeedback(){ return feedbackHistory.get(feedbackHistory.size()-1).giveHint(); } public List<Mark> generateMarks(String guess) { List<Mark> marks = new ArrayList<>(); List<Character> presentList = new ArrayList<>(); int index = 0; for (char character : wordToGuess.toCharArray()) { if (guess.charAt(index) == character) { marks.add(index, Mark.CORRECT); index++; continue; } else if (!presentList.contains(guess.charAt(index)) && wordToGuess.contains(Character.toString(guess.charAt(index)))) { marks.add(index, Mark.PRESENT); presentList.add(guess.charAt(index)); index++; continue; } marks.add(index, ABSENT); index++; } return marks; } public int calculateScore(){ return 5 * (5-feedbackHistory.size()) + 5; } }
True
628
13
730
13
776
11
730
13
893
12
false
false
false
false
false
true
608
62412_6
import be.gilles.Acteur; import java.util.*; import java.util.stream.Collectors; public class Main { private static final Acteur[] testdata = { new Acteur("Cameron Diaz", 1972), new Acteur("Anna Faris", 1976), new Acteur("Angelina Jolie", 1975), new Acteur("Jennifer Lopez", 1970), new Acteur("Reese Witherspoon", 1976), new Acteur("Neve Campbell", 1973), new Acteur("Catherine Zeta-Jones", 1969), new Acteur("Kirsten Dunst", 1982), new Acteur("Kate Winslet", 1975), new Acteur("Gina Philips", 1975), new Acteur("Shannon Elisabeth", 1973), new Acteur("Carmen Electra", 1972), new Acteur("Drew Barrymore", 1975), new Acteur("Elisabeth Hurley", 1965), new Acteur("Tara Reid", 1975), new Acteur("Katie Holmes", 1978), new Acteur("Anna Faris", 1976) }; public static void main(String[] args) { Acteur reese = new Acteur("Reese Witherspoon", 1976); Acteur drew = new Acteur("Drew Barrymore", 1975); Acteur anna = new Acteur("Anna Faris", 1976); Acteur thandie = new Acteur("Thandie Newton", 1972); List<Acteur> acteurs = new ArrayList<Acteur>(); acteurs.addAll(Arrays.asList(testdata)); acteurs.add(reese); acteurs.add(drew); acteurs.add(anna); acteurs.add(thandie); // Toon de inhoud van de collection (zonder iterator) Arrays.stream(testdata).forEach(System.out::println); // Verwijder de objecten reese en thandie acteurs.removeAll(Arrays.asList(reese, thandie)); // Verwijder alle acteurs geboren in 1975 (met iterator) acteurs.removeIf(x -> x.getGeboortejaar() == 1975); // Using an iterator (the less efficient way :x) for (Iterator<Acteur> it = acteurs.iterator(); it.hasNext(); ) { if (it.next().getGeboortejaar() == 1975) it.remove(); } // Verwijder alle dubbele acteurs in de lijst (doe dit bijvoorbeeld door een // nieuwe lijst te maken zonder dubbels. Je kan “contains” gebruiken om te // kijken of een element al in de lijst zit. //acteurs = acteurs.stream().distinct().collect(Collectors.toList()); -> Updating // acteurs.stream().sorted(Acteur::compareTo).forEach(System.out::println); System.out.println("Uiteindelijke inhoud: "); acteurs.stream().distinct().sorted(Acteur::compareTo).forEach(System.out::println); } }
GillesClsns/Programming-OO-Concepts
P2-2022/P2-W4/Acteurs/src/Main.java
841
// kijken of een element al in de lijst zit.
line_comment
nl
import be.gilles.Acteur; import java.util.*; import java.util.stream.Collectors; public class Main { private static final Acteur[] testdata = { new Acteur("Cameron Diaz", 1972), new Acteur("Anna Faris", 1976), new Acteur("Angelina Jolie", 1975), new Acteur("Jennifer Lopez", 1970), new Acteur("Reese Witherspoon", 1976), new Acteur("Neve Campbell", 1973), new Acteur("Catherine Zeta-Jones", 1969), new Acteur("Kirsten Dunst", 1982), new Acteur("Kate Winslet", 1975), new Acteur("Gina Philips", 1975), new Acteur("Shannon Elisabeth", 1973), new Acteur("Carmen Electra", 1972), new Acteur("Drew Barrymore", 1975), new Acteur("Elisabeth Hurley", 1965), new Acteur("Tara Reid", 1975), new Acteur("Katie Holmes", 1978), new Acteur("Anna Faris", 1976) }; public static void main(String[] args) { Acteur reese = new Acteur("Reese Witherspoon", 1976); Acteur drew = new Acteur("Drew Barrymore", 1975); Acteur anna = new Acteur("Anna Faris", 1976); Acteur thandie = new Acteur("Thandie Newton", 1972); List<Acteur> acteurs = new ArrayList<Acteur>(); acteurs.addAll(Arrays.asList(testdata)); acteurs.add(reese); acteurs.add(drew); acteurs.add(anna); acteurs.add(thandie); // Toon de inhoud van de collection (zonder iterator) Arrays.stream(testdata).forEach(System.out::println); // Verwijder de objecten reese en thandie acteurs.removeAll(Arrays.asList(reese, thandie)); // Verwijder alle acteurs geboren in 1975 (met iterator) acteurs.removeIf(x -> x.getGeboortejaar() == 1975); // Using an iterator (the less efficient way :x) for (Iterator<Acteur> it = acteurs.iterator(); it.hasNext(); ) { if (it.next().getGeboortejaar() == 1975) it.remove(); } // Verwijder alle dubbele acteurs in de lijst (doe dit bijvoorbeeld door een // nieuwe lijst te maken zonder dubbels. Je kan “contains” gebruiken om te // kijken of<SUF> //acteurs = acteurs.stream().distinct().collect(Collectors.toList()); -> Updating // acteurs.stream().sorted(Acteur::compareTo).forEach(System.out::println); System.out.println("Uiteindelijke inhoud: "); acteurs.stream().distinct().sorted(Acteur::compareTo).forEach(System.out::println); } }
True
738
13
849
15
773
11
849
15
886
15
false
false
false
false
false
true
881
82291_32
package nl.hva.ict.data.MySQL; import nl.hva.ict.models.Accommodatie; import nl.hva.ict.models.BoekingsOverzicht; import nl.hva.ict.models.Reiziger; import nl.hva.ict.models.Reservering; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; /** * DAO voor de accommodatie * * @author HBO-ICT */ public class MySQLBoekingsOverzicht extends MySQL<BoekingsOverzicht> { private final List<BoekingsOverzicht> boekingsOverzicht; /** * Constructor */ public MySQLBoekingsOverzicht() { // init arraylist boekingsOverzicht = new ArrayList<>(); // Laad bij startup load(); } /** * Doe dit bij het maken van dit object */ private void load() { // Vul hier je SQL code in String sql = ""; // Als je nog geen query hebt ingevuld breek dan af om een error te voorkomen. if (sql.equals("")) return; try { // Roep de methode aan in de parent class en geen je SQL door PreparedStatement ps = getStatement(sql); //Voer je query uit en stop het antwoord in een result set ResultSet rs = executeSelectPreparedStatement(ps); // Loop net zolang als er records zijn while (rs.next()) { int idReservering = 0; Date aankomstDatum = rs.getDate("aankomstDatum"); Date vertrekDatum = rs.getDate("vertrekDatum"); boolean betaald = rs.getBoolean("betaald"); String accommodatieCode = rs.getString("accommodatieCode"); String reizerCode = rs.getString("reizigerCode"); String voornaam = ""; // not in use String achternaam = rs.getString("reiziger"); // combine voor en achternaam String adres = ""; // not in use String postcode = ""; String plaats = ""; String land = ""; String hoofdreiziger = ""; String accommodatieNaam = rs.getString("naam"); String accommodatieStad = rs.getString("stad"); String accommodatieLand = rs.getString("land"); // Maak models aan Reservering reservering = new Reservering(idReservering, aankomstDatum, vertrekDatum, betaald, accommodatieCode, reizerCode); Reiziger reiziger = new Reiziger(reizerCode, voornaam, achternaam, adres, postcode, plaats, land, hoofdreiziger); Accommodatie accommodatie = new Accommodatie(); accommodatie.setNaam(accommodatieNaam); accommodatie.setStad(accommodatieStad); accommodatie.setLand(accommodatieLand); //voeg die toe aan de arraylist boekingsOverzicht.add(new BoekingsOverzicht(accommodatie, reiziger, reservering)); } } catch (SQLException e) { e.printStackTrace(); } } /** * Haal de boekingen op voor 1 reiziger * * @param reizigerscode Welke reiziger wil je de boekingen voor? * @return Een list van boekingen */ public List<BoekingsOverzicht> getBoekingVoor(String reizigerscode) { // Maak een arraylist List<BoekingsOverzicht> reserveringVoor = new ArrayList<>(); // Voer hier je query in String sql = """ SELECT r.id, r.aankomst_datum AS aankomstDatum, r.vertrek_datum AS vertrekDatum, r.betaald, r.accommodatie_code AS accommodatieCode, r.reiziger_code AS reizigerCode, re.voornaam, re.achternaam, re.plaats, a.naam, a.stad, a.land FROM `reservering` AS r INNER JOIN reiziger AS re ON r.reiziger_code = re.reiziger_code INNER JOIN `accommodatie` AS a ON r.accommodatie_code = a.accommodatie_code WHERE r.reiziger_code = ? """; try { // Maak je statement PreparedStatement ps = getStatement(sql); // Vervang het eerste vraagteken met de reizigerscode. Pas dit eventueel aan voor jou eigen query ps.setString(1, reizigerscode); // Voer het uit ResultSet rs = executeSelectPreparedStatement(ps); // Loop net zolang als er records zijn while (rs.next()) { int idReservering = 0; Date aankomstDatum = rs.getDate("aankomstDatum"); Date vertrekDatum = rs.getDate("vertrekDatum"); boolean betaald = rs.getBoolean("betaald"); String accommodatieCode = rs.getString("accommodatieCode"); String reizigerVoornaam = rs.getString("voornaam"); String reizigerAchternaam = rs.getString("achternaam"); String reizigerPlaats = rs.getString("plaats"); String accommodatieNaam = rs.getString("naam"); String accommodatieStad = rs.getString("stad"); String accommodatieLand = rs.getString("land"); // Maak model objecten Reservering reservering = new Reservering(idReservering, aankomstDatum, vertrekDatum, betaald, accommodatieCode, reizigerscode); Accommodatie accommodatie = new Accommodatie(); accommodatie.setNaam(accommodatieNaam); accommodatie.setStad(accommodatieStad); accommodatie.setLand(accommodatieLand); Reiziger reiziger = new Reiziger(); reiziger.setVoornaam(reizigerVoornaam); reiziger.setAchternaam(reizigerAchternaam); reiziger.setPlaats(reizigerPlaats); // Voeg de reservering toe aan de arraylist reserveringVoor.add(new BoekingsOverzicht(accommodatie, reiziger, reservering)); } } catch (SQLException throwables) { // Oeps probleem throwables.printStackTrace(); } // Geef de arrayList terug met de juiste reserveringen return reserveringVoor; } /** * Haal de reizigerscode op voor een bepaalde boeking per accommodate en datum * * @param pCode de accommodatecode * @param pDatum de datum van verblijf * @return De reizigerscode */ private String getReizigerscode(String pCode, LocalDate pDatum) { String sql = """ SELECT GeboektOp(?, ?) AS reizigerCode; """; // default waarde String reizigerCode = ""; // convert datum naar ander formaat Date date = Date.valueOf(pDatum); try { // query voorbereiden PreparedStatement ps = getStatement(sql); // Vervang de vraagtekens met de juiste waarde. Pas eventueel aan je eigen query ps.setString(1, pCode); ps.setDate(2, date); // Voer het uit ResultSet rs = executeSelectPreparedStatement(ps); // Loop net zolang als er records zijn while (rs.next()) { reizigerCode = rs.getString("reizigerCode"); } } catch (SQLException throwables) { throwables.printStackTrace(); } // Geef de reizigercode terug return reizigerCode; } /** * Haal een lijst met reserveringen op voor een bepaalde boeking per accommodate en datum * * @param pCode de accommodate code * @param pDatum de datum van verblijf * @return Lijst met reserveringen */ public List<Reiziger> GeboektOp(String pCode, LocalDate pDatum) { // Init arraylist List<Reiziger> geboektOp = new ArrayList<>(); //Stop null pointer error als datum nog niet is ingevuld. if (pDatum == null) return geboektOp; // Spring naar de methode hierboven om de reizigerscode op te halen voor deze boeking String reizigerscode = getReizigerscode(pCode, pDatum); if (reizigerscode != null) { // Haal alle reserveringen op String sql = """ SELECT reiziger.voornaam, reiziger.achternaam, reiziger.adres, reiziger.postcode, reiziger.plaats, reiziger.land, CONCAT(reiziger.voornaam, ' ', reiziger.achternaam) AS hoofdreiziger FROM `reiziger` WHERE reiziger.reiziger_code = ? """; // Als je nog geen query hebt ingevuld breek dan af om een error te voorkomen. if (sql.equals("")) return geboektOp; try { // Roep de methode aan in de parent class en geef je SQL door PreparedStatement ps = getStatement(sql); // vervang de eerste vraagteken met de reizigerscode ps.setString(1, reizigerscode); // Voer je query uit ResultSet rs = executeSelectPreparedStatement(ps); // Loop net zolang als er records zijn while (rs.next()) { String voornaam = rs.getString("voornaam"); String achternaam = rs.getString("achternaam"); String adres = rs.getString("adres"); String postcode = rs.getString("postcode"); String plaats = rs.getString("plaats"); String land = rs.getString("land"); String hoofdreiziger = rs.getString("hoofdreiziger"); // Maak reserveringsobject en voeg direct toe aan arraylist geboektOp.add(new Reiziger(reizigerscode, voornaam, achternaam, adres, postcode, plaats, land, hoofdreiziger)); } } catch (SQLException throwables) { throwables.printStackTrace(); } } // Geef de array terug met reserveringen return geboektOp; } /** * Haal alle boekingen op door de gehele arraylist terug te geven * * @return Een arraylist van accommodaties */ @Override public List<BoekingsOverzicht> getAll() { return boekingsOverzicht; } /** * Haal 1 boeking op * * @return Een arraylist van accommodaties */ @Override public BoekingsOverzicht get() { // nog niet uitgewerkt geeft nu even null terug return null; } /** * Voeg een boeking toe * * @param boekingsOverzicht de boeking */ @Override public void add(BoekingsOverzicht boekingsOverzicht) { // nog niet uitgewerkt } /** * Update de boeking * * @param boekingsOverzicht de boeking */ @Override public void update(BoekingsOverzicht boekingsOverzicht) { // nog niet uitgewerkt } /** * Verwijder een boeking * * @param object de boeking */ @Override public void remove(BoekingsOverzicht object) { // nog niet uitgewerkt } }
JuniorBrPr/DB2
src/nl/hva/ict/data/MySQL/MySQLBoekingsOverzicht.java
3,300
// Spring naar de methode hierboven om de reizigerscode op te halen voor deze boeking
line_comment
nl
package nl.hva.ict.data.MySQL; import nl.hva.ict.models.Accommodatie; import nl.hva.ict.models.BoekingsOverzicht; import nl.hva.ict.models.Reiziger; import nl.hva.ict.models.Reservering; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; /** * DAO voor de accommodatie * * @author HBO-ICT */ public class MySQLBoekingsOverzicht extends MySQL<BoekingsOverzicht> { private final List<BoekingsOverzicht> boekingsOverzicht; /** * Constructor */ public MySQLBoekingsOverzicht() { // init arraylist boekingsOverzicht = new ArrayList<>(); // Laad bij startup load(); } /** * Doe dit bij het maken van dit object */ private void load() { // Vul hier je SQL code in String sql = ""; // Als je nog geen query hebt ingevuld breek dan af om een error te voorkomen. if (sql.equals("")) return; try { // Roep de methode aan in de parent class en geen je SQL door PreparedStatement ps = getStatement(sql); //Voer je query uit en stop het antwoord in een result set ResultSet rs = executeSelectPreparedStatement(ps); // Loop net zolang als er records zijn while (rs.next()) { int idReservering = 0; Date aankomstDatum = rs.getDate("aankomstDatum"); Date vertrekDatum = rs.getDate("vertrekDatum"); boolean betaald = rs.getBoolean("betaald"); String accommodatieCode = rs.getString("accommodatieCode"); String reizerCode = rs.getString("reizigerCode"); String voornaam = ""; // not in use String achternaam = rs.getString("reiziger"); // combine voor en achternaam String adres = ""; // not in use String postcode = ""; String plaats = ""; String land = ""; String hoofdreiziger = ""; String accommodatieNaam = rs.getString("naam"); String accommodatieStad = rs.getString("stad"); String accommodatieLand = rs.getString("land"); // Maak models aan Reservering reservering = new Reservering(idReservering, aankomstDatum, vertrekDatum, betaald, accommodatieCode, reizerCode); Reiziger reiziger = new Reiziger(reizerCode, voornaam, achternaam, adres, postcode, plaats, land, hoofdreiziger); Accommodatie accommodatie = new Accommodatie(); accommodatie.setNaam(accommodatieNaam); accommodatie.setStad(accommodatieStad); accommodatie.setLand(accommodatieLand); //voeg die toe aan de arraylist boekingsOverzicht.add(new BoekingsOverzicht(accommodatie, reiziger, reservering)); } } catch (SQLException e) { e.printStackTrace(); } } /** * Haal de boekingen op voor 1 reiziger * * @param reizigerscode Welke reiziger wil je de boekingen voor? * @return Een list van boekingen */ public List<BoekingsOverzicht> getBoekingVoor(String reizigerscode) { // Maak een arraylist List<BoekingsOverzicht> reserveringVoor = new ArrayList<>(); // Voer hier je query in String sql = """ SELECT r.id, r.aankomst_datum AS aankomstDatum, r.vertrek_datum AS vertrekDatum, r.betaald, r.accommodatie_code AS accommodatieCode, r.reiziger_code AS reizigerCode, re.voornaam, re.achternaam, re.plaats, a.naam, a.stad, a.land FROM `reservering` AS r INNER JOIN reiziger AS re ON r.reiziger_code = re.reiziger_code INNER JOIN `accommodatie` AS a ON r.accommodatie_code = a.accommodatie_code WHERE r.reiziger_code = ? """; try { // Maak je statement PreparedStatement ps = getStatement(sql); // Vervang het eerste vraagteken met de reizigerscode. Pas dit eventueel aan voor jou eigen query ps.setString(1, reizigerscode); // Voer het uit ResultSet rs = executeSelectPreparedStatement(ps); // Loop net zolang als er records zijn while (rs.next()) { int idReservering = 0; Date aankomstDatum = rs.getDate("aankomstDatum"); Date vertrekDatum = rs.getDate("vertrekDatum"); boolean betaald = rs.getBoolean("betaald"); String accommodatieCode = rs.getString("accommodatieCode"); String reizigerVoornaam = rs.getString("voornaam"); String reizigerAchternaam = rs.getString("achternaam"); String reizigerPlaats = rs.getString("plaats"); String accommodatieNaam = rs.getString("naam"); String accommodatieStad = rs.getString("stad"); String accommodatieLand = rs.getString("land"); // Maak model objecten Reservering reservering = new Reservering(idReservering, aankomstDatum, vertrekDatum, betaald, accommodatieCode, reizigerscode); Accommodatie accommodatie = new Accommodatie(); accommodatie.setNaam(accommodatieNaam); accommodatie.setStad(accommodatieStad); accommodatie.setLand(accommodatieLand); Reiziger reiziger = new Reiziger(); reiziger.setVoornaam(reizigerVoornaam); reiziger.setAchternaam(reizigerAchternaam); reiziger.setPlaats(reizigerPlaats); // Voeg de reservering toe aan de arraylist reserveringVoor.add(new BoekingsOverzicht(accommodatie, reiziger, reservering)); } } catch (SQLException throwables) { // Oeps probleem throwables.printStackTrace(); } // Geef de arrayList terug met de juiste reserveringen return reserveringVoor; } /** * Haal de reizigerscode op voor een bepaalde boeking per accommodate en datum * * @param pCode de accommodatecode * @param pDatum de datum van verblijf * @return De reizigerscode */ private String getReizigerscode(String pCode, LocalDate pDatum) { String sql = """ SELECT GeboektOp(?, ?) AS reizigerCode; """; // default waarde String reizigerCode = ""; // convert datum naar ander formaat Date date = Date.valueOf(pDatum); try { // query voorbereiden PreparedStatement ps = getStatement(sql); // Vervang de vraagtekens met de juiste waarde. Pas eventueel aan je eigen query ps.setString(1, pCode); ps.setDate(2, date); // Voer het uit ResultSet rs = executeSelectPreparedStatement(ps); // Loop net zolang als er records zijn while (rs.next()) { reizigerCode = rs.getString("reizigerCode"); } } catch (SQLException throwables) { throwables.printStackTrace(); } // Geef de reizigercode terug return reizigerCode; } /** * Haal een lijst met reserveringen op voor een bepaalde boeking per accommodate en datum * * @param pCode de accommodate code * @param pDatum de datum van verblijf * @return Lijst met reserveringen */ public List<Reiziger> GeboektOp(String pCode, LocalDate pDatum) { // Init arraylist List<Reiziger> geboektOp = new ArrayList<>(); //Stop null pointer error als datum nog niet is ingevuld. if (pDatum == null) return geboektOp; // Spring naar<SUF> String reizigerscode = getReizigerscode(pCode, pDatum); if (reizigerscode != null) { // Haal alle reserveringen op String sql = """ SELECT reiziger.voornaam, reiziger.achternaam, reiziger.adres, reiziger.postcode, reiziger.plaats, reiziger.land, CONCAT(reiziger.voornaam, ' ', reiziger.achternaam) AS hoofdreiziger FROM `reiziger` WHERE reiziger.reiziger_code = ? """; // Als je nog geen query hebt ingevuld breek dan af om een error te voorkomen. if (sql.equals("")) return geboektOp; try { // Roep de methode aan in de parent class en geef je SQL door PreparedStatement ps = getStatement(sql); // vervang de eerste vraagteken met de reizigerscode ps.setString(1, reizigerscode); // Voer je query uit ResultSet rs = executeSelectPreparedStatement(ps); // Loop net zolang als er records zijn while (rs.next()) { String voornaam = rs.getString("voornaam"); String achternaam = rs.getString("achternaam"); String adres = rs.getString("adres"); String postcode = rs.getString("postcode"); String plaats = rs.getString("plaats"); String land = rs.getString("land"); String hoofdreiziger = rs.getString("hoofdreiziger"); // Maak reserveringsobject en voeg direct toe aan arraylist geboektOp.add(new Reiziger(reizigerscode, voornaam, achternaam, adres, postcode, plaats, land, hoofdreiziger)); } } catch (SQLException throwables) { throwables.printStackTrace(); } } // Geef de array terug met reserveringen return geboektOp; } /** * Haal alle boekingen op door de gehele arraylist terug te geven * * @return Een arraylist van accommodaties */ @Override public List<BoekingsOverzicht> getAll() { return boekingsOverzicht; } /** * Haal 1 boeking op * * @return Een arraylist van accommodaties */ @Override public BoekingsOverzicht get() { // nog niet uitgewerkt geeft nu even null terug return null; } /** * Voeg een boeking toe * * @param boekingsOverzicht de boeking */ @Override public void add(BoekingsOverzicht boekingsOverzicht) { // nog niet uitgewerkt } /** * Update de boeking * * @param boekingsOverzicht de boeking */ @Override public void update(BoekingsOverzicht boekingsOverzicht) { // nog niet uitgewerkt } /** * Verwijder een boeking * * @param object de boeking */ @Override public void remove(BoekingsOverzicht object) { // nog niet uitgewerkt } }
True
2,686
23
2,887
25
2,815
19
2,887
25
3,300
26
false
false
false
false
false
true
4,450
14078_1
package domein; import java.io.FileInputStream; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; import dto.SpelerDTO; public class DomeinController{ private SpelerRepository spelerrepo; private KaartRepository kaartrepo; private EdeleRepository edelerepo; private Speler speler; private List<Speler> spelers; private Spel spel = new Spel(); private static String padTaal ="src/talen/taal.properties"; static final Properties taal = new Properties(); static { try { taal.load(new FileInputStream(padTaal)); } catch (Exception e) { e.printStackTrace(); } }; //Dit is de constructor voor de klasse DomeinController. public DomeinController(){ this.spelerrepo = new SpelerRepository(); this.kaartrepo = new KaartRepository(); this.edelerepo = new EdeleRepository(); } //Deze methode start een spel public void startSpel() { this.spel = new Spel(); } public void voegSpeler(String username, int geboortejaar) { spel.voegSpelerToe(spelerrepo.geefSpeler(username, geboortejaar)); } //Deze methode registreert een nieuwe speler public void registreer(String username, String voornaam, String achternaam, int geboortejaar) { spelerrepo.voegToe(new Speler(geboortejaar, voornaam, achternaam, username, false)); } //Deze methode geeft alle info van de speler terug. public SpelerDTO geefSpeler() { if(speler != null) { return new SpelerDTO(speler.getGeboortejaar(), speler.getVoornaam(), speler.getAchternaam(), speler.getUsername(), speler.getScore(), speler.getEdelstenen(), speler.getKaarten()); } return null; } //Deze methode geeft de score van de speler terug public int geefScore() { return speler.getScore(); } //Deze methode controleert of het spel gedaan is. public boolean isEindeSpel() { return spel.isEindeSpel(); } //Meld een speler aan, aan de hand van zijn username en geboortejaar. public void meldAan(String username, int geboortejaar) { speler = spelerrepo.geefSpeler(username, geboortejaar); } public boolean controleerSpeler(String username) { boolean antwoord =false; if(spelerrepo.bestaatSpeler(username)) { antwoord =true; } return antwoord; } public void infoSpeler(String taalKeuze) { spel.infoSpeler(taalKeuze); } public List geefKaartNiveau1(String taalkeuze) { List<Kaart> pick3 = kaartrepo.geefKaartNiveau1(); return pick3; } public List<Kaart> geefKaartNiveau2(String taalKeuze) { List<Kaart> pick3 = kaartrepo.geefKaartNiveau2(); return pick3; } public List<Kaart> geefKaartNiveau3(String taalKeuze) { List<Kaart> pick3 = kaartrepo.geefKaartNiveau3(); return pick3; } public List<Kaart> toonKaartenVanSpeler(Speler speler2) { return speler2.getKaarten(); } public List<Edele> geefEdelen(String taalkeuze) { List<Edele> pick4 = edelerepo.geefEdelen(); return pick4; /*for (Edele edele : pick4) { System.out.printf("%s %s", edele.getPrijs(), edele.getWaarde()); }*/ } }
taylon-vandenbroecke/splendor
src/domein/DomeinController.java
1,203
//Deze methode start een spel
line_comment
nl
package domein; import java.io.FileInputStream; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; import dto.SpelerDTO; public class DomeinController{ private SpelerRepository spelerrepo; private KaartRepository kaartrepo; private EdeleRepository edelerepo; private Speler speler; private List<Speler> spelers; private Spel spel = new Spel(); private static String padTaal ="src/talen/taal.properties"; static final Properties taal = new Properties(); static { try { taal.load(new FileInputStream(padTaal)); } catch (Exception e) { e.printStackTrace(); } }; //Dit is de constructor voor de klasse DomeinController. public DomeinController(){ this.spelerrepo = new SpelerRepository(); this.kaartrepo = new KaartRepository(); this.edelerepo = new EdeleRepository(); } //Deze methode<SUF> public void startSpel() { this.spel = new Spel(); } public void voegSpeler(String username, int geboortejaar) { spel.voegSpelerToe(spelerrepo.geefSpeler(username, geboortejaar)); } //Deze methode registreert een nieuwe speler public void registreer(String username, String voornaam, String achternaam, int geboortejaar) { spelerrepo.voegToe(new Speler(geboortejaar, voornaam, achternaam, username, false)); } //Deze methode geeft alle info van de speler terug. public SpelerDTO geefSpeler() { if(speler != null) { return new SpelerDTO(speler.getGeboortejaar(), speler.getVoornaam(), speler.getAchternaam(), speler.getUsername(), speler.getScore(), speler.getEdelstenen(), speler.getKaarten()); } return null; } //Deze methode geeft de score van de speler terug public int geefScore() { return speler.getScore(); } //Deze methode controleert of het spel gedaan is. public boolean isEindeSpel() { return spel.isEindeSpel(); } //Meld een speler aan, aan de hand van zijn username en geboortejaar. public void meldAan(String username, int geboortejaar) { speler = spelerrepo.geefSpeler(username, geboortejaar); } public boolean controleerSpeler(String username) { boolean antwoord =false; if(spelerrepo.bestaatSpeler(username)) { antwoord =true; } return antwoord; } public void infoSpeler(String taalKeuze) { spel.infoSpeler(taalKeuze); } public List geefKaartNiveau1(String taalkeuze) { List<Kaart> pick3 = kaartrepo.geefKaartNiveau1(); return pick3; } public List<Kaart> geefKaartNiveau2(String taalKeuze) { List<Kaart> pick3 = kaartrepo.geefKaartNiveau2(); return pick3; } public List<Kaart> geefKaartNiveau3(String taalKeuze) { List<Kaart> pick3 = kaartrepo.geefKaartNiveau3(); return pick3; } public List<Kaart> toonKaartenVanSpeler(Speler speler2) { return speler2.getKaarten(); } public List<Edele> geefEdelen(String taalkeuze) { List<Edele> pick4 = edelerepo.geefEdelen(); return pick4; /*for (Edele edele : pick4) { System.out.printf("%s %s", edele.getPrijs(), edele.getWaarde()); }*/ } }
True
939
8
1,106
9
1,056
6
1,106
9
1,243
9
false
false
false
false
false
true
2,223
189608_0
package nl.schutrup.cerina.service; import nl.schutrup.cerina.irma.client.IrmaServerClient; import nl.schutrup.cerina.irma.client.disclosure.DisclosureRequest; import nl.schutrup.cerina.irma.client.disclosure.Request; import nl.schutrup.cerina.irma.client.disclosure.SpRequest; import nl.schutrup.cerina.irma.client.issuance.CoronaIssuanceRequest; import nl.schutrup.cerina.irma.client.issuance.IssuanceRequest; import nl.schutrup.cerina.irma.client.session.result.ServerResult; import nl.schutrup.cerina.irma.client.session.start.response.ServerResponse; import org.irmacard.api.common.AttributeDisjunction; import org.irmacard.api.common.AttributeDisjunctionList; import org.irmacard.credentials.info.AttributeIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import static nl.schutrup.cerina.config.IrmaUserAttributeNames.*; @Component public class IrmaClientService { private static final Logger LOGGER = LoggerFactory.getLogger(IrmaClientService.class); @Autowired private IrmaServerClient irmaServerClient; public ServerResponse retrieveNewSessionJWT(String scenario) throws Exception { AttributeDisjunctionList attributeDisjunctions; DisclosureRequest disclosureRequest; switch (scenario) { case "scenario-1-jwt": case "scenario-5-jwt": case "scenario-16-jwt": attributeDisjunctions = buildList(IRMA_DEMO_MIJNOVERHEID_ADDRESS_CITY); // Request only woonplaats return irmaServerClient.retrieveNewSessionWithJWT(attributeDisjunctions); case "scenario-4-jwt": disclosureRequest = buildRequest(CERINA_DEMO_CERINA_ISSUER_CERINA_CREDENTIAL_NAAM, CERINA_DEMO_CERINA_ISSUER_CERINA_CREDENTIAL_STAD, CERINA_DEMO_CERINA_ISSUER_CERINA_CREDENTIAL_LEEFTIJD); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest); case "scenario-6-jwt": attributeDisjunctions = buildList(IRMA_DEMO_MIJNOVERHEID_ADDRESS_CITY, IRMA_DEMO_MIJNOVERHEID_FULLNAME_FIRSTNAME); // Now disjunction return irmaServerClient.retrieveNewSessionWithJWT(attributeDisjunctions); case "scenario-2-jwt": // Conjunction case "scenario-7-jwt": case "scenario-8-jwt": case "scenario-9-jwt": case "scenario-10-jwt": case "scenario-11-jwt": disclosureRequest = buildRequest(IRMA_DEMO_MIJNOVERHEID_ADDRESS_CITY, IRMA_DEMO_MIJNOVERHEID_FULLNAME_FIRSTNAME); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest); case "scenario-12-jwt": disclosureRequest = buildRequest(IRMA_DEMO_MIJNOVERHEID_ADDRESS_ZIPCODE); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest); case "scenario-13-jwt": disclosureRequest = buildRequest(IRMA_DEMO_MIJNOVERHEID_FULLNAME_FIRSTNAME); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest); case "scenario-15-jwt": List<String> a = new ArrayList<>(); a.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_GEVACCINEERD); a.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_AANTAL_VACCINATIES); List<String> b = new ArrayList<>(); b.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_VACCINATIEPASPOORT); b.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_SNELTEST); List<String> c = new ArrayList<>(); c.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_ANTILICHAMEN); c.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_ANTILICHAMEN_DATUM); List<String> d = new ArrayList<>(); d.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_SNELTEST); d.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_SNELTESTDATUM); List<List<String>> partialList = new ArrayList<>(); // builds an OR statement partialList.add(a); partialList.add(b); partialList.add(c); partialList.add(d); DisclosureRequest disclosureRequest1 = buildDisjunctionConjunctionRequest(partialList); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest1); default: throw new RuntimeException("Unsupported request: " + scenario); } } public AttributeDisjunctionList buildList(String... fields) { AttributeDisjunctionList attributeDisjunctions = new AttributeDisjunctionList(); AttributeDisjunction attributeDisjunction = new AttributeDisjunction(""); for (String field : fields) { AttributeIdentifier attributeIdentifier = new AttributeIdentifier(field); attributeDisjunction.add(attributeIdentifier); } attributeDisjunctions.add(attributeDisjunction); return attributeDisjunctions; } public DisclosureRequest buildDisjunctionConjunctionRequest(List<List<String>> partialList) { List<List<List<String>>> disclosureList = new ArrayList<>(); disclosureList.add(partialList); return build(disclosureList); } public DisclosureRequest buildRequest(String... fields) { List<String> discloses = new ArrayList<>(); for (String field : fields) { discloses.add(field); } List<List<List<String>>> disclosureList = new ArrayList<>(); List<List<String>> partialList = new ArrayList<>(); partialList.add(discloses); disclosureList.add(partialList); return build(disclosureList); } public DisclosureRequest build(List<List<List<String>>> disclosureList) { DisclosureRequest disclosureRequest = new DisclosureRequest(); Request request = new Request(); request.setContext("https://irma.app/ld/request/disclosure/v2"); request.setDisclose(disclosureList); SpRequest spRequest = new SpRequest(); spRequest.setRequest(request); disclosureRequest.setIat(System.currentTimeMillis() / 1000L); disclosureRequest.setSub("verification_request"); disclosureRequest.setSprequest(spRequest); return disclosureRequest; } public ServerResponse getIssuanceSession(IssuanceRequest issuanceRequest) throws Exception { try { return irmaServerClient.getIssuanceSession(issuanceRequest); } catch (Exception e) { throw new IllegalStateException(e); } } public ServerResponse getIssuanceSession(CoronaIssuanceRequest issuanceRequest) throws Exception { try { return irmaServerClient.getIssuanceSession(issuanceRequest); } catch (Exception e) { throw new IllegalStateException(e); } } public ServerResult retrieveSessionResult(String token) throws Exception { try { return irmaServerClient.retrieveSessionResult(token); } catch (Exception e) { throw e; } } public ServerResult retrieveSessionResultJWT(String token) throws Exception { return irmaServerClient.retrieveSessionResultJWT(token); } /** public ServerResponse retrieveNewSessionScenario1() throws Exception { return irmaServerClient.retrieveNewSessionScenario1(); } // OLD public ServerResponse retrieveNewSessionScenario2() throws Exception { return irmaServerClient.retrieveNewSessionScenario2(); } **/ }
bellmit/Cerina
src/main/java/nl/schutrup/cerina/service/IrmaClientService.java
2,412
// Request only woonplaats
line_comment
nl
package nl.schutrup.cerina.service; import nl.schutrup.cerina.irma.client.IrmaServerClient; import nl.schutrup.cerina.irma.client.disclosure.DisclosureRequest; import nl.schutrup.cerina.irma.client.disclosure.Request; import nl.schutrup.cerina.irma.client.disclosure.SpRequest; import nl.schutrup.cerina.irma.client.issuance.CoronaIssuanceRequest; import nl.schutrup.cerina.irma.client.issuance.IssuanceRequest; import nl.schutrup.cerina.irma.client.session.result.ServerResult; import nl.schutrup.cerina.irma.client.session.start.response.ServerResponse; import org.irmacard.api.common.AttributeDisjunction; import org.irmacard.api.common.AttributeDisjunctionList; import org.irmacard.credentials.info.AttributeIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import static nl.schutrup.cerina.config.IrmaUserAttributeNames.*; @Component public class IrmaClientService { private static final Logger LOGGER = LoggerFactory.getLogger(IrmaClientService.class); @Autowired private IrmaServerClient irmaServerClient; public ServerResponse retrieveNewSessionJWT(String scenario) throws Exception { AttributeDisjunctionList attributeDisjunctions; DisclosureRequest disclosureRequest; switch (scenario) { case "scenario-1-jwt": case "scenario-5-jwt": case "scenario-16-jwt": attributeDisjunctions = buildList(IRMA_DEMO_MIJNOVERHEID_ADDRESS_CITY); // Request only<SUF> return irmaServerClient.retrieveNewSessionWithJWT(attributeDisjunctions); case "scenario-4-jwt": disclosureRequest = buildRequest(CERINA_DEMO_CERINA_ISSUER_CERINA_CREDENTIAL_NAAM, CERINA_DEMO_CERINA_ISSUER_CERINA_CREDENTIAL_STAD, CERINA_DEMO_CERINA_ISSUER_CERINA_CREDENTIAL_LEEFTIJD); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest); case "scenario-6-jwt": attributeDisjunctions = buildList(IRMA_DEMO_MIJNOVERHEID_ADDRESS_CITY, IRMA_DEMO_MIJNOVERHEID_FULLNAME_FIRSTNAME); // Now disjunction return irmaServerClient.retrieveNewSessionWithJWT(attributeDisjunctions); case "scenario-2-jwt": // Conjunction case "scenario-7-jwt": case "scenario-8-jwt": case "scenario-9-jwt": case "scenario-10-jwt": case "scenario-11-jwt": disclosureRequest = buildRequest(IRMA_DEMO_MIJNOVERHEID_ADDRESS_CITY, IRMA_DEMO_MIJNOVERHEID_FULLNAME_FIRSTNAME); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest); case "scenario-12-jwt": disclosureRequest = buildRequest(IRMA_DEMO_MIJNOVERHEID_ADDRESS_ZIPCODE); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest); case "scenario-13-jwt": disclosureRequest = buildRequest(IRMA_DEMO_MIJNOVERHEID_FULLNAME_FIRSTNAME); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest); case "scenario-15-jwt": List<String> a = new ArrayList<>(); a.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_GEVACCINEERD); a.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_AANTAL_VACCINATIES); List<String> b = new ArrayList<>(); b.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_VACCINATIEPASPOORT); b.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_SNELTEST); List<String> c = new ArrayList<>(); c.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_ANTILICHAMEN); c.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_ANTILICHAMEN_DATUM); List<String> d = new ArrayList<>(); d.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_SNELTEST); d.add(CERINA_DEMO_CERINA_ISSUER_CERINA_CORONA_CREDENTIAL_SNELTESTDATUM); List<List<String>> partialList = new ArrayList<>(); // builds an OR statement partialList.add(a); partialList.add(b); partialList.add(c); partialList.add(d); DisclosureRequest disclosureRequest1 = buildDisjunctionConjunctionRequest(partialList); return irmaServerClient.retrieveNewSessionWithJWT(disclosureRequest1); default: throw new RuntimeException("Unsupported request: " + scenario); } } public AttributeDisjunctionList buildList(String... fields) { AttributeDisjunctionList attributeDisjunctions = new AttributeDisjunctionList(); AttributeDisjunction attributeDisjunction = new AttributeDisjunction(""); for (String field : fields) { AttributeIdentifier attributeIdentifier = new AttributeIdentifier(field); attributeDisjunction.add(attributeIdentifier); } attributeDisjunctions.add(attributeDisjunction); return attributeDisjunctions; } public DisclosureRequest buildDisjunctionConjunctionRequest(List<List<String>> partialList) { List<List<List<String>>> disclosureList = new ArrayList<>(); disclosureList.add(partialList); return build(disclosureList); } public DisclosureRequest buildRequest(String... fields) { List<String> discloses = new ArrayList<>(); for (String field : fields) { discloses.add(field); } List<List<List<String>>> disclosureList = new ArrayList<>(); List<List<String>> partialList = new ArrayList<>(); partialList.add(discloses); disclosureList.add(partialList); return build(disclosureList); } public DisclosureRequest build(List<List<List<String>>> disclosureList) { DisclosureRequest disclosureRequest = new DisclosureRequest(); Request request = new Request(); request.setContext("https://irma.app/ld/request/disclosure/v2"); request.setDisclose(disclosureList); SpRequest spRequest = new SpRequest(); spRequest.setRequest(request); disclosureRequest.setIat(System.currentTimeMillis() / 1000L); disclosureRequest.setSub("verification_request"); disclosureRequest.setSprequest(spRequest); return disclosureRequest; } public ServerResponse getIssuanceSession(IssuanceRequest issuanceRequest) throws Exception { try { return irmaServerClient.getIssuanceSession(issuanceRequest); } catch (Exception e) { throw new IllegalStateException(e); } } public ServerResponse getIssuanceSession(CoronaIssuanceRequest issuanceRequest) throws Exception { try { return irmaServerClient.getIssuanceSession(issuanceRequest); } catch (Exception e) { throw new IllegalStateException(e); } } public ServerResult retrieveSessionResult(String token) throws Exception { try { return irmaServerClient.retrieveSessionResult(token); } catch (Exception e) { throw e; } } public ServerResult retrieveSessionResultJWT(String token) throws Exception { return irmaServerClient.retrieveSessionResultJWT(token); } /** public ServerResponse retrieveNewSessionScenario1() throws Exception { return irmaServerClient.retrieveNewSessionScenario1(); } // OLD public ServerResponse retrieveNewSessionScenario2() throws Exception { return irmaServerClient.retrieveNewSessionScenario2(); } **/ }
True
1,720
7
1,996
8
2,010
5
1,996
8
2,440
7
false
false
false
false
false
true
486
23306_1
package nl.tudelft.jpacman.level; import nl.tudelft.jpacman.board.Unit; /** * Een tabel met alle (relevante) botsingen tussen verschillende typen * eenheden. * * @auteur Jeroen Roosen */ public interface CollisionMap { /** * Laat de twee eenheden in botsing komen en handelt het resultaat van de botsing af, wat mogelijk is * helemaal niets zijn. * * @param <C1> Het botstype. * @param <C2> Het botsende type (eenheid waarin is verplaatst). * @param botser De eenheid die de botsing veroorzaakt door een veld te bezetten * er staat al een ander apparaat op. * @param botst De eenheid die zich al op het veld bevindt dat wordt binnengevallen. */ <C1 extends Unit, C2 extends Unit> void collide(C1 botser, C2 botst); }
Eragon6080/examVVPackman
src/main/java/nl/tudelft/jpacman/level/CollisionMap.java
277
/** * Laat de twee eenheden in botsing komen en handelt het resultaat van de botsing af, wat mogelijk is * helemaal niets zijn. * * @param <C1> Het botstype. * @param <C2> Het botsende type (eenheid waarin is verplaatst). * @param botser De eenheid die de botsing veroorzaakt door een veld te bezetten * er staat al een ander apparaat op. * @param botst De eenheid die zich al op het veld bevindt dat wordt binnengevallen. */
block_comment
nl
package nl.tudelft.jpacman.level; import nl.tudelft.jpacman.board.Unit; /** * Een tabel met alle (relevante) botsingen tussen verschillende typen * eenheden. * * @auteur Jeroen Roosen */ public interface CollisionMap { /** * Laat de twee<SUF>*/ <C1 extends Unit, C2 extends Unit> void collide(C1 botser, C2 botst); }
True
233
145
279
163
236
135
279
163
281
163
false
false
false
false
false
true
119
125583_11
// Pets // Dog // Cat // Specific: // Lion int numberOfChildren; // Tiger int numberOfStripes; // Hond nameOfOwner, favoriteFoodBrand, species // Kat nameOfOwner, favoriteFoodBrand, species, indoorOutdoor // Wolf. packName // Zoo animals: // extends ZooAnimal // String nameOfPaddock; // Lion, tiger, Wolf - Vind ik een Zoo eigenschap // String dayLastFed; // Lion, tiger, Wolf // String landOfOrigin; // Lion, tiger, Wolf package nl.novi.javaprogrammeren.overerving; public abstract class Animal { private String name; // Lion, tiger, Dog, Cat, Wolf private final String gender; // Lion, tiger, Dog, Cat, Wolf // Protected: An access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses. (Not in superclass!) protected Animal(String name, String gender) { this.name = name; this.gender = gender; } public String getName() { return this.name; } public String getGender() { return this.gender; } public void setName(String name) { this.name = name; } public void move() { System.out.println(this.name + " has moved 0.25 meters."); } public void sleep() { System.out.println("The animal is going to sleep for 8 hours."); } public void eat(String food) { System.out.println(this.getName() + " is eating " + food); } // Dog of Cat moet een specifiek eigen geluid hebben. Vandaar @Overrule in de subclass public abstract void makeSound(); }
Aphelion-im/SD-BE-JP-Overerving-02-opdracht
src/nl/novi/javaprogrammeren/overerving/Animal.java
455
// Dog of Cat moet een specifiek eigen geluid hebben. Vandaar @Overrule in de subclass
line_comment
nl
// Pets // Dog // Cat // Specific: // Lion int numberOfChildren; // Tiger int numberOfStripes; // Hond nameOfOwner, favoriteFoodBrand, species // Kat nameOfOwner, favoriteFoodBrand, species, indoorOutdoor // Wolf. packName // Zoo animals: // extends ZooAnimal // String nameOfPaddock; // Lion, tiger, Wolf - Vind ik een Zoo eigenschap // String dayLastFed; // Lion, tiger, Wolf // String landOfOrigin; // Lion, tiger, Wolf package nl.novi.javaprogrammeren.overerving; public abstract class Animal { private String name; // Lion, tiger, Dog, Cat, Wolf private final String gender; // Lion, tiger, Dog, Cat, Wolf // Protected: An access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses. (Not in superclass!) protected Animal(String name, String gender) { this.name = name; this.gender = gender; } public String getName() { return this.name; } public String getGender() { return this.gender; } public void setName(String name) { this.name = name; } public void move() { System.out.println(this.name + " has moved 0.25 meters."); } public void sleep() { System.out.println("The animal is going to sleep for 8 hours."); } public void eat(String food) { System.out.println(this.getName() + " is eating " + food); } // Dog of<SUF> public abstract void makeSound(); }
True
372
23
434
26
418
21
434
26
475
24
false
false
false
false
false
true
1,213
79474_1
package nl.han.ica.icss.checker; import nl.han.ica.datastructures.HANLinkedList; import nl.han.ica.datastructures.IHANLinkedList; import nl.han.ica.icss.ast.*; import nl.han.ica.icss.ast.literals.*; import nl.han.ica.icss.ast.types.ExpressionType; import java.util.HashMap; public class Checker { private IHANLinkedList<HashMap<String, ExpressionType>> variableTypes; public void check(AST ast) { //ALL CODE Checker variableTypes = new HANLinkedList<>(); checkStyleSheet(ast.root); } private void checkStyleSheet(Stylesheet stylesheet){ variableTypes.addFirst(new HashMap<>()); for(ASTNode child: stylesheet.getChildren()){ String childLabel = child.getNodeLabel(); if(childLabel.equals("Stylerule")){ checkStylerule((Stylerule) child); } if(childLabel.contains("VariableAssignment")){ checkVariableAssignment((VariableAssignment) child); } } variableTypes.removeFirst(); } private void checkStylerule(Stylerule stylerule){ variableTypes.addFirst(new HashMap<>()); checkBody(stylerule); variableTypes.removeFirst(); } private void checkBody(ASTNode astNode){ for(ASTNode child: astNode.getChildren()){ String childLabel = child.getNodeLabel(); if(childLabel.equals("Declaration")){ checkDeclaration((Declaration) child); } if(childLabel.contains("VariableAssignment")){ checkVariableAssignment((VariableAssignment) child); } if(childLabel.equals("If_Clause")){ checkIfClause((IfClause) child); } } } private void checkDeclaration(Declaration declaration) { variableTypes.addFirst(new HashMap<>()); Expression expression = declaration.expression; ExpressionType expressionType = checkExpressionType(expression); //CH04 kijkt of literal past bij de naam if (expressionType == ExpressionType.UNDEFINED) { declaration.setError("ERROR_CODE 1: INVALID"); } if (declaration.property.name.equals("color") || declaration.property.name.equals("background-color")){ if (expressionType != ExpressionType.COLOR){ declaration.setError("ERROR_CODE 4:" + declaration.property.name+" "+declaration.expression.getNodeLabel() + " IS NOT VALID FOR PROPERTY"); } } if(declaration.property.name.equals("width") || declaration.property.name.equals("height")){ if(expressionType != ExpressionType.PIXEL && expressionType != ExpressionType.PERCENTAGE){ declaration.setError("ERROR_CODE 4:" + declaration.property.name+" "+declaration.expression.getNodeLabel() + " IS NOT VALID FOR PROPERTY"); } } variableTypes.removeFirst(); } private void checkVariableAssignment(VariableAssignment variableAssignment){ Expression expression = variableAssignment.expression; VariableReference variableReference = variableAssignment.name; ExpressionType expressionType = checkExpressionType(expression); if (expressionType == ExpressionType.UNDEFINED) { //check of variable een waarde heeft, DOET DE PARSER OOK AL variableAssignment.setError("ERROR_CODE 1: VARIABLE HAS NO VALUE"); } variableTypes.getFirst().put(variableReference.name,expressionType); } private void checkIfClause(IfClause ifClause) { variableTypes.addFirst(new HashMap<>()); ExpressionType expressionType = checkExpressionType(ifClause.conditionalExpression); if (expressionType != ExpressionType.BOOL) { //CH05 if clause moet een boolean zijn ifClause.setError("ERROR_CODE 3: CONDITIONAL EXPRESSION IS NOT A BOOLEAN"); } checkBody(ifClause); for (ASTNode node: ifClause.getChildren()) { if (node instanceof ElseClause) { checkElseClause((ElseClause) node); } } variableTypes.removeFirst(); } private void checkElseClause(ElseClause elseClause){ variableTypes.addFirst(new HashMap<>()); checkBody(elseClause); variableTypes.removeFirst(); } private ExpressionType checkExpressionType(Expression expression) { ExpressionType expressionType; if (expression instanceof Operation) { expressionType = this.checkOperation((Operation) expression); } else if (expression instanceof VariableReference) { expressionType = this.checkVariableReference((VariableReference) expression); } else if (expression instanceof Literal) { expressionType = this.checkLiteral((Literal) expression); } else { expressionType = ExpressionType.UNDEFINED; } return expressionType; } private ExpressionType checkLiteral(Literal expressionType){ if(expressionType instanceof PixelLiteral){ return ExpressionType.PIXEL; } if(expressionType instanceof PercentageLiteral){ return ExpressionType.PERCENTAGE; } if(expressionType instanceof ScalarLiteral){ return ExpressionType.SCALAR; } if(expressionType instanceof ColorLiteral){ return ExpressionType.COLOR; } if(expressionType instanceof BoolLiteral){ return ExpressionType.BOOL; } else{ return ExpressionType.UNDEFINED; } } private ExpressionType checkOperation(Operation operation) { ExpressionType lhs = checkExpressionType(operation.lhs); ExpressionType rhs = checkExpressionType(operation.rhs); //CH03 kleuren mogen niet gebruikt worden in operatoren if(lhs == ExpressionType.BOOL || rhs == ExpressionType.BOOL || lhs == ExpressionType.COLOR || rhs == ExpressionType.COLOR){ operation.setError("ERROR_CODE 7: BOOL/COLOR CAN NOT BE USED IN OPERATION"); return ExpressionType.UNDEFINED; } return lhs; } private ExpressionType checkVariableReference(VariableReference variableReference) { ExpressionType expressionType = ExpressionType.UNDEFINED; for (int i = 0; i < variableTypes.getSize(); i++) { if (variableTypes.get(i) != null && variableTypes.get(i).containsKey(variableReference.name)) { expressionType = variableTypes.get(i).get(variableReference.name); } } if (expressionType == ExpressionType.UNDEFINED) { //CH01 && CH06 Variabelen moeten een waarde hebben en mogen niet gebruikt worden als ze niet bestaan/buiten de scope vallen variableReference.setError("ERROR_CODE 2: VARIABLE NOT FOUND OR NOT USED IN SCOPE"); return null; } return expressionType; } }
NityeSkyRodin/CSS-Parser
icss2022-sep-main/icss2022-sep-main/icss2022-sep-main/startcode/src/main/java/nl/han/ica/icss/checker/Checker.java
1,835
//CH04 kijkt of literal past bij de naam
line_comment
nl
package nl.han.ica.icss.checker; import nl.han.ica.datastructures.HANLinkedList; import nl.han.ica.datastructures.IHANLinkedList; import nl.han.ica.icss.ast.*; import nl.han.ica.icss.ast.literals.*; import nl.han.ica.icss.ast.types.ExpressionType; import java.util.HashMap; public class Checker { private IHANLinkedList<HashMap<String, ExpressionType>> variableTypes; public void check(AST ast) { //ALL CODE Checker variableTypes = new HANLinkedList<>(); checkStyleSheet(ast.root); } private void checkStyleSheet(Stylesheet stylesheet){ variableTypes.addFirst(new HashMap<>()); for(ASTNode child: stylesheet.getChildren()){ String childLabel = child.getNodeLabel(); if(childLabel.equals("Stylerule")){ checkStylerule((Stylerule) child); } if(childLabel.contains("VariableAssignment")){ checkVariableAssignment((VariableAssignment) child); } } variableTypes.removeFirst(); } private void checkStylerule(Stylerule stylerule){ variableTypes.addFirst(new HashMap<>()); checkBody(stylerule); variableTypes.removeFirst(); } private void checkBody(ASTNode astNode){ for(ASTNode child: astNode.getChildren()){ String childLabel = child.getNodeLabel(); if(childLabel.equals("Declaration")){ checkDeclaration((Declaration) child); } if(childLabel.contains("VariableAssignment")){ checkVariableAssignment((VariableAssignment) child); } if(childLabel.equals("If_Clause")){ checkIfClause((IfClause) child); } } } private void checkDeclaration(Declaration declaration) { variableTypes.addFirst(new HashMap<>()); Expression expression = declaration.expression; ExpressionType expressionType = checkExpressionType(expression); //CH04 kijkt<SUF> if (expressionType == ExpressionType.UNDEFINED) { declaration.setError("ERROR_CODE 1: INVALID"); } if (declaration.property.name.equals("color") || declaration.property.name.equals("background-color")){ if (expressionType != ExpressionType.COLOR){ declaration.setError("ERROR_CODE 4:" + declaration.property.name+" "+declaration.expression.getNodeLabel() + " IS NOT VALID FOR PROPERTY"); } } if(declaration.property.name.equals("width") || declaration.property.name.equals("height")){ if(expressionType != ExpressionType.PIXEL && expressionType != ExpressionType.PERCENTAGE){ declaration.setError("ERROR_CODE 4:" + declaration.property.name+" "+declaration.expression.getNodeLabel() + " IS NOT VALID FOR PROPERTY"); } } variableTypes.removeFirst(); } private void checkVariableAssignment(VariableAssignment variableAssignment){ Expression expression = variableAssignment.expression; VariableReference variableReference = variableAssignment.name; ExpressionType expressionType = checkExpressionType(expression); if (expressionType == ExpressionType.UNDEFINED) { //check of variable een waarde heeft, DOET DE PARSER OOK AL variableAssignment.setError("ERROR_CODE 1: VARIABLE HAS NO VALUE"); } variableTypes.getFirst().put(variableReference.name,expressionType); } private void checkIfClause(IfClause ifClause) { variableTypes.addFirst(new HashMap<>()); ExpressionType expressionType = checkExpressionType(ifClause.conditionalExpression); if (expressionType != ExpressionType.BOOL) { //CH05 if clause moet een boolean zijn ifClause.setError("ERROR_CODE 3: CONDITIONAL EXPRESSION IS NOT A BOOLEAN"); } checkBody(ifClause); for (ASTNode node: ifClause.getChildren()) { if (node instanceof ElseClause) { checkElseClause((ElseClause) node); } } variableTypes.removeFirst(); } private void checkElseClause(ElseClause elseClause){ variableTypes.addFirst(new HashMap<>()); checkBody(elseClause); variableTypes.removeFirst(); } private ExpressionType checkExpressionType(Expression expression) { ExpressionType expressionType; if (expression instanceof Operation) { expressionType = this.checkOperation((Operation) expression); } else if (expression instanceof VariableReference) { expressionType = this.checkVariableReference((VariableReference) expression); } else if (expression instanceof Literal) { expressionType = this.checkLiteral((Literal) expression); } else { expressionType = ExpressionType.UNDEFINED; } return expressionType; } private ExpressionType checkLiteral(Literal expressionType){ if(expressionType instanceof PixelLiteral){ return ExpressionType.PIXEL; } if(expressionType instanceof PercentageLiteral){ return ExpressionType.PERCENTAGE; } if(expressionType instanceof ScalarLiteral){ return ExpressionType.SCALAR; } if(expressionType instanceof ColorLiteral){ return ExpressionType.COLOR; } if(expressionType instanceof BoolLiteral){ return ExpressionType.BOOL; } else{ return ExpressionType.UNDEFINED; } } private ExpressionType checkOperation(Operation operation) { ExpressionType lhs = checkExpressionType(operation.lhs); ExpressionType rhs = checkExpressionType(operation.rhs); //CH03 kleuren mogen niet gebruikt worden in operatoren if(lhs == ExpressionType.BOOL || rhs == ExpressionType.BOOL || lhs == ExpressionType.COLOR || rhs == ExpressionType.COLOR){ operation.setError("ERROR_CODE 7: BOOL/COLOR CAN NOT BE USED IN OPERATION"); return ExpressionType.UNDEFINED; } return lhs; } private ExpressionType checkVariableReference(VariableReference variableReference) { ExpressionType expressionType = ExpressionType.UNDEFINED; for (int i = 0; i < variableTypes.getSize(); i++) { if (variableTypes.get(i) != null && variableTypes.get(i).containsKey(variableReference.name)) { expressionType = variableTypes.get(i).get(variableReference.name); } } if (expressionType == ExpressionType.UNDEFINED) { //CH01 && CH06 Variabelen moeten een waarde hebben en mogen niet gebruikt worden als ze niet bestaan/buiten de scope vallen variableReference.setError("ERROR_CODE 2: VARIABLE NOT FOUND OR NOT USED IN SCOPE"); return null; } return expressionType; } }
True
1,349
13
1,483
14
1,591
12
1,483
14
1,841
13
false
false
false
false
false
true
3,178
4334_3
/* Model.java * ============================================================ * Copyright (C) 2001-2009 Universiteit Gent * * Bijlage bij de cursus 'Programmeren 2'. * * Auteur: Kris Coolsaet */ package ch9k.core; import java.awt.EventQueue; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; /** * Gemeenschappelijke bovenklasse van alle modellen die gebruik maken van * luisteraars van het type {@link ChangeListener}. */ public class Model { /** * Lijst van geregistreerde luisteraars. */ private EventListenerList listenerList = new EventListenerList(); /** * Registreer een luisteraar. */ public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } /** * Maak registratie ongedaan. */ public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } /** * Uniek gebeurtenisobject met dit model als bron. */ private final ChangeEvent changeEvent = new ChangeEvent(this); /** * Behandel een ChangeEvent-gebeurtenis die van het model * afkomstig is door een nieuwe gebeurtenis aan alle luisteraars * door te geven. De nieuwe gebeurtenis heeft dit model als bron. */ protected void fireStateChanged() { if(EventQueue.isDispatchThread()) { stateChange(); } else { EventQueue.invokeLater(new Runnable() { public void run() { stateChange(); } }); } } private void stateChange() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { ((ChangeListener) listeners[i + 1]).stateChanged(changeEvent); } } } }
javache/ChatHammer-9000
src/ch9k/core/Model.java
574
/** * Registreer een luisteraar. */
block_comment
nl
/* Model.java * ============================================================ * Copyright (C) 2001-2009 Universiteit Gent * * Bijlage bij de cursus 'Programmeren 2'. * * Auteur: Kris Coolsaet */ package ch9k.core; import java.awt.EventQueue; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; /** * Gemeenschappelijke bovenklasse van alle modellen die gebruik maken van * luisteraars van het type {@link ChangeListener}. */ public class Model { /** * Lijst van geregistreerde luisteraars. */ private EventListenerList listenerList = new EventListenerList(); /** * Registreer een luisteraar.<SUF>*/ public void addChangeListener(ChangeListener l) { listenerList.add(ChangeListener.class, l); } /** * Maak registratie ongedaan. */ public void removeChangeListener(ChangeListener l) { listenerList.remove(ChangeListener.class, l); } /** * Uniek gebeurtenisobject met dit model als bron. */ private final ChangeEvent changeEvent = new ChangeEvent(this); /** * Behandel een ChangeEvent-gebeurtenis die van het model * afkomstig is door een nieuwe gebeurtenis aan alle luisteraars * door te geven. De nieuwe gebeurtenis heeft dit model als bron. */ protected void fireStateChanged() { if(EventQueue.isDispatchThread()) { stateChange(); } else { EventQueue.invokeLater(new Runnable() { public void run() { stateChange(); } }); } } private void stateChange() { Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { ((ChangeListener) listeners[i + 1]).stateChanged(changeEvent); } } } }
True
453
14
510
14
512
16
510
14
565
15
false
false
false
false
false
true
200
52553_2
/** * Abstract class Figuur - write a description of the class here * * @author (your name here) * @version (version number or date here) */ public abstract class Figuur { // instance variables - replace the example below with your own private int xPosition; private int yPosition; private String color; private boolean isVisible; /** * Maak een nieuw Figuur */ public Figuur(int xPosition, int yPosition, String color) { this.xPosition = xPosition; this.yPosition = yPosition; this.color = color; } /** * Maak dit figuur zichtbaar */ public void maakZichtbaar() { isVisible = true; teken(); } /** * Maak dit figuur onzichtbaar */ public void maakOnzichtbaar() { wis(); isVisible = false; } /** * Beweeg dit figuur 20 pixels naar rechts */ public void beweegRechts() { beweegHorizontaal(20); } /** * Beweeg dit figuur 20 pixels naar links */ public void beweegLinks() { beweegHorizontaal(-20); } /** * Beweeg dit figuur 20 pixels naar boven */ public void beweegBoven() { beweegVertikaal(-20); } /** * Beweeg dit figuur 20 pixels naar beneden */ public void beweegBeneden() { beweegVertikaal(20); } /** * Beweeg dit figuur horizontaal adhv het aantal gegeven pixels */ public void beweegHorizontaal(int distance) { wis(); xPosition += distance; teken(); } /** * Beweeg dit figuur vertikaal adhv het aantal gegeven pixels */ public void beweegVertikaal(int distance) { wis(); yPosition += distance; teken(); } /** * Beweeg langzaam dit figuur horizontaal adhv het aantal gegeven pixels */ public void traagBeweegHorizontaal(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { xPosition += delta; teken(); } } /** * Beweeg langzaam dit figuur verticaal adhv het aantal gegeven pixels */ public void traagBeweegVertikaal(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { yPosition += delta; teken(); } } /** * Pas de kleur aan, mogelijke kleuren zijn "red", "yellow", "blue", "green", "magenta" and "black". */ public void veranderKleur(String newColor) { color = newColor; teken(); } /** * Wis het figuur van het scherm */ public void wis() { if(isVisible) { Canvas canvas = Canvas.getCanvas(); canvas.erase(this); } } /** * Bepaal of het figuur zichtbaar is */ public boolean isZichtbaar() { return isVisible; } /** * Geef de kleur van het figuur */ public String getKleur() { return color; } /** * Geef de positie op de x-as */ public int getXPositie() { return xPosition; } /** * Geef de positie op de y-as */ public int getYPositie() { return yPosition; } /** * Teken dit figuur op het scherm. * Dit is een abstracte method, het moet in de subclasses gedefinieerd worden. */ public abstract void teken(); }
BenVandenberk/vdab
05 OOP/Voorbeelden/FigurenVoorbeeld04/Figuur.java
1,207
/** * Maak een nieuw Figuur */
block_comment
nl
/** * Abstract class Figuur - write a description of the class here * * @author (your name here) * @version (version number or date here) */ public abstract class Figuur { // instance variables - replace the example below with your own private int xPosition; private int yPosition; private String color; private boolean isVisible; /** * Maak een nieuw<SUF>*/ public Figuur(int xPosition, int yPosition, String color) { this.xPosition = xPosition; this.yPosition = yPosition; this.color = color; } /** * Maak dit figuur zichtbaar */ public void maakZichtbaar() { isVisible = true; teken(); } /** * Maak dit figuur onzichtbaar */ public void maakOnzichtbaar() { wis(); isVisible = false; } /** * Beweeg dit figuur 20 pixels naar rechts */ public void beweegRechts() { beweegHorizontaal(20); } /** * Beweeg dit figuur 20 pixels naar links */ public void beweegLinks() { beweegHorizontaal(-20); } /** * Beweeg dit figuur 20 pixels naar boven */ public void beweegBoven() { beweegVertikaal(-20); } /** * Beweeg dit figuur 20 pixels naar beneden */ public void beweegBeneden() { beweegVertikaal(20); } /** * Beweeg dit figuur horizontaal adhv het aantal gegeven pixels */ public void beweegHorizontaal(int distance) { wis(); xPosition += distance; teken(); } /** * Beweeg dit figuur vertikaal adhv het aantal gegeven pixels */ public void beweegVertikaal(int distance) { wis(); yPosition += distance; teken(); } /** * Beweeg langzaam dit figuur horizontaal adhv het aantal gegeven pixels */ public void traagBeweegHorizontaal(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { xPosition += delta; teken(); } } /** * Beweeg langzaam dit figuur verticaal adhv het aantal gegeven pixels */ public void traagBeweegVertikaal(int distance) { int delta; if(distance < 0) { delta = -1; distance = -distance; } else { delta = 1; } for(int i = 0; i < distance; i++) { yPosition += delta; teken(); } } /** * Pas de kleur aan, mogelijke kleuren zijn "red", "yellow", "blue", "green", "magenta" and "black". */ public void veranderKleur(String newColor) { color = newColor; teken(); } /** * Wis het figuur van het scherm */ public void wis() { if(isVisible) { Canvas canvas = Canvas.getCanvas(); canvas.erase(this); } } /** * Bepaal of het figuur zichtbaar is */ public boolean isZichtbaar() { return isVisible; } /** * Geef de kleur van het figuur */ public String getKleur() { return color; } /** * Geef de positie op de x-as */ public int getXPositie() { return xPosition; } /** * Geef de positie op de y-as */ public int getYPositie() { return yPosition; } /** * Teken dit figuur op het scherm. * Dit is een abstracte method, het moet in de subclasses gedefinieerd worden. */ public abstract void teken(); }
True
1,008
13
1,068
13
1,138
12
1,068
13
1,220
14
false
false
false
false
false
true
3,147
33023_0
package be.pxl.h9.oef2; import java.time.LocalDate; public class VerkoopApp { public static void main(String[] args) { TeVerkopenBouwGrond bouw = new TeVerkopenBouwGrond("12ER", 12.4, "Open Bebouwing"); bouw.doeEenBod(10000, LocalDate.of(2021, 12, 7)); //nog geen notaris ==> bod wordt niet geregistreerd bouw.wijsEenNotarisToe("Dirk Peeters", LocalDate.of(2021, 12, 7)); bouw.doeEenBod(100000, LocalDate.of(2021, 12, 10)); // bod te vroeg bouw.doeEenBod(150000, LocalDate.of(2021, 12, 23)); bouw.doeEenBod(120000, LocalDate.of(2021, 12, 27)); // bod is lager ==> bod wordt niet geregistreerd bouw.doeEenBod(175000, LocalDate.of(2022, 1, 4)); System.out.println("Het hoogste bod is " + bouw.getHoogsteBod()); System.out.println("De notaris is " + bouw.getNotaris()); bouw.wijsEenNotarisToe("Ken Jans", LocalDate.now()); } }
jacymeertPXL/ComputerScience
Computer_Science/Batcholer/2022-2023/Herexams/Java/Oefeningen/H8/H8/extraoef1/VerkoopApp.java
381
//nog geen notaris ==> bod wordt niet geregistreerd
line_comment
nl
package be.pxl.h9.oef2; import java.time.LocalDate; public class VerkoopApp { public static void main(String[] args) { TeVerkopenBouwGrond bouw = new TeVerkopenBouwGrond("12ER", 12.4, "Open Bebouwing"); bouw.doeEenBod(10000, LocalDate.of(2021, 12, 7)); //nog geen<SUF> bouw.wijsEenNotarisToe("Dirk Peeters", LocalDate.of(2021, 12, 7)); bouw.doeEenBod(100000, LocalDate.of(2021, 12, 10)); // bod te vroeg bouw.doeEenBod(150000, LocalDate.of(2021, 12, 23)); bouw.doeEenBod(120000, LocalDate.of(2021, 12, 27)); // bod is lager ==> bod wordt niet geregistreerd bouw.doeEenBod(175000, LocalDate.of(2022, 1, 4)); System.out.println("Het hoogste bod is " + bouw.getHoogsteBod()); System.out.println("De notaris is " + bouw.getNotaris()); bouw.wijsEenNotarisToe("Ken Jans", LocalDate.now()); } }
True
367
15
411
16
361
13
411
16
417
13
false
false
false
false
false
true
1,147
190865_4
package LES1.P5; import java.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class ProductDAOPsql implements ProductDAO { private Connection conn; private OVChipkaartDAOPsql ovcdao; public ProductDAOPsql(Connection conn) { this.conn = conn; } public ProductDAOPsql(Connection conn, OVChipkaartDAOPsql ovcdao) { this.conn = conn; this.ovcdao = ovcdao; } public void setOvcdao(OVChipkaartDAOPsql ovcdao) { this.ovcdao = ovcdao; } @Override public boolean save(Product product) { String SQL = "INSERT INTO product VALUES (?, ?, ?, ?)"; String SQL2 = "INSERT INTO ov_chipkaart_product VALUES (?, ?, ?, ?)"; try { PreparedStatement prestat = conn.prepareStatement(SQL); prestat.setInt(1, product.getProduct_nummer()); prestat.setString(2, product.getNaam()); prestat.setString(3, product.getBeschrijving()); prestat.setFloat(4, product.getPrijs()); prestat.executeUpdate(); for (OVChipkaart o : product.getOVChipkaarten()) { PreparedStatement prestat2 = conn.prepareStatement(SQL2); prestat2.setInt(1, o.getKaart_nummer()); prestat2.setInt(2, product.getProduct_nummer()); prestat2.setString(3, "actief"); prestat2.setDate(4, Date.valueOf(LocalDate.now())); prestat2.executeUpdate(); } return true; } catch (SQLException throwables) { throwables.printStackTrace(); } return false; } @Override public boolean update(Product product) { // De update functie is niet heel erg uitgebreid of complex, maar als standaard heb ik genomen dat de prijs van het product met 5 word verhoogd String SQL = "UPDATE product SET prijs = prijs + 5 WHERE product_nummer = ?"; // Ik nam aan dat "last update" in de koppel tabel stond voor wanneer een product of ovchipkaart voor het laatst is veranderd/geupdate // En ik verander de prijs van een product, dus dan moet in de koppel tabel de "last update" upgedate worden op de plekken met dat zelfde product nummer String SQL2 = "DELETE FROM ov_chipkaart_product WHERE product_nummer = ?"; String SQL3 = "INSERT INTO ov_chipkaart_product VALUES (?, ?, ?, ?)"; try { PreparedStatement prestat = conn.prepareStatement(SQL); PreparedStatement prestat2 = conn.prepareStatement(SQL2); prestat.setInt(1, product.getProduct_nummer()); prestat2.setInt(1, product.getProduct_nummer()); prestat.executeUpdate(); prestat2.executeUpdate(); for (OVChipkaart o : product.getOVChipkaarten()) { PreparedStatement prestat3 = conn.prepareStatement(SQL3); prestat3.setInt(1, o.getKaart_nummer()); prestat3.setInt(2, product.getProduct_nummer()); prestat3.setString(3, "actief"); prestat3.setDate(4, Date.valueOf(LocalDate.now())); prestat3.executeUpdate(); } return true; } catch (SQLException throwables) { throwables.printStackTrace(); } return false; } @Override public boolean delete(Product product) { String SQL = "DELETE FROM product WHERE product_nummer = ?"; String SQL2 = "DELETE FROM ov_chipkaart_product WHERE product_nummer = ?"; try { PreparedStatement prestat = conn.prepareStatement(SQL); PreparedStatement prestat2 = conn.prepareStatement(SQL2); prestat.setInt(1, product.getProduct_nummer()); prestat2.setInt(1, product.getProduct_nummer()); prestat2.executeUpdate(); prestat.executeUpdate(); return true; } catch (SQLException throwables) { throwables.printStackTrace(); } return false; } public List<Product> findByOVChipkaart(OVChipkaart ovChipkaart) { String SQL = "SELECT ov_chipkaart_product.kaart_nummer, product.product_nummer, product.naam, product.beschrijving, product.prijs " + "FROM product " + "JOIN ov_chipkaart_product " + "ON ov_chipkaart_product.product_nummer = product.product_nummer " + "WHERE ov_chipkaart_product.kaart_nummer = ? " + "ORDER BY kaart_nummer, product_nummer"; try { PreparedStatement prestat = conn.prepareStatement(SQL); prestat.setInt(1, ovChipkaart.getKaart_nummer()); ResultSet rs = prestat.executeQuery(); List<Product> producten = new ArrayList<>(); while (rs.next()) { int prnr = rs.getInt("product_nummer"); String nm = rs.getString("naam"); String besch = rs.getString("beschrijving"); Float prijs = rs.getFloat("prijs"); Product pr = new Product(prnr, nm, besch, prijs); pr.addOVChipkaart(ovChipkaart); producten.add(pr); } return producten; } catch (SQLException throwables) { throwables.printStackTrace(); } return null; } public List<Product> findAll(){ // Hier veranderd van "SELECT * FROM product;" naar deze query met JOIN zodat je ook de ovchipkaarten ook op haalt en toevoegd aan de producten // Hetzelfde in OVChipkaartDAOPsql String SQL = "SELECT ov_chipkaart_product.kaart_nummer, ov_chipkaart.geldig_tot, ov_chipkaart.klasse, ov_chipkaart.saldo, ov_chipkaart.reiziger_id, product.product_nummer, product.naam, product.beschrijving, product.prijs " + "FROM product " + "JOIN ov_chipkaart_product " + "ON ov_chipkaart_product.product_nummer = product.product_nummer " + "JOIN ov_chipkaart " + "ON ov_chipkaart_product.kaart_nummer = ov_chipkaart.kaart_nummer " + "ORDER BY kaart_nummer, product_nummer;"; try { PreparedStatement prestat = conn.prepareStatement(SQL); ResultSet rs = prestat.executeQuery(); List<Product> producten = new ArrayList<>(); while(rs.next()) { int prnr = rs.getInt("product_nummer"); String nm = rs.getString("naam"); String besch = rs.getString("beschrijving"); Float prijs = rs.getFloat("prijs"); int knm = rs.getInt("kaart_nummer"); Date geldigTot = rs.getDate("geldig_tot"); int klasse = rs.getInt("klasse"); float saldo = rs.getFloat("saldo"); int rid = rs.getInt("reiziger_id"); OVChipkaart ov = new OVChipkaart(knm, geldigTot, klasse, saldo, rid); Product pr = new Product(prnr, nm, besch, prijs); for(Product p : producten){ if(p.getProduct_nummer() == pr.getProduct_nummer()){ p.addOVChipkaart(ov); break; } } pr.addOVChipkaart(ov); producten.add(pr); } return producten; } catch (SQLException throwables) { throwables.printStackTrace(); } return null; } }
MorrisT011/DP_OV-Chipkaart2
src/LES1/P5/ProductDAOPsql.java
2,247
// Hetzelfde in OVChipkaartDAOPsql
line_comment
nl
package LES1.P5; import java.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class ProductDAOPsql implements ProductDAO { private Connection conn; private OVChipkaartDAOPsql ovcdao; public ProductDAOPsql(Connection conn) { this.conn = conn; } public ProductDAOPsql(Connection conn, OVChipkaartDAOPsql ovcdao) { this.conn = conn; this.ovcdao = ovcdao; } public void setOvcdao(OVChipkaartDAOPsql ovcdao) { this.ovcdao = ovcdao; } @Override public boolean save(Product product) { String SQL = "INSERT INTO product VALUES (?, ?, ?, ?)"; String SQL2 = "INSERT INTO ov_chipkaart_product VALUES (?, ?, ?, ?)"; try { PreparedStatement prestat = conn.prepareStatement(SQL); prestat.setInt(1, product.getProduct_nummer()); prestat.setString(2, product.getNaam()); prestat.setString(3, product.getBeschrijving()); prestat.setFloat(4, product.getPrijs()); prestat.executeUpdate(); for (OVChipkaart o : product.getOVChipkaarten()) { PreparedStatement prestat2 = conn.prepareStatement(SQL2); prestat2.setInt(1, o.getKaart_nummer()); prestat2.setInt(2, product.getProduct_nummer()); prestat2.setString(3, "actief"); prestat2.setDate(4, Date.valueOf(LocalDate.now())); prestat2.executeUpdate(); } return true; } catch (SQLException throwables) { throwables.printStackTrace(); } return false; } @Override public boolean update(Product product) { // De update functie is niet heel erg uitgebreid of complex, maar als standaard heb ik genomen dat de prijs van het product met 5 word verhoogd String SQL = "UPDATE product SET prijs = prijs + 5 WHERE product_nummer = ?"; // Ik nam aan dat "last update" in de koppel tabel stond voor wanneer een product of ovchipkaart voor het laatst is veranderd/geupdate // En ik verander de prijs van een product, dus dan moet in de koppel tabel de "last update" upgedate worden op de plekken met dat zelfde product nummer String SQL2 = "DELETE FROM ov_chipkaart_product WHERE product_nummer = ?"; String SQL3 = "INSERT INTO ov_chipkaart_product VALUES (?, ?, ?, ?)"; try { PreparedStatement prestat = conn.prepareStatement(SQL); PreparedStatement prestat2 = conn.prepareStatement(SQL2); prestat.setInt(1, product.getProduct_nummer()); prestat2.setInt(1, product.getProduct_nummer()); prestat.executeUpdate(); prestat2.executeUpdate(); for (OVChipkaart o : product.getOVChipkaarten()) { PreparedStatement prestat3 = conn.prepareStatement(SQL3); prestat3.setInt(1, o.getKaart_nummer()); prestat3.setInt(2, product.getProduct_nummer()); prestat3.setString(3, "actief"); prestat3.setDate(4, Date.valueOf(LocalDate.now())); prestat3.executeUpdate(); } return true; } catch (SQLException throwables) { throwables.printStackTrace(); } return false; } @Override public boolean delete(Product product) { String SQL = "DELETE FROM product WHERE product_nummer = ?"; String SQL2 = "DELETE FROM ov_chipkaart_product WHERE product_nummer = ?"; try { PreparedStatement prestat = conn.prepareStatement(SQL); PreparedStatement prestat2 = conn.prepareStatement(SQL2); prestat.setInt(1, product.getProduct_nummer()); prestat2.setInt(1, product.getProduct_nummer()); prestat2.executeUpdate(); prestat.executeUpdate(); return true; } catch (SQLException throwables) { throwables.printStackTrace(); } return false; } public List<Product> findByOVChipkaart(OVChipkaart ovChipkaart) { String SQL = "SELECT ov_chipkaart_product.kaart_nummer, product.product_nummer, product.naam, product.beschrijving, product.prijs " + "FROM product " + "JOIN ov_chipkaart_product " + "ON ov_chipkaart_product.product_nummer = product.product_nummer " + "WHERE ov_chipkaart_product.kaart_nummer = ? " + "ORDER BY kaart_nummer, product_nummer"; try { PreparedStatement prestat = conn.prepareStatement(SQL); prestat.setInt(1, ovChipkaart.getKaart_nummer()); ResultSet rs = prestat.executeQuery(); List<Product> producten = new ArrayList<>(); while (rs.next()) { int prnr = rs.getInt("product_nummer"); String nm = rs.getString("naam"); String besch = rs.getString("beschrijving"); Float prijs = rs.getFloat("prijs"); Product pr = new Product(prnr, nm, besch, prijs); pr.addOVChipkaart(ovChipkaart); producten.add(pr); } return producten; } catch (SQLException throwables) { throwables.printStackTrace(); } return null; } public List<Product> findAll(){ // Hier veranderd van "SELECT * FROM product;" naar deze query met JOIN zodat je ook de ovchipkaarten ook op haalt en toevoegd aan de producten // Hetzelfde in<SUF> String SQL = "SELECT ov_chipkaart_product.kaart_nummer, ov_chipkaart.geldig_tot, ov_chipkaart.klasse, ov_chipkaart.saldo, ov_chipkaart.reiziger_id, product.product_nummer, product.naam, product.beschrijving, product.prijs " + "FROM product " + "JOIN ov_chipkaart_product " + "ON ov_chipkaart_product.product_nummer = product.product_nummer " + "JOIN ov_chipkaart " + "ON ov_chipkaart_product.kaart_nummer = ov_chipkaart.kaart_nummer " + "ORDER BY kaart_nummer, product_nummer;"; try { PreparedStatement prestat = conn.prepareStatement(SQL); ResultSet rs = prestat.executeQuery(); List<Product> producten = new ArrayList<>(); while(rs.next()) { int prnr = rs.getInt("product_nummer"); String nm = rs.getString("naam"); String besch = rs.getString("beschrijving"); Float prijs = rs.getFloat("prijs"); int knm = rs.getInt("kaart_nummer"); Date geldigTot = rs.getDate("geldig_tot"); int klasse = rs.getInt("klasse"); float saldo = rs.getFloat("saldo"); int rid = rs.getInt("reiziger_id"); OVChipkaart ov = new OVChipkaart(knm, geldigTot, klasse, saldo, rid); Product pr = new Product(prnr, nm, besch, prijs); for(Product p : producten){ if(p.getProduct_nummer() == pr.getProduct_nummer()){ p.addOVChipkaart(ov); break; } } pr.addOVChipkaart(ov); producten.add(pr); } return producten; } catch (SQLException throwables) { throwables.printStackTrace(); } return null; } }
True
1,639
13
1,857
16
1,862
13
1,857
16
2,255
16
false
false
false
false
false
true
3,384
23946_11
package entity; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.SecondaryTable; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import validation.OnPasswordUpdate; import validation.ValidPassword; import validation.ValidUsername; @Entity @Table(name = "TBL_USER") // We gaan de paswoorden opslaan in een aparte tabel, //dit is een goede gewoonte. @SecondaryTable(name = "USER_PASSWORD") @NamedQueries({ @NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"), @NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE UPPER(u.username) LIKE UPPER(:username)"), }) public class User implements Serializable { @Id @ValidUsername private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } private String fullName; public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } @Transient // Het plain text paswoord mag nooit opgeslagen worden. // En het moet enkel worden gevalideerd wanneer het is gewijzigd. @ValidPassword(groups = OnPasswordUpdate.class) private String plainPassword; @NotNull // Dit zou nooit mogen gebeuren. // Dit zou eveneens nooit mogen gebeuren (wijst op fout bij encryptie). @Pattern(regexp = "[A-Fa-f0-9]{64}+") @Column(name = "PASSWORD", table = "USER_PASSWORD") private String encryptedPassword; /* * Geef het geëncrypteerde paswoord terug, * of null indien er nog geen paswoord ingesteld is. */ public String getPassword() { return encryptedPassword; } /* * Verandert het paswoord en encrypteert het meteen. */ public void setPassword(String plainPassword) { this.plainPassword = plainPassword != null ? plainPassword.trim() : ""; // De onderstaande code zal het paswoord hashen met //SHA-256 en de hexadecimale hashcode opslaan. try { BigInteger hash = new BigInteger(1, MessageDigest.getInstance("SHA-256") .digest(this.plainPassword.getBytes("UTF-8"))); encryptedPassword = hash.toString(16); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { Logger.getLogger(User.class.getName()) .log(Level.SEVERE, null, ex); } } @ElementCollection // We kiezen hier zelf de naam voor de tabel en de //kolommen omdat we deze nodig hebben voor het // instellen van de security realm. @CollectionTable(name = "USER_ROLES", joinColumns = @JoinColumn(name = "USERNAME")) @Column(name = "ROLES") private final List<String> roles = new ArrayList<>(); public List<String> getRoles() { return roles; } @ManyToMany(fetch = FetchType.EAGER) private final List<Anime> animes = new ArrayList<>(); public List<Anime> getAnimes() { return animes; } public void addAnime(Anime a) { animes.add(a); } public void RemoveAnime(Anime a) { animes.remove(a); } @Override public int hashCode() { int hash = 7; hash = 13 * hash + Objects.hashCode(this.username); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User other = (User) obj; return Objects.equals(this.username, other.username); } @Override public String toString() { return username; } }
ko-htut/AnimeList
src/java/entity/User.java
1,378
//kolommen omdat we deze nodig hebben voor het
line_comment
nl
package entity; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.SecondaryTable; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import validation.OnPasswordUpdate; import validation.ValidPassword; import validation.ValidUsername; @Entity @Table(name = "TBL_USER") // We gaan de paswoorden opslaan in een aparte tabel, //dit is een goede gewoonte. @SecondaryTable(name = "USER_PASSWORD") @NamedQueries({ @NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"), @NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE UPPER(u.username) LIKE UPPER(:username)"), }) public class User implements Serializable { @Id @ValidUsername private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } private String fullName; public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } @Transient // Het plain text paswoord mag nooit opgeslagen worden. // En het moet enkel worden gevalideerd wanneer het is gewijzigd. @ValidPassword(groups = OnPasswordUpdate.class) private String plainPassword; @NotNull // Dit zou nooit mogen gebeuren. // Dit zou eveneens nooit mogen gebeuren (wijst op fout bij encryptie). @Pattern(regexp = "[A-Fa-f0-9]{64}+") @Column(name = "PASSWORD", table = "USER_PASSWORD") private String encryptedPassword; /* * Geef het geëncrypteerde paswoord terug, * of null indien er nog geen paswoord ingesteld is. */ public String getPassword() { return encryptedPassword; } /* * Verandert het paswoord en encrypteert het meteen. */ public void setPassword(String plainPassword) { this.plainPassword = plainPassword != null ? plainPassword.trim() : ""; // De onderstaande code zal het paswoord hashen met //SHA-256 en de hexadecimale hashcode opslaan. try { BigInteger hash = new BigInteger(1, MessageDigest.getInstance("SHA-256") .digest(this.plainPassword.getBytes("UTF-8"))); encryptedPassword = hash.toString(16); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { Logger.getLogger(User.class.getName()) .log(Level.SEVERE, null, ex); } } @ElementCollection // We kiezen hier zelf de naam voor de tabel en de //kolommen omdat<SUF> // instellen van de security realm. @CollectionTable(name = "USER_ROLES", joinColumns = @JoinColumn(name = "USERNAME")) @Column(name = "ROLES") private final List<String> roles = new ArrayList<>(); public List<String> getRoles() { return roles; } @ManyToMany(fetch = FetchType.EAGER) private final List<Anime> animes = new ArrayList<>(); public List<Anime> getAnimes() { return animes; } public void addAnime(Anime a) { animes.add(a); } public void RemoveAnime(Anime a) { animes.remove(a); } @Override public int hashCode() { int hash = 7; hash = 13 * hash + Objects.hashCode(this.username); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User other = (User) obj; return Objects.equals(this.username, other.username); } @Override public String toString() { return username; } }
True
1,005
11
1,174
17
1,226
10
1,174
17
1,372
12
false
false
false
false
false
true
1,851
113326_7
package com.vitaquest.challengeservice.Mock; import com.vitaquest.challengeservice.Database.Repository.ChallengeRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class DataLoader implements ApplicationRunner { private final ChallengeRepository repository; public DataLoader(ChallengeRepository repository){ this.repository = repository; } @Override public void run(ApplicationArguments args) throws Exception { // Challenge c1 = Challenge.builder() // .title("Beweging") // .description("Meer bewegen begint met minder zitten. Elke dag iets meer bewegen draagt bij aan een beter balans. De gemiddelde Nederlander zit 7,5uur per dag, dat kan beter! Minder zitten op werkdagen zorgt voor een welkome onderbreking en werkt als een energizer zodat je met hernieuwde energie lekker verder kan die dag.") // .startDate(LocalDate.now()) // .endDate(LocalDate.of(2022, 7, 23)) // .Reward("Een appel") // .build(); // // Challenge c2 = Challenge.builder() // .title("Veerkracht") // .description("Meer bewegen begint met minder zitten. Elke dag iets meer bewegen draagt bij aan een beter balans. De gemiddelde Nederlander zit 7,5uur per dag, dat kan beter! Minder zitten op werkdagen zorgt voor een welkome onderbreking en werkt als een energizer zodat je met hernieuwde energie lekker verder kan die dag.") // .startDate(LocalDate.now()) // .endDate(LocalDate.of(2022, 7, 23)) // .Reward("Een appel") // .build(); // // Challenge c3 = Challenge.builder() // .title("Beweging") // .description("Meer bewegen begint met minder zitten. Elke dag iets meer bewegen draagt bij aan een beter balans. De gemiddelde Nederlander zit 7,5uur per dag, dat kan beter! Minder zitten op werkdagen zorgt voor een welkome onderbreking en werkt als een energizer zodat je met hernieuwde energie lekker verder kan die dag.") // .startDate(LocalDate.now()) // .endDate(LocalDate.of(2022, 7, 23)) // .Reward("Een appel") // .build(); //repository.saveAll(List.of(c1, c2, c3)); } }
VitaApp-S7/VitaApp-Backend
services/challenge-service/src/main/java/com/vitaquest/challengeservice/Mock/DataLoader.java
692
// .description("Meer bewegen begint met minder zitten. Elke dag iets meer bewegen draagt bij aan een beter balans. De gemiddelde Nederlander zit 7,5uur per dag, dat kan beter! Minder zitten op werkdagen zorgt voor een welkome onderbreking en werkt als een energizer zodat je met hernieuwde energie lekker verder kan die dag.")
line_comment
nl
package com.vitaquest.challengeservice.Mock; import com.vitaquest.challengeservice.Database.Repository.ChallengeRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class DataLoader implements ApplicationRunner { private final ChallengeRepository repository; public DataLoader(ChallengeRepository repository){ this.repository = repository; } @Override public void run(ApplicationArguments args) throws Exception { // Challenge c1 = Challenge.builder() // .title("Beweging") // .description("Meer bewegen begint met minder zitten. Elke dag iets meer bewegen draagt bij aan een beter balans. De gemiddelde Nederlander zit 7,5uur per dag, dat kan beter! Minder zitten op werkdagen zorgt voor een welkome onderbreking en werkt als een energizer zodat je met hernieuwde energie lekker verder kan die dag.") // .startDate(LocalDate.now()) // .endDate(LocalDate.of(2022, 7, 23)) // .Reward("Een appel") // .build(); // // Challenge c2 = Challenge.builder() // .title("Veerkracht") // .description("Meer bewegen begint met minder zitten. Elke dag iets meer bewegen draagt bij aan een beter balans. De gemiddelde Nederlander zit 7,5uur per dag, dat kan beter! Minder zitten op werkdagen zorgt voor een welkome onderbreking en werkt als een energizer zodat je met hernieuwde energie lekker verder kan die dag.") // .startDate(LocalDate.now()) // .endDate(LocalDate.of(2022, 7, 23)) // .Reward("Een appel") // .build(); // // Challenge c3 = Challenge.builder() // .title("Beweging") // .description("Meer bewegen<SUF> // .startDate(LocalDate.now()) // .endDate(LocalDate.of(2022, 7, 23)) // .Reward("Een appel") // .build(); //repository.saveAll(List.of(c1, c2, c3)); } }
False
589
100
701
114
582
76
701
114
709
103
false
false
false
false
false
true
3,587
147398_0
// Wildebeest Migration Framework // Copyright © 2013 - 2018, Matheson Ventures Pte Ltd // // This file is part of Wildebeest // // Wildebeest is free software: you can redistribute it and/or modify it under // the terms of the GNU General Public License v2 as published by the Free // Software Foundation. // // Wildebeest is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR // A PARTICULAR PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with // Wildebeest. If not, see http://www.gnu.org/licenses/gpl-2.0.html package co.mv.wb; import co.mv.wb.framework.ArgumentNullException; import java.util.Optional; import java.util.UUID; /** * Global definitions and functions for Wildebeest. * * @since 4.0 */ public class Wildebeest { /** * Attempts to find the {@link State} matching the supplied stateRef reference in the supplied {@link Resource}. * * @param resource the Resource in which to search for the State * @param stateRef the reference to the State to search for. May be the ID or the name of the State. * @return the State that matches the supplied stateRef reference. */ public static State findState( Resource resource, String stateRef) throws InvalidReferenceException { if (resource == null) throw new ArgumentNullException("resource"); if (stateRef == null) throw new ArgumentNullException("stateRef"); Optional<State> result = resource .getStates().stream() .filter(s -> s.matchesStateRef(stateRef)) .findFirst(); if (!result.isPresent()) { throw InvalidReferenceException.oneReference( EntityType.State, stateRef); } return result.get(); } public static String stateDisplayName( UUID stateId, String name) { String result; if (stateId == null) { result = "(non-existent)"; } else { if (name == null) { result = stateId.toString(); } else { result = String.format("%s:%s", stateId, name); } } return result; } public static String getPluginHandlerUri(ResourcePlugin plugin) { if (plugin == null) throw new ArgumentNullException("plugin"); return Wildebeest.getPluginHandlerUriInner(plugin); } public static String getPluginHandlerUri(AssertionPlugin plugin) { if (plugin == null) throw new ArgumentNullException("plugin"); return Wildebeest.getPluginHandlerUriInner(plugin); } public static String getPluginHandlerUri(MigrationPlugin plugin) { if (plugin == null) throw new ArgumentNullException("plugin"); return Wildebeest.getPluginHandlerUriInner(plugin); } private static String getPluginHandlerUriInner(Object plugin) { if (plugin == null) throw new ArgumentNullException("plugin"); PluginHandler info = plugin.getClass().getAnnotation(PluginHandler.class); if (info == null) { throw new RuntimeException(String.format( "plugin class %s is not annotated with PluginHandler", plugin.getClass().getName())); } return info.uri(); } }
mathesonventures/wildebeest
MV.Wildebeest.Core/source/core/java/co/mv/wb/Wildebeest.java
926
// Wildebeest Migration Framework
line_comment
nl
// Wildebeest Migration<SUF> // Copyright © 2013 - 2018, Matheson Ventures Pte Ltd // // This file is part of Wildebeest // // Wildebeest is free software: you can redistribute it and/or modify it under // the terms of the GNU General Public License v2 as published by the Free // Software Foundation. // // Wildebeest is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR // A PARTICULAR PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with // Wildebeest. If not, see http://www.gnu.org/licenses/gpl-2.0.html package co.mv.wb; import co.mv.wb.framework.ArgumentNullException; import java.util.Optional; import java.util.UUID; /** * Global definitions and functions for Wildebeest. * * @since 4.0 */ public class Wildebeest { /** * Attempts to find the {@link State} matching the supplied stateRef reference in the supplied {@link Resource}. * * @param resource the Resource in which to search for the State * @param stateRef the reference to the State to search for. May be the ID or the name of the State. * @return the State that matches the supplied stateRef reference. */ public static State findState( Resource resource, String stateRef) throws InvalidReferenceException { if (resource == null) throw new ArgumentNullException("resource"); if (stateRef == null) throw new ArgumentNullException("stateRef"); Optional<State> result = resource .getStates().stream() .filter(s -> s.matchesStateRef(stateRef)) .findFirst(); if (!result.isPresent()) { throw InvalidReferenceException.oneReference( EntityType.State, stateRef); } return result.get(); } public static String stateDisplayName( UUID stateId, String name) { String result; if (stateId == null) { result = "(non-existent)"; } else { if (name == null) { result = stateId.toString(); } else { result = String.format("%s:%s", stateId, name); } } return result; } public static String getPluginHandlerUri(ResourcePlugin plugin) { if (plugin == null) throw new ArgumentNullException("plugin"); return Wildebeest.getPluginHandlerUriInner(plugin); } public static String getPluginHandlerUri(AssertionPlugin plugin) { if (plugin == null) throw new ArgumentNullException("plugin"); return Wildebeest.getPluginHandlerUriInner(plugin); } public static String getPluginHandlerUri(MigrationPlugin plugin) { if (plugin == null) throw new ArgumentNullException("plugin"); return Wildebeest.getPluginHandlerUriInner(plugin); } private static String getPluginHandlerUriInner(Object plugin) { if (plugin == null) throw new ArgumentNullException("plugin"); PluginHandler info = plugin.getClass().getAnnotation(PluginHandler.class); if (info == null) { throw new RuntimeException(String.format( "plugin class %s is not annotated with PluginHandler", plugin.getClass().getName())); } return info.uri(); } }
False
745
6
863
7
858
6
863
7
1,026
8
false
false
false
false
false
true
273
44897_0
package model; /** * @author Vincent Velthuizen <v.r.velthuizen@pl.hanze.nl> * Eigenschappen van die personen die in vaste dienst zijn bij mijn bedrijf */ public class Werknemer extends Persoon { private static final double GRENSWAARDE_BONUS = 4500; private static final double DEFAULT_MAAND_SALARIS = 0.0; private static final int MAANDEN_PER_JAAR = 12; private double maandSalaris; public Werknemer(String naam, String woonplaats, Afdeling afdeling, double maandSalaris) { super(naam, woonplaats, afdeling); setMaandsalaris(maandSalaris); } public Werknemer(String naam) { super(naam); setMaandsalaris(DEFAULT_MAAND_SALARIS); } public Werknemer() { super(); setMaandsalaris(DEFAULT_MAAND_SALARIS); } public boolean heeftRechtOpBonus() { return maandSalaris >= GRENSWAARDE_BONUS; } @Override public double berekenJaarinkomen() { double jaarinkomen = MAANDEN_PER_JAAR * maandSalaris; if (heeftRechtOpBonus()) { jaarinkomen += maandSalaris; } return jaarinkomen; } @Override public String toString() { return String.format("%s en is een werknemer %s recht op bonus", super.toString(), heeftRechtOpBonus() ? "met" : "zonder"); } public double getMaandSalaris() { return maandSalaris; } private void setMaandsalaris(double maandSalaris) { if (maandSalaris < 0) { throw new IllegalArgumentException("Het maandsalaris mag niet negatief zijn."); } this.maandSalaris = maandSalaris; } }
C12-MIWNN/Bedrijf
src/model/Werknemer.java
530
/** * @author Vincent Velthuizen <v.r.velthuizen@pl.hanze.nl> * Eigenschappen van die personen die in vaste dienst zijn bij mijn bedrijf */
block_comment
nl
package model; /** * @author Vincent Velthuizen<SUF>*/ public class Werknemer extends Persoon { private static final double GRENSWAARDE_BONUS = 4500; private static final double DEFAULT_MAAND_SALARIS = 0.0; private static final int MAANDEN_PER_JAAR = 12; private double maandSalaris; public Werknemer(String naam, String woonplaats, Afdeling afdeling, double maandSalaris) { super(naam, woonplaats, afdeling); setMaandsalaris(maandSalaris); } public Werknemer(String naam) { super(naam); setMaandsalaris(DEFAULT_MAAND_SALARIS); } public Werknemer() { super(); setMaandsalaris(DEFAULT_MAAND_SALARIS); } public boolean heeftRechtOpBonus() { return maandSalaris >= GRENSWAARDE_BONUS; } @Override public double berekenJaarinkomen() { double jaarinkomen = MAANDEN_PER_JAAR * maandSalaris; if (heeftRechtOpBonus()) { jaarinkomen += maandSalaris; } return jaarinkomen; } @Override public String toString() { return String.format("%s en is een werknemer %s recht op bonus", super.toString(), heeftRechtOpBonus() ? "met" : "zonder"); } public double getMaandSalaris() { return maandSalaris; } private void setMaandsalaris(double maandSalaris) { if (maandSalaris < 0) { throw new IllegalArgumentException("Het maandsalaris mag niet negatief zijn."); } this.maandSalaris = maandSalaris; } }
True
464
46
506
55
478
42
506
55
552
52
false
false
false
false
false
true
2,646
151474_2
/** * Copyright 2004 * * This file is part of Peertrust. * * Peertrust is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Peertrust is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Peertrust; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.peertrust.config; import org.peertrust.TrustClient; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.mem.ModelMem; import com.hp.hpl.jena.rdf.model.RDFException; /** * <p> * Specifies the vocabulary accepted by the configurator in the configuration file. * </p><p> * $Id: Vocabulary.java,v 1.5 2005/12/13 15:23:37 token77 Exp $ * <br/> * Date: 05-Dec-2003 * <br/> * Last changed: $Date: 2005/12/13 15:23:37 $ * by $Author: token77 $ * </p> * @author olmedilla */ public class Vocabulary { public static final String uri = "http://www.l3s.de/~olmedilla/peertrust/Vocabulary#"; public static String getURI() { return(Vocabulary.uri); } public static Property javaClass; /** * Peer */ public static Resource PeertrustEngine; // public static Property peerName ; // // public static Property baseFolder ; // // public static Property entitiesFile ; // // public static Property hostName ; // // public static Property port ; // // public static Property keyStoreFile ; // // public static Property keyPassword ; // // public static Property storePassword ; // /** * Inference engine */ public static Resource InferenceEngine; // // public static Property prologFiles ; // // public static Property rdfFiles ; // // public static Property license ; // /** * Queue */ public static Resource Queue; /** * CommunicationChannel */ public static Resource CommunicationChannelFactory; /** * CredentialStore */ public static Resource CredentialStore; /** * MetaIntepreter */ public static Resource MetaInterpreter; /** * MetaIntepreterListener */ public static Resource MetaInterpreterListener ; /** * RunTimeOptions */ public static Resource RunTimeOptions; /** * EntitiesTable */ public static Resource EntitiesTable; /** * EventListener */ public static Resource EventListener ; /** * EventDispatcher */ public static Resource EventDispatcher ; ////////////////////////////////////////////////////////////////////////// //////////////////Vocabulary entries for web application////////////////// ////////////////////////////////////////////////////////////////////////// /** * Manager trustnegotiation for the web application */ public static Resource TrustManager; /** * PeertrustClient, which provide an fasade to start and wait * for negotiation outcome */ static public Resource TrustClient; /** * Classifies a resource identify by an url */ public static Resource ResourceClassifier; /** * A store of policy */ static public Resource PolicySystem; /** * PolicyEvaluator; it evaluate policies if necessary * customized for the actual peers */ static public Resource PolicyEvaluator; /** * Reprsents the setup file of the resource management. */ static public Resource ResourceManagementSetupFile; /** * A local messenger, used when direct sending of message * is not possible; e.g. in case of http client as peer. */ static public Resource Messenger; /** * SessionRegisterer */ static public Resource SessionRegisterer; /////////////////////////////////////////////////////////////////////////// static { try { Model m = new ModelMem(); javaClass = m.createProperty(Vocabulary.uri + "javaClass") ; PeertrustEngine = m.createResource(Vocabulary.uri + "PeertrustEngine"); InferenceEngine = m.createResource(Vocabulary.uri + "InferenceEngine"); Queue = m.createResource(Vocabulary.uri + "Queue"); CommunicationChannelFactory = m.createResource(Vocabulary.uri + "CommunicationChannelFactory"); CredentialStore = m.createResource(Vocabulary.uri + "CredentialStore"); MetaInterpreter = m.createResource(Vocabulary.uri + "MetaInterpreter"); MetaInterpreterListener = m.createResource(Vocabulary.uri + "MetaInterpreterListener"); RunTimeOptions = m.createResource(Vocabulary.uri + "RunTimeOptions"); EntitiesTable = m.createResource(Vocabulary.uri + "EntitiesTable"); EventListener = m.createResource(Vocabulary.uri + "EventListener"); EventDispatcher = m.createResource(Vocabulary.uri + "EventDispatcher"); ///// TrustManager= m.createResource(Vocabulary.uri+"TrustManager"); TrustClient= m.createResource(Vocabulary.uri+"TrustClient"); ResourceClassifier= m.createResource(Vocabulary.uri+"ResourceClassifier"); PolicySystem= m.createResource(Vocabulary.uri+"PolicySystem"); PolicyEvaluator= m.createResource(Vocabulary.uri+"PolicyEvaluator"); ResourceManagementSetupFile= m.createResource(Vocabulary.uri+"ResourceManagementSetupFile"); Messenger= m.createResource(Vocabulary.uri+"Messenger"); SessionRegisterer= m.createResource(Vocabulary.uri+"SessionRegisterer"); } catch (RDFException rdfe) { throw(new RuntimeException(rdfe.getMessage())); } } // private static final String METAI_PREFIX = "metaI." ; // public static final String PEERNAME = METAI_PREFIX + "peerName" ; // public static final String BASE_FOLDER_TAG = METAI_PREFIX + "baseFolder" ; // public static final String SERVER_PORT_TAG = METAI_PREFIX + "serverPort" ; // public static final String LOCAL_ADDRESS_TAG = METAI_PREFIX + "address" ; // public static final String KEYSTORE_FILE_TAG = METAI_PREFIX + "keystoreFile" ; // public static final String KEY_PASSWORD_TAG = METAI_PREFIX + "keyPassword" ; // public static final String STORE_PASSWORD_TAG = METAI_PREFIX + "storePassword" ; }
elitak/peertrust
src/org/peertrust/config/Vocabulary.java
2,041
/** * Peer */
block_comment
nl
/** * Copyright 2004 * * This file is part of Peertrust. * * Peertrust is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Peertrust is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Peertrust; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.peertrust.config; import org.peertrust.TrustClient; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.mem.ModelMem; import com.hp.hpl.jena.rdf.model.RDFException; /** * <p> * Specifies the vocabulary accepted by the configurator in the configuration file. * </p><p> * $Id: Vocabulary.java,v 1.5 2005/12/13 15:23:37 token77 Exp $ * <br/> * Date: 05-Dec-2003 * <br/> * Last changed: $Date: 2005/12/13 15:23:37 $ * by $Author: token77 $ * </p> * @author olmedilla */ public class Vocabulary { public static final String uri = "http://www.l3s.de/~olmedilla/peertrust/Vocabulary#"; public static String getURI() { return(Vocabulary.uri); } public static Property javaClass; /** * Peer <SUF>*/ public static Resource PeertrustEngine; // public static Property peerName ; // // public static Property baseFolder ; // // public static Property entitiesFile ; // // public static Property hostName ; // // public static Property port ; // // public static Property keyStoreFile ; // // public static Property keyPassword ; // // public static Property storePassword ; // /** * Inference engine */ public static Resource InferenceEngine; // // public static Property prologFiles ; // // public static Property rdfFiles ; // // public static Property license ; // /** * Queue */ public static Resource Queue; /** * CommunicationChannel */ public static Resource CommunicationChannelFactory; /** * CredentialStore */ public static Resource CredentialStore; /** * MetaIntepreter */ public static Resource MetaInterpreter; /** * MetaIntepreterListener */ public static Resource MetaInterpreterListener ; /** * RunTimeOptions */ public static Resource RunTimeOptions; /** * EntitiesTable */ public static Resource EntitiesTable; /** * EventListener */ public static Resource EventListener ; /** * EventDispatcher */ public static Resource EventDispatcher ; ////////////////////////////////////////////////////////////////////////// //////////////////Vocabulary entries for web application////////////////// ////////////////////////////////////////////////////////////////////////// /** * Manager trustnegotiation for the web application */ public static Resource TrustManager; /** * PeertrustClient, which provide an fasade to start and wait * for negotiation outcome */ static public Resource TrustClient; /** * Classifies a resource identify by an url */ public static Resource ResourceClassifier; /** * A store of policy */ static public Resource PolicySystem; /** * PolicyEvaluator; it evaluate policies if necessary * customized for the actual peers */ static public Resource PolicyEvaluator; /** * Reprsents the setup file of the resource management. */ static public Resource ResourceManagementSetupFile; /** * A local messenger, used when direct sending of message * is not possible; e.g. in case of http client as peer. */ static public Resource Messenger; /** * SessionRegisterer */ static public Resource SessionRegisterer; /////////////////////////////////////////////////////////////////////////// static { try { Model m = new ModelMem(); javaClass = m.createProperty(Vocabulary.uri + "javaClass") ; PeertrustEngine = m.createResource(Vocabulary.uri + "PeertrustEngine"); InferenceEngine = m.createResource(Vocabulary.uri + "InferenceEngine"); Queue = m.createResource(Vocabulary.uri + "Queue"); CommunicationChannelFactory = m.createResource(Vocabulary.uri + "CommunicationChannelFactory"); CredentialStore = m.createResource(Vocabulary.uri + "CredentialStore"); MetaInterpreter = m.createResource(Vocabulary.uri + "MetaInterpreter"); MetaInterpreterListener = m.createResource(Vocabulary.uri + "MetaInterpreterListener"); RunTimeOptions = m.createResource(Vocabulary.uri + "RunTimeOptions"); EntitiesTable = m.createResource(Vocabulary.uri + "EntitiesTable"); EventListener = m.createResource(Vocabulary.uri + "EventListener"); EventDispatcher = m.createResource(Vocabulary.uri + "EventDispatcher"); ///// TrustManager= m.createResource(Vocabulary.uri+"TrustManager"); TrustClient= m.createResource(Vocabulary.uri+"TrustClient"); ResourceClassifier= m.createResource(Vocabulary.uri+"ResourceClassifier"); PolicySystem= m.createResource(Vocabulary.uri+"PolicySystem"); PolicyEvaluator= m.createResource(Vocabulary.uri+"PolicyEvaluator"); ResourceManagementSetupFile= m.createResource(Vocabulary.uri+"ResourceManagementSetupFile"); Messenger= m.createResource(Vocabulary.uri+"Messenger"); SessionRegisterer= m.createResource(Vocabulary.uri+"SessionRegisterer"); } catch (RDFException rdfe) { throw(new RuntimeException(rdfe.getMessage())); } } // private static final String METAI_PREFIX = "metaI." ; // public static final String PEERNAME = METAI_PREFIX + "peerName" ; // public static final String BASE_FOLDER_TAG = METAI_PREFIX + "baseFolder" ; // public static final String SERVER_PORT_TAG = METAI_PREFIX + "serverPort" ; // public static final String LOCAL_ADDRESS_TAG = METAI_PREFIX + "address" ; // public static final String KEYSTORE_FILE_TAG = METAI_PREFIX + "keystoreFile" ; // public static final String KEY_PASSWORD_TAG = METAI_PREFIX + "keyPassword" ; // public static final String STORE_PASSWORD_TAG = METAI_PREFIX + "storePassword" ; }
False
1,509
7
1,662
6
1,831
8
1,662
6
2,123
9
false
false
false
false
false
true
3,607
38458_0
package nl.hsleiden.exercise_1; /** * Created by Bart on 17-3-14. * * ============================== * JAVA OPDRACHT HSLEIDEN MARTIJN * ============================== * * Groepje 1 bouwt een Java Desktop Applicatie met alleen een formulier, waarin persoonsgegevens ingevuld dienen te worden. * Naam bestand & Achternaam, tussenvoegsel, voornaam, voorletters, geslacht, geboortedatum, adres, postcode, woonplaats, * vaste telefoonnummer, mobiele nummer (06), e-mailadres. * Wanneer je op OK klikt, worden die gegevens in 2 keer opgeslagen. * De 1e keer in een tekstbestand en de 2e keer in een binair bestand. * Eis hierbij is dat je elk veld checkt of de invoer juist is en dat elke nieuwe invoer wordt toegevoegd (append) aan bestand. * * Groepje 2 bouwt een Java Desktop Applicatie, waarbij een tekstfile of een binair file kan worden geopend. * Bij de bestandselectie wordt de inhoud van dat bestand gelezen en getoond op het scherm (in een textarea). * * =========================== * EINDE OPDRACHT BESCHRIJVING * =========================== */ public class Main { public static void main(String[] args) { CanvasFrame canvasFrame = new CanvasFrame(); } }
mbernson/ScratchBook
src/nl/hsleiden/exercise_1/Main.java
396
/** * Created by Bart on 17-3-14. * * ============================== * JAVA OPDRACHT HSLEIDEN MARTIJN * ============================== * * Groepje 1 bouwt een Java Desktop Applicatie met alleen een formulier, waarin persoonsgegevens ingevuld dienen te worden. * Naam bestand & Achternaam, tussenvoegsel, voornaam, voorletters, geslacht, geboortedatum, adres, postcode, woonplaats, * vaste telefoonnummer, mobiele nummer (06), e-mailadres. * Wanneer je op OK klikt, worden die gegevens in 2 keer opgeslagen. * De 1e keer in een tekstbestand en de 2e keer in een binair bestand. * Eis hierbij is dat je elk veld checkt of de invoer juist is en dat elke nieuwe invoer wordt toegevoegd (append) aan bestand. * * Groepje 2 bouwt een Java Desktop Applicatie, waarbij een tekstfile of een binair file kan worden geopend. * Bij de bestandselectie wordt de inhoud van dat bestand gelezen en getoond op het scherm (in een textarea). * * =========================== * EINDE OPDRACHT BESCHRIJVING * =========================== */
block_comment
nl
package nl.hsleiden.exercise_1; /** * Created by Bart<SUF>*/ public class Main { public static void main(String[] args) { CanvasFrame canvasFrame = new CanvasFrame(); } }
False
345
308
396
352
335
289
395
351
417
365
true
true
true
true
true
false
99
38108_17
/* * Tencent is pleased to support the open source community by making Angel available. * * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/Apache-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.tencent.angel.ps.server.data; import com.tencent.angel.conf.AngelConf; import com.tencent.angel.ps.PSContext; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.ipc.metrics.RpcMetrics; /** * PS running context */ public class RunningContext { private static final Log LOG = LogFactory.getLog(RunningContext.class); private final ConcurrentHashMap<Integer, ClientRunningContext> clientRPCCounters = new ConcurrentHashMap<>(); private final AtomicInteger totalRPCCounter = new AtomicInteger(0); private final AtomicInteger totalRunningRPCCounter = new AtomicInteger(0); private final AtomicInteger oomCounter = new AtomicInteger(0); private final AtomicInteger lastOOMRunningRPCCounter = new AtomicInteger(0); private final AtomicInteger maxRunningRPCCounter = new AtomicInteger(0); private final AtomicInteger generalRunningRPCCounter = new AtomicInteger(0); private final AtomicInteger infligtingRPCCounter = new AtomicInteger(0); private volatile Thread tokenTimeoutChecker; private final int tokenTimeoutMs; private final AtomicBoolean stopped = new AtomicBoolean(false); private volatile long lastOOMTs = System.currentTimeMillis(); private final float genFactor; /* private final ConcurrentHashMap<Integer, PSRPCMetrics> methodIdToMetricsMap = new ConcurrentHashMap<>(); class PSRPCMetrics { private final AtomicInteger rpcCallTime = new AtomicInteger(0); private final AtomicLong totalUseTime = new AtomicLong(0); public void add(long useTime) { rpcCallTime.incrementAndGet(); totalUseTime.addAndGet(useTime); } @Override public String toString() { if(rpcCallTime.get() == 0) { return "PSRPCMetrics{" + "rpcCallTime=" + rpcCallTime.get() + ", totalUseTime=" + totalUseTime.get() + '}'; } else { return "PSRPCMetrics{" + "rpcCallTime=" + rpcCallTime.get() + ", totalUseTime=" + totalUseTime.get() + ", avg use time=" + totalUseTime.get() / rpcCallTime.get() + '}'; } } } */ public RunningContext(PSContext context) { LOG.info("Runtime.getRuntime().availableProcessors() = " + Runtime.getRuntime().availableProcessors()); int workerNum = context.getConf().getInt(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_WORKER_POOL_SIZE, AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_WORKER_POOL_SIZE); float factor = context.getConf() .getFloat(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_FACTOR, AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_FACTOR); genFactor = context.getConf() .getFloat(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_GENERAL_FACTOR, AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_GENERAL_FACTOR); int serverMem = context.getConf().getInt(AngelConf.ANGEL_PS_MEMORY_GB, AngelConf.DEFAULT_ANGEL_PS_MEMORY_GB) * 1024; int estSize = (int) ((serverMem - 512) * 0.45 / 8); //int maxRPCCounter = Math.max(estSize, (int) (workerNum * factor)); int maxRPCCounter = context.getConf().getInt("angel.ps.max.rpc.counter", 10000); maxRunningRPCCounter.set(maxRPCCounter); generalRunningRPCCounter.set((int) (maxRPCCounter * genFactor)); tokenTimeoutMs = context.getConf() .getInt(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_TOKEN_TIMEOUT_MS, AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_TOKEN_TIMEOUT_MS); } /** * Start token timeout checker: if some tokens are not used within a specified time, just release them */ public void start() { tokenTimeoutChecker = new Thread(() -> { while (!stopped.get() && !Thread.interrupted()) { long ts = System.currentTimeMillis(); for (Map.Entry<Integer, ClientRunningContext> clientEntry : clientRPCCounters.entrySet()) { int inflightRPCCounter = clientEntry.getValue().getInflightingRPCCounter(); long lastUpdateTs = clientEntry.getValue().getLastUpdateTs(); LOG.debug( "inflightRPCCounter=" + inflightRPCCounter + ", lastUpdateTs=" + lastUpdateTs + ", ts=" + ts); if (inflightRPCCounter != 0 && (ts - lastUpdateTs) > tokenTimeoutMs) { LOG.info("client " + clientEntry.getKey() + " token is timeout"); relaseToken(clientEntry.getKey(), inflightRPCCounter); } } checkOOM(); if (LOG.isDebugEnabled()) { printToken(); } else { printTokenIfBusy(); } printToken(); try { Thread.sleep(30000); } catch (InterruptedException e) { if (!stopped.get()) { LOG.error("token-timeout-checker is interrupted"); } } } }); tokenTimeoutChecker.setName("token-timeout-checker"); tokenTimeoutChecker.start(); } private void printTokenIfBusy() { if(getState() == ServerState.BUSY) { printToken(); } } /** * Print context */ public void printToken() { LOG.info("=====================Server running context start======================="); LOG.info("state = " + getState()); LOG.info("totalRunningRPCCounter = " + totalRunningRPCCounter.get()); LOG.info("infligtingRPCCounter = " + infligtingRPCCounter.get()); LOG.info("oomCounter = " + oomCounter.get()); LOG.info("maxRunningRPCCounter = " + maxRunningRPCCounter.get()); LOG.info("generalRunningRPCCounter = " + generalRunningRPCCounter.get()); LOG.info("lastOOMRunningRPCCounter = " + lastOOMRunningRPCCounter.get()); LOG.info("totalRPCCounter = " + totalRPCCounter.get()); //for (Map.Entry<Integer, ClientRunningContext> clientEntry : clientRPCCounters.entrySet()) { // LOG.info("client " + clientEntry.getKey() + " running context:"); // clientEntry.getValue().printToken(); //} LOG.info("total=" + WorkerPool.total.get()); LOG.info("normal=" + WorkerPool.normal); LOG.info("network=" + WorkerPool.network); LOG.info("channelInUseCounter=" + WorkerPool.channelInUseCounter); LOG.info("oom=" + WorkerPool.oom); LOG.info("unknown=" + WorkerPool.unknown); /* for(Entry<Integer, PSRPCMetrics> metricEntry : methodIdToMetricsMap.entrySet()) { LOG.info("Method " + TransportMethod.valueOf(metricEntry.getKey()) + " use time " + metricEntry.getValue()); } */ LOG.info("=====================Server running context end ======================="); } /** * Stop token timeout checker */ public void stop() { if (!stopped.compareAndSet(false, true)) { if (tokenTimeoutChecker != null) { tokenTimeoutChecker.interrupt(); tokenTimeoutChecker = null; } } } /** * Before handle a request, update counters * * @param clientId client id * @param seqId request id */ public void before(int clientId, int seqId) { totalRPCCounter.incrementAndGet(); totalRunningRPCCounter.incrementAndGet(); getClientRunningContext(clientId).before(seqId); } /** * After handle a request, update counters * * @param clientId client id * @param seqId request id */ public void after(int clientId, int seqId) { totalRunningRPCCounter.decrementAndGet(); getClientRunningContext(clientId).after(seqId); if (totalRunningRPCCounter.get() + infligtingRPCCounter.get() < 0.7 * lastOOMRunningRPCCounter .get()) { oomCounter.set(0); } } private void checkOOM() { if (totalRunningRPCCounter.get() + infligtingRPCCounter.get() < 0.7 * lastOOMRunningRPCCounter .get()) { oomCounter.set(0); } } /** * OOM happened */ public void oom() { oomCounter.incrementAndGet(); int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter(); lastOOMRunningRPCCounter.set(runningAndInfightingRPCCounter); maxRunningRPCCounter.set((int) (runningAndInfightingRPCCounter * 0.8)); generalRunningRPCCounter.set((int) (runningAndInfightingRPCCounter * 0.8 * genFactor)); LOG.info("OOM happened, lastOOMRunningRPCCounter=" + lastOOMRunningRPCCounter.get() + ", maxRunningRPCCounter=" + maxRunningRPCCounter.get() + ", generalRunningRPCCounter=" + generalRunningRPCCounter.get()); } /** * Is OOM happened * * @return true means happened */ public boolean isOOM() { return oomCounter.get() > 0; } /** * Get total running rpc number * * @return total running rpc number */ public int getTotalRunningRPCCounter() { return totalRunningRPCCounter.get(); } /** * Get Server running state * * @return server running state */ public ServerState getState() { //return ServerState.GENERAL; int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter(); if (isOOM()) { return ServerState.BUSY; } if (runningAndInfightingRPCCounter >= maxRunningRPCCounter.get()) { return ServerState.BUSY; } else if ((runningAndInfightingRPCCounter < maxRunningRPCCounter.get()) && ( runningAndInfightingRPCCounter >= generalRunningRPCCounter.get())) { return ServerState.GENERAL; } else { return ServerState.IDLE; } } private int getRunningAndInflightingRPCCounter() { return totalRunningRPCCounter.get() + infligtingRPCCounter.get(); } /** * Allocate token for a request * * @param clientId client id * @param dataSize request size * @return token number */ public int allocateToken(int clientId, int dataSize) { if (isOOM()) { return 0; } else { int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter(); if (maxRunningRPCCounter.get() - runningAndInfightingRPCCounter >= 1) { infligtingRPCCounter.incrementAndGet(); getClientRunningContext(clientId).allocateToken(1); return 1; } else { return 0; } } } /** * Release token * * @param clientId client id * @param tokenNum token number */ public void relaseToken(int clientId, int tokenNum) { infligtingRPCCounter.addAndGet(-tokenNum); getClientRunningContext(clientId).releaseToken(tokenNum); } /** * Get client running context * * @param clientId client id * @return client running context */ public ClientRunningContext getClientRunningContext(int clientId) { ClientRunningContext clientContext = clientRPCCounters.get(clientId); if (clientContext == null) { clientContext = clientRPCCounters.putIfAbsent(clientId, new ClientRunningContext()); if (clientContext == null) { clientContext = clientRPCCounters.get(clientId); } } return clientContext; } /* public void methodUseTime(int methodId, long useTime) { PSRPCMetrics metrics = methodIdToMetricsMap.get(methodId); if(metrics == null) { metrics = methodIdToMetricsMap.putIfAbsent(methodId, new PSRPCMetrics()); if(metrics == null) { metrics = methodIdToMetricsMap.get(methodId); } } metrics.add(useTime); } */ }
Angel-ML/angel
angel-ps/core/src/main/java/com/tencent/angel/ps/server/data/RunningContext.java
3,779
/** * Release token * * @param clientId client id * @param tokenNum token number */
block_comment
nl
/* * Tencent is pleased to support the open source community by making Angel available. * * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/Apache-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.tencent.angel.ps.server.data; import com.tencent.angel.conf.AngelConf; import com.tencent.angel.ps.PSContext; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.ipc.metrics.RpcMetrics; /** * PS running context */ public class RunningContext { private static final Log LOG = LogFactory.getLog(RunningContext.class); private final ConcurrentHashMap<Integer, ClientRunningContext> clientRPCCounters = new ConcurrentHashMap<>(); private final AtomicInteger totalRPCCounter = new AtomicInteger(0); private final AtomicInteger totalRunningRPCCounter = new AtomicInteger(0); private final AtomicInteger oomCounter = new AtomicInteger(0); private final AtomicInteger lastOOMRunningRPCCounter = new AtomicInteger(0); private final AtomicInteger maxRunningRPCCounter = new AtomicInteger(0); private final AtomicInteger generalRunningRPCCounter = new AtomicInteger(0); private final AtomicInteger infligtingRPCCounter = new AtomicInteger(0); private volatile Thread tokenTimeoutChecker; private final int tokenTimeoutMs; private final AtomicBoolean stopped = new AtomicBoolean(false); private volatile long lastOOMTs = System.currentTimeMillis(); private final float genFactor; /* private final ConcurrentHashMap<Integer, PSRPCMetrics> methodIdToMetricsMap = new ConcurrentHashMap<>(); class PSRPCMetrics { private final AtomicInteger rpcCallTime = new AtomicInteger(0); private final AtomicLong totalUseTime = new AtomicLong(0); public void add(long useTime) { rpcCallTime.incrementAndGet(); totalUseTime.addAndGet(useTime); } @Override public String toString() { if(rpcCallTime.get() == 0) { return "PSRPCMetrics{" + "rpcCallTime=" + rpcCallTime.get() + ", totalUseTime=" + totalUseTime.get() + '}'; } else { return "PSRPCMetrics{" + "rpcCallTime=" + rpcCallTime.get() + ", totalUseTime=" + totalUseTime.get() + ", avg use time=" + totalUseTime.get() / rpcCallTime.get() + '}'; } } } */ public RunningContext(PSContext context) { LOG.info("Runtime.getRuntime().availableProcessors() = " + Runtime.getRuntime().availableProcessors()); int workerNum = context.getConf().getInt(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_WORKER_POOL_SIZE, AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_WORKER_POOL_SIZE); float factor = context.getConf() .getFloat(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_FACTOR, AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_FACTOR); genFactor = context.getConf() .getFloat(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_GENERAL_FACTOR, AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_RPC_LIMIT_GENERAL_FACTOR); int serverMem = context.getConf().getInt(AngelConf.ANGEL_PS_MEMORY_GB, AngelConf.DEFAULT_ANGEL_PS_MEMORY_GB) * 1024; int estSize = (int) ((serverMem - 512) * 0.45 / 8); //int maxRPCCounter = Math.max(estSize, (int) (workerNum * factor)); int maxRPCCounter = context.getConf().getInt("angel.ps.max.rpc.counter", 10000); maxRunningRPCCounter.set(maxRPCCounter); generalRunningRPCCounter.set((int) (maxRPCCounter * genFactor)); tokenTimeoutMs = context.getConf() .getInt(AngelConf.ANGEL_MATRIXTRANSFER_SERVER_TOKEN_TIMEOUT_MS, AngelConf.DEFAULT_ANGEL_MATRIXTRANSFER_SERVER_TOKEN_TIMEOUT_MS); } /** * Start token timeout checker: if some tokens are not used within a specified time, just release them */ public void start() { tokenTimeoutChecker = new Thread(() -> { while (!stopped.get() && !Thread.interrupted()) { long ts = System.currentTimeMillis(); for (Map.Entry<Integer, ClientRunningContext> clientEntry : clientRPCCounters.entrySet()) { int inflightRPCCounter = clientEntry.getValue().getInflightingRPCCounter(); long lastUpdateTs = clientEntry.getValue().getLastUpdateTs(); LOG.debug( "inflightRPCCounter=" + inflightRPCCounter + ", lastUpdateTs=" + lastUpdateTs + ", ts=" + ts); if (inflightRPCCounter != 0 && (ts - lastUpdateTs) > tokenTimeoutMs) { LOG.info("client " + clientEntry.getKey() + " token is timeout"); relaseToken(clientEntry.getKey(), inflightRPCCounter); } } checkOOM(); if (LOG.isDebugEnabled()) { printToken(); } else { printTokenIfBusy(); } printToken(); try { Thread.sleep(30000); } catch (InterruptedException e) { if (!stopped.get()) { LOG.error("token-timeout-checker is interrupted"); } } } }); tokenTimeoutChecker.setName("token-timeout-checker"); tokenTimeoutChecker.start(); } private void printTokenIfBusy() { if(getState() == ServerState.BUSY) { printToken(); } } /** * Print context */ public void printToken() { LOG.info("=====================Server running context start======================="); LOG.info("state = " + getState()); LOG.info("totalRunningRPCCounter = " + totalRunningRPCCounter.get()); LOG.info("infligtingRPCCounter = " + infligtingRPCCounter.get()); LOG.info("oomCounter = " + oomCounter.get()); LOG.info("maxRunningRPCCounter = " + maxRunningRPCCounter.get()); LOG.info("generalRunningRPCCounter = " + generalRunningRPCCounter.get()); LOG.info("lastOOMRunningRPCCounter = " + lastOOMRunningRPCCounter.get()); LOG.info("totalRPCCounter = " + totalRPCCounter.get()); //for (Map.Entry<Integer, ClientRunningContext> clientEntry : clientRPCCounters.entrySet()) { // LOG.info("client " + clientEntry.getKey() + " running context:"); // clientEntry.getValue().printToken(); //} LOG.info("total=" + WorkerPool.total.get()); LOG.info("normal=" + WorkerPool.normal); LOG.info("network=" + WorkerPool.network); LOG.info("channelInUseCounter=" + WorkerPool.channelInUseCounter); LOG.info("oom=" + WorkerPool.oom); LOG.info("unknown=" + WorkerPool.unknown); /* for(Entry<Integer, PSRPCMetrics> metricEntry : methodIdToMetricsMap.entrySet()) { LOG.info("Method " + TransportMethod.valueOf(metricEntry.getKey()) + " use time " + metricEntry.getValue()); } */ LOG.info("=====================Server running context end ======================="); } /** * Stop token timeout checker */ public void stop() { if (!stopped.compareAndSet(false, true)) { if (tokenTimeoutChecker != null) { tokenTimeoutChecker.interrupt(); tokenTimeoutChecker = null; } } } /** * Before handle a request, update counters * * @param clientId client id * @param seqId request id */ public void before(int clientId, int seqId) { totalRPCCounter.incrementAndGet(); totalRunningRPCCounter.incrementAndGet(); getClientRunningContext(clientId).before(seqId); } /** * After handle a request, update counters * * @param clientId client id * @param seqId request id */ public void after(int clientId, int seqId) { totalRunningRPCCounter.decrementAndGet(); getClientRunningContext(clientId).after(seqId); if (totalRunningRPCCounter.get() + infligtingRPCCounter.get() < 0.7 * lastOOMRunningRPCCounter .get()) { oomCounter.set(0); } } private void checkOOM() { if (totalRunningRPCCounter.get() + infligtingRPCCounter.get() < 0.7 * lastOOMRunningRPCCounter .get()) { oomCounter.set(0); } } /** * OOM happened */ public void oom() { oomCounter.incrementAndGet(); int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter(); lastOOMRunningRPCCounter.set(runningAndInfightingRPCCounter); maxRunningRPCCounter.set((int) (runningAndInfightingRPCCounter * 0.8)); generalRunningRPCCounter.set((int) (runningAndInfightingRPCCounter * 0.8 * genFactor)); LOG.info("OOM happened, lastOOMRunningRPCCounter=" + lastOOMRunningRPCCounter.get() + ", maxRunningRPCCounter=" + maxRunningRPCCounter.get() + ", generalRunningRPCCounter=" + generalRunningRPCCounter.get()); } /** * Is OOM happened * * @return true means happened */ public boolean isOOM() { return oomCounter.get() > 0; } /** * Get total running rpc number * * @return total running rpc number */ public int getTotalRunningRPCCounter() { return totalRunningRPCCounter.get(); } /** * Get Server running state * * @return server running state */ public ServerState getState() { //return ServerState.GENERAL; int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter(); if (isOOM()) { return ServerState.BUSY; } if (runningAndInfightingRPCCounter >= maxRunningRPCCounter.get()) { return ServerState.BUSY; } else if ((runningAndInfightingRPCCounter < maxRunningRPCCounter.get()) && ( runningAndInfightingRPCCounter >= generalRunningRPCCounter.get())) { return ServerState.GENERAL; } else { return ServerState.IDLE; } } private int getRunningAndInflightingRPCCounter() { return totalRunningRPCCounter.get() + infligtingRPCCounter.get(); } /** * Allocate token for a request * * @param clientId client id * @param dataSize request size * @return token number */ public int allocateToken(int clientId, int dataSize) { if (isOOM()) { return 0; } else { int runningAndInfightingRPCCounter = getRunningAndInflightingRPCCounter(); if (maxRunningRPCCounter.get() - runningAndInfightingRPCCounter >= 1) { infligtingRPCCounter.incrementAndGet(); getClientRunningContext(clientId).allocateToken(1); return 1; } else { return 0; } } } /** * Release token <SUF>*/ public void relaseToken(int clientId, int tokenNum) { infligtingRPCCounter.addAndGet(-tokenNum); getClientRunningContext(clientId).releaseToken(tokenNum); } /** * Get client running context * * @param clientId client id * @return client running context */ public ClientRunningContext getClientRunningContext(int clientId) { ClientRunningContext clientContext = clientRPCCounters.get(clientId); if (clientContext == null) { clientContext = clientRPCCounters.putIfAbsent(clientId, new ClientRunningContext()); if (clientContext == null) { clientContext = clientRPCCounters.get(clientId); } } return clientContext; } /* public void methodUseTime(int methodId, long useTime) { PSRPCMetrics metrics = methodIdToMetricsMap.get(methodId); if(metrics == null) { metrics = methodIdToMetricsMap.putIfAbsent(methodId, new PSRPCMetrics()); if(metrics == null) { metrics = methodIdToMetricsMap.get(methodId); } } metrics.add(useTime); } */ }
False
2,831
27
3,268
24
3,333
29
3,268
24
3,890
30
false
false
false
false
false
true
1,344
77371_10
package dshomewrok; import java.util.*; public class JudgeRedBlackTree { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int x) { val = x; } } public static void main(String[] args) { int n = 0; int i = 0,j = 0, k = 0,tmp = 0; Scanner sc = new Scanner(System.in); n = sc.nextInt(); TreeNode root1 = null; for(i = 0;i < n;i++) { // judge n trees root1 = null; k = sc.nextInt(); // k is number of the tree's node for(j = 0;j < k;j++) { tmp = sc.nextInt(); root1 = BuildTree(root1,tmp); } // System.out.println("build new tree finished"); judge(root1); // System.out.println("judge new tree finished"); } sc.close(); } /*build a Tree from x */ public static TreeNode BuildTree(TreeNode root, int x) { if(root == null) { root = new TreeNode(x); root.left = null; root.right = null; } else if(Math.abs(x) < Math.abs(root.val)) { root.left = BuildTree(root.left, x); } else { root.right = BuildTree(root.right, x); } return root; } /* property 4, There can be no two consecutive red nodes on all paths from each leaf to the root) */ public static Boolean Pro4(TreeNode root ) { // System.out.println("judge property 4 begin"); if(root == null) { // System.out.println("pro4 is true "); return true; } if(root.val < 0) { //if this node is red // System.out.println("root.val = "+root.val); if( root.left != null ) { // System.out.println("root.left.val = "+root.left.val); if(root.left.val < 0) return false; } if( root.right != null ) { // System.out.println("root.right.val = "+root.right.val); if(root.right.val < 0) return false; } // System.out.println(root.val+"red node is checked "); // don't have right or left node is red //red node we judge left and right } // System.out.println("root.val = "+root.val); // black node we judge left subtree and right subtree return Pro4(root.left) && Pro4(root.right); } /* get from the node to leaf node will go through how many black node */ public static int getHeight(TreeNode root ) { if(root == null) return 0 ; // System.out.println("getHeight of"+root.val); int leftHeight = getHeight(root.left); int rightHeight = getHeight(root.right); // System.out.println("rootheight left right = "+root.val+leftHeight+rightHeight); if(root.val > 0 ) //if root is black node return Math.max(leftHeight,rightHeight) +1; else return Math.max(leftHeight,rightHeight); } /* judge property 5, whether or not any node go to leaf node through same number black node */ public static Boolean Pro5(TreeNode root ) { // System.out.println("judge property 5 begin"); if(root == null) return true; if( getHeight(root.left) == getHeight(root.right) ) { // System.out.println("this node is correct ,judge his subtree "); return Pro5(root.left) && Pro5(root.right); } else // System.out.println("pro5 is false "); return false; } /* judge print a Yes or no*/ public static void judge(TreeNode root ) { if(root == null) { System.out.println("No"); } if(root.val < 0 ) { System.out.println("No"); // property 2 ,root is black,value >0 } else { //property 4 if(Pro4(root) && Pro5(root)) { System.out.println("Yes"); } else { System.out.println("No"); } } } }
QSCTech/zju-icicles
数据结构基础/作业/dsHomework/tree/JudgeRedBlackTree.java
1,284
// System.out.println("root.left.val = "+root.left.val);
line_comment
nl
package dshomewrok; import java.util.*; public class JudgeRedBlackTree { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int x) { val = x; } } public static void main(String[] args) { int n = 0; int i = 0,j = 0, k = 0,tmp = 0; Scanner sc = new Scanner(System.in); n = sc.nextInt(); TreeNode root1 = null; for(i = 0;i < n;i++) { // judge n trees root1 = null; k = sc.nextInt(); // k is number of the tree's node for(j = 0;j < k;j++) { tmp = sc.nextInt(); root1 = BuildTree(root1,tmp); } // System.out.println("build new tree finished"); judge(root1); // System.out.println("judge new tree finished"); } sc.close(); } /*build a Tree from x */ public static TreeNode BuildTree(TreeNode root, int x) { if(root == null) { root = new TreeNode(x); root.left = null; root.right = null; } else if(Math.abs(x) < Math.abs(root.val)) { root.left = BuildTree(root.left, x); } else { root.right = BuildTree(root.right, x); } return root; } /* property 4, There can be no two consecutive red nodes on all paths from each leaf to the root) */ public static Boolean Pro4(TreeNode root ) { // System.out.println("judge property 4 begin"); if(root == null) { // System.out.println("pro4 is true "); return true; } if(root.val < 0) { //if this node is red // System.out.println("root.val = "+root.val); if( root.left != null ) { // System.out.println("root.left.val =<SUF> if(root.left.val < 0) return false; } if( root.right != null ) { // System.out.println("root.right.val = "+root.right.val); if(root.right.val < 0) return false; } // System.out.println(root.val+"red node is checked "); // don't have right or left node is red //red node we judge left and right } // System.out.println("root.val = "+root.val); // black node we judge left subtree and right subtree return Pro4(root.left) && Pro4(root.right); } /* get from the node to leaf node will go through how many black node */ public static int getHeight(TreeNode root ) { if(root == null) return 0 ; // System.out.println("getHeight of"+root.val); int leftHeight = getHeight(root.left); int rightHeight = getHeight(root.right); // System.out.println("rootheight left right = "+root.val+leftHeight+rightHeight); if(root.val > 0 ) //if root is black node return Math.max(leftHeight,rightHeight) +1; else return Math.max(leftHeight,rightHeight); } /* judge property 5, whether or not any node go to leaf node through same number black node */ public static Boolean Pro5(TreeNode root ) { // System.out.println("judge property 5 begin"); if(root == null) return true; if( getHeight(root.left) == getHeight(root.right) ) { // System.out.println("this node is correct ,judge his subtree "); return Pro5(root.left) && Pro5(root.right); } else // System.out.println("pro5 is false "); return false; } /* judge print a Yes or no*/ public static void judge(TreeNode root ) { if(root == null) { System.out.println("No"); } if(root.val < 0 ) { System.out.println("No"); // property 2 ,root is black,value >0 } else { //property 4 if(Pro4(root) && Pro5(root)) { System.out.println("Yes"); } else { System.out.println("No"); } } } }
False
972
15
1,199
22
1,240
21
1,199
22
1,384
23
false
false
false
false
false
true
1,960
86644_9
package uebung3; public class Aufgabe6c { /** * Aufgabe 6 * a) Schreiben Sie ein Programm mit einer einfachen Schleife, das nacheinander die fol- * genden Zahlen ausgibt * 50; 47.5; 45; 42.5; 40; 37.5; 35; 32.5; 30; 27.5; 25 * b) Erweitern Sie Ihre Programm, indem Sie zusätzlich am Ende noch Summe und Mit- * telwert der Zahlen ausgeben. * c) Erweitern Sie Ihr Programm derart, dass der Nutzer zu Beginn den Startwert, den * Endwert und Schrittweite eingeben kann. Anschließend soll mittels Schleife Summe * und Mittelwert berechnet werden. */ public static void main (String[] args) { //Kleine Start Nachricht System.out.println("UEBUNG 3 - AUFGABE 6c\n\n"); System.out.println("Maximal EINE Nachkommastelle"); //Abfrage des Startwertes System.out.print("Startwert: "); int Start = new java.util.Scanner(System.in).nextInt(); //Abfrage des Intervalls System.out.print("Intervall: "); double TempSteps = new java.util.Scanner(System.in).nextDouble(); //Konvertier Intervall in das 10-Fache int Steps = (int) (TempSteps * 10); //Summe der Werte int Sum = 0; //Anzahl der Werte int Count = 0; //Zähle in i als Zehnfaches der beabsichtigten Zahl //Zur verhinderung von Rundungsfehlern int i = Start * 10; for (;i>=250;i=i-Steps) { //Wandle die int in den gedachten double um double n = i / 10.0; //Gebe die Zahl aus System.out.println(n); //Summiere die Werte Sum += i; Count++; } //Ausgabe der Summe System.out.println("Die Summe ist: " + (Sum/10.0)); //Mittelwertberechnung double Middle = (Sum/10.0) / (double) Count; System.out.println("Der Mittelwert ist: " + Middle); } }
adiko01/HSPV-4.3-GdP
4-3-2-Uebung/src/uebung3/Aufgabe6c.java
657
//Wandle die int in den gedachten double um
line_comment
nl
package uebung3; public class Aufgabe6c { /** * Aufgabe 6 * a) Schreiben Sie ein Programm mit einer einfachen Schleife, das nacheinander die fol- * genden Zahlen ausgibt * 50; 47.5; 45; 42.5; 40; 37.5; 35; 32.5; 30; 27.5; 25 * b) Erweitern Sie Ihre Programm, indem Sie zusätzlich am Ende noch Summe und Mit- * telwert der Zahlen ausgeben. * c) Erweitern Sie Ihr Programm derart, dass der Nutzer zu Beginn den Startwert, den * Endwert und Schrittweite eingeben kann. Anschließend soll mittels Schleife Summe * und Mittelwert berechnet werden. */ public static void main (String[] args) { //Kleine Start Nachricht System.out.println("UEBUNG 3 - AUFGABE 6c\n\n"); System.out.println("Maximal EINE Nachkommastelle"); //Abfrage des Startwertes System.out.print("Startwert: "); int Start = new java.util.Scanner(System.in).nextInt(); //Abfrage des Intervalls System.out.print("Intervall: "); double TempSteps = new java.util.Scanner(System.in).nextDouble(); //Konvertier Intervall in das 10-Fache int Steps = (int) (TempSteps * 10); //Summe der Werte int Sum = 0; //Anzahl der Werte int Count = 0; //Zähle in i als Zehnfaches der beabsichtigten Zahl //Zur verhinderung von Rundungsfehlern int i = Start * 10; for (;i>=250;i=i-Steps) { //Wandle die<SUF> double n = i / 10.0; //Gebe die Zahl aus System.out.println(n); //Summiere die Werte Sum += i; Count++; } //Ausgabe der Summe System.out.println("Die Summe ist: " + (Sum/10.0)); //Mittelwertberechnung double Middle = (Sum/10.0) / (double) Count; System.out.println("Der Mittelwert ist: " + Middle); } }
False
602
11
673
13
605
10
673
13
722
13
false
false
false
false
false
true
4,543
22284_9
package org.tlh.profile.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDateTime; /** * <p> * 标签模型 * </p> * * @author 离歌笑 * @since 2021-03-20 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class TbTagModel implements Serializable { private static final long serialVersionUID=1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 标签ID(四级标签) */ private Long tagId; /** * 模型类型:1 匹配 2 统计 3 挖掘 */ private Integer modelType; /** * 模型名称 */ private String modelName; /** * 模型driver全限定名 */ private String modelMain; /** * 模型在hdfs中的地址 */ private String modelPath; /** * 模型jar包文件名 */ private String modelJar; /** * 模型参数 */ private String modelArgs; /** * spark的执行参数 */ private String sparkOpts; /** * oozie的调度规则 */ private String scheduleRule; /** * 操作人 */ private String operator; /** * 操作类型 */ private String operation; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; /** * 状态 */ private Integer state; /** * oozie调度任务ID */ private String oozieTaskId; }
tlhhup/litemall-dw
user-profile/profile-admin-api/src/main/java/org/tlh/profile/entity/TbTagModel.java
532
/** * oozie的调度规则 */
block_comment
nl
package org.tlh.profile.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDateTime; /** * <p> * 标签模型 * </p> * * @author 离歌笑 * @since 2021-03-20 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class TbTagModel implements Serializable { private static final long serialVersionUID=1L; @TableId(value = "id", type = IdType.AUTO) private Long id; /** * 标签ID(四级标签) */ private Long tagId; /** * 模型类型:1 匹配 2 统计 3 挖掘 */ private Integer modelType; /** * 模型名称 */ private String modelName; /** * 模型driver全限定名 */ private String modelMain; /** * 模型在hdfs中的地址 */ private String modelPath; /** * 模型jar包文件名 */ private String modelJar; /** * 模型参数 */ private String modelArgs; /** * spark的执行参数 */ private String sparkOpts; /** * oozie的调度规则 <SUF>*/ private String scheduleRule; /** * 操作人 */ private String operator; /** * 操作类型 */ private String operation; /** * 创建时间 */ private LocalDateTime createTime; /** * 更新时间 */ private LocalDateTime updateTime; /** * 状态 */ private Integer state; /** * oozie调度任务ID */ private String oozieTaskId; }
False
422
12
448
12
480
12
448
12
617
17
false
false
false
false
false
true
874
76402_1
/********************************************************************************_x000D_ * Copyright (c) 2015-2018 Contributors to the Eclipse Foundation_x000D_ *_x000D_ * See the NOTICE file(s) distributed with this work for additional_x000D_ * information regarding copyright ownership._x000D_ *_x000D_ * This program and the accompanying materials are made available under the_x000D_ * terms of the Eclipse Public License v. 2.0 which is available at_x000D_ * http://www.eclipse.org/legal/epl-2.0._x000D_ *_x000D_ * SPDX-License-Identifier: EPL-2.0_x000D_ *_x000D_ ********************************************************************************/_x000D_ package org.eclipse.mdm.mdfsorter.mdf3; import java.io.IOException;_x000D_ import java.nio.ByteBuffer;_x000D_ import java.util.zip.DataFormatException;_x000D_ _x000D_ import org.eclipse.mdm.mdfsorter.MDFAbstractProcessWriter; public class MDF3BlocksSplittMerger { /** * Parent Object. */ private MDF3ProcessWriter ps; /** * Pointer to block in which the data is written. */ private DTBLOCK curr; /** * Pointer to block that is currently written. If curr is an DZBlock, write * out data is buffered here, and zipped and written out, once all data for * this block is read. */ private final MDF3GenBlock parentnode; /** * Total length of the new Data section. Needs to be calculated in advance * before processing blocks. */ private final long totdatalength; /** * Amount of bytes of data written behind the output block */ private long datawritten = 0; /** * An offset in the global data section, only used, if the block that is * read from is not known (towrite == null) */ private long globalReadPtr = 0; /** * Data Provider for reading blocks. This Object manages unzipping of * blocks. */ private MDF3DataProvider prov; /** * Create a new Datasection with the given options, to write data without * concern about the underlying block structure. Totaldatalength and prov * can be passed manually. Therfore oldsection is not needed. * * @param ps * The parent ProcessWriter * @param parentnode * Node that is parent of this datasection. * @param totdatalength * The length of data that will be written. * @param prov * The DataProvider to read from. */ public MDF3BlocksSplittMerger(MDF3ProcessWriter ps, MDF3GenBlock parentnode, long totdatalength, MDF3DataProvider prov) { this.ps = ps; this.parentnode = parentnode; this.totdatalength = totdatalength; this.prov = prov; } public DTBLOCK getStructuralRoot() { return curr; } /** * Append the datasection beginning at <code>startaddress</code> until * length to the output. * * @param startaddress * Beginning of the section. * @param length * Length of the section. * @throws IOException * If an input error occurs. * @throws DataFormatException * If zipped data is in an invalid format. */ public void splitmerge(long startaddress, long length) throws IOException, DataFormatException { globalReadPtr = startaddress; appendDataFromPos(length); } /** * Reads leftbytes from the current position and appends them to the output * section. * * @param leftbytes * The number of bytes to append. * @throws IOException * If an I/O-Error occurs. * @throws DataFormatException * If zipped data is in an invalid format. */ public void appendDataFromPos(long leftbytes) throws IOException, DataFormatException { // check if space in curr-Block is available, and fill with first data, // or attach all data if it fits if (curr == null) { curr = abstractcreate(totdatalength); } if (datawritten + leftbytes <= totdatalength) { // Space available abstractcopy(leftbytes); datawritten += leftbytes; } else { throw new RuntimeException("MDF3Merger got more data than space was reserved."); } } /** * Read data was read from the stream or Cache. * * @param length * Number of Bytes to get. * @return A Bytebuffer where <code>length</code> Bytes can be read from. * @throws IOException * If an I/O-Error occurs. * @throws DataFormatException * If zipped data is in an invalid format. */ public ByteBuffer abstractread(int length) throws IOException, DataFormatException { return prov.cachedRead(globalReadPtr, length); } public void abstractput(ByteBuffer buf, int length) { ps.performPut(buf, length, true); } /** * This Method creats a new data block. * * @param newblocklength * Datalength of the new block * @return The newly created block. * @throws IOException * If an I/O-Error occurs. */ public DTBLOCK abstractcreate(long newblocklength) throws IOException { DTBLOCK ret; ret = ps.create(newblocklength); return ret; } /** * Reads length bytes with <code>reader</code> and writes them out. This * happens in smaller blocks. * * @param length * The number of bytes to copy. * @throws IOException * If an I/O-Error occurs. * @throws DataFormatException * If zipped data is in an invalid format. */ public void abstractcopy(long length) throws IOException, DataFormatException { long written = 0L; do { int bytesread = 0; if (written + MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE > length) { bytesread = (int) (length - written); ByteBuffer custombuffer = abstractread(bytesread); abstractput(custombuffer, bytesread); } else { ByteBuffer buffer = abstractread(MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE); bytesread = MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE; abstractput(buffer, bytesread); } written += bytesread; } while (written < length); if (length != written) { throw new IOException(new StringBuilder().append("written length not equal to blocklength: ").append(length).append("/").append(written).toString()); } } public void setLinks() { if (parentnode instanceof DGBLOCK) { parentnode.setLink(3, curr); } else { System.err.println("Unable to set link to data block. Parent block not recognized."); } } /** * ONLY FOR TESTING! Used in MDFUnsorter, replaces this splitmerger's * provider. * * @param prov * The new data provider. */ public void setProv(MDF3DataProvider prov) { this.prov = prov; } }
Jsparrow/org.eclipse.mdm.mdfsorter
src/main/java/org/eclipse/mdm/mdfsorter/mdf3/MDF3BlocksSplittMerger.java
1,908
/** * Parent Object. */
block_comment
nl
/********************************************************************************_x000D_ * Copyright (c) 2015-2018 Contributors to the Eclipse Foundation_x000D_ *_x000D_ * See the NOTICE file(s) distributed with this work for additional_x000D_ * information regarding copyright ownership._x000D_ *_x000D_ * This program and the accompanying materials are made available under the_x000D_ * terms of the Eclipse Public License v. 2.0 which is available at_x000D_ * http://www.eclipse.org/legal/epl-2.0._x000D_ *_x000D_ * SPDX-License-Identifier: EPL-2.0_x000D_ *_x000D_ ********************************************************************************/_x000D_ package org.eclipse.mdm.mdfsorter.mdf3; import java.io.IOException;_x000D_ import java.nio.ByteBuffer;_x000D_ import java.util.zip.DataFormatException;_x000D_ _x000D_ import org.eclipse.mdm.mdfsorter.MDFAbstractProcessWriter; public class MDF3BlocksSplittMerger { /** * Parent Object. <SUF>*/ private MDF3ProcessWriter ps; /** * Pointer to block in which the data is written. */ private DTBLOCK curr; /** * Pointer to block that is currently written. If curr is an DZBlock, write * out data is buffered here, and zipped and written out, once all data for * this block is read. */ private final MDF3GenBlock parentnode; /** * Total length of the new Data section. Needs to be calculated in advance * before processing blocks. */ private final long totdatalength; /** * Amount of bytes of data written behind the output block */ private long datawritten = 0; /** * An offset in the global data section, only used, if the block that is * read from is not known (towrite == null) */ private long globalReadPtr = 0; /** * Data Provider for reading blocks. This Object manages unzipping of * blocks. */ private MDF3DataProvider prov; /** * Create a new Datasection with the given options, to write data without * concern about the underlying block structure. Totaldatalength and prov * can be passed manually. Therfore oldsection is not needed. * * @param ps * The parent ProcessWriter * @param parentnode * Node that is parent of this datasection. * @param totdatalength * The length of data that will be written. * @param prov * The DataProvider to read from. */ public MDF3BlocksSplittMerger(MDF3ProcessWriter ps, MDF3GenBlock parentnode, long totdatalength, MDF3DataProvider prov) { this.ps = ps; this.parentnode = parentnode; this.totdatalength = totdatalength; this.prov = prov; } public DTBLOCK getStructuralRoot() { return curr; } /** * Append the datasection beginning at <code>startaddress</code> until * length to the output. * * @param startaddress * Beginning of the section. * @param length * Length of the section. * @throws IOException * If an input error occurs. * @throws DataFormatException * If zipped data is in an invalid format. */ public void splitmerge(long startaddress, long length) throws IOException, DataFormatException { globalReadPtr = startaddress; appendDataFromPos(length); } /** * Reads leftbytes from the current position and appends them to the output * section. * * @param leftbytes * The number of bytes to append. * @throws IOException * If an I/O-Error occurs. * @throws DataFormatException * If zipped data is in an invalid format. */ public void appendDataFromPos(long leftbytes) throws IOException, DataFormatException { // check if space in curr-Block is available, and fill with first data, // or attach all data if it fits if (curr == null) { curr = abstractcreate(totdatalength); } if (datawritten + leftbytes <= totdatalength) { // Space available abstractcopy(leftbytes); datawritten += leftbytes; } else { throw new RuntimeException("MDF3Merger got more data than space was reserved."); } } /** * Read data was read from the stream or Cache. * * @param length * Number of Bytes to get. * @return A Bytebuffer where <code>length</code> Bytes can be read from. * @throws IOException * If an I/O-Error occurs. * @throws DataFormatException * If zipped data is in an invalid format. */ public ByteBuffer abstractread(int length) throws IOException, DataFormatException { return prov.cachedRead(globalReadPtr, length); } public void abstractput(ByteBuffer buf, int length) { ps.performPut(buf, length, true); } /** * This Method creats a new data block. * * @param newblocklength * Datalength of the new block * @return The newly created block. * @throws IOException * If an I/O-Error occurs. */ public DTBLOCK abstractcreate(long newblocklength) throws IOException { DTBLOCK ret; ret = ps.create(newblocklength); return ret; } /** * Reads length bytes with <code>reader</code> and writes them out. This * happens in smaller blocks. * * @param length * The number of bytes to copy. * @throws IOException * If an I/O-Error occurs. * @throws DataFormatException * If zipped data is in an invalid format. */ public void abstractcopy(long length) throws IOException, DataFormatException { long written = 0L; do { int bytesread = 0; if (written + MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE > length) { bytesread = (int) (length - written); ByteBuffer custombuffer = abstractread(bytesread); abstractput(custombuffer, bytesread); } else { ByteBuffer buffer = abstractread(MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE); bytesread = MDFAbstractProcessWriter.MAX_OUTPUTBLOCKSIZE; abstractput(buffer, bytesread); } written += bytesread; } while (written < length); if (length != written) { throw new IOException(new StringBuilder().append("written length not equal to blocklength: ").append(length).append("/").append(written).toString()); } } public void setLinks() { if (parentnode instanceof DGBLOCK) { parentnode.setLink(3, curr); } else { System.err.println("Unable to set link to data block. Parent block not recognized."); } } /** * ONLY FOR TESTING! Used in MDFUnsorter, replaces this splitmerger's * provider. * * @param prov * The new data provider. */ public void setProv(MDF3DataProvider prov) { this.prov = prov; } }
False
1,688
8
1,819
8
1,889
10
1,819
8
2,098
10
false
false
false
false
false
true
4,181
129160_6
/*_x000D_ * Framework code written for the Multimedia course taught in the first year_x000D_ * of the UvA Informatica bachelor._x000D_ *_x000D_ * Nardi Lam, 2015 (based on code by I.M.J. Kamps, S.J.R. van Schaik, R. de Vries, 2013)_x000D_ */_x000D_ _x000D_ package comthedudifulmoneymoneymoney.httpsgithub.coincounter;_x000D_ _x000D_ import android.content.Context;_x000D_ import android.graphics.Canvas;_x000D_ import android.graphics.Matrix;_x000D_ import android.util.AttributeSet;_x000D_ import android.util.DisplayMetrics;_x000D_ import android.util.Log;_x000D_ import android.view.View;_x000D_ import android.graphics.Bitmap;_x000D_ _x000D_ _x000D_ /*_x000D_ * This is a View that displays incoming images._x000D_ */_x000D_ public class ImageDisplayView extends View implements ImageListener {_x000D_ _x000D_ CircleDetection CD_cur = new CircleDetection();_x000D_ CircleDetection CD_done = new CircleDetection();_x000D_ _x000D_ // Canvas matrix om image te roteren en schalen_x000D_ Matrix matrix = new Matrix();_x000D_ // Thread om cirkeldetectie in te draaien_x000D_ Thread t = null;_x000D_ _x000D_ _x000D_ /*** Constructors ***/_x000D_ _x000D_ public ImageDisplayView(Context context) {_x000D_ super(context);_x000D_ }_x000D_ _x000D_ public ImageDisplayView(Context context, AttributeSet attrs) {_x000D_ super(context, attrs);_x000D_ }_x000D_ _x000D_ public ImageDisplayView(Context context, AttributeSet attrs, int defStyle) {_x000D_ super(context, attrs, defStyle);_x000D_ }_x000D_ _x000D_ public int dpToPx(int dp) {_x000D_ DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();_x000D_ int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));_x000D_ return px;_x000D_ }_x000D_ _x000D_ /*** Image drawing ***/_x000D_ _x000D_ private Bitmap currentImage = null;_x000D_ _x000D_ _x000D_ @Override_x000D_ public void onImage(Bitmap argb) {_x000D_ _x000D_ // Voeg schaling toe aan canvas matrix_x000D_ matrix.reset();_x000D_ matrix.postScale(((float) this.getHeight()) / argb.getWidth(), ((float) this.getWidth()) / argb.getHeight());_x000D_ _x000D_ // Laad nieuwe frame_x000D_ CD_done.LoadImage(argb);_x000D_ _x000D_ // Alleen eerste frame (bij opstarten camera)_x000D_ if (t == null) {_x000D_ Log.i("Thread", "Threading begonnen");_x000D_ _x000D_ // Doe eerste berekening in Main thread_x000D_ CD_done.run();_x000D_ _x000D_ // Start nieuwe Thread_x000D_ CD_cur = new CircleDetection(argb);_x000D_ t = new Thread(CD_cur);_x000D_ t.start();_x000D_ }_x000D_ _x000D_ // Als de Thread klaar is met rekenen_x000D_ if (!this.t.isAlive()) {_x000D_ _x000D_ // Einde Thread afhandelen_x000D_ CD_done = CD_cur;_x000D_ CD_done.LoadImage(argb);_x000D_ _x000D_ // Nieuwe Thread beginnen_x000D_ CD_cur = new CircleDetection(argb);_x000D_ t = new Thread(CD_cur);_x000D_ t.start();_x000D_ }_x000D_ _x000D_ // Geef frame door_x000D_ this.currentImage = CD_done.image;_x000D_ this.invalidate();_x000D_ _x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void onDraw(Canvas canvas) {_x000D_ super.onDraw(canvas);_x000D_ _x000D_ /* If there is an image to be drawn: */_x000D_ if (this.currentImage != null) {_x000D_ _x000D_ // Teken meest recente cirkels + totaal op frame_x000D_ CD_done.DrawCircles();_x000D_ MainActivity.text.setText("Totaal: \u20ac" + String.format("%.2f", CD_done.totaal));_x000D_ _x000D_ // Pas canvas matrix aan_x000D_ matrix.postRotate(90);_x000D_ matrix.postTranslate(canvas.getWidth(), dpToPx(30));_x000D_ _x000D_ canvas.setMatrix(matrix);_x000D_ canvas.drawBitmap(CD_done.image, 0, 0, null);_x000D_ }_x000D_ }_x000D_ _x000D_ /*** Source selection ***/_x000D_ private ImageSource source = null;_x000D_ _x000D_ public void setImageSource(ImageSource source) {_x000D_ if (this.source != null) {_x000D_ this.source.setOnImageListener(null);_x000D_ }_x000D_ source.setOnImageListener(this);_x000D_ this.source = source;_x000D_ }_x000D_ _x000D_ public ImageSource getImageSource() {_x000D_ return this.source;_x000D_ }_x000D_ _x000D_ }
rkalis/uva-multimedia
app/src/main/java/comthedudifulmoneymoneymoney/httpsgithub/coincounter/ImageDisplayView.java
1,158
// Alleen eerste frame (bij opstarten camera)_x000D_
line_comment
nl
/*_x000D_ * Framework code written for the Multimedia course taught in the first year_x000D_ * of the UvA Informatica bachelor._x000D_ *_x000D_ * Nardi Lam, 2015 (based on code by I.M.J. Kamps, S.J.R. van Schaik, R. de Vries, 2013)_x000D_ */_x000D_ _x000D_ package comthedudifulmoneymoneymoney.httpsgithub.coincounter;_x000D_ _x000D_ import android.content.Context;_x000D_ import android.graphics.Canvas;_x000D_ import android.graphics.Matrix;_x000D_ import android.util.AttributeSet;_x000D_ import android.util.DisplayMetrics;_x000D_ import android.util.Log;_x000D_ import android.view.View;_x000D_ import android.graphics.Bitmap;_x000D_ _x000D_ _x000D_ /*_x000D_ * This is a View that displays incoming images._x000D_ */_x000D_ public class ImageDisplayView extends View implements ImageListener {_x000D_ _x000D_ CircleDetection CD_cur = new CircleDetection();_x000D_ CircleDetection CD_done = new CircleDetection();_x000D_ _x000D_ // Canvas matrix om image te roteren en schalen_x000D_ Matrix matrix = new Matrix();_x000D_ // Thread om cirkeldetectie in te draaien_x000D_ Thread t = null;_x000D_ _x000D_ _x000D_ /*** Constructors ***/_x000D_ _x000D_ public ImageDisplayView(Context context) {_x000D_ super(context);_x000D_ }_x000D_ _x000D_ public ImageDisplayView(Context context, AttributeSet attrs) {_x000D_ super(context, attrs);_x000D_ }_x000D_ _x000D_ public ImageDisplayView(Context context, AttributeSet attrs, int defStyle) {_x000D_ super(context, attrs, defStyle);_x000D_ }_x000D_ _x000D_ public int dpToPx(int dp) {_x000D_ DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();_x000D_ int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));_x000D_ return px;_x000D_ }_x000D_ _x000D_ /*** Image drawing ***/_x000D_ _x000D_ private Bitmap currentImage = null;_x000D_ _x000D_ _x000D_ @Override_x000D_ public void onImage(Bitmap argb) {_x000D_ _x000D_ // Voeg schaling toe aan canvas matrix_x000D_ matrix.reset();_x000D_ matrix.postScale(((float) this.getHeight()) / argb.getWidth(), ((float) this.getWidth()) / argb.getHeight());_x000D_ _x000D_ // Laad nieuwe frame_x000D_ CD_done.LoadImage(argb);_x000D_ _x000D_ // Alleen eerste<SUF> if (t == null) {_x000D_ Log.i("Thread", "Threading begonnen");_x000D_ _x000D_ // Doe eerste berekening in Main thread_x000D_ CD_done.run();_x000D_ _x000D_ // Start nieuwe Thread_x000D_ CD_cur = new CircleDetection(argb);_x000D_ t = new Thread(CD_cur);_x000D_ t.start();_x000D_ }_x000D_ _x000D_ // Als de Thread klaar is met rekenen_x000D_ if (!this.t.isAlive()) {_x000D_ _x000D_ // Einde Thread afhandelen_x000D_ CD_done = CD_cur;_x000D_ CD_done.LoadImage(argb);_x000D_ _x000D_ // Nieuwe Thread beginnen_x000D_ CD_cur = new CircleDetection(argb);_x000D_ t = new Thread(CD_cur);_x000D_ t.start();_x000D_ }_x000D_ _x000D_ // Geef frame door_x000D_ this.currentImage = CD_done.image;_x000D_ this.invalidate();_x000D_ _x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void onDraw(Canvas canvas) {_x000D_ super.onDraw(canvas);_x000D_ _x000D_ /* If there is an image to be drawn: */_x000D_ if (this.currentImage != null) {_x000D_ _x000D_ // Teken meest recente cirkels + totaal op frame_x000D_ CD_done.DrawCircles();_x000D_ MainActivity.text.setText("Totaal: \u20ac" + String.format("%.2f", CD_done.totaal));_x000D_ _x000D_ // Pas canvas matrix aan_x000D_ matrix.postRotate(90);_x000D_ matrix.postTranslate(canvas.getWidth(), dpToPx(30));_x000D_ _x000D_ canvas.setMatrix(matrix);_x000D_ canvas.drawBitmap(CD_done.image, 0, 0, null);_x000D_ }_x000D_ }_x000D_ _x000D_ /*** Source selection ***/_x000D_ private ImageSource source = null;_x000D_ _x000D_ public void setImageSource(ImageSource source) {_x000D_ if (this.source != null) {_x000D_ this.source.setOnImageListener(null);_x000D_ }_x000D_ source.setOnImageListener(this);_x000D_ this.source = source;_x000D_ }_x000D_ _x000D_ public ImageSource getImageSource() {_x000D_ return this.source;_x000D_ }_x000D_ _x000D_ }
True
1,680
18
1,889
21
1,915
18
1,889
21
2,041
18
false
false
false
false
false
true
40
53192_4
package com.amaze.quit.app; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.ColorDrawable; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.viewpagerindicator.LinePageIndicator; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class HealthProgress extends Fragment { static int position; private static final int UpdateProgress = 0; private UserVisibilityEvent uservisibilityevent; Handler handler; //teken vooruitgang progressbars met cijfers protected void drawElements(int id) { Activity a = getActivity(); int progress = getProgress(id); int barId = getResources().getIdentifier("progressBar_gezondheid_" + id, "id", a.getPackageName()); ProgressBar gezondheidBar = (ProgressBar) a.findViewById(barId); gezondheidBar.setProgress(progress); int tId = getResources().getIdentifier("health_procent" + id, "id", a.getPackageName()); TextView t = (TextView) a.findViewById(tId); t.setText(progress + "%"); long tijd = getRemainingTime(id); //draw days, hours, minutes long dagen = tijd / 1440; long uren = (tijd - dagen * 1440) / 60; long minuten = tijd - dagen * 1440 - uren * 60; int timerId = getResources().getIdentifier("health_timer" + id, "id", a.getPackageName()); TextView timer = (TextView) a.findViewById(timerId); String timerText = ""; if (dagen > 0) { if (dagen == 1) { timerText += dagen + " dag "; } else { timerText += dagen + " dagen "; } } if (uren > 0) { timerText += uren + " uur "; } timerText += minuten; if(minuten == 1) { timerText += " minuut"; } else { timerText += " minuten"; } timer.setText(timerText); } //tekent algemene gezonheid protected void drawAverage() { //teken de progress van de algemene gezondheid bar (gemiddelde van alle andere) int totalProgress = 0; for (int i = 1; i <= 9; i++) { totalProgress += getProgress(i); } int average = totalProgress / 9; ProgressBar totaalGezondheidBar = (ProgressBar) getActivity().findViewById(R.id.progressBar_algemeenGezondheid); totaalGezondheidBar.setProgress(average); //totaalGezondheidBar.getProgressDrawable(). } //tekent vooruitgang protected void drawProgress() { Activity a = getActivity(); Date today = new Date(); //teken de progress van elke individuele bar + procenten for (int i = 1; i <= 9; i++) { drawElements(i); } drawAverage(); } //geeft progress terug public int getProgress(int id) { double progress; double max; double current; DatabaseHandler db = new DatabaseHandler(getActivity()); Calendar stopDate = DateUtils.calendarFor(db.getUser(1).getQuitYear(), db.getUser(1).getQuitMonth(), db.getUser(1).getQuitDay(), db.getUser(1).getQuitHour(), db.getUser(1).getQuitMinute()); long stoppedMinutes = DateUtils.GetMinutesSince(stopDate); //close the database db.close(); switch (id) { case 1: current = stoppedMinutes; max = 1 * 24 * 60; break; // max in days case 2: current = stoppedMinutes; max = 365 * 24 * 60; break; case 3: current = stoppedMinutes; max = 2 * 24 * 60; break; case 4: current = stoppedMinutes; max = 4 * 24 * 60; break; case 5: current = stoppedMinutes; max = 2 * 24 * 60; break; case 6: current = stoppedMinutes; max = 40 * 24 * 60; break; case 7: current = stoppedMinutes; max = 14 * 24 * 60; break; case 8: current = stoppedMinutes; max = 3 * 365 * 24 * 60; break; case 9: current = stoppedMinutes; max = 10 * 365 * 24 * 60; break; default: current = 100; max = 100; break; } progress = (current / max) * 100; if (progress > 100) { progress = 100; } return (int) progress; } //geeft tijd over terug protected int getRemainingTime(int id) { long tijd = 0; DatabaseHandler db = new DatabaseHandler(getActivity()); Calendar today = Calendar.getInstance(); Calendar stopDate = DateUtils.calendarFor(db.getUser(1).getQuitYear(), db.getUser(1).getQuitMonth(), db.getUser(1).getQuitDay(), db.getUser(1).getQuitHour(), db.getUser(1).getQuitMinute()); Calendar maxDate = stopDate; //close the database db.close(); switch (id) { case 1: maxDate.add(Calendar.DAY_OF_MONTH, 1); break; // STOPDATUM + HOEVEEL DAGEN HET DUURT case 2: maxDate.add(Calendar.YEAR, 1); break; case 3: maxDate.add(Calendar.DAY_OF_MONTH, 2); break; case 4: maxDate.add(Calendar.DAY_OF_MONTH, 4); break; case 5: maxDate.add(Calendar.DAY_OF_MONTH, 2); break; case 6: maxDate.add(Calendar.DAY_OF_MONTH, 40); break; case 7: maxDate.add(Calendar.DAY_OF_MONTH, 14); break; case 8: maxDate.add(Calendar.YEAR, 3); break; case 9: maxDate.add(Calendar.YEAR, 10); break; default: break; } tijd = DateUtils.GetMinutesBetween(today, maxDate); if (tijd < 0) { tijd = 0; } return (int) tijd; } public static final HealthProgress newInstance(int i) { HealthProgress f = new HealthProgress(); Bundle bdl = new Bundle(1); f.setArguments(bdl); position = i; return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.activity_health_progress, container, false); handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == UpdateProgress) { if (getActivity() != null) { Activity a = getActivity(); TextView t1 = (TextView) a.findViewById(R.id.health_procent1); if (t1 != null) { drawProgress(); } } } super.handleMessage(msg); } }; //timer Thread updateProcess = new Thread() { public void run() { while (1 == 1) { try { sleep(10000); Message msg = new Message(); msg.what = UpdateProgress; handler.sendMessage(msg); } catch (InterruptedException e) { e.printStackTrace(); } finally { } } } }; updateProcess.start(); //update on startup Message msg = new Message(); msg.what = UpdateProgress; handler.sendMessage(msg); return v; } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { //implements the main method what every fragment should do when it's visible uservisibilityevent.viewIsVisible(getActivity(), position, "green", "title_activity_health_progress"); } } }
A-Maze/Quit
app/src/main/java/com/amaze/quit/app/HealthProgress.java
2,524
//teken de progress van elke individuele bar + procenten
line_comment
nl
package com.amaze.quit.app; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.ColorDrawable; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.viewpagerindicator.LinePageIndicator; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class HealthProgress extends Fragment { static int position; private static final int UpdateProgress = 0; private UserVisibilityEvent uservisibilityevent; Handler handler; //teken vooruitgang progressbars met cijfers protected void drawElements(int id) { Activity a = getActivity(); int progress = getProgress(id); int barId = getResources().getIdentifier("progressBar_gezondheid_" + id, "id", a.getPackageName()); ProgressBar gezondheidBar = (ProgressBar) a.findViewById(barId); gezondheidBar.setProgress(progress); int tId = getResources().getIdentifier("health_procent" + id, "id", a.getPackageName()); TextView t = (TextView) a.findViewById(tId); t.setText(progress + "%"); long tijd = getRemainingTime(id); //draw days, hours, minutes long dagen = tijd / 1440; long uren = (tijd - dagen * 1440) / 60; long minuten = tijd - dagen * 1440 - uren * 60; int timerId = getResources().getIdentifier("health_timer" + id, "id", a.getPackageName()); TextView timer = (TextView) a.findViewById(timerId); String timerText = ""; if (dagen > 0) { if (dagen == 1) { timerText += dagen + " dag "; } else { timerText += dagen + " dagen "; } } if (uren > 0) { timerText += uren + " uur "; } timerText += minuten; if(minuten == 1) { timerText += " minuut"; } else { timerText += " minuten"; } timer.setText(timerText); } //tekent algemene gezonheid protected void drawAverage() { //teken de progress van de algemene gezondheid bar (gemiddelde van alle andere) int totalProgress = 0; for (int i = 1; i <= 9; i++) { totalProgress += getProgress(i); } int average = totalProgress / 9; ProgressBar totaalGezondheidBar = (ProgressBar) getActivity().findViewById(R.id.progressBar_algemeenGezondheid); totaalGezondheidBar.setProgress(average); //totaalGezondheidBar.getProgressDrawable(). } //tekent vooruitgang protected void drawProgress() { Activity a = getActivity(); Date today = new Date(); //teken de<SUF> for (int i = 1; i <= 9; i++) { drawElements(i); } drawAverage(); } //geeft progress terug public int getProgress(int id) { double progress; double max; double current; DatabaseHandler db = new DatabaseHandler(getActivity()); Calendar stopDate = DateUtils.calendarFor(db.getUser(1).getQuitYear(), db.getUser(1).getQuitMonth(), db.getUser(1).getQuitDay(), db.getUser(1).getQuitHour(), db.getUser(1).getQuitMinute()); long stoppedMinutes = DateUtils.GetMinutesSince(stopDate); //close the database db.close(); switch (id) { case 1: current = stoppedMinutes; max = 1 * 24 * 60; break; // max in days case 2: current = stoppedMinutes; max = 365 * 24 * 60; break; case 3: current = stoppedMinutes; max = 2 * 24 * 60; break; case 4: current = stoppedMinutes; max = 4 * 24 * 60; break; case 5: current = stoppedMinutes; max = 2 * 24 * 60; break; case 6: current = stoppedMinutes; max = 40 * 24 * 60; break; case 7: current = stoppedMinutes; max = 14 * 24 * 60; break; case 8: current = stoppedMinutes; max = 3 * 365 * 24 * 60; break; case 9: current = stoppedMinutes; max = 10 * 365 * 24 * 60; break; default: current = 100; max = 100; break; } progress = (current / max) * 100; if (progress > 100) { progress = 100; } return (int) progress; } //geeft tijd over terug protected int getRemainingTime(int id) { long tijd = 0; DatabaseHandler db = new DatabaseHandler(getActivity()); Calendar today = Calendar.getInstance(); Calendar stopDate = DateUtils.calendarFor(db.getUser(1).getQuitYear(), db.getUser(1).getQuitMonth(), db.getUser(1).getQuitDay(), db.getUser(1).getQuitHour(), db.getUser(1).getQuitMinute()); Calendar maxDate = stopDate; //close the database db.close(); switch (id) { case 1: maxDate.add(Calendar.DAY_OF_MONTH, 1); break; // STOPDATUM + HOEVEEL DAGEN HET DUURT case 2: maxDate.add(Calendar.YEAR, 1); break; case 3: maxDate.add(Calendar.DAY_OF_MONTH, 2); break; case 4: maxDate.add(Calendar.DAY_OF_MONTH, 4); break; case 5: maxDate.add(Calendar.DAY_OF_MONTH, 2); break; case 6: maxDate.add(Calendar.DAY_OF_MONTH, 40); break; case 7: maxDate.add(Calendar.DAY_OF_MONTH, 14); break; case 8: maxDate.add(Calendar.YEAR, 3); break; case 9: maxDate.add(Calendar.YEAR, 10); break; default: break; } tijd = DateUtils.GetMinutesBetween(today, maxDate); if (tijd < 0) { tijd = 0; } return (int) tijd; } public static final HealthProgress newInstance(int i) { HealthProgress f = new HealthProgress(); Bundle bdl = new Bundle(1); f.setArguments(bdl); position = i; return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.activity_health_progress, container, false); handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == UpdateProgress) { if (getActivity() != null) { Activity a = getActivity(); TextView t1 = (TextView) a.findViewById(R.id.health_procent1); if (t1 != null) { drawProgress(); } } } super.handleMessage(msg); } }; //timer Thread updateProcess = new Thread() { public void run() { while (1 == 1) { try { sleep(10000); Message msg = new Message(); msg.what = UpdateProgress; handler.sendMessage(msg); } catch (InterruptedException e) { e.printStackTrace(); } finally { } } } }; updateProcess.start(); //update on startup Message msg = new Message(); msg.what = UpdateProgress; handler.sendMessage(msg); return v; } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { //implements the main method what every fragment should do when it's visible uservisibilityevent.viewIsVisible(getActivity(), position, "green", "title_activity_health_progress"); } } }
True
1,916
15
2,140
16
2,273
12
2,140
16
2,503
16
false
false
false
false
false
true
1,169
36399_11
/* * Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. * All rights reserved. */ /* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** NOTE: The Original Code (as defined below) has been licensed to Sun ** Microsystems, Inc. ("Sun") under the SGI Free Software License B ** (Version 1.1), shown above ("SGI License"). Pursuant to Section ** 3.2(3) of the SGI License, Sun is distributing the Covered Code to ** you under an alternative license ("Alternative License"). This ** Alternative License includes all of the provisions of the SGI License ** except that Section 2.2 and 11 are omitted. Any differences between ** the Alternative License and the SGI License are offered solely by Sun ** and not by SGI. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. ** ** Author: Eric Veach, July 1994 ** Java Port: Pepijn Van Eeckhoudt, July 2003 ** Java Port: Nathan Parker Burg, August 2003 */ package gov.nasa.worldwind.util.glu.tessellator; class Geom { private Geom() { } /* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w), * evaluates the t-coord of the edge uw at the s-coord of the vertex v. * Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. * If uw is vertical (and thus passes thru v), the result is zero. * * The calculation is extremely accurate and stable, even when v * is very close to u or w. In particular if we set v->t = 0 and * let r be the negated result (this evaluates (uw)(v->s)), then * r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t). */ static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) { double gapL, gapR; assert (VertLeq(u, v) && VertLeq(v, w)); gapL = v.s - u.s; gapR = w.s - v.s; if (gapL + gapR > 0) { if (gapL < gapR) { return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR)); } else { return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) { double gapL, gapR; assert (VertLeq(u, v) && VertLeq(v, w)); gapL = v.s - u.s; gapR = w.s - v.s; if (gapL + gapR > 0) { return (v.t - w.t) * gapL + (v.t - u.t) * gapR; } /* vertical line */ return 0; } /*********************************************************************** * Define versions of EdgeSign, EdgeEval with s and t transposed. */ static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) { /* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w), * evaluates the t-coord of the edge uw at the s-coord of the vertex v. * Returns v->s - (uw)(v->t), ie. the signed distance from uw to v. * If uw is vertical (and thus passes thru v), the result is zero. * * The calculation is extremely accurate and stable, even when v * is very close to u or w. In particular if we set v->s = 0 and * let r be the negated result (this evaluates (uw)(v->t)), then * r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s). */ double gapL, gapR; assert (TransLeq(u, v) && TransLeq(v, w)); gapL = v.t - u.t; gapR = w.t - v.t; if (gapL + gapR > 0) { if (gapL < gapR) { return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR)); } else { return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) { /* Returns a number whose sign matches TransEval(u,v,w) but which * is cheaper to evaluate. Returns > 0, == 0 , or < 0 * as v is above, on, or below the edge uw. */ double gapL, gapR; assert (TransLeq(u, v) && TransLeq(v, w)); gapL = v.t - u.t; gapR = w.t - v.t; if (gapL + gapR > 0) { return (v.s - w.s) * gapL + (v.s - u.s) * gapR; } /* vertical line */ return 0; } static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) { /* For almost-degenerate situations, the results are not reliable. * Unless the floating-point arithmetic can be performed without * rounding errors, *any* implementation will give incorrect results * on some degenerate inputs, so the client must have some way to * handle this situation. */ return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0; } /* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b), * or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces * this in the rare case that one argument is slightly negative. * The implementation is extremely stable numerically. * In particular it guarantees that the result r satisfies * MIN(x,y) <= r <= MAX(x,y), and the results are very accurate * even when a and b differ greatly in magnitude. */ static double Interpolate(double a, double x, double b, double y) { a = (a < 0) ? 0 : a; b = (b < 0) ? 0 : b; if (a <= b) { if (b == 0) { return (x + y) / 2.0; } else { return (x + (y - x) * (a / (a + b))); } } else { return (y + (x - y) * (b / (a + b))); } } static void EdgeIntersect(GLUvertex o1, GLUvertex d1, GLUvertex o2, GLUvertex d2, GLUvertex v) /* Given edges (o1,d1) and (o2,d2), compute their point of intersection. * The computed point is guaranteed to lie in the intersection of the * bounding rectangles defined by each edge. */ { double z1, z2; /* This is certainly not the most efficient way to find the intersection * of two line segments, but it is very numerically stable. * * Strategy: find the two middle vertices in the VertLeq ordering, * and interpolate the intersection s-value from these. Then repeat * using the TransLeq ordering to find the intersection t-value. */ if (!VertLeq(o1, d1)) { GLUvertex temp = o1; o1 = d1; d1 = temp; } if (!VertLeq(o2, d2)) { GLUvertex temp = o2; o2 = d2; d2 = temp; } if (!VertLeq(o1, o2)) { GLUvertex temp = o1; o1 = o2; o2 = temp; temp = d1; d1 = d2; d2 = temp; } if (!VertLeq(o2, d1)) { /* Technically, no intersection -- do our best */ v.s = (o2.s + d1.s) / 2.0; } else if (VertLeq(d1, d2)) { /* Interpolate between o2 and d1 */ z1 = EdgeEval(o1, o2, d1); z2 = EdgeEval(o2, d1, d2); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.s = Interpolate(z1, o2.s, z2, d1.s); } else { /* Interpolate between o2 and d2 */ z1 = EdgeSign(o1, o2, d1); z2 = -EdgeSign(o1, d2, d1); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.s = Interpolate(z1, o2.s, z2, d2.s); } /* Now repeat the process for t */ if (!TransLeq(o1, d1)) { GLUvertex temp = o1; o1 = d1; d1 = temp; } if (!TransLeq(o2, d2)) { GLUvertex temp = o2; o2 = d2; d2 = temp; } if (!TransLeq(o1, o2)) { GLUvertex temp = o2; o2 = o1; o1 = temp; temp = d2; d2 = d1; d1 = temp; } if (!TransLeq(o2, d1)) { /* Technically, no intersection -- do our best */ v.t = (o2.t + d1.t) / 2.0; } else if (TransLeq(d1, d2)) { /* Interpolate between o2 and d1 */ z1 = TransEval(o1, o2, d1); z2 = TransEval(o2, d1, d2); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.t = Interpolate(z1, o2.t, z2, d1.t); } else { /* Interpolate between o2 and d2 */ z1 = TransSign(o1, o2, d1); z2 = -TransSign(o1, d2, d1); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.t = Interpolate(z1, o2.t, z2, d2.t); } } static boolean VertEq(GLUvertex u, GLUvertex v) { return u.s == v.s && u.t == v.t; } static boolean VertLeq(GLUvertex u, GLUvertex v) { return u.s < v.s || (u.s == v.s && u.t <= v.t); } /* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */ static boolean TransLeq(GLUvertex u, GLUvertex v) { return u.t < v.t || (u.t == v.t && u.s <= v.s); } static boolean EdgeGoesLeft(GLUhalfEdge e) { return VertLeq(e.Sym.Org, e.Org); } static boolean EdgeGoesRight(GLUhalfEdge e) { return VertLeq(e.Org, e.Sym.Org); } static double VertL1dist(GLUvertex u, GLUvertex v) { return Math.abs(u.s - v.s) + Math.abs(u.t - v.t); } }
NASAWorldWind/WorldWindAndroid
worldwind/src/main/java/gov/nasa/worldwind/util/glu/tessellator/Geom.java
3,807
/* Interpolate between o2 and d1 */
block_comment
nl
/* * Portions Copyright (C) 2003-2006 Sun Microsystems, Inc. * All rights reserved. */ /* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** NOTE: The Original Code (as defined below) has been licensed to Sun ** Microsystems, Inc. ("Sun") under the SGI Free Software License B ** (Version 1.1), shown above ("SGI License"). Pursuant to Section ** 3.2(3) of the SGI License, Sun is distributing the Covered Code to ** you under an alternative license ("Alternative License"). This ** Alternative License includes all of the provisions of the SGI License ** except that Section 2.2 and 11 are omitted. Any differences between ** the Alternative License and the SGI License are offered solely by Sun ** and not by SGI. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. ** ** Author: Eric Veach, July 1994 ** Java Port: Pepijn Van Eeckhoudt, July 2003 ** Java Port: Nathan Parker Burg, August 2003 */ package gov.nasa.worldwind.util.glu.tessellator; class Geom { private Geom() { } /* Given three vertices u,v,w such that VertLeq(u,v) && VertLeq(v,w), * evaluates the t-coord of the edge uw at the s-coord of the vertex v. * Returns v->t - (uw)(v->s), ie. the signed distance from uw to v. * If uw is vertical (and thus passes thru v), the result is zero. * * The calculation is extremely accurate and stable, even when v * is very close to u or w. In particular if we set v->t = 0 and * let r be the negated result (this evaluates (uw)(v->s)), then * r is guaranteed to satisfy MIN(u->t,w->t) <= r <= MAX(u->t,w->t). */ static double EdgeEval(GLUvertex u, GLUvertex v, GLUvertex w) { double gapL, gapR; assert (VertLeq(u, v) && VertLeq(v, w)); gapL = v.s - u.s; gapR = w.s - v.s; if (gapL + gapR > 0) { if (gapL < gapR) { return (v.t - u.t) + (u.t - w.t) * (gapL / (gapL + gapR)); } else { return (v.t - w.t) + (w.t - u.t) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } static double EdgeSign(GLUvertex u, GLUvertex v, GLUvertex w) { double gapL, gapR; assert (VertLeq(u, v) && VertLeq(v, w)); gapL = v.s - u.s; gapR = w.s - v.s; if (gapL + gapR > 0) { return (v.t - w.t) * gapL + (v.t - u.t) * gapR; } /* vertical line */ return 0; } /*********************************************************************** * Define versions of EdgeSign, EdgeEval with s and t transposed. */ static double TransEval(GLUvertex u, GLUvertex v, GLUvertex w) { /* Given three vertices u,v,w such that TransLeq(u,v) && TransLeq(v,w), * evaluates the t-coord of the edge uw at the s-coord of the vertex v. * Returns v->s - (uw)(v->t), ie. the signed distance from uw to v. * If uw is vertical (and thus passes thru v), the result is zero. * * The calculation is extremely accurate and stable, even when v * is very close to u or w. In particular if we set v->s = 0 and * let r be the negated result (this evaluates (uw)(v->t)), then * r is guaranteed to satisfy MIN(u->s,w->s) <= r <= MAX(u->s,w->s). */ double gapL, gapR; assert (TransLeq(u, v) && TransLeq(v, w)); gapL = v.t - u.t; gapR = w.t - v.t; if (gapL + gapR > 0) { if (gapL < gapR) { return (v.s - u.s) + (u.s - w.s) * (gapL / (gapL + gapR)); } else { return (v.s - w.s) + (w.s - u.s) * (gapR / (gapL + gapR)); } } /* vertical line */ return 0; } static double TransSign(GLUvertex u, GLUvertex v, GLUvertex w) { /* Returns a number whose sign matches TransEval(u,v,w) but which * is cheaper to evaluate. Returns > 0, == 0 , or < 0 * as v is above, on, or below the edge uw. */ double gapL, gapR; assert (TransLeq(u, v) && TransLeq(v, w)); gapL = v.t - u.t; gapR = w.t - v.t; if (gapL + gapR > 0) { return (v.s - w.s) * gapL + (v.s - u.s) * gapR; } /* vertical line */ return 0; } static boolean VertCCW(GLUvertex u, GLUvertex v, GLUvertex w) { /* For almost-degenerate situations, the results are not reliable. * Unless the floating-point arithmetic can be performed without * rounding errors, *any* implementation will give incorrect results * on some degenerate inputs, so the client must have some way to * handle this situation. */ return (u.s * (v.t - w.t) + v.s * (w.t - u.t) + w.s * (u.t - v.t)) >= 0; } /* Given parameters a,x,b,y returns the value (b*x+a*y)/(a+b), * or (x+y)/2 if a==b==0. It requires that a,b >= 0, and enforces * this in the rare case that one argument is slightly negative. * The implementation is extremely stable numerically. * In particular it guarantees that the result r satisfies * MIN(x,y) <= r <= MAX(x,y), and the results are very accurate * even when a and b differ greatly in magnitude. */ static double Interpolate(double a, double x, double b, double y) { a = (a < 0) ? 0 : a; b = (b < 0) ? 0 : b; if (a <= b) { if (b == 0) { return (x + y) / 2.0; } else { return (x + (y - x) * (a / (a + b))); } } else { return (y + (x - y) * (b / (a + b))); } } static void EdgeIntersect(GLUvertex o1, GLUvertex d1, GLUvertex o2, GLUvertex d2, GLUvertex v) /* Given edges (o1,d1) and (o2,d2), compute their point of intersection. * The computed point is guaranteed to lie in the intersection of the * bounding rectangles defined by each edge. */ { double z1, z2; /* This is certainly not the most efficient way to find the intersection * of two line segments, but it is very numerically stable. * * Strategy: find the two middle vertices in the VertLeq ordering, * and interpolate the intersection s-value from these. Then repeat * using the TransLeq ordering to find the intersection t-value. */ if (!VertLeq(o1, d1)) { GLUvertex temp = o1; o1 = d1; d1 = temp; } if (!VertLeq(o2, d2)) { GLUvertex temp = o2; o2 = d2; d2 = temp; } if (!VertLeq(o1, o2)) { GLUvertex temp = o1; o1 = o2; o2 = temp; temp = d1; d1 = d2; d2 = temp; } if (!VertLeq(o2, d1)) { /* Technically, no intersection -- do our best */ v.s = (o2.s + d1.s) / 2.0; } else if (VertLeq(d1, d2)) { /* Interpolate between o2<SUF>*/ z1 = EdgeEval(o1, o2, d1); z2 = EdgeEval(o2, d1, d2); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.s = Interpolate(z1, o2.s, z2, d1.s); } else { /* Interpolate between o2 and d2 */ z1 = EdgeSign(o1, o2, d1); z2 = -EdgeSign(o1, d2, d1); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.s = Interpolate(z1, o2.s, z2, d2.s); } /* Now repeat the process for t */ if (!TransLeq(o1, d1)) { GLUvertex temp = o1; o1 = d1; d1 = temp; } if (!TransLeq(o2, d2)) { GLUvertex temp = o2; o2 = d2; d2 = temp; } if (!TransLeq(o1, o2)) { GLUvertex temp = o2; o2 = o1; o1 = temp; temp = d2; d2 = d1; d1 = temp; } if (!TransLeq(o2, d1)) { /* Technically, no intersection -- do our best */ v.t = (o2.t + d1.t) / 2.0; } else if (TransLeq(d1, d2)) { /* Interpolate between o2 and d1 */ z1 = TransEval(o1, o2, d1); z2 = TransEval(o2, d1, d2); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.t = Interpolate(z1, o2.t, z2, d1.t); } else { /* Interpolate between o2 and d2 */ z1 = TransSign(o1, o2, d1); z2 = -TransSign(o1, d2, d1); if (z1 + z2 < 0) { z1 = -z1; z2 = -z2; } v.t = Interpolate(z1, o2.t, z2, d2.t); } } static boolean VertEq(GLUvertex u, GLUvertex v) { return u.s == v.s && u.t == v.t; } static boolean VertLeq(GLUvertex u, GLUvertex v) { return u.s < v.s || (u.s == v.s && u.t <= v.t); } /* Versions of VertLeq, EdgeSign, EdgeEval with s and t transposed. */ static boolean TransLeq(GLUvertex u, GLUvertex v) { return u.t < v.t || (u.t == v.t && u.s <= v.s); } static boolean EdgeGoesLeft(GLUhalfEdge e) { return VertLeq(e.Sym.Org, e.Org); } static boolean EdgeGoesRight(GLUhalfEdge e) { return VertLeq(e.Org, e.Sym.Org); } static double VertL1dist(GLUvertex u, GLUvertex v) { return Math.abs(u.s - v.s) + Math.abs(u.t - v.t); } }
False
3,271
10
3,512
10
3,687
10
3,512
10
3,959
11
false
false
false
false
false
true
1,561
20477_1
package nl.enterbv.easion.View; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import nl.enterbv.easion.Model.Enquete; import nl.enterbv.easion.R; /** * Created by joepv on 15.jun.2016. */ public class TaskListAdapter extends ArrayAdapter<Enquete> { public TaskListAdapter(Context context, List<Enquete> objects) { super(context, -1, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_task_list, parent, false); } TextView title = (TextView) convertView.findViewById(R.id.tv_item_title); title.setText(getItem(position).getLabel()); TextView organization = (TextView) convertView.findViewById(R.id.tv_item_organization); organization.setText(getItem(position).getSender()); TextView date = (TextView) convertView.findViewById(R.id.tv_item_date); date.setText(getItem(position).getCreationDate()); View progress = convertView.findViewById(R.id.item_progress); //Progress of task: 0 = Nieuw, 1 = Bezig, 2 = Klaar switch (getItem(position).getProgress()) { case 0: progress.setBackgroundResource(R.drawable.nieuw); break; case 1: progress.setBackgroundResource(R.drawable.bezig); break; case 2: progress.setBackgroundResource(R.drawable.klaar); break; default: break; } return convertView; } }
SaxionHBO-ICT/parantion-enterbv
Easion/app/src/main/java/nl/enterbv/easion/View/TaskListAdapter.java
553
//Progress of task: 0 = Nieuw, 1 = Bezig, 2 = Klaar
line_comment
nl
package nl.enterbv.easion.View; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import nl.enterbv.easion.Model.Enquete; import nl.enterbv.easion.R; /** * Created by joepv on 15.jun.2016. */ public class TaskListAdapter extends ArrayAdapter<Enquete> { public TaskListAdapter(Context context, List<Enquete> objects) { super(context, -1, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_task_list, parent, false); } TextView title = (TextView) convertView.findViewById(R.id.tv_item_title); title.setText(getItem(position).getLabel()); TextView organization = (TextView) convertView.findViewById(R.id.tv_item_organization); organization.setText(getItem(position).getSender()); TextView date = (TextView) convertView.findViewById(R.id.tv_item_date); date.setText(getItem(position).getCreationDate()); View progress = convertView.findViewById(R.id.item_progress); //Progress of<SUF> switch (getItem(position).getProgress()) { case 0: progress.setBackgroundResource(R.drawable.nieuw); break; case 1: progress.setBackgroundResource(R.drawable.bezig); break; case 2: progress.setBackgroundResource(R.drawable.klaar); break; default: break; } return convertView; } }
True
357
24
462
24
476
21
462
24
535
23
false
false
false
false
false
true
1,392
15367_11
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class LevelExtra here. * * @author (your name) * @version (a version number or a date) */ public class LevelExtra extends World { private CollisionEngine ce; private TileEngine te; /** * Constructor for objects of class LevelExtra. * */ public LevelExtra() { super(1000, 800, 1,false); this.setBackground("4_Bg.png"); int[][] map = { {151,101,101,101,101,101,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,13,151,-1,-1,-1,-1,-1,-1}, {151,95,95,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,151,6,6,6,6,6,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,106,-1,-1,106,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,108,-1,-1,108,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,108,-1,-1,108,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,108,-1,-1,108,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,84,95,-1,-1,-1,-1,-1,-1,-1,-1,81,82,82,83,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,84,85,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,127,-1,-1,6,-1,-1,-1,-1,68,6}, {6,94,94,71,71,71,71,71,71,71,71,71,71,71,84,85,6,94,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,127,127,127,6,71,71,6,-1,6,6,6,67,6}, {6,8,8,8,8,8,8,8,8,8,8,8,8,8,6,6,6,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,6,6,6,6,8,8,6,8,8,8,8,8,6}, }; TileEngine te = new TileEngine(this, 60, 60, map); te.setTileFactory(new TileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(ce, te); //Declareren en initialiseren van de dia klassen Dia dia = new Dia(); //Declareren en initialiseren van de leven klassen Leven up1 = new Leven(); // Creeer een scoreboard Punten pu = new Punten(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 2040, 495); addObject(dia, 1675, 315); addObject(up1, 2785, 435); addObject(pu, 830, 45); addObject(new Hart(), 170, 45); addObject(new Sorry(), 2665, 200); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } }
ROCMondriaanTIN/project-greenfoot-game-SebastiaanBroeckaert
LevelExtra.java
1,696
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class LevelExtra here. * * @author (your name) * @version (a version number or a date) */ public class LevelExtra extends World { private CollisionEngine ce; private TileEngine te; /** * Constructor for objects of class LevelExtra. * */ public LevelExtra() { super(1000, 800, 1,false); this.setBackground("4_Bg.png"); int[][] map = { {151,101,101,101,101,101,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,13,151,-1,-1,-1,-1,-1,-1}, {151,95,95,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,166,151,6,6,6,6,6,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,106,-1,-1,106,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,108,-1,-1,108,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,108,-1,-1,108,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,108,-1,-1,108,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,84,95,-1,-1,-1,-1,-1,-1,-1,-1,81,82,82,83,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,6}, {6,94,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,84,85,94,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,127,-1,-1,6,-1,-1,-1,-1,68,6}, {6,94,94,71,71,71,71,71,71,71,71,71,71,71,84,85,6,94,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,127,127,127,6,71,71,6,-1,6,6,6,67,6}, {6,8,8,8,8,8,8,8,8,8,8,8,8,8,6,6,6,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,6,6,6,6,8,8,6,8,8,8,8,8,6}, }; TileEngine te = new TileEngine(this, 60, 60, map); te.setTileFactory(new TileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken Hero hero = new Hero(ce, te); //Declareren en initialiseren van de dia klassen Dia dia = new Dia(); //Declareren en initialiseren van de leven klassen Leven up1 = new Leven(); // Creeer een scoreboard Punten pu = new Punten(); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Alle objecten<SUF> addObject(camera, 0, 0); addObject(hero, 2040, 495); addObject(dia, 1675, 315); addObject(up1, 2785, 435); addObject(pu, 830, 45); addObject(new Hart(), 170, 45); addObject(new Sorry(), 2665, 200); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); } @Override public void act() { ce.update(); } }
True
1,787
19
1,844
25
1,838
18
1,844
25
1,917
20
false
false
false
false
false
true
4,271
160414_6
package roborally.model; import be.kuleuven.cs.som.annotate.Basic; import roborally.property.Energy; import roborally.property.Weight; /** * Deze klasse houdt een batterij bij. Deze heeft een positie, een gewicht en een hoeveelheid energie. Deze kan door een robot gedragen worden. * * @invar De hoeveelheid energie van een batterij moet altijd geldig zijn. * |isValidBatteryEnergyAmount(getEnergy()) * * @author Bavo Goosens (1e bachelor informatica, r0297884), Samuel Debruyn (1e bachelor informatica, r0305472) * * @version 2.1 */ public class Battery extends Item{ /** * Maakt een nieuwe batterij aan. * * @param energy * Energie van de nieuwe batterij. * * @param weight * Massa van de batterij. * * @post De energie van de nieuwe batterij is gelijk aan de gegeven energie. * |new.getEnergy().equals(energy) * * @post Het gewicht van de nieuwe batterij is gelijk aan het gegeven gewicht. * |new.getWeight().equals(weight) */ public Battery(Energy energy, Weight weight){ super(weight); setEnergy(energy); } /** * Deze methode wijzigt de energie van de batterij. * * @param energy * De nieuwe energie van het item. * * @pre Energie moet geldige hoeveelheid zijn. * |isValidBatteryEnergy(energy) * * @post De energie van het item is gelijk aan de gegeven energie. * |new.getEnergy().equals(energy) */ public void setEnergy(Energy energy) { this.energy = energy; } /** * Geeft de energie van de batterij. * * @return Energie van de batterij. * |energy */ @Basic public Energy getEnergy() { return energy; } /** * Energie in de batterij. */ private Energy energy; /** * Deze methode kijkt na of de gegeven energie geldig is voor een batterij. * * @param energy * De energie die nagekeken moet worden. * * @return Een boolean die true is als de energie geldig is. * |if(!Energy.isValidEnergyAmount(energy.getEnergy())) * | false * |(energy.getEnergy() <= MAX_ENERGY.getEnergy()) */ public static boolean isValidBatteryEnergy(Energy energy){ if(!Energy.isValidEnergyAmount(energy.getEnergy())) return false; return (energy.getEnergy() <= MAX_ENERGY.getEnergy()); } /** * De maximale energie van een batterij. */ public final static Energy MAX_ENERGY = new Energy(5000); /** * Deze methode wordt opgeroepen wanneer de batterij geraakt wordt door een laser of een surprise box. * * @post De nieuwe energie van de batterij is gelijk aan het maximum of aan 500 meer dan wat hij ervoor had. * |new.getEnergy().equals(MAX_ENERGY) || new.getEnergy().equals(Energy.energySum(getEnergy(), HIT_ENERGY)) */ @Override protected void damage(){ Energy newEnergy = Energy.energySum(getEnergy(), HIT_ENERGY); if (newEnergy.getEnergy() > MAX_ENERGY.getEnergy()) setEnergy(MAX_ENERGY); setEnergy(newEnergy); } /** * De hoeveelheid energie die een battery bij krijgt wanneer hij geraakt wordt. */ private final static Energy HIT_ENERGY = new Energy(500); /* * Deze methode zet het object om naar een String. * * @return Een textuele representatie van dit object waarbij duidelijk wordt wat de eigenschappen van dit object zijn. * |super.toString() + ", energie: " + getEnergy().toString() * * @see roborally.model.Item#toString() */ @Override public String toString() { return super.toString() + ", energie: " + getEnergy().toString(); } }
sdebruyn/student-Java-game-Roborally
src/roborally/model/Battery.java
1,279
/** * De maximale energie van een batterij. */
block_comment
nl
package roborally.model; import be.kuleuven.cs.som.annotate.Basic; import roborally.property.Energy; import roborally.property.Weight; /** * Deze klasse houdt een batterij bij. Deze heeft een positie, een gewicht en een hoeveelheid energie. Deze kan door een robot gedragen worden. * * @invar De hoeveelheid energie van een batterij moet altijd geldig zijn. * |isValidBatteryEnergyAmount(getEnergy()) * * @author Bavo Goosens (1e bachelor informatica, r0297884), Samuel Debruyn (1e bachelor informatica, r0305472) * * @version 2.1 */ public class Battery extends Item{ /** * Maakt een nieuwe batterij aan. * * @param energy * Energie van de nieuwe batterij. * * @param weight * Massa van de batterij. * * @post De energie van de nieuwe batterij is gelijk aan de gegeven energie. * |new.getEnergy().equals(energy) * * @post Het gewicht van de nieuwe batterij is gelijk aan het gegeven gewicht. * |new.getWeight().equals(weight) */ public Battery(Energy energy, Weight weight){ super(weight); setEnergy(energy); } /** * Deze methode wijzigt de energie van de batterij. * * @param energy * De nieuwe energie van het item. * * @pre Energie moet geldige hoeveelheid zijn. * |isValidBatteryEnergy(energy) * * @post De energie van het item is gelijk aan de gegeven energie. * |new.getEnergy().equals(energy) */ public void setEnergy(Energy energy) { this.energy = energy; } /** * Geeft de energie van de batterij. * * @return Energie van de batterij. * |energy */ @Basic public Energy getEnergy() { return energy; } /** * Energie in de batterij. */ private Energy energy; /** * Deze methode kijkt na of de gegeven energie geldig is voor een batterij. * * @param energy * De energie die nagekeken moet worden. * * @return Een boolean die true is als de energie geldig is. * |if(!Energy.isValidEnergyAmount(energy.getEnergy())) * | false * |(energy.getEnergy() <= MAX_ENERGY.getEnergy()) */ public static boolean isValidBatteryEnergy(Energy energy){ if(!Energy.isValidEnergyAmount(energy.getEnergy())) return false; return (energy.getEnergy() <= MAX_ENERGY.getEnergy()); } /** * De maximale energie<SUF>*/ public final static Energy MAX_ENERGY = new Energy(5000); /** * Deze methode wordt opgeroepen wanneer de batterij geraakt wordt door een laser of een surprise box. * * @post De nieuwe energie van de batterij is gelijk aan het maximum of aan 500 meer dan wat hij ervoor had. * |new.getEnergy().equals(MAX_ENERGY) || new.getEnergy().equals(Energy.energySum(getEnergy(), HIT_ENERGY)) */ @Override protected void damage(){ Energy newEnergy = Energy.energySum(getEnergy(), HIT_ENERGY); if (newEnergy.getEnergy() > MAX_ENERGY.getEnergy()) setEnergy(MAX_ENERGY); setEnergy(newEnergy); } /** * De hoeveelheid energie die een battery bij krijgt wanneer hij geraakt wordt. */ private final static Energy HIT_ENERGY = new Energy(500); /* * Deze methode zet het object om naar een String. * * @return Een textuele representatie van dit object waarbij duidelijk wordt wat de eigenschappen van dit object zijn. * |super.toString() + ", energie: " + getEnergy().toString() * * @see roborally.model.Item#toString() */ @Override public String toString() { return super.toString() + ", energie: " + getEnergy().toString(); } }
True
1,030
15
1,213
17
1,121
15
1,213
17
1,388
17
false
false
false
false
false
true
1,247
94220_16
/* * Copyright 2012-2023 The Feign Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package feign.auth; import java.io.UnsupportedEncodingException; /** * copied from <a href= * "https://github.com/square/okhttp/blob/master/okhttp-protocols/src/main/java/com/squareup/okhttp/internal/Base64.java">okhttp</a> * * @author Alexander Y. Kleymenov */ final class Base64 { public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final byte[] MAP = new byte[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private Base64() {} public static byte[] decode(byte[] in) { return decode(in, in.length); } public static byte[] decode(byte[] in, int len) { // approximate output length int length = len / 4 * 3; // return an empty array on empty or short input without padding if (length == 0) { return EMPTY_BYTE_ARRAY; } // temporary array byte[] out = new byte[length]; // number of padding characters ('=') int pad = 0; byte chr; // compute the number of the padding characters // and adjust the length of the input for (;; len--) { chr = in[len - 1]; // skip the neutral characters if ((chr == '\n') || (chr == '\r') || (chr == ' ') || (chr == '\t')) { continue; } if (chr == '=') { pad++; } else { break; } } // index in the output array int outIndex = 0; // index in the input array int inIndex = 0; // holds the value of the input character int bits = 0; // holds the value of the input quantum int quantum = 0; for (int i = 0; i < len; i++) { chr = in[i]; // skip the neutral characters if ((chr == '\n') || (chr == '\r') || (chr == ' ') || (chr == '\t')) { continue; } if ((chr >= 'A') && (chr <= 'Z')) { // char ASCII value // A 65 0 // Z 90 25 (ASCII - 65) bits = chr - 65; } else if ((chr >= 'a') && (chr <= 'z')) { // char ASCII value // a 97 26 // z 122 51 (ASCII - 71) bits = chr - 71; } else if ((chr >= '0') && (chr <= '9')) { // char ASCII value // 0 48 52 // 9 57 61 (ASCII + 4) bits = chr + 4; } else if (chr == '+') { bits = 62; } else if (chr == '/') { bits = 63; } else { return null; } // append the value to the quantum quantum = (quantum << 6) | (byte) bits; if (inIndex % 4 == 3) { // 4 characters were read, so make the output: out[outIndex++] = (byte) (quantum >> 16); out[outIndex++] = (byte) (quantum >> 8); out[outIndex++] = (byte) quantum; } inIndex++; } if (pad > 0) { // adjust the quantum value according to the padding quantum = quantum << (6 * pad); // make output out[outIndex++] = (byte) (quantum >> 16); if (pad == 1) { out[outIndex++] = (byte) (quantum >> 8); } } // create the resulting array byte[] result = new byte[outIndex]; System.arraycopy(out, 0, result, 0, outIndex); return result; } public static String encode(byte[] in) { int length = (in.length + 2) * 4 / 3; byte[] out = new byte[length]; int index = 0, end = in.length - in.length % 3; for (int i = 0; i < end; i += 3) { out[index++] = MAP[(in[i] & 0xff) >> 2]; out[index++] = MAP[((in[i] & 0x03) << 4) | ((in[i + 1] & 0xff) >> 4)]; out[index++] = MAP[((in[i + 1] & 0x0f) << 2) | ((in[i + 2] & 0xff) >> 6)]; out[index++] = MAP[(in[i + 2] & 0x3f)]; } switch (in.length % 3) { case 1: out[index++] = MAP[(in[end] & 0xff) >> 2]; out[index++] = MAP[(in[end] & 0x03) << 4]; out[index++] = '='; out[index++] = '='; break; case 2: out[index++] = MAP[(in[end] & 0xff) >> 2]; out[index++] = MAP[((in[end] & 0x03) << 4) | ((in[end + 1] & 0xff) >> 4)]; out[index++] = MAP[((in[end + 1] & 0x0f) << 2)]; out[index++] = '='; break; } try { return new String(out, 0, index, "US-ASCII"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } }
OpenFeign/feign
core/src/main/java/feign/auth/Base64.java
1,942
// char ASCII value
line_comment
nl
/* * Copyright 2012-2023 The Feign Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package feign.auth; import java.io.UnsupportedEncodingException; /** * copied from <a href= * "https://github.com/square/okhttp/blob/master/okhttp-protocols/src/main/java/com/squareup/okhttp/internal/Base64.java">okhttp</a> * * @author Alexander Y. Kleymenov */ final class Base64 { public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final byte[] MAP = new byte[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private Base64() {} public static byte[] decode(byte[] in) { return decode(in, in.length); } public static byte[] decode(byte[] in, int len) { // approximate output length int length = len / 4 * 3; // return an empty array on empty or short input without padding if (length == 0) { return EMPTY_BYTE_ARRAY; } // temporary array byte[] out = new byte[length]; // number of padding characters ('=') int pad = 0; byte chr; // compute the number of the padding characters // and adjust the length of the input for (;; len--) { chr = in[len - 1]; // skip the neutral characters if ((chr == '\n') || (chr == '\r') || (chr == ' ') || (chr == '\t')) { continue; } if (chr == '=') { pad++; } else { break; } } // index in the output array int outIndex = 0; // index in the input array int inIndex = 0; // holds the value of the input character int bits = 0; // holds the value of the input quantum int quantum = 0; for (int i = 0; i < len; i++) { chr = in[i]; // skip the neutral characters if ((chr == '\n') || (chr == '\r') || (chr == ' ') || (chr == '\t')) { continue; } if ((chr >= 'A') && (chr <= 'Z')) { // char ASCII value // A 65 0 // Z 90 25 (ASCII - 65) bits = chr - 65; } else if ((chr >= 'a') && (chr <= 'z')) { // char ASCII<SUF> // a 97 26 // z 122 51 (ASCII - 71) bits = chr - 71; } else if ((chr >= '0') && (chr <= '9')) { // char ASCII value // 0 48 52 // 9 57 61 (ASCII + 4) bits = chr + 4; } else if (chr == '+') { bits = 62; } else if (chr == '/') { bits = 63; } else { return null; } // append the value to the quantum quantum = (quantum << 6) | (byte) bits; if (inIndex % 4 == 3) { // 4 characters were read, so make the output: out[outIndex++] = (byte) (quantum >> 16); out[outIndex++] = (byte) (quantum >> 8); out[outIndex++] = (byte) quantum; } inIndex++; } if (pad > 0) { // adjust the quantum value according to the padding quantum = quantum << (6 * pad); // make output out[outIndex++] = (byte) (quantum >> 16); if (pad == 1) { out[outIndex++] = (byte) (quantum >> 8); } } // create the resulting array byte[] result = new byte[outIndex]; System.arraycopy(out, 0, result, 0, outIndex); return result; } public static String encode(byte[] in) { int length = (in.length + 2) * 4 / 3; byte[] out = new byte[length]; int index = 0, end = in.length - in.length % 3; for (int i = 0; i < end; i += 3) { out[index++] = MAP[(in[i] & 0xff) >> 2]; out[index++] = MAP[((in[i] & 0x03) << 4) | ((in[i + 1] & 0xff) >> 4)]; out[index++] = MAP[((in[i + 1] & 0x0f) << 2) | ((in[i + 2] & 0xff) >> 6)]; out[index++] = MAP[(in[i + 2] & 0x3f)]; } switch (in.length % 3) { case 1: out[index++] = MAP[(in[end] & 0xff) >> 2]; out[index++] = MAP[(in[end] & 0x03) << 4]; out[index++] = '='; out[index++] = '='; break; case 2: out[index++] = MAP[(in[end] & 0xff) >> 2]; out[index++] = MAP[((in[end] & 0x03) << 4) | ((in[end + 1] & 0xff) >> 4)]; out[index++] = MAP[((in[end + 1] & 0x0f) << 2)]; out[index++] = '='; break; } try { return new String(out, 0, index, "US-ASCII"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } }
False
1,633
4
1,692
4
1,817
4
1,692
4
1,925
4
false
false
false
false
false
true
1,055
194331_1
package nl.novi.techiteasy1121.config; import nl.novi.techiteasy1121.filter.JwtRequestFilter; import nl.novi.techiteasy1121.services.CustomUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /* Deze security is niet de enige manier om het te doen. In de andere branch van deze github repo staat een ander voorbeeld */ @Configuration @EnableWebSecurity public class SpringSecurityConfig { public final CustomUserDetailsService customUserDetailsService; private final JwtRequestFilter jwtRequestFilter; public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) { this.customUserDetailsService = customUserDetailsService; this.jwtRequestFilter = jwtRequestFilter; } // PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig. // Je kunt dit ook in een aparte configuratie klasse zetten. @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()) .and() .build(); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { http .csrf().disable() .httpBasic().disable() .cors().and() .authorizeHttpRequests() // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").permitAll() .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN") // Je mag meerdere paths tegelijk definieren .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll() .anyRequest().denyAll() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
Majda-Mech/backend-spring-boot-tech-it-easy-security-uitwerkingen
src/main/java/nl/novi/techiteasy1121/config/SpringSecurityConfig.java
1,140
// PasswordEncoderBean. Deze kun je overal in je applicatie injecteren waar nodig.
line_comment
nl
package nl.novi.techiteasy1121.config; import nl.novi.techiteasy1121.filter.JwtRequestFilter; import nl.novi.techiteasy1121.services.CustomUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /* Deze security is niet de enige manier om het te doen. In de andere branch van deze github repo staat een ander voorbeeld */ @Configuration @EnableWebSecurity public class SpringSecurityConfig { public final CustomUserDetailsService customUserDetailsService; private final JwtRequestFilter jwtRequestFilter; public SpringSecurityConfig(CustomUserDetailsService customUserDetailsService, JwtRequestFilter jwtRequestFilter) { this.customUserDetailsService = customUserDetailsService; this.jwtRequestFilter = jwtRequestFilter; } // PasswordEncoderBean. Deze<SUF> // Je kunt dit ook in een aparte configuratie klasse zetten. @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Authenticatie met customUserDetailsService en passwordEncoder @Bean public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()) .and() .build(); } // Authorizatie met jwt @Bean protected SecurityFilterChain filter (HttpSecurity http) throws Exception { http .csrf().disable() .httpBasic().disable() .cors().and() .authorizeHttpRequests() // Wanneer je deze uncomments, staat je hele security open. Je hebt dan alleen nog een jwt nodig. // .requestMatchers("/**").permitAll() .requestMatchers(HttpMethod.POST, "/users").permitAll() .requestMatchers(HttpMethod.GET,"/users").hasRole("ADMIN") .requestMatchers(HttpMethod.POST,"/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/users/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/cimodules").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/cimodules/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/remotecontrollers").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/remotecontrollers/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/televisions").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/televisions/**").hasRole("ADMIN") .requestMatchers(HttpMethod.POST, "/wallbrackets").hasRole("ADMIN") .requestMatchers(HttpMethod.DELETE, "/wallbrackets/**").hasRole("ADMIN") // Je mag meerdere paths tegelijk definieren .requestMatchers("/cimodules", "/remotecontrollers", "/televisions", "/wallbrackets").hasAnyRole("ADMIN", "USER") .requestMatchers("/authenticated").authenticated() .requestMatchers("/authenticate").permitAll() .anyRequest().denyAll() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } }
False
814
20
944
21
937
18
944
21
1,105
21
false
false
false
false
false
true
3,403
34708_21
//------------------------------------------------------------------------- // Kansas Java interface -- bringing Kansas to the Web // // Structure.java // // $Revision: 30.1 $ // Andy Collins, Sun Microsystems Laboratories, Summer 1996 //------------------------------------------------------------------------- //------------------------------------------------------------------ // Structure.java - general structural interfaces and classes for // the Java Self browsers // Andy Collins, 8/5/96 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Interfaces: // // BailInOut requires bailin () and bailout () methods to // connect or disconnect itself and all children. // All components in the browser will implement this // so that the top-level applet can be used as a // total browser bailout point to disconnect and // put the program in a state from which it can // reconnect. // // Browser a generalized view into some logical rectangular // areas, supporting management both of the view // area and damage-list style redraws. A browser // is presumed to use a BrowserCore to do the actual // drawing. // // Classes: // // BrowserPanel is a Panel which can contain a browser core // BrowserMorph is a Morph which can contain a browser core // // see Viewer.java and RadarViewer.java for browser core // implementations. The interface used is BailInOut down and // Browser up //------------------------------------------------------------------ import java.awt.*; import java.applet.Applet; import java.io.*; import java.net.*; import java.util.*; //------------------------------------------------------------------ //------------------------------------------------------------------ interface Browser extends BailInOut { public void setBrowserCore (BrowserCore core); // view area management public Point getViewOrigin (); public void setViewOrigin (Point p); public Dimension getViewSize (); public Rectangle getViewArea (); public void moveTowards (String direction); public void moveTowards (String direction, float fraction); // coordinate xforms public Rectangle screenToLogical (Rectangle screen); public Rectangle logicalToScreen (Rectangle logical); // painting management public void redrawRect (Rectangle r); public void issueRepaint (); // misc public void setMessage (String msg); public Point getGlobalMouseLoc (); public Component getComponent (); } //------------------------------------------------------------------ //------------------------------------------------------------------ class BrowserCore implements BailInOut { Browser ownerBrowser; BailInOut bailoutPoint; BrowserCore (BrowserPanel browser, BailInOut bailoutPt) { ownerBrowser = browser; bailoutPoint = bailoutPt; } public void bailin () { } public synchronized void bailout () { } public void paint (Graphics g, Rectangle region) { } public void notifyViewChanged () { } public void notifyShouldDisable (int numPaintsPending) { } public void notifyShouldEnable () { } public boolean uiEvent (Event evt, int x, int y, int key) { return (false); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // passback stuff void redrawRect (Rectangle r) { ownerBrowser.redrawRect (r); } void issueRepaint () { ownerBrowser.issueRepaint (); } public Component getComponent () { return (ownerBrowser.getComponent ()); } } //------------------------------------------------------------------ //------------------------------------------------------------------ class BrowserPanel extends Panel implements Browser { protected Point logicalViewOrigin = null; protected BrowserCore browserCore = null; protected Label messageLabel; public BrowserPanel (BrowserCore core, Point viewOrigin, Label messageLabel) { logicalViewOrigin = viewOrigin; browserCore = core; this.messageLabel = messageLabel; } public void setMessage (String msg) { messageLabel.setText (msg); } public Component getComponent () { return ((Component) this); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // BailInOut support public void bailin () { if (browserCore != null) browserCore.bailin (); } public synchronized void bailout () { if (browserCore != null) browserCore.bailout (); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Structure management public void setBrowserCore (BrowserCore core) { browserCore = core; // browserCores.addElement (core); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Get/Set the viewing area in logical coordinates: public Point getViewOrigin () { return (logicalViewOrigin); } public void setViewOrigin (Point p) { logicalViewOrigin.x = p.x; logicalViewOrigin.y = p.y; } // No sets because changing the logical to physical ratio is not allowed public Dimension getViewSize () { return (new Dimension (size ().width, size ().height)); } public Rectangle getViewArea () { return (new Rectangle (logicalViewOrigin.x, logicalViewOrigin.y, size ().width, size ().height)); } // Move towards one of ("N", "E", "S", "W", "NE", "NW", "SW", "SE") // by either an 1/2 or by a fraction of the current view // size in that dimension public void moveTowards (String direction) { moveTowards (direction, (float) 0.25); } public void moveTowards (String direction, float fraction) { Point viewOrigin = getViewOrigin (); Dimension viewSize = getViewSize (); if (direction.equals ("NW") || direction.equals ("N") || direction.equals ("NE")) viewOrigin.y -= viewSize.height * fraction; if (direction.equals ("SW") || direction.equals ("S") || direction.equals ("SE")) viewOrigin.y += viewSize.height * fraction; if (direction.equals ("NW") || direction.equals ("W") || direction.equals ("SW")) viewOrigin.x -= viewSize.width * fraction; if (direction.equals ("NE") || direction.equals ("E") || direction.equals ("SE")) viewOrigin.x += viewSize.width * fraction; Rectangle oldViewArea = getViewArea (); setViewOrigin (viewOrigin); redrawRect (oldViewArea); redrawRect (getViewArea ()); issueRepaint (); browserCore.notifyViewChanged (); } public void reshape (int x, int y, int width, int height) { super.reshape (x, y, width, height); makeDoubleBuffer (width, height); browserCore.notifyViewChanged (); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Coordinte transforms, to coords relative to this Panel public Rectangle screenToLogical (Rectangle screen) { // ***** return (new Rectangle (0,0,0,0)); } public Rectangle logicalToScreen (Rectangle logical) { // ***** return (new Rectangle (0,0,0,0)); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Painting management public void update (Graphics g) { paint (g); } protected Dimension offscreenSize; protected Image offscreenImage; protected Graphics offscreenGC = null; protected void makeDoubleBuffer (int width, int height) { if ((width > 0) && (height > 0)) { offscreenSize = new Dimension (width, height); offscreenImage = createImage (width, height); offscreenGC = offscreenImage.getGraphics (); offscreenGC.setColor (new Color (240, 240, 240)); offscreenGC.fillRect (0, 0, width, height); } else offscreenGC = null; } private Vector damageRects = new Vector (); public void redrawRect (Rectangle passedRect) { boolean foundOne = false; Rectangle rect = new Rectangle (passedRect.x - 20, passedRect.y - 20, passedRect.width + 40, passedRect.height + 40); synchronized (damageRects) { for (int i=0; i<damageRects.size (); ++i) if (rect.intersects ((Rectangle) damageRects.elementAt (i))) { foundOne = true; damageRects.setElementAt (((Rectangle) damageRects.elementAt (i)).union (rect), i); } if (!foundOne) damageRects.addElement (rect); } } protected int numPaintsPending = 0; protected boolean paintsPending = false; public void issueRepaint () { synchronized (damageRects) { if (!paintsPending) repaint (); paintsPending = true; ++numPaintsPending; if ((numPaintsPending % 10) == 0) System.out.println ("!!! now have " + numPaintsPending + " paints pending."); browserCore.notifyShouldDisable (numPaintsPending); } } public void paint (Graphics g) { if (offscreenGC == null) makeDoubleBuffer (size ().width, size ().height); if (offscreenGC == null) return; synchronized (damageRects) { for (int i=0; i < damageRects.size (); ++i) { Point viewOrigin = getViewOrigin (); Rectangle rect = (Rectangle) damageRects.elementAt (i); Rectangle xlated = new Rectangle (rect.x - viewOrigin.x, rect.y - viewOrigin.y, rect.width, rect.height); Graphics drawOnGC = offscreenGC.create (); drawOnGC.setColor (new Color (240, 240, 240)); drawOnGC.fillRect (xlated.x, xlated.y, xlated.width, xlated.height); drawOnGC.clipRect (xlated.x, xlated.y, xlated.width, xlated.height); browserCore.paint (drawOnGC, xlated); } damageRects = new Vector (); paintsPending = false; numPaintsPending = 0; browserCore.notifyShouldEnable (); } g.drawImage (offscreenImage, 0, 0, this); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // event and focus management Boolean haveFocus = Boolean.FALSE; public boolean gotFocus (Event evt, Object what) { synchronized (haveFocus) { haveFocus = Boolean.TRUE; } return (true); } public boolean lostFocus (Event evt, Object what) { synchronized (haveFocus) { haveFocus = Boolean.FALSE; } return (true); } private boolean uiEvent (Event evt, int x, int y, int key) { boolean needToGetFocus; synchronized (haveFocus) { needToGetFocus = !haveFocus.booleanValue (); } if (needToGetFocus) requestFocus (); if ((evt.id == Event.MOUSE_MOVE) || (evt.id == Event.MOUSE_DRAG)) { xMouseLoc = x; yMouseLoc = y; } return (browserCore.uiEvent (evt, x, y, key)); } int xMouseLoc; int yMouseLoc; public Point getGlobalMouseLoc () { return (new Point (xMouseLoc + getViewOrigin ().x, yMouseLoc + getViewOrigin ().y)); } public boolean mouseMove (Event evt, int x, int y) { xMouseLoc = x; yMouseLoc = y; return (uiEvent (evt, x, y, -1)); } public boolean mouseDrag (Event evt, int x, int y) { xMouseLoc = x; yMouseLoc = y; return (uiEvent (evt, x, y, -1)); } public boolean mouseUp (Event evt, int x, int y) { xMouseLoc = x; yMouseLoc = y; return (uiEvent (evt, x, y, -1)); } public boolean mouseDown (Event evt, int x, int y) { xMouseLoc = x; yMouseLoc = y; return (uiEvent (evt, x, y, -1)); } public boolean keyUp (Event evt, int key) { return (uiEvent (evt, xMouseLoc, yMouseLoc, key)); } public boolean keyDown (Event evt, int key) { return (uiEvent (evt, xMouseLoc, yMouseLoc, key)); } }
krono/self
objects/applications/javaClient/Structure.java
3,752
// view area management
line_comment
nl
//------------------------------------------------------------------------- // Kansas Java interface -- bringing Kansas to the Web // // Structure.java // // $Revision: 30.1 $ // Andy Collins, Sun Microsystems Laboratories, Summer 1996 //------------------------------------------------------------------------- //------------------------------------------------------------------ // Structure.java - general structural interfaces and classes for // the Java Self browsers // Andy Collins, 8/5/96 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Interfaces: // // BailInOut requires bailin () and bailout () methods to // connect or disconnect itself and all children. // All components in the browser will implement this // so that the top-level applet can be used as a // total browser bailout point to disconnect and // put the program in a state from which it can // reconnect. // // Browser a generalized view into some logical rectangular // areas, supporting management both of the view // area and damage-list style redraws. A browser // is presumed to use a BrowserCore to do the actual // drawing. // // Classes: // // BrowserPanel is a Panel which can contain a browser core // BrowserMorph is a Morph which can contain a browser core // // see Viewer.java and RadarViewer.java for browser core // implementations. The interface used is BailInOut down and // Browser up //------------------------------------------------------------------ import java.awt.*; import java.applet.Applet; import java.io.*; import java.net.*; import java.util.*; //------------------------------------------------------------------ //------------------------------------------------------------------ interface Browser extends BailInOut { public void setBrowserCore (BrowserCore core); // view area<SUF> public Point getViewOrigin (); public void setViewOrigin (Point p); public Dimension getViewSize (); public Rectangle getViewArea (); public void moveTowards (String direction); public void moveTowards (String direction, float fraction); // coordinate xforms public Rectangle screenToLogical (Rectangle screen); public Rectangle logicalToScreen (Rectangle logical); // painting management public void redrawRect (Rectangle r); public void issueRepaint (); // misc public void setMessage (String msg); public Point getGlobalMouseLoc (); public Component getComponent (); } //------------------------------------------------------------------ //------------------------------------------------------------------ class BrowserCore implements BailInOut { Browser ownerBrowser; BailInOut bailoutPoint; BrowserCore (BrowserPanel browser, BailInOut bailoutPt) { ownerBrowser = browser; bailoutPoint = bailoutPt; } public void bailin () { } public synchronized void bailout () { } public void paint (Graphics g, Rectangle region) { } public void notifyViewChanged () { } public void notifyShouldDisable (int numPaintsPending) { } public void notifyShouldEnable () { } public boolean uiEvent (Event evt, int x, int y, int key) { return (false); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // passback stuff void redrawRect (Rectangle r) { ownerBrowser.redrawRect (r); } void issueRepaint () { ownerBrowser.issueRepaint (); } public Component getComponent () { return (ownerBrowser.getComponent ()); } } //------------------------------------------------------------------ //------------------------------------------------------------------ class BrowserPanel extends Panel implements Browser { protected Point logicalViewOrigin = null; protected BrowserCore browserCore = null; protected Label messageLabel; public BrowserPanel (BrowserCore core, Point viewOrigin, Label messageLabel) { logicalViewOrigin = viewOrigin; browserCore = core; this.messageLabel = messageLabel; } public void setMessage (String msg) { messageLabel.setText (msg); } public Component getComponent () { return ((Component) this); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // BailInOut support public void bailin () { if (browserCore != null) browserCore.bailin (); } public synchronized void bailout () { if (browserCore != null) browserCore.bailout (); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Structure management public void setBrowserCore (BrowserCore core) { browserCore = core; // browserCores.addElement (core); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Get/Set the viewing area in logical coordinates: public Point getViewOrigin () { return (logicalViewOrigin); } public void setViewOrigin (Point p) { logicalViewOrigin.x = p.x; logicalViewOrigin.y = p.y; } // No sets because changing the logical to physical ratio is not allowed public Dimension getViewSize () { return (new Dimension (size ().width, size ().height)); } public Rectangle getViewArea () { return (new Rectangle (logicalViewOrigin.x, logicalViewOrigin.y, size ().width, size ().height)); } // Move towards one of ("N", "E", "S", "W", "NE", "NW", "SW", "SE") // by either an 1/2 or by a fraction of the current view // size in that dimension public void moveTowards (String direction) { moveTowards (direction, (float) 0.25); } public void moveTowards (String direction, float fraction) { Point viewOrigin = getViewOrigin (); Dimension viewSize = getViewSize (); if (direction.equals ("NW") || direction.equals ("N") || direction.equals ("NE")) viewOrigin.y -= viewSize.height * fraction; if (direction.equals ("SW") || direction.equals ("S") || direction.equals ("SE")) viewOrigin.y += viewSize.height * fraction; if (direction.equals ("NW") || direction.equals ("W") || direction.equals ("SW")) viewOrigin.x -= viewSize.width * fraction; if (direction.equals ("NE") || direction.equals ("E") || direction.equals ("SE")) viewOrigin.x += viewSize.width * fraction; Rectangle oldViewArea = getViewArea (); setViewOrigin (viewOrigin); redrawRect (oldViewArea); redrawRect (getViewArea ()); issueRepaint (); browserCore.notifyViewChanged (); } public void reshape (int x, int y, int width, int height) { super.reshape (x, y, width, height); makeDoubleBuffer (width, height); browserCore.notifyViewChanged (); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Coordinte transforms, to coords relative to this Panel public Rectangle screenToLogical (Rectangle screen) { // ***** return (new Rectangle (0,0,0,0)); } public Rectangle logicalToScreen (Rectangle logical) { // ***** return (new Rectangle (0,0,0,0)); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Painting management public void update (Graphics g) { paint (g); } protected Dimension offscreenSize; protected Image offscreenImage; protected Graphics offscreenGC = null; protected void makeDoubleBuffer (int width, int height) { if ((width > 0) && (height > 0)) { offscreenSize = new Dimension (width, height); offscreenImage = createImage (width, height); offscreenGC = offscreenImage.getGraphics (); offscreenGC.setColor (new Color (240, 240, 240)); offscreenGC.fillRect (0, 0, width, height); } else offscreenGC = null; } private Vector damageRects = new Vector (); public void redrawRect (Rectangle passedRect) { boolean foundOne = false; Rectangle rect = new Rectangle (passedRect.x - 20, passedRect.y - 20, passedRect.width + 40, passedRect.height + 40); synchronized (damageRects) { for (int i=0; i<damageRects.size (); ++i) if (rect.intersects ((Rectangle) damageRects.elementAt (i))) { foundOne = true; damageRects.setElementAt (((Rectangle) damageRects.elementAt (i)).union (rect), i); } if (!foundOne) damageRects.addElement (rect); } } protected int numPaintsPending = 0; protected boolean paintsPending = false; public void issueRepaint () { synchronized (damageRects) { if (!paintsPending) repaint (); paintsPending = true; ++numPaintsPending; if ((numPaintsPending % 10) == 0) System.out.println ("!!! now have " + numPaintsPending + " paints pending."); browserCore.notifyShouldDisable (numPaintsPending); } } public void paint (Graphics g) { if (offscreenGC == null) makeDoubleBuffer (size ().width, size ().height); if (offscreenGC == null) return; synchronized (damageRects) { for (int i=0; i < damageRects.size (); ++i) { Point viewOrigin = getViewOrigin (); Rectangle rect = (Rectangle) damageRects.elementAt (i); Rectangle xlated = new Rectangle (rect.x - viewOrigin.x, rect.y - viewOrigin.y, rect.width, rect.height); Graphics drawOnGC = offscreenGC.create (); drawOnGC.setColor (new Color (240, 240, 240)); drawOnGC.fillRect (xlated.x, xlated.y, xlated.width, xlated.height); drawOnGC.clipRect (xlated.x, xlated.y, xlated.width, xlated.height); browserCore.paint (drawOnGC, xlated); } damageRects = new Vector (); paintsPending = false; numPaintsPending = 0; browserCore.notifyShouldEnable (); } g.drawImage (offscreenImage, 0, 0, this); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // event and focus management Boolean haveFocus = Boolean.FALSE; public boolean gotFocus (Event evt, Object what) { synchronized (haveFocus) { haveFocus = Boolean.TRUE; } return (true); } public boolean lostFocus (Event evt, Object what) { synchronized (haveFocus) { haveFocus = Boolean.FALSE; } return (true); } private boolean uiEvent (Event evt, int x, int y, int key) { boolean needToGetFocus; synchronized (haveFocus) { needToGetFocus = !haveFocus.booleanValue (); } if (needToGetFocus) requestFocus (); if ((evt.id == Event.MOUSE_MOVE) || (evt.id == Event.MOUSE_DRAG)) { xMouseLoc = x; yMouseLoc = y; } return (browserCore.uiEvent (evt, x, y, key)); } int xMouseLoc; int yMouseLoc; public Point getGlobalMouseLoc () { return (new Point (xMouseLoc + getViewOrigin ().x, yMouseLoc + getViewOrigin ().y)); } public boolean mouseMove (Event evt, int x, int y) { xMouseLoc = x; yMouseLoc = y; return (uiEvent (evt, x, y, -1)); } public boolean mouseDrag (Event evt, int x, int y) { xMouseLoc = x; yMouseLoc = y; return (uiEvent (evt, x, y, -1)); } public boolean mouseUp (Event evt, int x, int y) { xMouseLoc = x; yMouseLoc = y; return (uiEvent (evt, x, y, -1)); } public boolean mouseDown (Event evt, int x, int y) { xMouseLoc = x; yMouseLoc = y; return (uiEvent (evt, x, y, -1)); } public boolean keyUp (Event evt, int key) { return (uiEvent (evt, xMouseLoc, yMouseLoc, key)); } public boolean keyDown (Event evt, int key) { return (uiEvent (evt, xMouseLoc, yMouseLoc, key)); } }
False
2,907
4
3,077
4
3,352
4
3,077
4
3,671
4
false
false
false
false
false
true