text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public State parseState(CharSequence content) {
boolean isDoubled = false;
Matcher doubledMatcher = DOUBLED.matcher(content);
if(doubledMatcher.matches()) {
isDoubled = true;
content = doubledMatcher.group(1);
}
Map<String, String> styles = new HashMap<String, String>();
Matcher matcher = META.matcher(content);
if (matcher.find()) {
parseStyles(styles, matcher.group(2));
content = matcher.replaceFirst("");
}
String[] parts = PARTS.split(content);
State state = new State(parts[0], getOrNull(parts, 1));
if(isDoubled) {
state.markDoubled();
}
return state.usingStyles(styles);
} | 3 |
public void run() {
ArrayList<ClientThread> clientTheads = this.clientThreads;
try {
/*
* Create input and output streams for this client.
*/
inputStream = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()));
outputStream = new PrintStream(clientSocket.getOutputStream());
/*
* Messages
*
*/
while(true){
String inputHeader;
String inputMessage;
inputHeader = inputStream.readLine();
inputMessage = inputStream.readLine();
if(inputHeader!=null){
if(inputHeader.equals(FINISHING_MESSAGE)){
break;
}
System.out.println(inputHeader);
if(inputMessage!=null){
if (inputHeader.startsWith(MSG_ADD_TASK)){
Gson gson = new Gson();
Task task = gson.fromJson(inputMessage, Task.class);
communicator.addTask(task);
sendMessageToEveryOneExceptMe(MSG_ADD_TASK, inputMessage);
}else if(inputHeader.startsWith(MSG_SYNC_ALL)){
syncAllTasks(this);
}
}else{
}
}
}
/*
* Clean up. Set the current thread variable to null so that a new client
* could be accepted by the server.
*/
synchronized (this) {
clientTheads.remove(this);
}
/*
* Close the output stream, close the input stream, close the socket.
*/
inputStream.close();
outputStream.close();
clientSocket.close();
} catch (IOException e) {
}
} | 7 |
public RectControls(Redrawable redrawable, Rectangle rect)
{
super();
this.rectangle = rect;
this.redrawable = redrawable;
setPadding(new Insets(10,10,10,10));
setVgap(5);
int line = 0;
//W
add(new Label("Width"),0,line);
width = new Slider(1, 200, rect.getW());
add(width,1,line);
widthOut = new Label(Integer.toString(rect.getW()));
widthOut.setMinWidth(40);
add(widthOut,2,line);
width.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> ov,
Number oldVal, Number newVal) {
widthOut.setText(String.format("%3d",newVal.intValue()));
rectangle.setW(newVal.intValue());
redrawable.reDraw();
}
});
line++;
//H
add(new Label("Height"),0,line);
height = new Slider(1, 200, rect.getH());
add(height,1,line);
heightOut = new Label(Integer.toString(rect.getH()));
heightOut.setMinWidth(40);
add(heightOut,2,line);
height.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> ov,
Number oldVal, Number newVal) {
heightOut.setText(String.format("%3d",newVal.intValue()));
rectangle.setH(newVal.intValue());
redrawable.reDraw();
}
});
line++;
//Fill
fillPicker = new ColorPicker(rect.getFillColor());
fillPicker.valueProperty().addListener(new ChangeListener<Color>() {
@Override
public void changed(ObservableValue<? extends Color> oc,
Color oldColor, Color newColor) {
rectangle.setFillColor(newColor);
redrawable.reDraw();
}
});
add(new Label("Fill"),0,line);
add(fillPicker,1,line);
line++;
//Border Color
borderPicker = new ColorPicker(rect.getBorderColor());
borderPicker.valueProperty().addListener(new ChangeListener<Color>() {
@Override
public void changed(ObservableValue<? extends Color> oc,
Color oldColor, Color newColor) {
rectangle.setBorderColor(newColor);
redrawable.reDraw();
}
});
add(new Label("Border"),0,line);
add(borderPicker,1,line);
line++;
//Stroke Width
add(new Label("Border Width"),0,line);
borderWidth = new Slider(1, 50, rect.getBorderWidth());
add(borderWidth,1,line);
borderWidthOut = new Label(Double.toString(rect.getBorderWidth()));
borderWidthOut.setMinWidth(40);
add(borderWidthOut,2,line);
borderWidth.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> ov,
Number oldVal, Number newVal) {
borderWidthOut.setText(String.format("%3.2f",newVal.doubleValue()));
rectangle.setBorderWidth(newVal.doubleValue());
redrawable.reDraw();
}
});
line++;
//hasBorder
add(new Label("Enable Border"),0,line);
hasBorder = new CheckBox();
hasBorder.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> ov,
Boolean oldBool, Boolean newBool) {
rectangle.setHasBorder(newBool);
redrawable.reDraw();
}
});
hasBorder.setSelected(rect.hasBorder());
add(hasBorder,1,line);
line++;
//isRounded
add(new Label("Rounded Corners"),0,line);
isRounded = new CheckBox();
isRounded.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> ov,
Boolean oldBool, Boolean newBool) {
rectangle.setIsRounded(newBool);
redrawable.reDraw();
}
});
isRounded.setSelected(rect.isRounded());
add(isRounded,1,line);
line++;
} | 7 |
@Test
public void testDeity(){
Connection conn;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
System.out.println("success");
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} | 4 |
private String[][] getContent(int teamNumber)
{
FileScanner teamFileScanner = new FileScanner();
Extracter extract = new Extracter();
String currentDir = Main.currentDir;
String workspaceFolderName = Main.workspaceFolderName;
String teamFolderName = Main.teamFolderName;
teamFileScanner.openFile(currentDir + "/" + workspaceFolderName + "/" + teamFolderName, String.valueOf(teamNumber) + ".txt");
String nextLine = teamFileScanner.getNextLine();
while(nextLine.startsWith("#"))
{
nextLine = teamFileScanner.getNextLine();
}
int lineCount = 1;
while(teamFileScanner.hasNextEntry())
{
teamFileScanner.getNextLine();
lineCount++;
}
String content[] = new String[lineCount];
teamFileScanner.openFile(currentDir + "/" + workspaceFolderName + "/" + teamFolderName, String.valueOf(teamNumber) + ".txt");
nextLine = teamFileScanner.getNextLine();
while(nextLine.startsWith("#"))
{
nextLine = teamFileScanner.getNextLine();
}
content[0] = nextLine;
for(int j = 1; j < lineCount; j++)
//while(teamFileScanner.hasNextEntry())
{
content[j] = teamFileScanner.getNextLine();
}
String extractedData[][] = new String[lineCount][5];
for(int j = 0; j < lineCount; j++)
{
// <roundNum>:<autoPoints>:<mainPoints>:<endPoints>:<penalties>
extractedData[j][0] = extract.extractEntry(content[j], 1);
extractedData[j][1] = extract.extractEntry(content[j], 2);
extractedData[j][2] = extract.extractEntry(content[j], 3);
extractedData[j][3] = extract.extractEntry(content[j], 4);
extractedData[j][4] = extract.extractEntry(content[j], 5);
}
Sorter sort = new Sorter(5);
return sort.sortBest(extractedData, 0, Sorter.LOW_TO_HIGH);
} | 5 |
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] message)
{
if (this.permissionsManager == null) return;
ReplicatedPermissionsContainer query = null;
try
{
query = ReplicatedPermissionsContainer.fromBytes(message);
}
catch (Exception ex) {}
if (query != null)
{
query.sanitise();
if (!this.permissionsManager.checkVersion(player, query) && !player.hasPermission(ADMIN_PERMISSION_NODE) && !player.isOp())
{
this.getLogger().info("Kicking player [" + player.getName() + "] due to outdated mod [" + query.modName + "]. Has version " + query.modVersion);
player.kickPlayer(String.format("Mod '%s' is out of date", query.modName));
return;
}
this.monitor.onQuery(player, query);
this.permissionsManager.replicatePermissions(player, query);
}
} | 6 |
public Populator() throws SQLException {
this.generators = new Generators();
this.metaDataDao = new MetaDataDao();
} | 0 |
public int read(List<String> buf) {
if (buf == null) {
return 0;
}
buf.clear();
if (exists()) {
BufferedReader bfReader = null;
try {
FileReader flReader = new FileReader(this);
bfReader = new BufferedReader(flReader);
String line = null;
while ((line = bfReader.readLine()) != null) {
buf.add(line);
}
bfReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (bfReader != null) bfReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return buf.size();
} | 6 |
public void testPropertyPlusNoWrapSecond() {
LocalTime test = new LocalTime(10, 20, 30, 40);
LocalTime copy = test.secondOfMinute().addNoWrapToCopy(9);
check(test, 10, 20, 30, 40);
check(copy, 10, 20, 39, 40);
copy = test.secondOfMinute().addNoWrapToCopy(29);
check(copy, 10, 20, 59, 40);
copy = test.secondOfMinute().addNoWrapToCopy(30);
check(copy, 10, 21, 0, 40);
copy = test.secondOfMinute().addNoWrapToCopy(39 * 60 + 29);
check(copy, 10, 59, 59, 40);
copy = test.secondOfMinute().addNoWrapToCopy(39 * 60 + 30);
check(copy, 11, 0, 0, 40);
try {
test.secondOfMinute().addNoWrapToCopy(13 * 60 * 60 + 39 * 60 + 30);
fail();
} catch (IllegalArgumentException ex) {}
check(test, 10, 20, 30, 40);
copy = test.secondOfMinute().addNoWrapToCopy(-9);
check(copy, 10, 20, 21, 40);
copy = test.secondOfMinute().addNoWrapToCopy(-30);
check(copy, 10, 20, 0, 40);
copy = test.secondOfMinute().addNoWrapToCopy(-31);
check(copy, 10, 19, 59, 40);
copy = test.secondOfMinute().addNoWrapToCopy(-(10 * 60 * 60 + 20 * 60 + 30));
check(copy, 0, 0, 0, 40);
try {
test.secondOfMinute().addNoWrapToCopy(-(10 * 60 * 60 + 20 * 60 + 31));
fail();
} catch (IllegalArgumentException ex) {}
check(test, 10, 20, 30, 40);
} | 2 |
public int getCantidad() {
return cantidad;
} | 0 |
public int getAttributeSize(String name) {
Attrib a = attrib(name);
return a != null ? a.size : -1;
} | 1 |
public User connect(List<User> users) {
// User input.
List<String> words = this.getParser().getInput();
if (words.size() > 1) {
for (User u : users) {
// If the user is in the list, the connection succeed.
if (u.getFirstName().equalsIgnoreCase(words.get(0))
&& u.getLastName().equalsIgnoreCase(words.get(1))) {
return u;
}
}
}
return null;
} | 4 |
public static void make(String path,String[] files){
try {
byte data[] = new byte[BUFFER];
FileOutputStream dest = new FileOutputStream(path);
BufferedOutputStream buff = new BufferedOutputStream(dest);
ZipOutputStream out = new ZipOutputStream(buff);
out.setMethod(ZipOutputStream.DEFLATED);
out.setLevel(9);
for(int i=0; i<files.length; i++) {
FileInputStream fi = new FileInputStream(files[i]);
BufferedInputStream buffi = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(files[i]);
out.putNextEntry(entry);
int count;
while((count = buffi.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.closeEntry();
buffi.close();
}
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
public void processClick(int x, int y) {
Node p = getNode(x, y);
if (p != null) {
if (p.getPlayer() == getTurn() || p.getPlayer() == 0) {
if (getGridValue(p) != 0) {
if (getSelectedNode() != null) {
if (!hasInAttack()) {
addChangedGuti(selectedNode, p);
deSelectNode(selectedNode);
setSelectedNode(p);
}
} else {
addChangedGuti(p);
setSelectedNode(p);
}
setChangeGutiPosition();
} else {
if (getSelectedNode() != null) {
if (isValidMove(getSelectedNode(), p)) {
clearInAttack();
addChangedGuti(getSelectedNode(), p);
moveGuti(getSelectedNode(), p);
addChangedGuti(p);
deSelectNode(p);
changeTurn();
} else if (isValidAttack(getSelectedNode(), p)) {
setInAttack();
setMakeAnyMove();
addChangedGuti(getSelectedNode(), p, vulnarableNode);
moveGuti(getSelectedNode(), p);
deSelectNode(p);
setSelectedNode(p);
addChangedGuti(getSelectedNode(), p, vulnarableNode);
removeGuti(vulnarableNode);
decreaseGuti(getOppositionPlayerNo(getTurn()));
resetGameTimer();
vulnarableNode = null;
} else {
errormsg = true;
errormsg = false;
}
}
setChangeGutiPosition();
}
}
}
} | 9 |
private boolean jj_2_30(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_30(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(29, xla); }
} | 1 |
private CucaDiagramFileMakerResult createPng(OutputStream os, List<String> dotStrings,
FileFormatOption fileFormatOption) throws IOException, InterruptedException {
final StringBuilder cmap = new StringBuilder();
double supX = 0;
double supY = 0;
try {
final GraphvizMaker dotMaker = populateImagesAndCreateGraphvizMaker(dotStrings, fileFormatOption);
final String dotString = dotMaker.createDotString();
if (OptionFlags.getInstance().isKeepTmpFiles()) {
traceDotString(dotString);
}
final byte[] imageData = getImageData(dotString, cmap);
if (imageData.length == 0) {
createError(os, imageData.length, new FileFormatOption(FileFormat.PNG), "imageData.length == 0");
return null;
}
if (isPngHeader(imageData, 0) == false) {
createError(os, imageData.length, new FileFormatOption(FileFormat.PNG), "No PNG header found",
"Try -forcegd or -forcecairo flag");
return null;
}
final ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
BufferedImage im = ImageIO.read(bais);
if (im == null) {
createError(os, imageData.length, new FileFormatOption(FileFormat.PNG), "im == null");
return null;
}
bais.close();
dotMaker.clean();
final boolean isUnderline = dotMaker.isUnderline();
if (isUnderline) {
new UnderlineTrick(im, new Color(Integer.parseInt("FEFECF", 16)), Color.BLACK).process();
}
final HtmlColor background = diagram.getSkinParam().getBackgroundColor();
supY = getTitlePngHeight(stringBounder);
supY += getHeaderPngHeight(stringBounder);
supX = getOffsetX(stringBounder, im.getWidth());
im = addTitle(im, background);
im = addFooter(im, background);
im = addHeader(im, background);
im = scaleImage(im, diagram.getScale());
if (diagram.isRotation()) {
im = PngRotation.process(im);
}
im = PngSizer.process(im, diagram.getMinwidth());
im = addFlashcode(im, diagram.getColorMapper().getMappedColor(background));
PngIO.write(im, os, diagram.getMetadata(), diagram.getDpi(fileFormatOption));
} finally {
clean();
}
if (cmap.length() > 0) {
return new CucaDiagramFileMakerResult(translateXY(cmap.toString(), (int) Math.round(supX),
(int) Math.round(supY)));
}
return null;
} | 7 |
public void query(String query) {
boolean col=true;
int colNum = 0;
rowCount = 0;
try {
String date;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
numberOfColumns = rsmd.getColumnCount();
columnNames = new String[numberOfColumns];
dataValues = new String[CONSTANTS.NUMBEROFSTOCKS][numberOfColumns];
while (rs.next()) {
if(col){
for(int j = 1;j<numberOfColumns+1;j++){
columnNames[j-1] = rsmd.getColumnName(j);
}
col=false;
}
for (int i = 1; i <= numberOfColumns; i++) {
String columnValue = rs.getString(i);
/*
* When fetching the date/time from the excel spreadsheet
* there is an arbitrary string appended to the end. This will
* parse the data and remove the string, normalizing the data.
*/
if(i == 6 || i == 7){
date = columnValue.substring(1);
date=date.replace("\"_x000D_", "");
columnValue = date;
}
dataValues[colNum][i-1] = columnValue;
}
colNum++;
rowCount++;
col = false;
}
st.close();
} catch (Exception ex) {
}
resizeData(rowCount);
convertToStock();
} | 7 |
public Row getChild(int index) {
return index >= 0 && index < getChildCount() ? mChildren.get(index) : null;
} | 2 |
public static <T extends Comparable<T>, E> void print(Map<String, String> content, String testName, Node<T,E> root,
boolean printHeader, boolean printFooter){
if(printHeader)
printHeader(testName);
if(content!=null)
for(String str : content.keySet()){
System.out.print(str);
for(int i=0; i<(30 -str.length()) ; i++)
System.out.print(" ");
System.out.print(" : ");
System.out.println(content.get(str));
}
if(root!=null){
BinaryTreePrinter.printNode(root);
}
if(printFooter)
printFooter();
} | 6 |
public String GetActionToBeTaken()
{
return action;
} | 0 |
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int p = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int[] a = new int[n];
for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
HashMap<Integer, Integer> mapB = new HashMap<Integer, Integer>();
for(int i=0; i<m; i++){
add(mapB, Integer.parseInt(st.nextToken()));
}
ArrayList<Integer> result = new ArrayList<Integer>();
for(int i=0; i<p; i++){
HashMap<Integer, Integer> mapA = new HashMap<Integer, Integer>();
int mismatched = m;
for(int j=0; i+j*p<n; j++){
if(j>=m){
int origDiff = getDifference(mapA, mapB, a[i+(j-m)*p]);
remove(mapA, a[i+(j-m)*p]);
int diff = getDifference(mapA, mapB, a[i+(j-m)*p]);
mismatched+=diff-origDiff;
}
int origDiff = getDifference(mapA, mapB, a[i+j*p]);
add(mapA, a[i+j*p]);
int diff = getDifference(mapA, mapB, a[i+j*p]);
mismatched+=diff-origDiff;
if(mismatched==0) result.add(i+(j-m+1)*p);
}
}
Collections.sort(result);
System.out.println(result.size());
for(int i=0; i<result.size(); i++){
if(i==result.size()-1) System.out.println(result.get(i)+1); else System.out.print((result.get(i)+1)+" ");
}
} | 8 |
public static Stella_Class nativeStorageSlotHome(StorageSlot slot, Stella_Class renamed_Class) {
{ StorageSlot slotwithknowntype = null;
loop000 : for (;;) {
if (Surrogate.unknownTypeP(slot.type())) {
break loop000;
}
slotwithknowntype = slot;
renamed_Class = Surrogate.typeToClass(slot.slotOwner);
if ((slot.slotDirectEquivalent != null) &&
StorageSlot.nativeSlotP(((StorageSlot)(slot.slotDirectEquivalent)))) {
slot = ((StorageSlot)(slot.slotDirectEquivalent));
}
else {
break loop000;
}
}
if (slotwithknowntype != null) {
return (renamed_Class);
}
if (StorageSlot.slotHasUnknownTypeP(slot, renamed_Class)) {
return (null);
}
{ Stella_Class renamed_Super = null;
Cons iter000 = renamed_Class.classAllSuperClasses;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
renamed_Super = ((Stella_Class)(iter000.value));
if (StorageSlot.slotHasUnknownTypeP(slot, renamed_Super)) {
return (renamed_Class);
}
else {
renamed_Class = renamed_Super;
}
}
}
return (renamed_Class);
}
} | 8 |
public static int sizeOfRawVarLong(final long value) {
if ((value & (0xffffffffffffffffL << 7)) == 0) {
return 1;
}
if ((value & (0xffffffffffffffffL << 14)) == 0) {
return 2;
}
if ((value & (0xffffffffffffffffL << 21)) == 0) {
return 3;
}
if ((value & (0xffffffffffffffffL << 28)) == 0) {
return 4;
}
if ((value & (0xffffffffffffffffL << 35)) == 0) {
return 5;
}
if ((value & (0xffffffffffffffffL << 42)) == 0) {
return 6;
}
if ((value & (0xffffffffffffffffL << 49)) == 0) {
return 7;
}
if ((value & (0xffffffffffffffffL << 56)) == 0) {
return 8;
}
if ((value & (0xffffffffffffffffL << 63)) == 0) {
return 9;
}
return 10;
} | 9 |
public String getURLString() throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Entry<String,String> entry : data.entrySet()){
if(entry.getKey() != null && entry.getValue() != null
&& entry.getKey().length() > 0 && entry.getValue().length() > 0 )
encoding.encodeDataPair(sb, entry.getKey(), entry.getValue());
}
if(sb.length() > 0)
return sb.toString();
else return "";
} | 6 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LoginGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoginGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoginGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoginGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LoginGui().setVisible(true);
}
});
} | 6 |
private static void isAnagram(String first, String second) {
if (first.length() == second.length()) {
int[] charCount = new int[NUMBER_OF_ASCII];
for (int i = 0; i < first.length(); i++) {
charCount[(int)first.charAt(i)]++;
charCount[(int)second.charAt(i)]--;
}
for (int i = 0; i < charCount.length; i++) {
if (charCount[i] != 0) {
System.out.println(NOT);
return;
}
}
System.out.println(ARE);
} else {
System.out.println(NOT);
}
} | 4 |
protected void setFoodLevel(int foodLevel)
{
this.foodLevel = foodLevel;
} | 0 |
public static String join(Iterable<?> items, String glue) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object item : items) {
if (!first) {
sb.append(glue);
}
first = false;
sb.append(item);
}
return sb.toString();
} | 3 |
public static void addNewRow(JTable table, Container controlsContainer) throws Exception {
Object[] row = new Object[controlsContainer.getComponentCount()];
Component comp;
String item = null;
Object objItem;
JTextField textField;
JComboBox comboBox;
for (int i = 0; i < controlsContainer.getComponentCount(); i++) {
comp = controlsContainer.getComponent(i);
if (comp instanceof JTextField) {
textField = (JTextField)comp;
row[i] = textField.getText();
textField.setText(EMPTY);
} else if (comp instanceof JComboBox) {
comboBox = (JComboBox)comp;
objItem = comboBox.getSelectedItem();
if (objItem instanceof StringBuffer) {
item = objItem.toString();
} else if (objItem instanceof String) {
item = (String) objItem;
}
if (item != null) {
if (item.indexOf(DELIMETER) > -1) {
row = new Object[2];
row[0] = item.substring(0, item.indexOf(DELIMETER));
row[1] = item.substring(item.indexOf(DELIMETER) + DELIMETER.length());
} else {
row[i] = item;
}
comboBox.removeItem(item);
} else {
return;
}
}
}
addRow(table, row);
controlsContainer.getComponent(0).requestFocus();
} | 7 |
private String getDigEmptySpace(BoardViewer board, String digIndex) {
if (digIndex.equals("\\")) {
for (int relativePosition=0; relativePosition < board.getBoardSize(); relativePosition++) {
String position = Integer.toString(relativePosition * (board.getBoardSize() + 1));
if (!board.getBoard().containsKey(position)) {
return position;
}
}
}
else if (digIndex.equals("/")) {
for (int relativePosition=0; relativePosition < board.getBoardSize(); relativePosition++) {
String position = Integer.toString((relativePosition + 1) * (board.getBoardSize() - 1));
if (!board.getBoard().containsKey(position)) {
return position;
}
}
}
return getRandomPosition(board.getBoardSize()^2); //should never return this
} | 6 |
public int divide(int _a, int _b) throws DivideByZeroException {
if(_b == 0) {
throw new DivideByZeroException("Simple.java: Tried to divide by 0.");
}
return _a / _b;
} | 1 |
@Override
public boolean propertyDefaultExists(String key) {
return default_values.containsKey(key);
} | 0 |
public Object pop() {
if (this.top == null) {
return null;
} else {
Object item = top.getHead();
this.top = top.getTail();
return item;
}
} | 1 |
public void testForFields_time_m() {
DateTimeFieldType[] fields = new DateTimeFieldType[] {
DateTimeFieldType.millisOfSecond(),
};
int[] values = new int[] {40};
List types = new ArrayList(Arrays.asList(fields));
DateTimeFormatter f = ISODateTimeFormat.forFields(types, true, false);
assertEquals("---.040", f.print(new Partial(fields, values)));
assertEquals(0, types.size());
types = new ArrayList(Arrays.asList(fields));
f = ISODateTimeFormat.forFields(types, false, false);
assertEquals("---.040", f.print(new Partial(fields, values)));
assertEquals(0, types.size());
types = new ArrayList(Arrays.asList(fields));
try {
ISODateTimeFormat.forFields(types, true, true);
fail();
} catch (IllegalArgumentException ex) {}
types = new ArrayList(Arrays.asList(fields));
try {
ISODateTimeFormat.forFields(types, false, true);
fail();
} catch (IllegalArgumentException ex) {}
} | 2 |
public OutputFile(String fileName)
{
//set the config file filename
this.fileName = fileName;
//open the file for output
OpenFile();
} | 0 |
public void setTokenType(int newTokenType) {
boolean isValidType = 0<newTokenType && 10>newTokenType;
if(isValidType) {
this.tokenType = newTokenType;
}
} | 2 |
@Override
public User findUser(String name) {
// TODO Auto-generated method stub
for (User user : fdb.getUsers()) {
if (user.getName().equals(name)){
return user;
}
}
return null;
} | 2 |
@Override
public Iterable<PlanTicket> filter(Iterable<PlanTicket> source,
final TicketPoolQueryArgs args) throws Exception {
return Queries.query(source).where(new Predicate<PlanTicket>(){
@Override
public boolean evaluate(PlanTicket ticket) throws Exception {
long t1 = ticket.getSeat().getSeatType();
long t2 = args.getSeatType();
return (t1 & t2) != 0;
}});
} | 0 |
public MemorySourceJavaFileObject(String name, String code) {
super(createUriFromName(name), Kind.SOURCE);
if (code == null) {
throw new NullPointerException("code");
}
this.code = code;
} | 1 |
private void readLuminance() {
int type = sourceImage.getType();
if (type == BufferedImage.TYPE_INT_RGB
|| type == BufferedImage.TYPE_INT_ARGB) {
int[] pixels = (int[]) sourceImage.getData().getDataElements(0, 0,
width, height, null);
for (int i = 0; i < picsize; i++) {
int p = pixels[i];
int r = (p & 0xff0000) >> 16;
int g = (p & 0xff00) >> 8;
int b = p & 0xff;
data[i] = luminance(r, g, b);
}
} else if (type == BufferedImage.TYPE_BYTE_GRAY) {
byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0,
0, width, height, null);
for (int i = 0; i < picsize; i++) {
data[i] = (pixels[i] & 0xff);
}
} else if (type == BufferedImage.TYPE_USHORT_GRAY) {
short[] pixels = (short[]) sourceImage.getData().getDataElements(0,
0, width, height, null);
for (int i = 0; i < picsize; i++) {
data[i] = (pixels[i] & 0xffff) / 256;
}
} else if (type == BufferedImage.TYPE_3BYTE_BGR) {
byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0,
0, width, height, null);
int offset = 0;
for (int i = 0; i < picsize; i++) {
int b = pixels[offset++] & 0xff;
int g = pixels[offset++] & 0xff;
int r = pixels[offset++] & 0xff;
data[i] = luminance(r, g, b);
}
} else {
throw new IllegalArgumentException("Unsupported image type: "
+ type);
}
} | 9 |
private void generateLabyrinth(Node2 node) {
node.visit();
int x = node.getX();
int y = node.getY();
ArrayList<Node2> surroundingNodes = new ArrayList<Node2>();
if (x > 0) surroundingNodes.add(nodeNetwork[x-1][y]);
if (y > 0) surroundingNodes.add(nodeNetwork[x][y-1]);
if (x < width - 1) surroundingNodes.add(nodeNetwork[x+1][y]);
if (y < height - 1) surroundingNodes.add(nodeNetwork[x][y+1]);
Collections.shuffle(surroundingNodes);
for (Node2 nextNode : surroundingNodes) {
if (!nextNode.getVisited()) {
node.addChild(nextNode);
nextNode.addChild(node);
generateLabyrinth(nextNode);
}
}
} | 6 |
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
} | 0 |
private Trainer getTrainerFromCurrentRow(ResultSet results)
{
Integer id = extractNumber(results,"idEntity");
String valueEntity = extractString(results, "valueEntity");
Trainer t = new Trainer(valueEntity);
t.setId(id);
ResultSet rs = this.getResultsOfQuery("SELECT * FROM "+megatable+" WHERE idEntity = "+id);
try {
while (rs.next())
{
String name = extractString(rs, "name");
String value = extractString(rs , "value");
switch (name) {
case "OWN":
String[] pokemon_ids = value.split(",");
for (String p_id_number : pokemon_ids)
{
String p_id = p_id_number.substring(0,p_id_number.indexOf("("));
System.out.println(p_id);
for (Pokemon p : getAllPokemon())
if (p.getId() == Integer.valueOf(p_id))
t.pool.add(p);
}
break;
}
}
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
return t;
} | 6 |
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 1155, 900);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
ImageIcon refreshImage = new ImageIcon(getClass().getResource("ref.png"));
JButton btn_Refresh = new JButton("", refreshImage);
btn_Refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Refresh();
}
});
btn_Refresh.setBounds(10, 11, 35, 35);
this.add(btn_Refresh);
txt_PatientID = new JTextField();
txt_PatientID.setBounds(510, 72, 219, 20);
txt_PatientID.setEnabled(false);
this.add(txt_PatientID);
JLabel lbl_PatientID = new JLabel("Patient Num:");
lbl_PatientID.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_PatientID.setBounds(400, 75, 100, 14);
this.add(lbl_PatientID);
lbl_SIN = new JLabel("SIN:");
lbl_SIN.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_SIN.setBounds(400, 106, 100, 14);
this.add(lbl_SIN);
txt_SIN = new JTextField();
txt_SIN.setColumns(10);
txt_SIN.setBounds(510, 103, 219, 20);
this.add(txt_SIN);
txt_FirstName = new JTextField();
txt_FirstName.setColumns(10);
txt_FirstName.setBounds(510, 131, 219, 20);
this.add(txt_FirstName);
lbl_FirstName = new JLabel("First Name:");
lbl_FirstName.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_FirstName.setBounds(400, 134, 100, 14);
this.add(lbl_FirstName);
lbl_LastName = new JLabel("Last Name");
lbl_LastName.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_LastName.setBounds(400, 165, 100, 14);
this.add(lbl_LastName);
txt_LastName = new JTextField();
txt_LastName.setColumns(10);
txt_LastName.setBounds(510, 162, 219, 20);
this.add(txt_LastName);
txt_HealthCardNum = new JTextField();
txt_HealthCardNum.setColumns(10);
txt_HealthCardNum.setBounds(510, 192, 219, 20);
this.add(txt_HealthCardNum);
lbl_HealthCardNumber = new JLabel("Health Card Num:");
lbl_HealthCardNumber.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_HealthCardNumber.setBounds(400, 198, 100, 14);
this.add(lbl_HealthCardNumber);
lbl_Address = new JLabel("Address:");
lbl_Address.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_Address.setBounds(400, 259, 100, 14);
this.add(lbl_Address);
txt_Address = new JTextField();
txt_Address.setColumns(10);
txt_Address.setBounds(510, 256, 219, 20);
this.add(txt_Address);
txt_LastVisitDate = new JTextField();
txt_LastVisitDate.setColumns(10);
txt_LastVisitDate.setBounds(510, 284, 219, 20);
txt_LastVisitDate.setEnabled(false);
this.add(txt_LastVisitDate);
lbl_LastVisitDate = new JLabel("Last Visit Date");
lbl_LastVisitDate.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_LastVisitDate.setBounds(400, 287, 100, 14);
this.add(lbl_LastVisitDate);
txt_PhoneNumber = new JTextField();
txt_PhoneNumber.setColumns(10);
txt_PhoneNumber.setBounds(510, 224, 219, 20);
this.add(txt_PhoneNumber);
lbl_PhoneNumber = new JLabel("Phone Number");
lbl_PhoneNumber.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_PhoneNumber.setBounds(400, 229, 100, 14);
this.add(lbl_PhoneNumber);
lbl_UpdateMessage = new JLabel("");
lbl_UpdateMessage.setHorizontalAlignment(SwingConstants.CENTER);
lbl_UpdateMessage.setBounds(350, 400, 200, 14);
this.add(lbl_UpdateMessage);
lbl_Doctor = new JLabel("Doctor:");
lbl_PhoneNumber.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_Doctor.setBounds(63, 40, 61, 16);
this.add(lbl_Doctor);
comboBox_Doctor = new JComboBox<CustomComboBoxItem>();
comboBox_Doctor.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e) {
// Prevent this event from firing until the combo box is fully populated (each item added fires this event)
if(e.getStateChange() == ItemEvent.SELECTED
&& isDoctorComboBoxLoaded)
{
PopulatePatientTable();
}
}
});
comboBox_Doctor.setBounds(118, 36, 219, 20);
this.add(comboBox_Doctor);
chckbx_CreateNew = new JCheckBox("Create New");
chckbx_CreateNew.setBounds(400, 36, 128, 23);
chckbx_CreateNew.setSelected(true);
chckbx_CreateNew.setEnabled(false);
if (pageLoadMode == PatientLoadMode.STAFF)
{
chckbx_CreateNew.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED)
{
txt_PatientID.setText(null);
txt_PatientID.setEnabled(false);
txt_SIN.setText(null);
txt_FirstName.setText(null);
txt_LastName.setText(null);
txt_HealthCardNum.setText(null);
txt_Address.setText(null);
txt_PhoneNumber.setText(null);
txt_LastVisitDate.setText(null);
btnUpdate.setText("Create");
chckbx_CreateNew.setEnabled(false);
table_Patients.clearSelection();
}
// else
// {
// txt_PatientID.setEnabled(true);
// dbQuery.Patient_UpdatePatientInformation(
// txt_PatientID.getText(), txt_SIN.getText(),
// txt_FirstName.getText(), txt_LastName.getText(),
// txt_HealthCardNum.getText(), txt_Address.getText(),
// txt_PhoneNumber.getText());
//
// //lbl_UpdateMessage.setText("Patient Update Successful.");
// }
}
});
this.add(chckbx_CreateNew);
}
else if (pageLoadMode == PatientLoadMode.DOCTOR)
{
chckbx_CreateNew.setVisible(false);
}
DefaultTableModel model = new DefaultTableModel(tableColumns, 0);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 75, 375, 275);
this.add(scrollPane);
table_Patients = new JTable(model)
{
/**
*
*/
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column) {
return false;
}
};
table_Patients.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table_Patients.getColumnModel().getColumn(0).setPreferredWidth(200);
table_Patients.removeColumn(table_Patients.getColumnModel().getColumn(TABLE_PATIENT_ID_COLUMN_INDEX));
table_Patients.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e)
{
if(table_Patients.getSelectedRow() != -1)
{
btnUpdate.setText("Update");
chckbx_CreateNew.setEnabled(true);
chckbx_CreateNew.setSelected(false);
String PatientID = (table_Patients.getModel().getValueAt(table_Patients.getSelectedRow(), TABLE_PATIENT_ID_COLUMN_INDEX).toString());
loadPatientInformation(PatientID);
}
}
});
table_Patients.setBorder(new LineBorder(new Color(0, 0, 0)));
table_Patients.setBounds(782, 495, -382, -100);
table_Patients.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
System.out.println(table_Patients.getModel());
scrollPane.setViewportView(table_Patients);
btnUpdate = new JButton();
btnUpdate.setText("Create");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO: error checking on patient update
// Update database with new patient information
if (!chckbx_CreateNew.isSelected())
{
dbQuery.Patient_UpdatePatientInformation(
txt_PatientID.getText(), txt_SIN.getText(),
txt_FirstName.getText(), txt_LastName.getText(),
txt_HealthCardNum.getText(), txt_Address.getText(),
txt_PhoneNumber.getText());
lbl_UpdateMessage.setText("Patient Update Successful.");
}
else
{
dbQuery.Patient_CreateNewPatientInformation(
txt_SIN.getText(), txt_FirstName.getText(),
txt_LastName.getText(),
txt_HealthCardNum.getText(), txt_Address.getText(),
txt_PhoneNumber.getText());
lbl_UpdateMessage.setText("Patient Creation Successful.");
}
}
});
btnUpdate.setBounds(375, 360, 117, 29);
if (pageLoadMode != PatientLoadMode.DOCTOR)
{
this.add(btnUpdate);
}
} | 8 |
public static void main(String[] args) {
CFG.INTERNET = Assistant.isInternetReachable();
Settings.loadSettings();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e1) {
e1.printStackTrace();
}
// -- UniVersion & Reporter initialization -- //
UniVersion.offline = !CFG.INTERNET;
UniVersion.init(Vloxlands.class, CFG.VERSION, CFG.PHASE);
if (!CFG.DEBUG) {
// -- Deactivated while in development stage -- //
// Reporter.init(new File(FileManager.dir, "Logs"));
}
MediaAssistant.init();
MediaAssistant.initNatives();
Thread.currentThread().setName("Main Thread");
System.setProperty("org.lwjgl.librarypath", new File(CFG.DIR, "natives").getAbsolutePath());
try {
running = true;
setFullscreen();
Display.setIcon(new ByteBuffer[] { Assistant.loadImage(Vloxlands.class.getResourceAsStream("/graphics/logo/logo16.png")),
Assistant.loadImage(Vloxlands.class.getResourceAsStream("/graphics/logo/logo32.png")) });
Display.setTitle("Vloxlands");
Display.setResizable(true);
try {
Display.create(new PixelFormat(0, 8, 0, 4));
} catch (Exception e) {
Display.create();
}
Game.initGLSettings();
Game.initGame();
Game.currentGame.addScene(new SceneLogo());
while (running) {
if (Display.isCloseRequested()) break;
Game.currentGame.gameLoop();
}
exit();
} catch (Exception e) {
e.printStackTrace();
}
} | 6 |
static final String encode(final String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\') {
sb.append("\\\\");
} else if (c < 0x20 || c > 0x7f) {
sb.append("\\u");
if (c < 0x10) {
sb.append("000");
} else if (c < 0x100) {
sb.append("00");
} else if (c < 0x1000) {
sb.append('0');
}
sb.append(Integer.toString(c, 16));
} else {
sb.append(c);
}
}
return sb.toString();
} | 7 |
private int countCharacterInNumber(int pN){
int count = 0;
int lastTwo = pN%100;
int hundreds = (pN%1000-lastTwo) / 100;
int thou = (pN%10000 - hundreds - lastTwo) / 1000;
if(lastTwo < 20 && lastTwo > 9){
int toTranslate = lastTwo%10;
System.out.println(lastTwo);
count+=teens[toTranslate];
} else {
int lastDigit = lastTwo%10;
int tensDigit = (lastTwo - lastDigit)/10;
System.out.println("" + tensDigit + lastDigit);
count += ones[lastDigit];
count += tens[tensDigit];
}
if(pN > 99 && count >0){
count += 3;
}
if (pN > 99 && hundreds > 0){
count += 7;
count += ones[hundreds];
}
if (pN >999){
count += 8;
count += ones[thou];
}
return count;
} | 7 |
public static void main(String[] args) throws IOException {
DataTuple[] trainingData = DataSaverLoader.LoadPacManData();
// We have 10 input neurons
double[][] pacmanTrainingInput = new double[trainingData.length][];
/*
* We'll have four outputs, each for one of possible movement.
* The order of output neurons per movement is respectively:
* UP[0], RIGHT[1], DOWN[2], LEFT[3]
*/
double[][] pacmanTrainingOutput = new double[trainingData.length][4];
// let's populate the training tuples with normalized data
for( int i=0; i < trainingData.length; i++ ) {
DataTuple oneTuple = trainingData[i];
double[] oneTrainingInput = getTrainingInputFromData( oneTuple );
pacmanTrainingInput[i] = oneTrainingInput;
pacmanTrainingOutput[i][0] = 0;
pacmanTrainingOutput[i][1] = 0;
pacmanTrainingOutput[i][2] = 0;
pacmanTrainingOutput[i][3] = 0;
switch ( oneTuple.DirectionChosen ) {
case UP:
pacmanTrainingOutput[i][0] = 1;
break;
case RIGHT:
pacmanTrainingOutput[i][1] = 1;
break;
case DOWN:
pacmanTrainingOutput[i][2] = 1;
break;
case LEFT:
pacmanTrainingOutput[i][3] = 1;
break;
default:
break;
}
}
/**
* Let's construct the feed forward network.
*
* We'll set the number if input neurons to the same number of elements in
* each row of pacmanTrainingOutput[][]
* Number out output neurons will be the same as the number of elements in
* each row of pacmanTrainingOutput[][]
*
* For the number of hidden neurons we'll start with the rule of thumb stating:
* "The number of hidden neurons should be 2/3 the size of the input layer,
* plus the size of the output layer."
* see: http://www.heatonresearch.com/node/707
*
*/
final Network network = new Network();
// input layer
network.addLayer( new Layer(pacmanTrainingInput[0].length) );
// hidden layer
/*
* Rule of thumb:
* The number of hidden neurons should be 2/3 the size of the input layer,
* plus the size of the output layer.
*/
// int hiddenNeuronCountAsFractionOfInputCount = Math.round(
// pacmanTrainingInput[0].length*((float)2/3));
// final int hiddenNeuronCount =
// hiddenNeuronCountAsFractionOfInputCount + pacmanTrainingOutput[0].length;
/*
* Rule of thumb:
* The number of hidden neurons should be less than twice the size of the input layer.
* - much worse?
*/
final int hiddenNeuronCount = (int)Math.round( pacmanTrainingInput[0].length * 1.7 );
// also bad:
// int hiddenNeuronCount = Math.round( (
// pacmanTrainingInput[0].length + pacmanTrainingOutput[0].length) / 2 );
System.out.println( "Input neuron count: " + pacmanTrainingInput[0].length);
System.out.println( "Hidden neuron count: " + hiddenNeuronCount);
// hiddenNeuronCount += 20;
network.addLayer( new Layer( hiddenNeuronCount ) );
// output layer
network.addLayer( new Layer( pacmanTrainingOutput[0].length ));
// let's initialize the network with random weights
network.initializeWithRandomWeights();
/*
* Let's save the the network if the training is interrupted:
*/
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
saveNetwork(network, hiddenNeuronCount);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
/**
* Let's assign back propagation to each of the layers.
* We'll have a fixed learning rate of 0.7 and a
* momentum of 0.9 which scales the learning from the previous iteration
* before applying it to the current iteration, i.e. it specifies
* how much of an effect the previous training iteration will have
* on the current iteration.
*/
// double learningRateDivisor = 1;
// double learningRate = 1 / learningRateDivisor;
double learningRate = 0.1;
// double learningRate = 1;
Backpropagation train = new Backpropagation(
network, pacmanTrainingInput, pacmanTrainingOutput, learningRate );
int epoch = 1;
/**
* Let's do one million training iterations
* or stop training when the error rate is less than .001
*/
do {
if( epoch % 100 == 0 ) {
// learningRateDivisor++;
// learningRate = 1 / learningRateDivisor;
// train.setLearningRate( learningRate );
System.out.println( "Epoch #" + epoch +
" Error: " + train.getError() +
" Learning rate: " + learningRate );
}
// train.setLearningRate( (double)1 / epoch );
train.performTrainingIteration();
epoch++;
} while( epoch < 1000000 && train.getError() > .001 );
/**
* Now after training is complete, we'll save the trained network to disk
* to be able to load it later in a pac man controller.
*/
saveNetwork(network, hiddenNeuronCount);
} | 9 |
public static void setSize(int width, int height) {
System.out.println("Target: " +width +", " +height);
//get preset screen size
int nw = Display.getDesktopDisplayMode().getWidth();
int nh = Display.getDesktopDisplayMode().getHeight();
System.out.println("Native: " +nw +", " +nh);
try {
//derive biggest supported size limited by
//native size, allowing for menus
double scale = 0, maxScale = 0;
for (DisplayMode d: Display.getAvailableDisplayModes()){
//System.out.println(d.toString());
int w = d.getWidth(), h = d.getHeight();
scale = Math.min((double)w/width, (double)h/height);
if (scale > maxScale &&
(width*scale)<=(nw-80) && (height*scale)<=(nh-80))
{
maxScale = scale;
}
}
System.out.println("Derive: scale @ " +maxScale);
//cap scale to within target and apply
scale = Math.min(maxScale, 1);
_width = (int)Math.floor(scale*width);
_height = (int)Math.floor(scale*height);
_scale = scale;
System.out.println("Attempt: " +_width +", " +_height);
Display.setDisplayMode(new DisplayMode(_width, _height));
} catch (LWJGLException e) {
e.printStackTrace();
}
} | 5 |
private boolean outOfBounds(int var1, int var2) {
return var1 < 0 || var1 >= 32 || var2 < 0 || var2 >= 32;
} | 3 |
public ArrayList<Element> arrangeElement() {
ArrayList<Element> operator = new ArrayList<Element>();
int max = elementArray.size();
int Eleindex = 0;
int opeindex = 0;
for(int i = 0; i < max; i++){
if(elementArray.get(i).elementTrue == true){
arrangeElementArray.add(elementArray.get(i));
Eleindex++;
}else if(Pattern.matches("[¥*¥/]", elementArray.get(i).getData())){
arrangeElementArray.add(elementArray.get(i+1));
arrangeElementArray.add(elementArray.get(i));
i++;
Eleindex++;
}else if(elementArray.size() - i > 1 & Pattern.matches("[¥*¥/]", elementArray.get(i+2).getData())){
arrangeElementArray.add(elementArray.get(i+1));
arrangeElementArray.add(elementArray.get(i+3));
arrangeElementArray.add(elementArray.get(i+2));
arrangeElementArray.add(elementArray.get(i));
i +=3;
}else{
arrangeElementArray.add(elementArray.get(i+1));
arrangeElementArray.add(elementArray.get(i));
i++;
}
}
while(opeindex > 0){
arrangeElementArray.add(operator.get(opeindex-1));
opeindex--;
}
return arrangeElementArray;
} | 5 |
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("currentTime"))
getResponse().setCurrentTime(getDate());
else if (qName.equals("cachedUntil"))
getResponse().setCachedUntil(getDate());
else if (qName.equals("error"))
error.setError(getString());
} | 3 |
public void doReply(InputStream in, OutputStream out, String cmd)
throws IOException, BadHttpRequest
{
if (cmd.startsWith("POST /rmi "))
processRMI(in, out);
else if (cmd.startsWith("POST /lookup "))
lookupName(cmd, in, out);
else
super.doReply(in, out, cmd);
} | 2 |
@Test
public void testDescendingIterator() {
ThriftyList<Integer> list = new ThriftyList<Integer>();
Iterator<Integer> ri = list.descendingIterator();
Assert.assertFalse(ri.hasNext());
try {
ri.next();
Assert.fail();
} catch (NoSuchElementException e) {
}
try {
ri.remove();
Assert.fail();
} catch (IllegalStateException e) {
}
int testCount = 100;
for (int j = 0; j < testCount; j++) {
list.add(j);
}
ri = list.descendingIterator();
for (int j = testCount - 1; j >= 0; j--) {
Assert.assertTrue(ri.hasNext());
Assert.assertEquals(Integer.valueOf(j), ri.next());
}
ri = list.descendingIterator();
try {
ri.remove();
Assert.fail();
} catch (IllegalStateException e) {
}
for (int j = testCount - 1; j >= 0; j--) {
Assert.assertTrue(ri.hasNext());
Assert.assertEquals(Integer.valueOf(j), ri.next());
ri.remove();
}
Assert.assertFalse(ri.hasNext());
Assert.assertEquals(0, list.size());
try {
ri.next();
Assert.fail();
} catch (NoSuchElementException e) {
}
} | 7 |
public ArrayList<Integer> searchOR(String str){
int lg = str.length();
int indexOfAnd = str.indexOf(" OR ");
String firstElement = str.substring(0 , indexOfAnd);
String secondElement = str.substring(indexOfAnd+4,lg);
ArrayList<Integer> rs1 = search(firstElement);
ArrayList<Integer> rs2 = search(secondElement);
ArrayList<Integer> rst = new ArrayList<Integer>();
int index1 = 0;
int index2 = 0;
while(index1<rs1.size() && index2<rs2.size()){
if(rs1.get(index1) < rs2.get(index2)){
rst.add(rs1.get(index1));
index1++;
}else if(rs1.get(index1) > rs2.get(index2)){
rst.add(rs2.get(index2));
index2++;
}else {
rst.add(rs2.get(index2));
index1++;
index2++;
}
}
if(index1<rs1.size()){
for(int x = index1; x<rs1.size(); x++){
rst.add(rs1.get(x));
}
}
if(index2<rs2.size()){
for(int x = index2; x<rs2.size(); x++){
rst.add(rs2.get(x));
}
}
return rst;
} | 8 |
public int[] bytesEnInt(byte[] octets){
int aRetourner[] = new int[octets.length*8];
int curseurInt = 0;
for(int i = 0;i<octets.length;i++){
for(int j=0;j<8;j++){
aRetourner[curseurInt] = recupererBit(octets[i],j);
curseurInt++;
}
}
return aRetourner;
} | 2 |
private void _initStreamsterApiInterfaceProxy() {
try {
streamsterApiInterface = (new com.novativa.www.ws.streamsterapi.StreamsterApiLocator()).getStreamsterApiPort();
if (streamsterApiInterface != null) {
if (_endpoint != null)
((javax.xml.rpc.Stub)streamsterApiInterface)._setProperty("javax.xml.rpc.service.endpoint.address", _endpoint);
else
_endpoint = (String)((javax.xml.rpc.Stub)streamsterApiInterface)._getProperty("javax.xml.rpc.service.endpoint.address");
}
}
catch (javax.xml.rpc.ServiceException serviceException) {}
} | 3 |
private static void hamilton(int node, int level) {
// Add the current node in the cycle
currentCycle[level] = node + 1;
if ((START_NODE == node) && (level > 0)) {
if (level == GRAPH_SIZE) {
// the cycle is hamilton with min sum
minSum = curSum;
System.arraycopy(currentCycle, 0, minHamCycle, 0, currentCycle.length);
}
}
if (used[node]) {
// the cycle is not hamilton
return;
}
used[node] = true;
for (int i = 0; i < GRAPH_SIZE; i++) {
if (graph[node][i] > 0 && node != i) {
curSum += graph[node][i];
// check if there is a hamilton cycle shorter than the current path
if (curSum < minSum) {
hamilton(i, level + 1);
}
// Remove the node -> i length from the current sum (step back)
curSum -= graph[node][i];
}
}
// Step back
used[node] = false;
} | 8 |
public static void insert(Node currentNode, JoeTree tree, OutlineLayoutManager layout) {
// Abort if node is not editable
if (!currentNode.isEditable()) {
return;
}
tree.clearSelection();
Node newNode = new NodeImpl(tree,"");
int newNodeIndex = currentNode.currentIndex() + 1;
Node newNodeParent = currentNode.getParent();
newNode.setDepth(currentNode.getDepth());
newNodeParent.insertChild(newNode, newNodeIndex);
//int visibleIndex = tree.insertNodeAfter(node, newNode);
tree.insertNode(newNode);
// Record the EditingNode and CursorPosition and ComponentFocus
tree.setEditingNode(newNode);
tree.setCursorPosition(0);
tree.getDocument().setPreferredCaretPosition(0);
tree.setComponentFocus(OutlineLayoutManager.TEXT);
// Put the Undoable onto the UndoQueue
CompoundUndoableInsert undoable = new CompoundUndoableInsert(newNodeParent);
undoable.setName("Insert Node Below");
undoable.addPrimitive(new PrimitiveUndoableInsert(newNodeParent, newNode, newNodeIndex));
tree.getDocument().getUndoQueue().add(undoable);
// Redraw and Set Focus
layout.draw(newNode, OutlineLayoutManager.TEXT);
} | 1 |
public void paintComponent(Graphics aGraphics)
{
int width = this.getWidth();
int height = this.getHeight();
aGraphics.setColor(Color.white);
aGraphics.fillRect(0,0,width,height);
BufferedImage picture = (BufferedImage)this.createImage(width,height);
Graphics aGraphicsBuffer = picture.getGraphics();
aGraphicsBuffer.setColor(Color.white);
aGraphicsBuffer.fillRect(0,0,width,height);
aGraphicsBuffer.setColor(Color.black);
ForestModel aForestModel = (ForestModel)(this.model);
Forest aForest= aForestModel.getForest();
ArrayList<Tree> trees = aForest.getTrees();
Iterator iterator = trees.iterator();
while(iterator.hasNext()){
Tree aTree = (Tree)iterator.next();
HashMap<Integer,Node> nodes=aTree.getNodes();
for(Node aNode:nodes.values()){
Point aPoint = aNode.getLocation();
Dimension aDimension = aNode.getSize();
aGraphicsBuffer.setFont(aNode.getFont());
aGraphicsBuffer.drawString(aNode.getNodeName(), aPoint.x, aPoint.y+aNode.getSize().height-Constans.HEIGHT);
aGraphicsBuffer.drawRect(aPoint.x,aPoint.y, aDimension.width, aDimension.height);
}
ArrayList<Branch> branches = aForestModel.getBranches();
for(Branch aBranch : branches){
int aParentNumber = aBranch.getParentNumber();
int aChildNumber = aBranch.getChildNumber();
if(nodes.containsKey(aParentNumber)&&nodes.containsKey(aChildNumber)){
Point aParentPoint= nodes.get(aParentNumber).getLocation();
Dimension aParentDimension = nodes.get(aParentNumber).getSize();
Point aChildPoint = nodes.get(aChildNumber).getLocation();
Dimension aChildDimension = nodes.get(aChildNumber).getSize();
aGraphicsBuffer.drawLine(aParentPoint.x+aParentDimension.width, aParentPoint.y+aParentDimension.height/2, aChildPoint.x, aChildPoint.y+aChildDimension.height/2);
}
}
}
Point aPoint = this.scrollAmount();
aGraphics.drawImage(picture,0-aPoint.x,0-aPoint.y,this);
} | 5 |
public int[] nextInts(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; ++i) {
res[i] = nextInt();
}
return res;
} | 1 |
@Override
protected Void doInBackground() throws Exception {
Client loginClient = new Client(4096 * 2, 4096 * 2);
loginClient.getKryo().register(PacketLogin.class);
loginClient.getKryo().register(PacketLoginResponse.class);
loginClient.getKryo().register(PacketRequestCaptcha.class);
loginClient.getKryo().register(PacketCaptchaImage.class);
loginClient.getKryo().register(byte[].class);
loginClient.getKryo().register(PacketRegister.class);
loginClient.getKryo().register(PacketRegistered.class);
loginClient.addListener(new Listener() {
@Override
public void received(Connection connection, Object object) {
if (object instanceof PacketCaptchaImage) {
PacketCaptchaImage response = (PacketCaptchaImage) object;
System.out.println("Invalid captcha, new: " + response.toString());
publish(new RegistrationState(response));
connection.close();
} else if (object instanceof PacketRegistered) {
PacketRegistered response = (PacketRegistered) object;
System.out.println("Registered: " + response.toString());
publish(new RegistrationState(true));
connection.close();
}
}
});
loginClient.start();
try {
loginClient.connect(5000, Constants.SERVER_HOST, Constants.SERVER_PORT);
PacketRegister pr = new PacketRegister();
pr.username = login;
pr.password = password;
pr.captchaKey = key;
pr.captchaAnswer = ans;
loginClient.sendTCP(pr);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
} | 3 |
private final int method433(Class39_Sub2 class39Sub2, int i, short word0) {
int j = class39Sub2.xPositions[i];
int k = class39Sub2.yPositions[i];
int l = class39Sub2.zPositions[i];
for (int i1 = 0; i1 < anInt2818; i1++) {
if (j == xPositions[i1] && k == yPositions[i1] && l == zPositions[i1]) {
aShortArray2831[i1] |= word0;
return i1;
}
}
xPositions[anInt2818] = j;
yPositions[anInt2818] = k;
zPositions[anInt2818] = l;
aShortArray2831[anInt2818] = word0;
if (class39Sub2.anIntArray2816 != null) {
anIntArray2816[anInt2818] = class39Sub2.anIntArray2816[i];
}
return anInt2818++;
} | 5 |
public LogisticRegression(PdfFeatureAwareLogisticRegression pdf, double[] instanceWeights,
double[][] featureValues, int[] labels,
String type, //Bijection featureMapping, Bijection labelMapping,
double[] regularizationWeights, double[] regularizationBiases,
double LBFGS_TOLERANCE, int LBFGS_MAX_ITERS ) {
if (featureValues.length != labels.length) {
System.out.println("featureValues.length != outcomes.length!");
System.exit(1);
}
if (featureValues[0].length != pdf.getFeatureWeights().length) {
System.out
.println("featureValues[0].length != opdf.featureWeights.length");
System.exit(1);
}
if (instanceWeights == null || instanceWeights.length != labels.length) {
System.out.println("ERROR: instance/class weights are null || weights.length != outcomes.length");
System.exit(1);
}
this.pdf = new PdfFeatureAwareLogisticRegression(pdf);
this.initalFeatureWeights = new double[pdf.getFeatureWeights().length];
for (int f = 0; f < initalFeatureWeights.length; f++)
initalFeatureWeights[f] = pdf.getFeatureWeights()[f];
this.instanceWeights = new double[instanceWeights.length];
for (int i = 0; i < instanceWeights.length; i++)
this.instanceWeights[i] = instanceWeights[i];
this.featureValues = new double[featureValues.length][featureValues[0].length];
for (int i = 0; i < featureValues.length; i++)
for (int j = 0; j < featureValues[0].length; j++)
this.featureValues[i][j] = featureValues[i][j];
this.labels = new int[labels.length];
for (int i = 0; i < labels.length; i++)
this.labels[i] = labels[i];
//this.featureMapping = new Bijection(featureMapping);
//this.labelMapping = new Bijection(labelMapping);
this.type = type;
this.regularizationWeights = regularizationWeights;
this.regularizationBiases = regularizationBiases;
this.LBFGS_TOLERANCE = LBFGS_TOLERANCE;
this.LBFGS_MAX_ITERS = LBFGS_MAX_ITERS;
} | 9 |
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
JLPaciente = new javax.swing.JLabel();
JTFPaciente = new javax.swing.JTextField();
JLPeriodo = new javax.swing.JLabel();
JFTDataInicio = new javax.swing.JFormattedTextField();
jLabel3 = new javax.swing.JLabel();
JFTDataFim = new javax.swing.JFormattedTextField();
JLProcedimento = new javax.swing.JLabel();
JCBProcedimento = new javax.swing.JComboBox();
JLCpf = new javax.swing.JLabel();
JFTFCpf = new javax.swing.JFormattedTextField();
JBPesquisar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
JTabelaPaciente = new javax.swing.JTable();
JBExportar = new javax.swing.JButton();
setClosable(true);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Relatório de Consultas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
JLPaciente.setText("Paciente:");
JLPeriodo.setText("Periodo:");
try {
JFTDataInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
jLabel3.setText("á");
try {
JFTDataFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
JLProcedimento.setText("Procedimento:");
JCBProcedimento.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
JLCpf.setText("CPF:");
try {
JFTFCpf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
JBPesquisar.setText("Pesquisar");
JBPesquisar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JBPesquisarActionPerformed(evt);
}
});
JTabelaPaciente.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null},
{null, null},
{null, null},
{null, null}
},
new String [] {
"Código", "Paciente"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(JTabelaPaciente);
if (JTabelaPaciente.getColumnModel().getColumnCount() > 0) {
JTabelaPaciente.getColumnModel().getColumn(0).setMinWidth(50);
JTabelaPaciente.getColumnModel().getColumn(0).setMaxWidth(120);
JTabelaPaciente.getColumnModel().getColumn(1).setMinWidth(150);
JTabelaPaciente.getColumnModel().getColumn(1).setMaxWidth(300);
}
JBExportar.setText("Exportar");
JBExportar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JBExportarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(JLProcedimento)
.addComponent(JLPaciente))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(JTFPaciente, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(JLPeriodo)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(JCBProcedimento, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 73, Short.MAX_VALUE)
.addComponent(JLCpf)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JFTFCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(JFTDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addGap(6, 6, 6)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(JBPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(JFTDataFim, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(10, 10, 10))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(301, 301, 301)
.addComponent(JBExportar))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(135, 135, 135)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 423, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JLPaciente)
.addComponent(JTFPaciente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(JLPeriodo)
.addComponent(jLabel3)
.addComponent(JFTDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(JFTDataFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JLCpf)
.addComponent(JLProcedimento)
.addComponent(JCBProcedimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(JFTFCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(JBPesquisar)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JBExportar)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(16, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents | 4 |
public void setEspecialidad(String especialidad) {
this.especialidad = especialidad;
} | 0 |
@Override
public State nextState(Random random) {
State newState;
int value = random.nextInt(100);
if (Utils.isBetween(value, 0, P_MU)) {
newState = new Unmodified();
} else if (Utils.isBetween(value, P_MU, P_MD)) {
newState = new Deleted();
} else {
newState = new Modified();
}
return newState;
} | 2 |
public void actionPerformed(ActionEvent ae) {
String act = ae.getActionCommand();
this.repaint();
if (act.compareTo("Start") == 0)
{
b2.setBackground(Color.red);
b1.setVisible(false);
b2.setVisible(true);
b1.setDisplayedMnemonicIndex(0);
t = new webserver();
if (t.isRuning()) {
t.setRuning(false);
}
t.setRuning(true);
t.setDaemon(true);
t.start();
System.out.println("Starting up the server");
this.repaint();
}
if (act.compareTo("Stop") == 0)
{
b1.setVisible(true);
b2.setVisible(false);
b2.setBackground(Color.LIGHT_GRAY);
b1.setBackground(Color.LIGHT_GRAY);
t.setRuning(false);
// t.destroy();
// t.interrupt();
try {
Socket s = new Socket("localhost",80);
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Server stopped");
this.repaint();
}
if (act.compareTo("Setting") == 0)
{
this.repaint();
}
if (act.compareTo("Info") == 0 )
{
System.out.println("Reached the points");
JFrame j = new JFrame();
j.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
j.setContentPane(new info());
j.setTitle("WebServer");
j.setSize(200,200);
j.setVisible(true);
this.repaint();
}
this.repaint();
} | 7 |
@Override
public void mousePressed(MouseEvent event) {
if (isEnabled() && !event.isPopupTrigger() && event.getButton() == 1) {
mInMouseDown = true;
mPressed = true;
repaint();
MouseCapture.start(this, Cursor.getDefaultCursor());
}
} | 3 |
public static void main(String[] args) {
//Bonus problem is worked out below all commented text
//Part 1a: Experimenting with if
/*Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int age = keyboard.nextInt();*/
/* if (age > 20) // no semicolon here!!!
{
System.out.println("You can legally buy and consume alcohol in the USA.");
}
keyboard.close(); // not necessary, but good practice
System.out.println("End of program.");*/
//Part 1b: Same thing, streamlined
/* if (age >= 21)
{
System.out.println("You can legally buy and consume alcohol in the USA.");
}
keyboard.close();
System.out.println("End of program.");*/
//Part 2: More with if
/* if (age == 21)
{
System.out.println("Wow! You are 21 years old!");
}
if (age != 21)
{
System.out.println("Interesting! You are NOT 21 years old!");
}
keyboard.close();
System.out.println("End of program.");*/
//Part 3a: if... else...
/* if (age == 21)
{
System.out.println("Wow! You are 21 years old!");
}
else
{
System.out.println("Interesting! You are NOT 21 years old!");
}
System.out.println("End of program.");*/
//Part 3b: if... else... applied to legal drinking age
/*if (age >= 21)
{
System.out.println("You can legally buy and consume alcohol in the USA.");
}
else
{
System.out.println("You are under 21 and cannot legally buy and consume alcohol in the USA.");
}
System.out.println("End of program.");*/
//Part 4a: if... else if...
/*if (age == 21)
{
System.out.println("Boom! You are 21!");
}
else if (age == 18)
{
System.out.println("Hey-o! You're 18 years old!");
}
System.out.println("End of program.");*/
//Part 4b: as many else if's as we want
/* if (age == 21)
{
System.out.println("You are 21 and the same age as Miley Cyrus! Not sure if that's good or bad.");
}
else if (age == 18)
{
System.out.println("You're 18 years old! and the same age as Zendaya. No idea who she was -- I had to Google her.");
}
else if (age == 20)
{
System.out.println("You're 20 years old and the same age as Justin Bieber! Has he retired yet?");
}
else if (age == 16)
{
System.out.println("You're 16 years old and the same age as Jaden 'Don't call me Will' Smith!");
}
System.out.println("End of program.");*/
//Part 5: Bring it together
/* if (age == 21)
{
System.out.println("You are 21 and the same age as Miley Cyrus! Not sure if that's good or bad.");
}
else if (age == 18)
{
System.out.println("You're 18 years old! and the same age as Zendaya. No idea who she was -- I had to Google her.");
}
else if (age == 20)
{
System.out.println("You're 20 years old and the same age as Justin Bieber! Has he retired yet?");
}
else if (age == 16)
{
System.out.println("You're 16 years old and the same age as Jaden 'Don't call me Will' Smith!");
}
else
{
System.out.println("Oops! You're not the age of any people I know.");
}
System.out.println("End of program.");*/
//Part 6a: Question to solve
//does this code have a problem? ANS: We can shorten this code by combining the two if statements.
/*boolean canDrive;
if (age >= 16)
{
canDrive = true;
}
if (canDrive == true)
{
System.out.println("According to our records, you can legally drive a car in the USA.");
}
else
{
System.out.println("According to our records, you are prohibited from driving a car in the USA.");
}
System.out.println("End of program.");*/
//Part 6b: Question to solve
//**Q: How could you rewrite this so that if the user enters 22, both facts are printed?*
/*if (age >= 21)
{
System.out.println("You can legally buy and consume alcohol in the USA.");
}
**else** if (age >= 18) //**ANS: remove the else from the else if command.**
{
System.out.println("Can legally drive a car in the USA.");
}
else
{
System.out.println("You're under 18 years old.");
}
System.out.println("End of program.");*/
//Part 7: Getting even more control with && and || (logical AND and OR)
//now we're going to slightly change our program to do something else:
/* if ( (age > 11) && (age < 20) ) // the extra parentheses help readability, but aren't necessary...
{
System.out.println("You are a teenager!");
}
else if (age > 100 || age < 2) // ...as demonstrated here
{
System.out.println("You are either Gandalf or learning to walk.");
}
else
{
System.out.println("I have nothing interesting to say.");
}
keyboard.close();
System.out.println("End of program.");*/
//Bonus Part
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a full name: ");
String fullName = keyboard.next().toLowerCase();
System.out.print("Is the person happy? (y/n): ");
char happyAnswer = keyboard.next().toLowerCase().charAt(0);
boolean isHappy = happyAnswer == 'y';
if ( fullName.equals("indiana jones") == false)
{
System.out.println("Dude, suckin' at somethin' is the first step towards bein' sorta good at something.");
}
if ( fullName.equals("indiana jones") && isHappy == true)
{
System.out.println("Looks like Indy's find ended up in a museum!");
}
else if ( fullName.equals("indiana jones") && isHappy == false)
{
System.out.println("Looks like Indy lost his hat!");
}
keyboard.close();
System.out.println("End of program.");
} | 5 |
public void testNegated() {
Months test = Months.months(12);
assertEquals(-12, test.negated().getMonths());
assertEquals(12, test.getMonths());
try {
Months.MIN_VALUE.negated();
fail();
} catch (ArithmeticException ex) {
// expected
}
} | 1 |
public void getEntitiesOfTypeWithinAAAB(Class par1Class, AxisAlignedBB par2AxisAlignedBB, List par3List)
{
int var4 = MathHelper.floor_double((par2AxisAlignedBB.minY - World.MAX_ENTITY_RADIUS) / 16.0D);
int var5 = MathHelper.floor_double((par2AxisAlignedBB.maxY + World.MAX_ENTITY_RADIUS) / 16.0D);
if (var4 < 0)
{
var4 = 0;
}
else if (var4 >= this.entityLists.length)
{
var4 = this.entityLists.length - 1;
}
if (var5 >= this.entityLists.length)
{
var5 = this.entityLists.length - 1;
}
else if (var5 < 0)
{
var5 = 0;
}
for (int var6 = var4; var6 <= var5; ++var6)
{
List var7 = this.entityLists[var6];
for (int var8 = 0; var8 < var7.size(); ++var8)
{
Entity var9 = (Entity)var7.get(var8);
if (par1Class.isAssignableFrom(var9.getClass()) && var9.boundingBox.intersectsWith(par2AxisAlignedBB))
{
par3List.add(var9);
}
}
}
} | 8 |
@Override
public String execute() throws Exception {
try {
Map session = ActionContext.getContext().getSession();
Campaign camp = (Campaign) session.get("campa");
CampaignDemography campdemo = new CampaignDemography();
campdemo.setCampaign(camp);
campdemo.setSex(gender);
campdemo.setAge(getAge());
getMyDao().getDbsession().save(campdemo);
return "success";
} catch (HibernateException e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Recheck All Fields ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
}
} | 3 |
public void checkMailFiles() {
// Order, in dem die Mails liegen
File mailDirectory = Proxy.MAIL_STORAGE_PATH.toFile();
// Ordner und Datein im Mailordner
File[] mailFiles = mailDirectory.listFiles();
// Auswerten, ob die Dateien, die direkt im Mailordner liegen, bereits
// bekannt sind, sonst hinzufuegen.
for (int i = 0; i < mailFiles.length; i++) {
if (!mails.containsValue(mailFiles[i].getName())) {
mails.put(++mailCounter, mailFiles[i].getName());
}
}
} | 2 |
private void chooseStartingTile(Match match, int number) throws RuntimeException {
// whoops - must set tile
Tile[][] tiles = match.getTiles();
int height = tiles.length;
int width = tiles[0].length;
if (number == 0) {
tile = tiles[0][0];
} else if (number == 1) {
tile = tiles[height - 1][0];
} else if (number == 2) {
tile = tiles[height - 1][width - 1];
} else if (number == 3) {
tile = tiles[0][width - 1];
} else {
System.out.println("DBG: cannot choose tile");
throw new RuntimeException("Cannot have over 4 players");
}
tile.addBomber(this);
setStartingPosition(tile);
} | 4 |
@Override
public boolean equals( Object other ) {
if ( other == this ) {
return true;
}
if ( !( other instanceof TDoubleList ) ) return false;
if ( other instanceof TDoubleArrayList ) {
TDoubleArrayList that = ( TDoubleArrayList )other;
if ( that.size() != this.size() ) return false;
for ( int i = _pos; i-- > 0; ) {
if ( this._data[ i ] != that._data[ i ] ) {
return false;
}
}
return true;
}
else {
TDoubleList that = ( TDoubleList )other;
if ( that.size() != this.size() ) return false;
for( int i = 0; i < _pos; i++ ) {
if ( this._data[ i ] != that.get( i ) ) {
return false;
}
}
return true;
}
} | 9 |
int checkFitness(RoomScheme chromo){
Subject subject;
int fitness = 0;
ArrayList<Integer> subjectsChecked = new ArrayList<>();
//Check conditions for 1 Subjects
for(int a=0; a<5; a++){
for(int b=0; b<6; b++){
subject = chromo.rooms[a][b];
if(subjectsChecked.indexOf(subject.getCode()) == -1){
fitness = fitness + checkHours(chromo, subject.getCode())+checkRepeat(chromo, subject.getCode(), a)+checkConsecutives(chromo, subject.getCode(), a);
}
subjectsChecked.add(subject.getCode());
}
}
return fitness;
} | 3 |
public void reserveBook(int idNumber, String userName) {
int numberOfBooksChecked = 0;
for (Book item : books) {
numberOfBooksChecked++;
if ( item.getIdNumber() == idNumber)
{
AddBookIdAndUserToReservedList(idNumber,userName);
myView.thanksUser();
break;
}
if(numberOfBooksChecked == books.size()) {
myView.informOfAbsenceOfBook();
}
}
} | 3 |
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String FirstName = request.getParameter("FirstName");
String LastName = request.getParameter("LastName");
String PhoneNumber = request.getParameter("PhoneNumber");
try {
DBOperation.addToDB(FirstName, LastName, PhoneNumber);
out.println("<center><br> Contact: " + FirstName + " " + LastName + ": " + PhoneNumber + "<br> SUCCESSFULLY added!<br>");
out.println("<input type=\"button\" value=\"Close\" onclick=\"self.close()\">");
} catch (SQLException e) {
out.println("ERROR <br>");
out.println(e);
}
} | 1 |
private String addOptionalsToLaTex() {
String palautettava = "";
if (volume != 0) {
palautettava += "VOLUME = {" + volume + "},\n";
}
if (series != null) {
palautettava += "SERIES = {" + parser.parse(series) + "},\n";
}
if (address != null) {
palautettava += "ADDRESS = {" + parser.parse(address) + "},\n";
}
if (edition != null) {
palautettava += "EDITION = {" + parser.parse(edition) + "},\n";
}
if (month != null) {
palautettava += "MONTH = {" + parser.parse(month) + "},\n";
}
if (note != null) {
palautettava += "NOTE = {" + parser.parse(note) + "},\n";
}
if (key != null) {
palautettava += "KEY"
+ " = {" + parser.parse(key) + "},\n";
}
return palautettava;
} | 7 |
public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (; ;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (; ;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} | 9 |
public String find(int n) {
int ans = 0;
int a;
while(true){
a = find_f(n);
if(a == n)break;
ans++;
n = n - a;
}
if(ans % 2 == 1){
return "John";
}else{
return "Brus";
}
} | 3 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final StockPK other = (StockPK) obj;
if (!Objects.equals(this.Pcode, other.Pcode)) {
return false;
}
if (!Objects.equals(this.TangalStock, other.TangalStock)) {
return false;
}
return true;
} | 4 |
private static void show_Statistics(War war) {
int hit = 0;
int damage = 0;
int launched = 0;
int intercept = 0;
int destroyed_launcher = 0;
for (EnemyMissile missile : war.getAllMissiles()) {
if (missile.getMode() == EnemyMissile.Mode.Hit) {
hit += 1;
launched += 1;
damage += missile.getDamage();
} else if (missile.getMode() == EnemyMissile.Mode.Launched) {
launched += 1;
}
}
for (IronDome iron_dome : war.getIronDomes()) {
for (Interceptor interceptor : iron_dome.getAllInterceptor()) {
// if interceptor intercept missile
if (interceptor.getStatus() == Interceptor.Status.Intercept) {
intercept += 1;
}
}
}
for (EnemyLauncher launcher : war.getLaunchers()) {
// launcher is down
if (launcher.alive() == false) {
destroyed_launcher += 1;
}
}
System.out.println("Total Missiles Fired: " + launched);
System.out.println("Total Missiles Intercepted:" + intercept);
System.out.println("Total Missiles that hit target: " + hit);
System.out.println("Total Launchers destroyed: " + destroyed_launcher);
System.out.println("Total Missiles damage: " + damage);
} | 8 |
@Override
public int loadGame(String name) throws IOException{
XStream xstream = new XStream();
File file = new File("saves/" + name + ".xml");
ServerModel game = (ServerModel) xstream.fromXML(file);
ArrayList<Road> roads = game.getMap().getRoads();
ArrayList<Settlement> settlements = game.getMap().getSettlements();
ArrayList<City> cities = game.getMap().getCities();
for (Road road : roads) {
try {
road.initializeLocation();
}
catch(Exception e) {
System.err.print(e);
}
}
for (Settlement settlement : settlements) {
try {
settlement.initializeLocation();
}
catch(Exception e) {
System.err.print(e);
}
}
for (City city : cities) {
try {
city.initializeLocation();
}
catch(Exception e) {
System.err.print(e);
}
}
List<Player> players = game.getPlayers();
List<PlayerDescription> playerDescriptions = new ArrayList<>();
if(players != null){
for(int i = 0; i < players.size(); i++){
if(players.get(i) != null){
PlayerDescription pDescrip = new PlayerDescription(players.get(i).getColor(),players.get(i).getPlayerID(),
players.get(i).getName());
playerDescriptions.add(pDescrip);
}
}
}
GameDescription gs = new GameDescription(name, gameModelsList.size(), playerDescriptions);
gameModelsList.add(game);
gameDescriptionsList.add(gs);
return gs.getId();
} | 9 |
public Display getActiveDisplay()
{
for(Display display : displays)
{
if(display.isActive())
{
return display;
}
}
return null;
} | 2 |
public boolean quizTaken(int week, User user) {
PreparedStatement statement = null;
Connection connection = null;
try {
try {
connection = data.getConnection();
statement = connection.prepareStatement("SELECT week FROM UserQuiz WHERE week = ? AND userName = ?");
statement.setInt(1, week);
statement.setString(2, user.getUsername());
ResultSet results = statement.executeQuery();
if(results.next()) {
return true;
}
return false;
}
finally {
if(statement != null) {
statement.close();
}
if(connection != null) {
connection.close();
}
}
}
catch (SQLException ex) {
System.out.println("Error checking if the quiz was taken");
ex.printStackTrace();
return false;
}
} | 4 |
public boolean getOpenHr(int i, int j){
return openHr[i][j];
} | 0 |
@Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
Vector<String> origCmds=new XVector<String>(commands);
if(CMLib.flags().isSleeping(mob))
{
CMLib.commands().doCommandFail(mob,origCmds,L("You are already asleep!"));
return false;
}
final Room R=mob.location();
if(R==null)
return false;
if(commands.size()<=1)
{
final CMMsg msg=CMClass.getMsg(mob,null,null,CMMsg.MSG_SLEEP,L("<S-NAME> lay(s) down and take(s) a nap."));
if(R.okMessage(mob,msg))
R.send(mob,msg);
return false;
}
final String possibleRideable=CMParms.combine(commands,1);
final Environmental E=R.fetchFromRoomFavorItems(null,possibleRideable);
if((E==null)||(!CMLib.flags().canBeSeenBy(E,mob)))
{
CMLib.commands().doCommandFail(mob,origCmds,L("You don't see '@x1' here.",possibleRideable));
return false;
}
String mountStr=null;
if(E instanceof Rideable)
mountStr="<S-NAME> "+((Rideable)E).mountString(CMMsg.TYP_SLEEP,mob)+" <T-NAME>.";
else
mountStr=L("<S-NAME> sleep(s) on <T-NAME>.");
String sourceMountStr=null;
if(!CMLib.flags().canBeSeenBy(E,mob))
sourceMountStr=mountStr;
else
{
sourceMountStr=CMStrings.replaceAll(mountStr,"<T-NAME>",E.name());
sourceMountStr=CMStrings.replaceAll(sourceMountStr,"<T-NAMESELF>",E.name());
}
final CMMsg msg=CMClass.getMsg(mob,E,null,CMMsg.MSG_SLEEP,sourceMountStr,mountStr,mountStr);
if(R.okMessage(mob,msg))
R.send(mob,msg);
return false;
} | 9 |
private void push(JSONObject jo) throws JSONException {
if (this.top >= maxdepth) {
throw new JSONException("Nesting too deep.");
}
this.stack[this.top] = jo;
this.mode = jo == null ? 'a' : 'k';
this.top += 1;
} | 2 |
public boolean PerformTestNav() {
if (AboutUsTest() && TestImage(0)) {
driver.get(baseUrl);
if (MenuTest() && TestImage(1)) {
driver.get(baseUrl);
if (ServicesTest() && TestImage(2)) {
driver.get(baseUrl);
if (ContactTest() && TestImage(3)) {
driver.get(baseUrl);
return true;
}
}
}
}
driver.get(baseUrl);
return false;
} | 8 |
@Override
public void setPlayers(PlayerInfo[] value) {
//set header label indicating how many players are still needed
String labelText = "";
if(value.length == NUMBER_OF_PLAYERS){
labelText = "This game is ready to go!";
//addAiButton.setEnabled(false);
}
else{
labelText = ("Waiting for Players: Need " + (NUMBER_OF_PLAYERS-value.length) + " more");
addAiButton.setEnabled(true);
}
label.setText(labelText);
//the center panel contains the individual player panels
center.removeAll();
//build an individual player panel and add it to the center panel
for(int i = 0; i < value.length; i++){
String builtString = (i+1) + " " + value[i].getName();
JPanel playerPanel = new JPanel();
playerPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); //left justify the text in the panel
playerPanel.setPreferredSize(new Dimension(200,50));
playerPanel.setBackground(value[i].getColor().getJavaColor()); //set the background color of the player
JLabel playerLabel = new JLabel(builtString, SwingConstants.LEFT); //justify the text left
FontUtils.setFont(playerLabel, LABEL_TEXT_SIZE);
playerPanel.add(playerLabel);
center.add(playerPanel);
//add space between player panels
Dimension minSize = new Dimension(5, 10);
Dimension prefSize = new Dimension(5, 10);
Dimension maxSize = new Dimension(Short.MAX_VALUE, 10);
center.add(new Box.Filler(minSize, prefSize, maxSize));
}
} | 2 |
public static RenderMaster getRenderMaster()
{
if(renderMaster != null)
{
return renderMaster;
}
try{
Display.setDisplayMode(new DisplayMode(800, 600));
Display.create();
}
catch (Exception e)
{
System.out.println("RenderMasterFactory Failing hardcore " + e);
System.exit(-1);
}
if(GLContext.getCapabilities().OpenGL30){
System.out.println("30 capable");
}
if(GLContext.getCapabilities().OpenGL31){
System.out.println("31 capable");
}
if(GLContext.getCapabilities().OpenGL32)
{
renderMaster = new CurrentRenderMaster();
}
else
{
renderMaster = new CompatibilityRenderMaster();
}
return renderMaster;
} | 5 |
@Override
public void keyTyped(KeyEvent e) {
if(keyBind[0]){
SubTerra.getLevel().p.move(0, -1);
}
if(keyBind[1]){
SubTerra.getLevel().p.move(0, 1);
}
if(keyBind[2]){
SubTerra.getLevel().p.move(1, 0);
}
if(keyBind[3]){
SubTerra.getLevel().p.move(-1, 0);
}
} | 4 |
public boolean checkFields(JTextField name, JTextField direction,
JTextField speed, JTextField rowField, JTextField columnField) {
if (name.getText().equals("") || direction.getText().equals("")
|| speed.getText().equals("")
|| rowField.getText().equals("")
|| columnField.getText().equals("")) {
JOptionPane.showMessageDialog(rescue,
"All fields need to be filled!", "ERROR",
JOptionPane.ERROR_MESSAGE);
return false;
} else if (Searcher.decodeDirection(direction.getText()) == null) {
JOptionPane.showMessageDialog(rescue,
"That is not a valid direction!", "ERROR",
JOptionPane.ERROR_MESSAGE);
return false;
} else {
try {
Integer.parseInt(rowField.getText());
Integer.parseInt(columnField.getText());
Integer.parseInt(speed.getText());
} catch (NumberFormatException n) {
JOptionPane.showMessageDialog(rescue,
"Row, column, and speed need to be integers!",
"ERROR", JOptionPane.ERROR_MESSAGE);
return false;
}
}
return true;
} | 7 |
public boolean setShutdownmenuButtonHeight(int height) {
boolean ret = true;
if (height < 0) {
this.buttonShutdownmenu_Height = UISizeInits.SHDMENU_BTN.getHeight();
ret = false;
} else {
this.buttonShutdownmenu_Height = height;
}
somethingChanged();
return ret;
} | 1 |
public void setCompany(Company company) {
this.company = company;
} | 0 |
private void initializeFilter() throws CustomFilterException {
String regExFilter = this.configuration.getRegExFilter();
if (regExFilter == null) {
String[] customFilter = this.configuration.getCustomFilter();
if (customFilter == null) {
this.logger.setFilter(null);
} else {
CustomFactory filterFactory = new CustomFactory();
this.logger.setFilter(filterFactory.createCustomFilter(customFilter[0], java.util.Arrays.copyOfRange(customFilter, 1, customFilter.length)));
}
} else {
this.logger.setFilter(new RegexFilter(regExFilter));
}
} | 2 |
public void afficherVisiteur(Visiteur unVisiteur){
this.vue.getjTextFieldNom().setText(unVisiteur.getNom());
this.vue.getjTextFieldPrenom().setText(unVisiteur.getPrenom());
this.vue.getjTextFieldAdresse().setText(unVisiteur.getAdresse());
this.vue.getjTextFieldCP().setText(unVisiteur.getCp());
this.vue.getjTextFieldVille().setText(unVisiteur.getVille());
if(unVisiteur.getCode_sec() != null){
this.vue.getjComboBoxSecteur().setSelectedItem(unVisiteur.getCode_sec().getLibelle());
} else{
this.vue.getjComboBoxSecteur().setSelectedItem("");
}
this.vue.getjComboBoxLabo().setSelectedItem(unVisiteur.getCode_lab().getNom());
} | 1 |
private void jButtonGuardarNovoFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarNovoFornecedorActionPerformed
// BOTAO GUARDAR NOVO FORNECEDOR -> JANELA NOVO FORNECEDOR
String nome = jTextFieldNomeFornecedor.getText();
String morada = jTextFieldMoradaFornecedor.getText();
String codPostal = jTextFieldCodPostalFornecedor.getText();
String localidade = jTextFieldLocalidadeFornecedor.getText();
String contacto = jTextFieldContactoFornecedor.getText();
String email = jTextFieldEmailFornecedor.getText();
String nif = jTextFieldNIFFornecedor.getText();
String tipoProduto = jTextFieldTipoProdutoFornecedor.getText();
if (nome.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Nome !");
} else if (morada.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira a Morada !");
} else if (codPostal.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Codigo Postal !");
} else if (localidade.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira a Localidade !");
} else if (contacto.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Contacto !");
} else if (nif.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o NIF !");
} else if (tipoProduto.equals("")) {
JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Tipo de Produto !");
} else {
InserirNovoFornecedor();
LimpaNovoFornecedor();
jDialogNovoFornecedor.setVisible(false);
}
} | 7 |
Subsets and Splits