text stringlengths 14 410k | label int32 0 9 |
|---|---|
private static boolean isEmptyMap(Map<?, ?> map) {
return null == map || map.isEmpty();
} | 3 |
public static void main(String[] p_agrs) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Main());
} | 4 |
public static int[][] lenghtLCS(int[] x, int[] y){
// TODO Auto-generated method stub
int m = x.length;
int n = y.length;
int[][] c = new int[m + 1][n + 1];//保存LCS(Xi,Yj)的长度
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(x[i] == y[j]){
c[i + 1][j + 1] = c[i][j] + 1;
}else{
if(c[i][j + 1] > c[i + 1][j]){
c[i + 1][j + 1] = c[i][j + 1];
}else{
c[i + 1][j + 1] = c[i + 1][j];
}
}
}
}
for(int i=0; i<=m; i++){
for(int j=0; j<=n; j++){
System.out.print(c[i][j] + " ");
}
System.out.println();
}
return c;
} | 6 |
public static void main(String[] args) {
int no_of_students;
int no_of_scores;
Scanner scan = new Scanner(System.in);
String[] firstInput = scan.nextLine().split(" ");
no_of_students = Integer.parseInt(firstInput[0]);
no_of_scores = Integer.parseInt(firstInput[1]);
String[] names = new String[no_of_students];
double[] grades = new double[no_of_scores];
double average_grade = 0.0;
for(int i=0; i<no_of_students ;i++){
String[] raw_data = scan.nextLine().split(" ");
names[i] = raw_data[0];
for(int j=1; j<=no_of_scores ;j++) {
grades[i] += (Integer.parseInt(raw_data[j]));
}
average_grade +=grades[i]/(no_of_scores*no_of_students);
}
System.out.println(average_grade);
for(int i=0;i<no_of_students;i++) {
System.out.println(names[i] +" "+ (grades[i]/no_of_scores));
}
//System.out.println(no_of_students + " "+ no_of_scores);
} | 3 |
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(Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Ventas.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 Ventas().setVisible(true);
Limpiar.setIcon(new ImageIcon(this.getClass().getResource("/Imagen/Clean.png")));
Eliminar.setIcon(new ImageIcon(this.getClass().getResource("/Imagen/Del.png")));
Acept.setIcon(new ImageIcon(this.getClass().getResource("/Imagen/Ok.png")));
jTable1.setModel(new DefaultTableModel(
new Object[][]{},new String [] {
"Id", "Nombre", "Marca", "Cantidad", "Precio","Total"
}
){
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
}
});
} | 6 |
public void runResultView(){
if(resultView == null){
resultView = new ResultView("Result");
}
} | 1 |
@Override
public boolean allocateHostForVm(Vm vm)
{
double minMetric = -1;
PowerHost ChoosenHost = null;
//Log.formatLine("In ChooseHostForNewVm function...");
for (PowerHost host : this.<PowerHost> getHostList()) {
double tmpMetric = MetricWattPerMips(host);
// Log.printLine("MetricHost value for HOST #" + host.getId() + " = " + tmpMetric);
if(minMetric != -1 && tmpMetric < minMetric)
{
minMetric = tmpMetric;
ChoosenHost = host;
// Log.printLine("Temp CHOSEN HOST is : Host #" + ChosenHost.getId());
}
else if(minMetric == -1)
{
minMetric = tmpMetric;
ChoosenHost = host;
}
}
Log.printLine("CHOSEN HOST for VM " + vm.getId()+ " is : Host #" + ChoosenHost.getId());
boolean allocationOK = false;
allocationOK = allocateHostForVm(vm,ChoosenHost);
if(allocationOK)
return true;
if(!allocationOK && ChoosenHost.isEnableDVFS() )
{
Log.printLine("Not enough free MIPS in the choosen HOST !");
Log.printLine("Trying to decrease VMs size in this HOST!");
ChoosenHost = TryDVFSEnableHost(ChoosenHost,vm);
if( allocateHostForVm(vm,ChoosenHost))
{
Log.printLine("VMs size decreased successfully !");
return true;
}
else
Log.printLine("Error , VMs size not enough decreased successfully !");
}
return false;
} | 8 |
@Override
public void serialize(Buffer buf) {
buf.writeByte(teleporterType);
buf.writeUShort(mapIds.length);
for (int entry : mapIds) {
buf.writeInt(entry);
}
buf.writeUShort(subAreaIds.length);
for (short entry : subAreaIds) {
buf.writeShort(entry);
}
buf.writeUShort(costs.length);
for (short entry : costs) {
buf.writeShort(entry);
}
} | 3 |
public String cambio(String palabra, int brin) {
int al=0,r=0;
String cambio = " ",cambio2="",cambio3="",cambio4="";
String acum = "", acum2 = "", acum3 = "", acum4 ="";
for (int i = 0; i < palabra.length(); i++) {
acum="";
acum += palabra.charAt(i);
for (int j = 0; j < alfa.length&&j<mayusculas.length||j<num.length; j++) {
acum2 = alfa[j];
acum3 = mayusculas[j];
if (acum2.equals(acum)) {
al = j + brin;
cambio += alfa[al];
cambio3+=cambio;
cambio="";
}if(j<num.length-1){
if(acum.equals(num[j])){
al = j + brin;
cambio2 += num[al];
cambio3+=cambio2;
cambio2="";
}
}else{
if(acum3.equals(acum)){
al = j + brin;
cambio4 += mayusculas[al];
cambio3+=cambio4;
cambio4="";
}
}
}
}
return cambio3;
} | 8 |
private void findPrimes () {
myPrimes = new ArrayList<Integer> ();
// Create many threads
Thread[] threads = new Thread[myNumThreads];
for (int i=0; i<myNumThreads; i++) {
threads[i] = new Thread () {
@Override
public void run() {
while (!myInputs.isEmpty()) {
Integer input;
synchronized(myInputs) {
input = myInputs.poll();
}
if (input == null) {
return;
}
if (SimplePrime.checkPrime (input)) {
synchronized(myPrimes) {
myPrimes.add(input);
}
}
}
}
};
}
for (int i=0; i<myNumThreads; i++) {
threads[i].start();
}
try {
for (int i=0; i<myNumThreads; i++) {
threads[i].join();
}
} catch (InterruptedException e) {
System.out.println("interrupt caught");
}
} | 7 |
public static boolean esPalindrom(String p1) {
Stack s1 = new Stack();
String p2 = "";
// Emplanem l'Stack amb la caracters separats de la paraula p1 que ens
// an entrat
for (int i = 0; i < p1.length(); i++) {
s1.push(p1.charAt(i));
}
// Concatanem tot l'stack al reves
while (!s1.empty()) {
p2 += s1.pop();
}
// Comprovacio de si la paraula es
if (p1.equals(p2)) {
return true;
} else {
return false;
}
} | 3 |
@Override
public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) {
OutlinerDocument doc = (OutlinerDocument) e.getDocument();
updateText(doc);
if (doc != null) {
calculateEnabledState(doc.getTree());
}
} | 1 |
public void scrollAndAnimateTo(int index) {
if(loadingDone && (scrollerTimer == null ||
!scrollerTimer.isRunning())) {
if (index < 0)
index = 0;
else if (index >= avatars.size())
index = avatars.size() - 1;
DrawableAvatar drawable = null;
if(drawableAvatars != null) {
for (DrawableAvatar avatar: drawableAvatars) {
if (avatar.index == index) {
drawable = avatar;
break;
}
}
}
if(drawable != null)
scrollAndAnimate(drawable);
else
setSelectedIndex(index);
}
} | 9 |
public ArrowMinimizeTool(AutomatonPane view, AutomatonDrawer drawer) {
super(view, drawer);
} | 0 |
private boolean checkContent(VElement elem, T o, Method m) throws Exception {
if (getAnnotation(m, Content.class) == null) {
return false;
}
Class cls = m.getReturnType();
String value = null;
if (!cls.isPrimitive() && !isWrapperType(cls) && cls != String.class) {
// otherwise check if it defines a converter
Converter con = getAnnotation(m, Converter.class);
if (con == null) {
throw new VXMLBindingException(
"Content Specification is invalid. The following Content class is not accepted:"
+ cls.getName());
}
VConverter vcon = (VConverter) con.converter().newInstance();
if (!vcon.isConvertCapable(cls)) {
throw new VXMLBindingException(
"Content Specification is invalid. The following Content class: "
+ ""
+ cls.getName()
+ " could not be converted with the specified converter: "
+ vcon.getClass());
}
value = vcon.convert(m.invoke(o, new Object[]{}));
} else {
Object resValue = m.invoke(o, new Object[]{});
if (resValue != null) {
value = resValue.toString();
}
}
if (value != null) {
// is the value content supposed to be CDATA
CData cData = getAnnotation(m, CData.class);
if (cData != null) {
value = "<![CDATA[" + value + "]]>";
}
elem.addChild(new VContent(value));
}
return true;
} | 9 |
@Override
public void tick() {
if (!paused) {
if (isWon()) {
if (gameOverListener != null) {
gameOverListener.onGameOver(true);
}
}
ticksSinceMove++;
if (ticksSinceMove >= TICKS_PER_MOVE) {
tetromino.moveDownAndPlace(this);
}
moveLeft(leftPressed);
moveRight(rightPressed);
moveDown(downPressed);
}
} | 4 |
public void run(){
try {
while(true){
message = in.readLine();
out.println(type + message);
}
} catch (IOException e) {
e.printStackTrace();
}
} | 2 |
private static String[][] parseStringArray(DynamicArray<String> matrix) {
if (matrix.get(0).toLowerCase().equals("directed")) {
matrix.delete(0);
directed = true;
} else {
directed = false;
}
String[][] adjacencyMatrix = new String[matrix.getSize()][matrix.getSize()];
for (int i = 0; i < matrix.getSize(); i++) {
String[] parsedString = matrix.get(i).split("\\s+");
for (int j = 0; j < parsedString.length; j++) {
adjacencyMatrix[i][j] = parsedString[j];
}
}
return adjacencyMatrix;
} | 3 |
public void set_LabOrder(MsgParse mp)
throws SQLException {
String labOrderProvider = "";
try {
// We need to get the provider ID from the initial Visit which was sent by bedboard
PreparedStatement prepStmt = connection.prepareStatement(
"select attending_provider_number from visit "
+ "where visit_number = ? ");
prepStmt.setString(1, mp.patient.getAcctNum());
ResultSet rs = prepStmt.executeQuery();
while (rs.next()){
labOrderProvider = rs.getString(1);
System.out.println("labOrderProvider: " + labOrderProvider);
}
prepStmt.execute();
//We're inserting into the labOrders table, breaking a little bit of referential inegrity
// because I'm inserting the provider ID directly into the table after getting it from visit above
//psst... we're not using the provider table
prepStmt = connection.prepareStatement(
"insert into Lab_orders (placerNum, visit_vid, labOrderControl, fillerOrderNum, dateTransaction, "
+ "serviceIdentifier, visit_patient_pid, provider_providerID) "
+ "values (?, ?, ?, ?, ?, ?,"
+ "(select pid from patient where mrn = ?), ?)");
prepStmt.setString(1, mp.labOrder.getPlacerNum());
//Getting the "VISIT NUMBER" from PID-18 in Patient
prepStmt.setString(2, mp.patient.getAcctNum());
prepStmt.setString(3, mp.labOrder.getLabOrderControl());
//TODO : Need to write a method to generate a fillerNumber
prepStmt.setString(4, "fakefiller");
prepStmt.setString(5, mp.labOrder.getDateTransaction());
prepStmt.setString(6, mp.labOrder.getServiceIdentifier());
prepStmt.setString(7, mp.patient.getMRN());
prepStmt.setString(8, labOrderProvider);
prepStmt.execute();
prepStmt.close();
} catch (SQLException se) {
System.out.println("Error in DBLoader.set_LabOrder: " + se);
}
} | 2 |
private AbstractNode<V> optimize(MutableNode<V> n) {
if (n.getChildren() == null) {
// this is a leaf node
return new LeafNode<V>(n.getPrefix(), n.getValue());
}
if (n.getChildren().length == 1) {
// this is a single-child node
return new SingleChildNode<V>(n.getPrefix(), n.getValue(), optimize(n.getChildren()[0]));
}
// it's a multi-child node
AbstractNode<V>[] optimizedChildren = new AbstractNode[n.getChildren().length];
for (int i = 0; i < optimizedChildren.length; i++) {
optimizedChildren[i] = optimize(n.getChildren()[i]);
}
Arrays.sort(optimizedChildren, new Comparator<AbstractNode<V>>(){
@Override
public int compare(AbstractNode<V> arg0, AbstractNode<V> arg1) {
char[] prefix0 = arg0.getPrefix();
char[] prefix1 = arg1.getPrefix();
for (int i = 0; i < Math.min(prefix0.length, prefix1.length); i++) {
if (prefix0[i] < prefix1[i]) {
return -1;
} else if (prefix0[i] > prefix1[i]) {
return 1;
}
}
throw new IllegalStateException("Nodes " + arg0 + " and " + arg1 + " have matching prefixes!");
}
});
if (n.getPrefix().length == 1) {
// if (isContiguous(optimizedChildren)) {
// return new ContiguousRangeNode<V>(n.getPrefixFirst(), n.getValue(), optimizedChildren);
// }
return new SingleLengthMultiChildNode<V>(n.getPrefix()[0], n.getValue(), optimizedChildren);
}
// // special case for the root
// if (n.getPrefix().length == 0) {
// if (isContiguous(optimizedChildren)) {
// return new ContiguousRangeNode<V>('\0', n.getValue(), optimizedChildren);
// }
// }
return new MultiChildNode<V>(n.getPrefix(), n.getValue(), optimizedChildren);
} | 7 |
public boolean[] getAction()
{
double[] inputs;// = new double[numberOfInputs];
byte[][] scene = levelScene;
inputs = new double[numberOfInputs];
int which = 0;
for (int i = -3; i < 4; i++) {
for (int j = -3; j < 4; j++) {
inputs[which++] = probe(i, j, scene);
}
}
for (int i = -3; i < 4; i++) {
for (int j = -3; j < 4; j++) {
inputs[which++] = probe(i, j, enemies);
}
}
inputs[inputs.length - 3] = isMarioOnGround ? 1 : 0;
inputs[inputs.length - 2] = isMarioAbleToJump ? 1 : 0;
inputs[inputs.length - 1] = 1;
double[] outputs = mlp.propagate (inputs);
boolean[] action = new boolean[numberOfOutputs];
for (int i = 0; i < action.length; i++) {
action[i] = outputs[i] > 0;
}
return action;
} | 7 |
@EventHandler
public void onQuit(PlayerQuitEvent e){
Player p = e.getPlayer();
if(Main.Main.players.contains(p)){
Main.Main.players.remove(p);
Main.Main.playerTeam.remove(p);
tm.removePlayer(p);
for(Player broad : Main.Main.players){
broad.sendMessage(Main.Main.Prefix + "§c" + p + " §ahat das Spiel verlassen");
}
}
} | 2 |
public static void main (String[] args)
{ //abre public main
//declarações
InputStream entrada = System.in;
Scanner scanner = new Scanner (entrada);
float a, b, valor, igual;
String op;
//fimDeclarações
System.out.println("Siga as instruções a seguir para usar a calculadora \n"); //mensagem inicial
System.out.println("Digite o primeiro valor");
a = scanner.nextFloat(); //a Receberá o primeiro valor
System.out.println("Digite a operação (Use + para soma, - para subtração, * para multiplicação, / para divisão e ^ para subtração");
op=scanner.next();
System.out.println("Digite segundo valor");
b = scanner.nextFloat(); //b Receberá o segundo valor
if (op.equals("+")) //em caso de soma
{
igual=soma(a, b);
System.out.println("O resultado da soma é: " +igual);
/*valor = (a+b);
System.out.println("O resultado da soma é: " +valor); //mostra resultado em caso de soma
*/
}
if (op.equals("-")) //em caso de subtraçao/
{
valor=menos(a, b);
System.out.println("O resultado da subtração é: " +valor); //mostra resultado em caso de subtração
}
if (op.equals("*"))
{
valor=vezes(a, b);
System.out.println("O resultado da multiplicação é: "+valor); //mostra resultado em caso de multiplicação
}
if (op.equals("/"))
{
valor=divide (a, b);
System.out.println("O resultado da divisão é: " +valor); //mostra resultado em caso de divisão
}
if (op.equals("^"))
{
valor=potencia(a, b);
System.out.println("O resultado da potenciação é: " +valor); //mostra resultado em caso de potencia
}
} //fecha public main | 5 |
public final void modifyHunger(int toMod)
{
hunger+=toMod;
if(hunger > 100)
{
hunger = 100;
}
else if(hunger < 0)
{
hunger = 0; //kinda screwed
}
} | 2 |
@Test(expected=IOException.class)
public void malformedUrl() throws IOException {
TeleSignRequest tr;
if(!timeouts && !isHttpsProtocolSet)
tr = new TeleSignRequest(":junk/rest.telesign.com", "/v1/phoneid/standard/15551234567", "GET", "customer_id", "");
else if(timeouts && !isHttpsProtocolSet)
tr = new TeleSignRequest(":junk/rest.telesign.com", "/v1/phoneid/standard/15551234567", "GET", "customer_id", "", connectTimeout, readTimeout);
else if(!timeouts && isHttpsProtocolSet)
tr = new TeleSignRequest(":junk/rest.telesign.com", "/v1/phoneid/standard/15551234567", "GET", "customer_id", "", HTTPS_PROTOCOL);
else
tr = new TeleSignRequest(":junk/rest.telesign.com", "/v1/phoneid/standard/15551234567", "GET", "customer_id", "", connectTimeout, readTimeout, HTTPS_PROTOCOL);
assertNotNull(tr);
tr.executeRequest();
} | 6 |
public Transition getExistingOutgoingTransition(Transition t) {
Transition existing = null;
State toState = t.getToState();
for(int i=0; i<outgoingTransitions.size() && existing == null; i++) {
State from = outgoingTransitions.get(i).getFromState();
State to = outgoingTransitions.get(i).getToState();
if(from.equals(this) && to.equals(toState)) {
existing = outgoingTransitions.get(i);
}
}
return existing;
} | 4 |
public String getFileFilterExclude() {
return this.fileFilterExclude;
} | 0 |
*/
public void addInstruction(final Instruction inst) {
Assert.isTrue(!inst.isJsr() && !inst.isConditionalJump(),
"Wrong addInstruction called with " + inst);
this.next = null;
addInst(inst);
} | 1 |
public void updateScores(Player winner) {
Player[] players = new Player[Game.linkedGet().getNumPlayers()];
int[] playerScores = new int[players.length];
for (int i = 0; i < players.length; i++) {
players[i] = Game.linkedGet().getPlayers().get(i);
playerScores[i] = Game.determineScore(players[i]);
}
sortPlayersScores(players, playerScores);
winnerText.setText(winner.getName() + " Wins!");
int i;
for (i = 0; i < players.length; i++) {
playerNames[i].setText(players[i].getName());
scores[i].setText(String.valueOf(playerScores[i]));
playerNames[i].setTextVisible(true);
scores[i].setTextVisible(true);
dots[i].setTextVisible(true);
playerNames[i].setColor(players[i].getColor(), false);
scores[i].setColor(players[i].getColor(), false);
}
while (i < playerNames.length) {
playerNames[i].setTextVisible(false);
scores[i].setTextVisible(false);
dots[i].setTextVisible(false);
i++;
}
playerNames[0].animateColor(new RGBColorAnimation(1000, Animation.PACE_LINEAR_FLIP, true, playerNames[0].getTrueColor(), ProjUtils.WHITE, true));
scores[0].animateColor(new RGBColorAnimation(1000, Animation.PACE_LINEAR_FLIP, true, scores[0].getTrueColor(), ProjUtils.WHITE, true));
} | 3 |
@Override
public boolean equals(Object obj) {
System.out.println("user equals");
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
return true;
} | 4 |
public void testProperty() {
LocalTime test = new LocalTime(10, 20, 30, 40);
assertEquals(test.hourOfDay(), test.property(DateTimeFieldType.hourOfDay()));
assertEquals(test.minuteOfHour(), test.property(DateTimeFieldType.minuteOfHour()));
assertEquals(test.secondOfMinute(), test.property(DateTimeFieldType.secondOfMinute()));
assertEquals(test.millisOfSecond(), test.property(DateTimeFieldType.millisOfSecond()));
assertEquals(test.millisOfDay(), test.property(DateTimeFieldType.millisOfDay()));
assertEquals(test, test.property(DateTimeFieldType.minuteOfDay()).getLocalTime());
assertEquals(test, test.property(DateTimeFieldType.secondOfDay()).getLocalTime());
assertEquals(test, test.property(DateTimeFieldType.millisOfDay()).getLocalTime());
assertEquals(test, test.property(DateTimeFieldType.hourOfHalfday()).getLocalTime());
assertEquals(test, test.property(DateTimeFieldType.halfdayOfDay()).getLocalTime());
assertEquals(test, test.property(DateTimeFieldType.clockhourOfHalfday()).getLocalTime());
assertEquals(test, test.property(DateTimeFieldType.clockhourOfDay()).getLocalTime());
try {
test.property(DateTimeFieldType.dayOfWeek());
fail();
} catch (IllegalArgumentException ex) {}
try {
test.property(null);
fail();
} catch (IllegalArgumentException ex) {}
} | 2 |
public Configuration build(String consumerKey, String consumerSecret, String accessToken, String accessSecret) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessSecret);
return cb.build();
} | 0 |
private boolean jj_3R_16() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_56()) jj_scanpos = xsp;
xsp = jj_scanpos;
if (jj_3_57()) jj_scanpos = xsp;
xsp = jj_scanpos;
if (jj_3_58()) {
jj_scanpos = xsp;
if (jj_3_59()) {
jj_scanpos = xsp;
if (jj_3_60()) {
jj_scanpos = xsp;
if (jj_3_61()) return true;
}
}
}
if (jj_3R_29()) return true;
return false;
} | 7 |
public void nextPermutation(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int start = -1, end = -1;
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
start = i;
break;
}
}
if (start == -1) {
Arrays.sort(nums);
return;
}
for (int i = nums.length - 1; i > start; i--) {
if (nums[i] > nums[start]) {
end = i;
break;
}
}
int swap = nums[start];
nums[start] = nums[end];
nums[end] = swap;
start++;
end = nums.length - 1;
while (start < end) {
swap = nums[start];
nums[start] = nums[end];
nums[end] = swap;
start++;
end--;
}
} | 8 |
private boolean boardEquals(Board board0, Board board1) {
boolean result = true;
for (int i = 0; i < board0.getFields().length; i++) {
if (board0.getFields()[i] != board0.getFields()[i]) {
result = false;
}
}
for (int i = 0; i < board0.getFields().length; i++) {
if (board0.coordinates[i] != board1.coordinates[i]) {
result = false;
}
}
return result;
} | 4 |
public boolean exists(String w) {
String word = w.toUpperCase();
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[0].length; col++) {
if (word.charAt(0) == board[row][col])
if (check(word.substring(1), row, col))
return true;
}
}
return false;
} | 4 |
public static int evalRPN(String[] tokens) {
if(tokens==null||tokens.length==0){
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
for(String token : tokens){
if(token.equals("+")){
stack.push(stack.pop() + stack.pop());
}else if(token.equals("-")){
int rOperand = stack.pop();
stack.push(stack.pop() - rOperand);
}else if(token.equals("*")){
stack.push(stack.pop() * stack.pop());
}else if(token.equals("/")){
int rOperand = stack.pop();
stack.push(stack.pop() / rOperand);
}else{
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
} | 7 |
public boolean jumpMayBeChanged() {
return (catchBlock.jump != null || catchBlock.jumpMayBeChanged());
} | 1 |
public static void write() throws Exception
{
if (patchNo == 0)
{
newFile = new File(ActionHandler.outputPatchSelectedFile.toString() + "/Patch.txt");
}
else
{
newFile = new File(ActionHandler.outputPatchSelectedFile.toString() + "/Patch" + patchNo + ".txt");
}
if (newFile.exists())
{
System.out.println("The file already exists, adding number...");
patchNo++;
write();
}
else
{
newFile.createNewFile();
create();
}
} | 2 |
public void renderTiles(Screen screen, int xOffset, int yOffset, boolean isForeground) {
if (xOffset < 0)
xOffset = 0;
if (xOffset > ((width << 4) - screen.width))
xOffset = ((width << 4) - screen.width);
if (yOffset < 0)
yOffset = 0;
if (yOffset > ((height << 4) - screen.height))
yOffset = ((height << 4) - screen.height);
screen.setOffset(xOffset, yOffset);
for (int y = (yOffset >> 4); y < (yOffset + screen.height >> 4) + 1; y++) {
for (int x = (xOffset >> 4); x < (xOffset + screen.width >> 4) + 1; x++) {
if (isForeground)
getForeTile(x, y).render(screen, this, x << 4, y << 4);
else
getBackTile(x, y).render(screen, this, x << 4, y << 4);
}
}
} | 7 |
StarSystemEnum(String nameObject, double mass, float radius, SimpleVector initialPosition, SimpleVector velocity) {
this.nameObject = nameObject;
this.mass = mass;
this.radius = radius;
this.initialPosition = initialPosition;
this.velocity = velocity;
} | 0 |
@Override
public void processAI() {
if (!move()) {
goldAdded = true;
setDead(true);
GameConfig.player.spendLife();
}
for (Effect effect : effects)
if (modifier != null)
modifier.inflict(effect, this);
else
effect.inflict(this);
Iterator<Effect> it = effects.iterator();
while (it.hasNext())
if (it.next().hasEnd())
it.remove();
} | 5 |
public void map_place(int x, int y, int btn, int mod) {
if (plob != null) {
Gob pgob;
synchronized (glob.oc) {
pgob = glob.oc.getgob(playergob);
}
if (pgob == null)
return;
Coord mc = tilify(pgob.position());
Coord offset = new Coord(x, y).mul(tileSize);
mc = mc.add(offset);
wdgmsg("place", mc, btn, mod);
}
} | 2 |
public void setCommandButtonFonttype(Fonttype fonttype) {
if (fonttype == null) {
this.buttonComFontType = UIFontInits.COMBUTTON.getType();
} else {
this.buttonComFontType = fonttype;
}
somethingChanged();
} | 1 |
static final void method226(int i, int i_0_, int i_1_, int i_2_,
int i_3_) {
for (int i_4_ = i_2_; Class348_Sub38.anInt7008 > i_4_; i_4_++) {
Rectangle rectangle = Class180.aRectangleArray2371[i_4_];
if ((rectangle.width + rectangle.x ^ 0xffffffff) < (i ^ 0xffffffff)
&& (rectangle.x ^ 0xffffffff) > (i_0_ + i ^ 0xffffffff)
&& ((rectangle.y - -rectangle.height ^ 0xffffffff)
< (i_1_ ^ 0xffffffff))
&& rectangle.y < i_1_ + i_3_)
Class152.aBooleanArray2076[i_4_] = true;
}
anInt219++;
Class338.method2663(i_2_ + -5590, i, i - -i_0_, i_1_, i_3_ + i_1_);
} | 5 |
@Override
public Map<Noppa, Integer> poistaPienempiPari(Map<Noppa, Integer> kelpoisatnopat){
Map<Noppa, Integer> nopatlistalla = kelpoisatnopat;
if(super.tyyppi==8) {
Noppa poistettavanoppa = null;
for(Noppa noppa : nopatlistalla.keySet()) {
poistettavanoppa = noppa;
if(nopatlistalla.get(noppa)>1){
if(poistettavanoppa.annaSilmaluku()>noppa.annaSilmaluku()){
poistettavanoppa=noppa;
}
}
}
nopatlistalla.remove(poistettavanoppa);
}
return nopatlistalla;
} | 4 |
public String getSessionQuery(int session, int subsession) {
String query = new String();
//piece together the query string
if (sessionExists(session, subsession)) {
query = "&Session=" + ((session <= 20) ? "rd" : "jd") + session + "l" + subsession + "se";
} else {
query = "Session data does not exist";
}
return query;
} | 2 |
private void improveCorners() {
Point[] newP = new Point[corners.size()];
for (Corner c : corners) {
if (c.border) {
newP[c.index] = c.loc;
} else {
double x = 0;
double y = 0;
for (Center center : c.touches) {
x += center.loc.x;
y += center.loc.y;
}
newP[c.index] = new Point(x / c.touches.size(), y / c.touches.size());
}
}
corners.stream().forEach((c) -> {
c.loc = newP[c.index];
});
edges.stream().filter((e) -> (e.v0 != null && e.v1 != null)).forEach((e) -> {
e.setVornoi(e.v0, e.v1);
});
} | 4 |
public SMELTGui() {
final JPanel center = new JPanel();
center.setLayout(new GridBagLayout());
final JPanel pinPanel = new JPanel();
pinPanel.setLayout(new BorderLayout());
pinPanel.setBorder(new TitledBorder("Bank pin"));
frame = new JFrame("Tornado's AIO Smelter");
frame.setMinimumSize(new Dimension(400, 250));
frame.getContentPane().setLayout(new BorderLayout());
logo = new JLabel("AIO Smelter");
logo.setHorizontalAlignment(JLabel.CENTER);
logo.setFont(new Font("Calibri", Font.BOLD, 16));
final DefaultComboBoxModel<Bar> modelone = new DefaultComboBoxModel<>();
for(Bar f : Bar.values()) {
modelone.addElement(f);
}
final DefaultComboBoxModel<Location> modeltwo = new DefaultComboBoxModel<>();
for(Location g : Location.values()) {
modeltwo.addElement(g);
}
selection = new JComboBox<>(modelone);
selection.setFont(new Font("Calibri", Font.PLAIN, 13));
location = new JComboBox<>(modeltwo);
location.setFont(new Font("Calibri", Font.PLAIN, 13));
coalbag = new JCheckBox("Coalbag (unsupported)");
coalbag.setFont(new Font("Calibri", Font.PLAIN, 14));
start = new JButton("Start Smelting");
start.setFont(new Font("Calibri", Font.PLAIN, 15));
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
startActionListener(arg0);
}
});
pf = new JPasswordField();
final GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0; c.gridy = 1;
center.add(selection, c);
c.gridx = 1; c.gridy = 1;
center.add(location, c);
c.gridx = 1; c.gridy = 0;
center.add(coalbag, c);
c.gridx = 0; c.gridy = 0;
center.add(pinPanel, c);
pinPanel.add(pf, BorderLayout.SOUTH);
frame.getContentPane().add(logo, BorderLayout.NORTH);
frame.getContentPane().add(center, BorderLayout.CENTER);
frame.getContentPane().add(start, BorderLayout.SOUTH);
frame.pack();
} | 2 |
public void saveInstrument(VInstrument toSave)
{
if (toSave.isBuilt())
{
File target;
JFileChooser fileChosser = new JFileChooser();
int option = fileChosser.showSaveDialog(VMainWindow.window);
switch (option)
{
case JFileChooser.APPROVE_OPTION:
try
{
target = fileChosser.getSelectedFile();
FileOutputStream outputStream = new FileOutputStream(target);
ObjectOutputStream outputObject = new ObjectOutputStream(outputStream);
outputObject.writeObject(toSave);
outputObject.close();
outputStream.close();
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
}
break;
}
}
else
{
JOptionPane.showMessageDialog(VMainWindow.window, "The instrument is not properly built");
}
} | 4 |
public void startElement(String uri, String localName, String name, Attributes attributes)
throws SAXException
{
if (RECORD.equals(name))
{
currentRecord = new QuickBaseRecord();
}
else if (F.equals(name))
{
currentField = new StringBuffer();
currentFieldID = Integer.parseInt(attributes.getValue(ID));
}
else if (ERRCODE.equals(name) || ERRTEXT.equals(name) || ERRDETAIL.equals(name))
{
error = new StringBuffer();
}
else if (currentField != null)
{
// Some <f id="..."> elements may contain additional nested elements such as <url> or
// <BR>; these elements should be incorporated into the field content:
//
appendNestedTagToCurrentField(name, attributes);
}
} | 6 |
void gameLoop(){
if(!running){
clientListen.running = false;
return;
}
game.operateEntities(period);
game.sendData(clientListen.streams, gameTime, clientListen.newPlayer);
clientListen.newPlayer = -1;
gameTime += period;
} | 1 |
private void saveAll()
{
try{
FileOutputStream saveFile = new FileOutputStream("save.sav");
ObjectOutputStream save = new ObjectOutputStream(saveFile);
ArrayList<SaveVariables> lowerVar = new ArrayList<SaveVariables>();
ArrayList<SaveVariables> middleVar = new ArrayList<SaveVariables>();
ArrayList<SaveVariables> invVar = new ArrayList<SaveVariables>();
ArrayList<SaveVariables> enemyVar = new ArrayList<SaveVariables>();
SaveVariables newPlayer = new SaveVariables(player.getCoords().getX(), player.getCoords().getY(), player.getLife());
for (Coords coords: lowerLayers.keySet()) {
SaveVariables newItem = new SaveVariables(coords.getX(), coords.getY(), lowerLayers.get(coords).getType());
lowerVar.add(newItem);
}
for (Coords coords: middleLayers.keySet()) {
SaveVariables newItem = new SaveVariables(coords.getX(), coords.getY(), middleLayers.get(coords).getType());
middleVar.add(newItem);
}
for (Inventory inventory : inventorys) {
SaveVariables newItem = new SaveVariables(inventory.getItemCode(), inventory.getQuantity(), 0);
invVar.add(newItem);
}
for (Coords coords: enemyLayers.keySet()) {
SaveVariables newItem = new SaveVariables(coords.getX(), coords.getY(), enemyLayers.get(coords).type);
enemyVar.add(newItem);
}
save.writeObject(lowerVar);
save.writeObject(middleVar);
save.writeObject(invVar);
save.writeObject(enemyVar);
save.writeObject(newPlayer);
save.writeObject(equipped);
save.writeObject(xLLimit);
save.writeObject(xRLimit);
save.writeObject(yULimit);
save.writeObject(yDLimit);
save.close();
}
catch(Exception ex){
ex.printStackTrace();
}
} | 5 |
@Override
public void run()
{
int numberOfThreads = settings.getInt("threadCount");
threads = new TestCaseThread[numberOfThreads];
for(int i = 0; i <= numberOfThreads - 1; i++)
{
threads[i] = new TestCaseThread(i + 1, testCase.clone(), settings);
threads[i].start();
}
if(settings.getBool("runToTarget"))
{
boolean stillRunning;
while(run)
{
stillRunning = false;
for(int i = 0; i <= numberOfThreads - 1; i++)
{
if(threads[i].isRunning())
{
stillRunning = true;
break;
}
}
if(!stillRunning)
{
for(int i = 0; i <= numberOfThreads - 1; i++)
{
int[] result = threads[i].getResults();
results[0] += result[0];
results[1] += result[1];
results[2] += result[2];
}
if(settings.getBool("verbose"))
{
System.out.println("Simulation results: (" + results[0] + " : " + results[1] + " : " + (double) Math.round((double) results[2]/ (double) (results[0] + results[1]) * 100) / 100 + ")");
}
run = false;
}
}
}
} | 8 |
public void testApp()
{
assertTrue( true );
} | 0 |
public void setCompanyId(long companyId) {
this.companyId = companyId;
} | 0 |
protected Invocable getInvocable(String path, MapleClient c) {
try {
path = "scripts/" + path;
engine = null;
if (c != null) {
engine = c.getScriptEngine(path);
}
if (engine == null) {
File scriptFile = new File(path);
if (!scriptFile.exists())
return null;
engine = sem.getEngineByName("javascript");
if (c != null) {
c.setScriptEngine(path, engine);
}
FileReader fr = new FileReader(scriptFile);
engine.eval(fr);
fr.close();
}
return (Invocable) engine;
} catch (Exception e) {
log.error("Error executing script.", e);
return null;
}
} | 5 |
public void render(int xp, int yp, Sprite sprite){
xp -= xOffset;
yp -= yOffset;
for(int y = 0; y < sprite.getHeight(); y++){
int ya = y + yp; //y absolute position is equal to y + yOffset
int ys = y;
for(int x = 0; x < sprite.getWidth(); x++){
int xa = x + xp;
int xs = x;
if(xa < -(sprite.getWidth()) || xa >= width || ya < 0 || ya >= height) break;
if(xa < 0) xa = 0;
int color = sprite.getPixels()[xs + ys * sprite.getWidth()];
if(color != colorToIgnore && color != colorToIgnore2) pixels[xa + ya * width] = color;
}
}
} | 9 |
protected boolean canSinkFrom(Room fromHere, int direction)
{
if((fromHere==null)||(direction<0)||(direction>=Directions.NUM_DIRECTIONS()))
return false;
final Room toHere=fromHere.getRoomInDir(direction);
if((toHere==null)
||(fromHere.getExitInDir(direction)==null)
||(!fromHere.getExitInDir(direction).isOpen()))
return false;
if((!CMLib.flags().isWaterySurfaceRoom(toHere))&&(!CMLib.flags().isUnderWateryRoom(toHere)))
return false;
return true;
} | 8 |
private boolean jj_3R_48() {
if (jj_3R_60()) return true;
if (jj_scan_token(COLONEQUAL)) return true;
if (jj_3R_49()) return true;
return false;
} | 3 |
@Override
public void build(JSONObject json, FieldsMetadata metadata, IContext context) {
// iterate on all images
Iterator<?> iter = json.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<?,?> entry = (Map.Entry<?,?>)iter.next();
// set the FieldsMetaData
metadata.addFieldAsImage(entry.getKey().toString());
// create the image
IImageProvider img = new FileImageProvider(new File(entry.getValue().toString()));
img.setUseImageSize(true);
// add it to the report's context
context.put(entry.getKey().toString(), img);
}
} | 6 |
public boolean currentlyTransmitting() {
return active;
} | 0 |
public SpriteSheet getSheet(String name){
for(SpriteSheetTicket ticket : this.tickets){
if(ticket.getName().equals(name)){
return ticket.getSheet();
}
}
Debug.error("SpriteSheet not found '" + name + "'");
return null;
} | 2 |
public boolean isAutoscrollOnStatus() {
if(frame == null) buildGUI();
return autoscrollStatus.isSelected();
} | 1 |
public List<Candy> getCandy() {
if (candy == null) {
candy = new ArrayList<Candy>();
}
return this.candy;
} | 1 |
public static void main(String[] args) {
String[] words = {"one","two","three","four","five","six",
"seven","eight","nine","ten","eleven","twelve",
"thirteen","fourteen","fifteen","sixteen","seventeen",
"eighteen", "nineteen", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety", "hundred","thousand"};
int total = 0;
for (int count = 1; count <= 1000; count++) {
String number = "";
if (count <= 20) {
number = words[count-1];
}
else {
String pickNumber = Integer.toString(count);
if (pickNumber.length() == 2) {
number += words[Integer.parseInt(pickNumber.substring(0,1))+17];
if (Integer.parseInt(pickNumber.substring(1)) != 0) {
number += words[Integer.parseInt(pickNumber.substring(1))-1];
}
}
else if (pickNumber.length() == 3) {
number += words[Integer.parseInt(pickNumber.substring(0,1))-1];
number += words[27];
if (!pickNumber.substring(1).equals("00")) {
number += "and";
if (Integer.parseInt(pickNumber.substring(1)) <= 20) {
number += words[Integer.parseInt(pickNumber.substring(1)) -1];
}
else {
number += words[Integer.parseInt(pickNumber.substring(1,2))+17];
if (Integer.parseInt(pickNumber.substring(2)) != 0) {
number += words[Integer.parseInt(pickNumber.substring(2))-1];
}
}
}
}
else {
number += words[0];
number += words[28];
}
}
System.out.println(count + "|" + number);
total += number.length();
}
System.out.println(total);
} | 8 |
public void setAlgorithm(String value) {
this.algorithm = value;
} | 0 |
public Production[] getUnitProductions(Grammar grammar) {
ArrayList list = new ArrayList();
ProductionChecker pc = new ProductionChecker();
Production[] productions = grammar.getProductions();
for (int k = 0; k < productions.length; k++) {
if (ProductionChecker.isUnitProduction(productions[k])) {
list.add(productions[k]);
}
}
return (Production[]) list.toArray(new Production[0]);
} | 2 |
@Override
public void printState() {
for (Field field : this) {
if (field.getPosition() != 0 && field.getPosition() % sizeX == 0) {
System.out.println("");
}
if (field.getPosition() % sizeX == 0 && field instanceof FakeField)
System.out.print(" ");
if (field instanceof FakeField)
System.out.print(field);
else System.out.print("/" + field + "\\");
}
} | 6 |
public boolean find(int key) {
Tree234Node node = root;
while (node != null) {
if (key < node.key1) {
node = node.child1;
} else if (key == node.key1) {
return true;
} else if ((node.keys == 1) || (key < node.key2)) {
node = node.child2;
} else if (key == node.key2) {
return true;
} else if ((node.keys == 2) || (key < node.key3)) {
node = node.child3;
} else if (key == node.key3) {
return true;
} else {
node = node.child4;
}
}
return false;
} | 9 |
public void setTileInstancePropertiesAt(int x, int y, Properties tip) {
if (bounds.contains(x, y)) {
Object key = new Point(x, y);
tileInstanceProperties.put(key, tip);
}
} | 1 |
public static boolean wawD(Instruction i1, Instruction i2)
{
// No dependency on branches or assembly directives
if (i1.instructionType==3 || i1.instruction.equals("NOP")) return false;
if (i2.instructionType==3 || i2.instruction.equals("NOP")) return false;
// Ensure 1 writes after 2 writes
if(!(i2.memoryAddress < i1.memoryAddress)) return false;
// No writing happening
if (i2.instructionType!=0 || i1.instructionType!=0) return false;
if (i1.operands.get(0).equals(i2.operands.get(0)))
{
System.out.println("waw dep- " + i1.instruction + " is dependent on " + i2.instruction);
return true;
}
return false;
} | 8 |
void countCustomers() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
String currentDate = df.format(d);
String sql = "SELECT COUNT(*) FROM Sales WHERE SUBSTR(DateTime, 1, 10) = ?;";
String count = getPersist().read(String.class, sql, currentDate);
lblCustomers.setText(String.format("来客数 %s 人", count));
} | 0 |
public void sort(double[] input) {
int N = input.length;
int h = 1;
while (h < N / 3) {
h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...
}
while (h >= 1) { // h-sort the array.
for (int i = h; i < N; i++) { // Insert a[i] among a[i-h], a[i-2*h], a[i-3*h]... .
for (int j = i; j >= h && Helper.less(input, j, j - h); j -= h) {
Helper.exch(input, j, j - h);
}
}
h = h / 3;
}
} | 5 |
public int Open(String Filename, int NewMode)
{
int retcode = DDC_SUCCESS;
if ( fmode != RFM_UNKNOWN )
{
retcode = Close();
}
if ( retcode == DDC_SUCCESS )
{
switch ( NewMode )
{
case RFM_WRITE:
try
{
file = new RandomAccessFile(Filename,"rw");
try
{
// Write the RIFF header...
// We will have to come back later and patch it!
byte[] br = new byte[8];
br[0] = (byte) ((riff_header.ckID >>> 24) & 0x000000FF);
br[1] = (byte) ((riff_header.ckID >>> 16) & 0x000000FF);
br[2] = (byte) ((riff_header.ckID >>> 8) & 0x000000FF);
br[3] = (byte) (riff_header.ckID & 0x000000FF);
byte br4 = (byte) ((riff_header.ckSize >>> 24)& 0x000000FF);
byte br5 = (byte) ((riff_header.ckSize >>> 16)& 0x000000FF);
byte br6 = (byte) ((riff_header.ckSize >>> 8)& 0x000000FF);
byte br7 = (byte) (riff_header.ckSize & 0x000000FF);
br[4] = br7;
br[5] = br6;
br[6] = br5;
br[7] = br4;
file.write(br,0,8);
fmode = RFM_WRITE;
} catch (IOException ioe)
{
file.close();
fmode = RFM_UNKNOWN;
}
} catch (IOException ioe)
{
fmode = RFM_UNKNOWN;
retcode = DDC_FILE_ERROR;
}
break;
case RFM_READ:
try
{
file = new RandomAccessFile(Filename,"r");
try
{
// Try to read the RIFF header...
byte[] br = new byte[8];
file.read(br,0,8);
fmode = RFM_READ;
riff_header.ckID = ((br[0]<<24)& 0xFF000000) | ((br[1]<<16)&0x00FF0000) | ((br[2]<<8)&0x0000FF00) | (br[3]&0x000000FF);
riff_header.ckSize = ((br[4]<<24)& 0xFF000000) | ((br[5]<<16)&0x00FF0000) | ((br[6]<<8)&0x0000FF00) | (br[7]&0x000000FF);
} catch (IOException ioe)
{
file.close();
fmode = RFM_UNKNOWN;
}
} catch (IOException ioe)
{
fmode = RFM_UNKNOWN;
retcode = DDC_FILE_ERROR;
}
break;
default:
retcode = DDC_INVALID_CALL;
}
}
return retcode;
} | 8 |
String defaultMethod()
{
return "default";
} | 0 |
public static <T> boolean equalDeep(T[] a1, T[] a2) {
if (a1 == null) return a2 == null;
if (a2 == null) return false;
if (a1.length != a2.length) return false;
for (int i = 0; i < a1.length; ++i) if (!Calc.equal(a1[i], a2[i])) return false;
return true;
} | 5 |
public List<Element> getAll() {
return this.elements;
} | 0 |
private void interpretData(String msg) {
Scanner scan = new Scanner(msg);
String firstWord =scan.next();
switch (firstWord){
case nameKey: // Client is alerting server to the name of the character connecting.
String name = scan.next(); // Msg of form: "N [name]" so scan.next is username.
if(gameMaster.getID(name) == -1){
sendData("makeNew"); // code for the applet needs to make a character.
}
setUsername(name);
break;
case createPlayerKey:
String newName = scan.next();
int classCode = scan.nextInt();
uid = gameMaster.addPlayer(newName, classCode);
break;
case moveKey:
movePlayer(scan.nextInt()); // due to "m [directionCode]" form, scan.nextInt() is the direction code to pass.
break;
case combatKey: // could be any of a large number of combat-related commands.
//figure out which command and do it.
// note, that if it's to set the attackTarget, need to make sure that attackTarget is not already at lookup.missCode.
// use gameMaster.combat.METHOD() to do things. that way it remains only one instance of the combatHandler.
break;
}
} | 5 |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
// if(obj instanceof Integer) {
// if(image_id == (int) obj) {
// System.out.println("TSCHAKKA"); // FIXME
// return true;
// }
// }
if (!(obj instanceof Image)) {
return false;
}
Image other = (Image) obj;
if (image_id != other.image_id) {
return false;
}
return true;
} | 4 |
public void setAutostart(Boolean autostart) {
this.autostart = autostart;
} | 0 |
public void commandLine() {
while (true) {
System.out.print(">");
command = userInput.nextLine().split(" ");
//String junk = userInput.next();
if (command[0].equals("addplayer")) {
comAddplayer();
} else if (command[0].equals("removeplayer")) {
comRemoveplayer();
} else if (command[0].equals("editplayer")) {
comEditplayer();
} else if (command[0].equals("resetstats")) {
comResetstats();
} else if (command[0].equals("displayplayer")) {
comDisplayplayer();
} else if (command[0].equals("rankings")) {
comRankings();
} else if (command[0].equals("startgame")) {
comStartgame();
} else if (command[0].equals("exit")) {
comExit();
} else {
System.out.println();
}
}// end loop
}// end method | 9 |
public DataStore setTeachers(ArrayList<Teacher> teachers) {
//System.out.println("DataStore.setTeachers() : " + teachers);
if (teachers != null)
this.teachers = teachers;
else
this.teachers = new ArrayList<Teacher>();
return this;
} | 1 |
public int compareTo(Entry e) {
int i = score - e.getScore();
if(i == 0) return name.compareTo(e.getName());
return i;
} | 1 |
public List<Statement> parse(Map<String, Integer> labels) {
List<Statement> statements = new ArrayList<Statement>();
while (true) {
// Ignore empty lines.
while (match(TokenType.LINE));
if (match(TokenType.LABEL)) {
// Mark the index of the statement after the label.
labels.put(last(1).text, statements.size());
} else if (match(TokenType.WORD, TokenType.EQUALS)) {
String name = last(2).text;
Expression value = expression();
statements.add(new AssignStatement(name, value));
} else if (match("print")) {
statements.add(new PrintStatement(expression()));
} else if (match("input")) {
statements.add(new InputStatement(
consume(TokenType.WORD).text));
} else if (match("goto")) {
statements.add(new GotoStatement(
consume(TokenType.WORD).text));
} else if (match("if")) {
Expression condition = expression();
consume("then");
String label = consume(TokenType.WORD).text;
statements.add(new IfThenStatement(condition, label));
} else break; // Unexpected token (likely EOF), so end.
}
return statements;
} | 8 |
public void actionPerformed(ActionEvent ae)
{
if (mApply.equals(ae.getSource()) || mOK.equals(ae.getSource()))
{
for (int i = 0; i < mPanels.size(); i++)
{
E5OptionPanel panel = (E5OptionPanel) mPanels.elementAt(i);
panel.savePreferences(mPreferences);
}
}
if (mCancel.equals(ae.getSource()) || mOK.equals(ae.getSource()))
{
setVisible(false);
}
} | 5 |
public Gopinich(int room) {
super(new FireBall(), new MeteorStorm(), 65.0*room, 152.0*room, 103.00*room, 2.0*room, 50.0*room, 55.0*room, "Gopinich");
} // End DVC | 0 |
public static void main(String[] args) {
InputStreamReader stdin = new InputStreamReader(System.in);
BufferedReader cache = new BufferedReader(stdin);
System.out.println("Are you new? (yes|no)");
String choice = "";
try {
choice = cache.readLine();
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.exit(-1);
}
choice = choice.toLowerCase();
switch (choice) {
case "yes":
case "y":
System.out.println("What is your name?");
String name = "";
String age = "";
try {
name = cache.readLine();
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.exit(-1);
}
System.out.println("What age?");
try {
age = cache.readLine();
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.exit(-1);
}
int _age_ = Integer.parseInt(age);
Test main = new Test (name, _age_);
main.mainMenu();
break;
case "no":
case "n":
Test mainx = new Test("Nil", 0);
mainx.loadGame();
break;
}
} | 7 |
public void editMeal(long id, String newName, double newCalories, double newProtein) {
SimpleMealDaoImpl dao = getSimpleMealDaoImpl();
Session session = null;
Transaction tx = null;
try {
session = HbUtil.getSession();
//TRANSACTION START
tx = session.beginTransaction();
SimpleMeal mealToEdit = dao.getSimpleMeal(id);
mealToEdit.setName(newName);
mealToEdit.setCalories(newCalories);
mealToEdit.setProtein(newProtein);
tx.commit();
//TRANSACTION END
//SESSION CLOSE
} catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
} | 4 |
public void setElement(int itemId, double rating){
int beginIndex = 0, halfIndex = 0, endIndex = itemIds.length;
if(itemIds.length > 0) {
while(true){
halfIndex = (endIndex - beginIndex) / 2 + beginIndex;
if(itemId < itemIds[halfIndex]){
if(endIndex - beginIndex <= 1){
break;
}
endIndex = halfIndex;
}else if(itemId > itemIds[halfIndex]){
if(endIndex - beginIndex <= 1){
halfIndex++;
break;
}
beginIndex = halfIndex;
}else{
ratings[halfIndex] = rating;
return;
}
}
}
int[] newItemIds = new int[itemIds.length + 1];
double[] newRatings = new double[ratings.length + 1];
System.arraycopy(itemIds, 0, newItemIds, 0, halfIndex);
newItemIds[halfIndex] = itemId;
System.arraycopy(itemIds, halfIndex, newItemIds, halfIndex + 1, itemIds.length - halfIndex);
System.arraycopy(ratings, 0, newRatings, 0, halfIndex);
newRatings[halfIndex] = rating;
System.arraycopy(ratings, halfIndex, newRatings, halfIndex + 1, ratings.length - halfIndex);
itemIds = newItemIds;
ratings = newRatings;
} | 6 |
public static void main(String[] args) {
System.out.println("SERVERDb: main");
ServerDb serverDb;
try {
serverDb = new ServerDb();
args = new String[3];
args[0] = "jdbc:derby://localhost:1527/JHelpDB";
args[1] = "adm";
args[2] = "adm";
if (serverDb.connect(args) != JHelp.READY) {
throw new IOException("Check connection with data base");
}
serverDb.run();
serverDb.disconnect();
} catch (IOException ex) {
System.err.println(ex.getMessage() + "---main1");
} catch (SQLException ex) {
System.err.println(ex.getMessage() + "---main2");
} catch (Exception ex) {
System.err.println(ex.getMessage() + "---main3");
}
} | 4 |
@Override
public AFUNIXSocket accept () throws IOException {
if ( isClosed() )
throw new SocketException("Socket is closed");
AFUNIXSocket as = AFUNIXSocket.newInstance();
this.impl.accept(as.impl);
as.addr = this.boundEndpoint;
NativeUnixSocket.setConnected(as);
return as;
} | 1 |
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
System.out.println(KeyEvent.getKeyText(key));
if (key == KeyEvent.VK_LEFT)
scrollX -= tileSize / 4;
else if (key == KeyEvent.VK_RIGHT)
scrollX += tileSize / 4;
else if (key == KeyEvent.VK_UP)
scrollY -= tileSize / 4;
else if (key == KeyEvent.VK_DOWN)
scrollY += tileSize / 4;
else if (key == KeyEvent.VK_ESCAPE) {
Client.instance.setGuiScreen(new GuiPauseMenu());
firstClick = true;
}
if (scrollX < 0)
scrollX = 0;
if (scrollY < 0)
scrollY = 0;
int mapWidth = mapCache.length;
int mapHeight = mapCache[0].length;
if (scrollX > (int) (mapWidth * tileSize * zoom - width))
scrollX = (int) (mapWidth * tileSize * zoom - width);
if (scrollY > (int) (mapHeight * tileSize * zoom - height))
scrollY = (int) (mapHeight * tileSize * zoom - height);
} | 9 |
public boolean isBot(long userId) {
long currTotal = totalEvents.incrementAndGet();
if (currTotal%10000 == 0) {
System.out.println("Handled " + totalEvents + " requests and curent table entries " + allElements.size());
}
UidBaseElement uide = allElements.get(userId);
if (uide == null) {
createElement(userId);
return false;
}
else {
return uide.occurence();
}
} | 2 |
@Override
protected void handleMessage(Object o) throws Throwable {
if(state != null && state.isDisconnected()) {
agentPrintMessage("Peer disconnected, ignoring message "+o.getClass().getCanonicalName());
return;
}
try {
if(o instanceof UncheckedMnTreeMessage) {
handleUncheckedMnTreeMessage(o);
} else if(o instanceof MnTreeMessage) {
if(state == null) {
waitingState.addLast((MnTreeMessage) o);
return;
}
MnTreeMessage mnm = (MnTreeMessage) o;
MnId dest = mnm.getRecipientMn();
if(dest == null)
throw new Error("Destination MN id not set for message "+mnm.getClass().getName());
if(! dest.equals(state.getThisMnId())) {
agentPrintMessage("Wrongly routed message: "+
o.getClass().getSimpleName());
if(! (mnm instanceof WrongRouteMessage)) {
com.sendDatagramMessage(new WrongRouteMessage(mnm.getSender(), state.getThisMnId(),
mnm.getSenderMn(), mnm));
}
return;
}
handleCheckedMnTreeMessage(o);
} else {
handleEvent(o);
}
} catch (Throwable e) {
agentPrintMessage("Following error occured during message handling:");
agentPrintMessage(e);
agentPrintMessage("Propagating error...");
propagateError(e);
}
} | 9 |
private void btn_aceptarActionPerformed(java.awt.event.ActionEvent evt) {
if (lab_modo.getText().equals("Alta")){
if (camposCompletos()){
if (validarFechas()){
ocultar_Msj();
insertar();
combo_tipo.setEnabled(true);
field_desdee.setEnabled(true);
field_hasta.setEnabled(true);
menuDisponible(true);
modoConsulta();
updateTabla();
}
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
else{
if (lab_modo.getText().equals("Baja")){
if (!field_tasa.getText().equals("")){
if(!existe(Integer.parseInt(lab_ID.getText()))){
mostrar_Msj_Error("Ingrese una cuenta que se encuentre registrada en el sistema");
field_tasa.requestFocus();
}
else{
ocultar_Msj();
eliminar();
menuDisponible(true);
modoConsulta();
vaciarCampos();
updateTabla();
}
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
else{
if (lab_modo.getText().equals("Modificación")){
if (!field_tasa.getText().equals("")){
if (camposCompletos()){
ocultar_Msj();
modificar();
menuDisponible(true);
modoConsulta();
updateTabla();
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
else{
mostrar_Msj_Error("Por favor, complete todos los campos solicitados");
}
}
}
}
} | 9 |
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(args[0]));
String s;
while ((s = br.readLine()) != null) {
String[] a = s.split(",");
List<String> b = new LinkedList<String>();
List<String> c = new LinkedList<String>();
for (int i = 0; i < a.length; i++) {
int t;
try {
t = Integer.parseInt(a[i]);
c.add("" + t);
} catch (Exception e) {
b.add(a[i]);
}
}
for (int i = 0; i < b.size(); i++) {
System.out.print(b.get(i));
if (i < b.size() - 1) {
System.out.print(',');
}
}
if (!b.isEmpty() && !c.isEmpty()) {
System.out.print('|');
}
for (int i = 0; i < c.size(); i++) {
System.out.print(c.get(i));
if (i < c.size() - 1) {
System.out.print(',');
}
}
System.out.println();
}
} | 9 |
public char nextClean() throws JSONException {
for (;;) {
char c = this.next();
if (c == 0 || c > ' ') {
return c;
}
}
} | 3 |
@Override
public void aiStep() {
this.inventory.tick();
this.oBob = this.bob;
this.input.updateMovement();
super.aiStep();
float var1 = MathHelper.sqrt(this.xd * this.xd + this.zd * this.zd);
float var2 = (float)Math.atan((double)(-this.yd * 0.2F)) * 15.0F;
if(var1 > 0.1F) {
var1 = 0.1F;
}
if(!this.onGround || this.health <= 0) {
var1 = 0.0F;
}
if(this.onGround || this.health <= 0) {
var2 = 0.0F;
}
this.bob += (var1 - this.bob) * 0.4F;
this.tilt += (var2 - this.tilt) * 0.8F;
List var3;
if(this.health > 0 && (var3 = this.level.findEntities(this, this.bb.grow(1.0F, 0.0F, 1.0F))) != null) {
for(int var4 = 0; var4 < var3.size(); ++var4) {
((Entity)var3.get(var4)).playerTouch(this);
}
}
} | 8 |
@Override
public final void testAssumptionFailure(final Failure failure) {
super.testAssumptionFailure(failure);
selectListener(failure.getDescription()).testAssumptionFailure(failure);
} | 0 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.