method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
3ffdfdb7-c910-4ba0-970b-4b5660100e98
| 3
|
private Node join(Node leftTree, Node rightTree) {
if (leftTree == null)
return rightTree;
if (rightTree == null)
return leftTree;
if (bernoulli((double) leftTree.count
/ (leftTree.count + rightTree.count))) {
leftTree.right = join(leftTree.right, rightTree);
leftTree.count = 1 + size(leftTree.left) + size(leftTree.right);
return leftTree;
} else {
rightTree.left = join(leftTree, rightTree.left);
rightTree.count = 1 + size(rightTree.left) + size(rightTree.right);
return rightTree;
}
}
|
603513b3-f93b-4949-a6c9-034cccaa5f89
| 7
|
public static List<ClanMember> getAll(String clan) throws IOException {
List<ClanMember> list = new ArrayList<ClanMember>();
HttpURLConnection http = (HttpURLConnection) new URL(clanHome + clan).openConnection();
http.setConnectTimeout(15000);
http.setReadTimeout(30000);
BufferedReader inLines = new BufferedReader(new InputStreamReader(http.getInputStream(), "UTF-8"));
// Need to Open the Clan home to find the number of members before
// running
// Could run the name parser until it errors. This is a better
// solution (I THINK)
int members = -1;
String s = inLines.readLine();
while (s != null) {
if (s.startsWith("<a class=\"clanStats\" id=\"Clanstat_1")) {
// This is the members line.
String beginStr = "<span class=\"clanstatVal FlatHeader\">";
int beginIndex = s.indexOf(beginStr);
int endIndex = s.indexOf("</span>", beginIndex);
s = s.substring(beginIndex + beginStr.length(), endIndex);
members = Integer.parseInt(s.trim());
break;
}
s = inLines.readLine();
}
inLines.close();
if (members == -1) {
return list;
}
for (int i = 1; i <= (members + PER_PAGE - 1) / PER_PAGE; i++) {
// Open a Socket to the Page.
String built = String.format(strFormat, i, clan, PER_PAGE);
http = (HttpURLConnection) new URL(built).openConnection();
http.setConnectTimeout(15000);
http.setReadTimeout(30000);
inLines = new BufferedReader(new InputStreamReader(http.getInputStream(), "UTF-8"));
s = inLines.readLine();
while (s != null) {
if (s.endsWith("<div class=\"membersListRow\">")) {
inLines.readLine(); // dummy read
inLines.readLine(); // dummy read
String name = nameCleanup.matcher(stripTags(inLines.readLine())).replaceAll(" ");
String rank = stripTags(inLines.readLine());
while (!s.contains("totalXP")) {
s = inLines.readLine(); // dummy reads
}
// except the last one, which contains the EXP
String xp = stripTags(s).replace(",", "");
long xpVal = Long.parseLong(xp);
String kills = stripTags(inLines.readLine());
kills = kills.replace(",", "");
int killsVal = Integer.parseInt(kills);
list.add(new ClanMember(name, rank, false, xpVal, killsVal));
}
s = inLines.readLine();
}
inLines.close();
}
return list;
}
|
8ccc2eac-eb2c-4d36-a03b-9203bb5ed53b
| 7
|
public String getRezepteTableau(){
String out = "";
for (int i=0; i< this.getNrRezepte(); i++ ){
Recipe recipe = this.modelData.getRecipes().getRecipe().get(i);
out += "<table border=\"1\" id=\"rezeptTable\" class=\"gridTable\" >\n";
out += "<tr class=\"gridTitleRow\" ><th colspan=\"5\">Rezepte "+(i+1)+"</th></tr>\n";
out += "<tr class=\"gridDataRow\"><td colspan=\"4\" style=\"width: 50%;\">";
out += "<b>ID: </b>"+recipe.getId()+"<br/>";
out += "<b>Name: </b>"+recipe.getName()+"<br/>";
out += "<b>Verkaufspreis: </b>"+recipe.getSalesPrice()+" €<br/>";
out += "<b>Minimale Produktion: </b>"+recipe.getProductionLwb()+" Stck<br/>";
out += "<b>Maximale Produktion: </b>"+recipe.getProductionUpb()+" Stck<br/>";
out += "<b>Beschreibung:</b><br/>"+recipe.getDescription()+"<br/>";
out += "<b>Zutaten:</b>";
out += "</td>\n";
out += "<td valign=\"top\" style=\"width: 50%;\"><b>Anleitung:</b><br/>"+recipe.getInstructions()+"</td></tr>\n";
out += "<tr><td colspan=\"5\">";
out += "<table border=\"0\" style=\"width: 100%; background-color: white;\" class=\"gridTable\" >\n";
out += "<tr><th>Id</th><th>Name</th><th>Menge</th><th>Einheit</th></tr>\n";
for(int j=0; j< this.modelData.getIngredients().getIngredient().size(); j++){
int modelZutatenId = this.modelData.getIngredients().getIngredient().get(j).getId();
for(int k=0;k<this.getNrZutaten(recipe.getId());k++){
int zutatenId = recipe.getRecipeIngredient().get(k).getIngredientId();
if(modelZutatenId == zutatenId){
out += "<tr>";
//out += "<td>"+zutatenId+"</td>";
//out += "<td>"+this.modelData.getIngredients().getIngredient().get(zutatenId).getId()+"</td>";
out += "<td>"+this.modelData.getIngredients().getIngredient().get(j).getId()+"</td>";
//out += "<td>"+this.modelData.getIngredients().getIngredient().get(zutatenId).getName()+"</td>";
out += "<td>"+this.modelData.getIngredients().getIngredient().get(j).getName()+"</td>";
out += "<td>"+recipe.getRecipeIngredient().get(k).getAmount()+"</td>";
//out += "<td>"+this.modelData.getIngredients().getIngredient().get(zutatenId).getUnit()+"</td>";
out += "<td>"+this.modelData.getIngredients().getIngredient().get(j).getUnit()+"</td>";
out += "</tr>\n";
}
}
}
out += "</table></td></tr>";
//out += "<tr>";
if(isWriteableByNutzer()){
out += "<td colspan=\"4\" style=\"text-align: center;\"><a href=\"Controller?action=31_updateRezept&modelId="+this.modelData.getId()+"&rezeptId="+this.modelData.getRecipes().getRecipe().get(i).getId()+"\">bearbeiten</a></td>";
}
else{
out += "<td colspan=\"4\" class=\"inactiveLink\" style=\"text-align: center;\">bearbeiten</td>";
}
if(isWriteableByNutzer()){
out += "<td colspan=\"1\" style=\"text-align: center;\"><a href=\"Controller?action=33_deleteRezept&modelId="+this.modelData.getId()+"&rezeptId="+this.modelData.getRecipes().getRecipe().get(i).getId()+"\">löschen</a></td>";
}
else{
out += "<td colspan=\"1\" class=\"inactiveLink\" style=\"text-align: center;\">löschen</td>";
}
out += "</tr>";
//out += "<tr ><td colspan=\"4\"> </td></tr>";
out += "</table>\n<br />";
}
out += "<table>";
if(isWriteableByNutzer()){
out += "<tr id=\"rezeptTable_addRow\" class=\"gridFooterRow\"><td colspan=\"4\"><a href=\"Controller?action=30_insertRezept&modelId="+this.modelData.getId()+"\" >Rezept hinzufügen</a></td></tr>";
}
else{
out += "<tr id=\"rezeptTable_addRow\" class=\"gridFooterRow inactiveLink\"><td colspan=\"4\">Rezept hinzufügen</td></tr>";
}
out += "</table>";
return out;
}
|
4011091f-e6f4-453e-ba03-1e21cfc68286
| 0
|
public void setCallType(CallType callType) {
this.callType = callType;
}
|
2831efec-7726-4eda-bb9c-9bbcde9411eb
| 1
|
public boolean login(String userID, String password) {
// TODO Auto-generated method stub
if (getFact.login(userID, password)) {
return true;
}
else
return false;
}
|
c765f5f8-5dfe-47db-ac25-0c856ee2db81
| 3
|
public void customMethod() {
String tmp = orgStr;
System.out.println("-----------------custom--------------");
long startDate = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
while (true) {
String splitStr = null;
int j = tmp.indexOf(";");
if (j < 0)
break;
splitStr = tmp.substring(0, 1);
tmp = tmp.substring(j + 1);
}
tmp = orgStr;
}
long endDate = System.currentTimeMillis();
System.out.println("Execution time:" + (endDate - startDate));
System.out.println("------------------------------------");
}
|
b8fb1560-5f58-4aad-9b49-c9ca0c8462d8
| 7
|
protected void noiziseOneSeq(Vector<Event> os, Vector<Event> ns){
int noiseLen=(int)(errorRate*os.size());
if(os.size()-noiseLen<0){
System.out.println("one sequence: os.size()-noiseLen<0");
return;
}
if(noiseLen<=1){
System.out.println("noiseLen<=1");
return;
}
int sIndex=(int)(Math.random()*(os.size()-noiseLen));
if(sIndex==(os.size()-noiseLen)){
sIndex--;
}
int eIndex=sIndex+noiseLen-1;
System.out.println("one sequence noise: "+sIndex+"~"+eIndex);
Vector<Event> temp=new Vector<Event>();
System.out.println("temp len: "+temp.size());
System.out.println("ns len: "+ns.size());
System.out.println("os len: "+os.size());
for(int j=0;j<os.size();j++){
System.out.print(os.get(j).toString());
System.out.print(ns.get(j).toString());
System.out.println("\n");
}
for(int i=sIndex;i<=eIndex;i++){
temp.add(ns.remove(sIndex));
}
for(int i=sIndex;i<=eIndex;i++){
ns.add(i,temp.remove(temp.size()-1));
}
System.out.println("temp len: "+temp.size());
System.out.println("ns len: "+ns.size());
System.out.println("os len: "+os.size());
for(int j=0;j<os.size();j++){
System.out.print(os.get(j).toString());
System.out.print(ns.get(j).toString());
System.out.println("\n");
}
}
|
d174499c-c591-4ac3-a54e-7678900083e8
| 0
|
public int getHeight() {
return height;
}
|
84078c79-2468-4db9-a775-b94135dcfdbe
| 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(teamRankingFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(teamRankingFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(teamRankingFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(teamRankingFrame.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 teamRankingFrame().setVisible(true);
}
});
}
|
b546fc25-6bbe-4f26-9645-cdd23a571822
| 4
|
public void calcFreq()
{
for(int i=0; i<g.getBoard().length; i++)
{
for(int j=0; j<g.getBoard()[0].length; j++)
{
for(int k=0; k<chroms.size(); k++)
{
chroms.get(k).checkChrom(g.getBoard()[i][j]);
}
if(!isInChromList(g.getBoard()[i][j]))
{
chroms.add(new ChromFreq(g.getBoard()[i][j]));
}
}
}
}
|
70d58ea6-625e-40fa-8ec4-4d9529304403
| 9
|
private static int[] getVector() {
boolean numberBegin = false;
boolean addDigit = false;
boolean isDigit;
int numberBeginPos = -1;
int[] vector;
int position = 0;
char eachChar;
String vector1;
String temporary = "";
Scanner input;
input = new Scanner(System.in);
vector = new int[3];
vector1 = input.nextLine();
for (int counter = 0, stringLength = vector1.length(); counter < stringLength; counter++) {
eachChar = vector1.charAt(counter);
isDigit = Character.isDigit(eachChar);
if (isDigit) {
temporary += eachChar;
numberBegin = !(counter == stringLength - 1);
if (numberBegin) {
numberBeginPos = counter;
}
if (!numberBegin) {
addDigit = true;
}
}
if (!isDigit && numberBegin) {
addDigit = true;
numberBegin = false;
}
if (addDigit) {
addDigit = false;
vector[position] = Integer.parseInt(temporary);
if (numberBeginPos > 0 && vector1.charAt(numberBeginPos - 1) == '-') {
vector[position] *= - 1;
System.out.println(vector[position]);
}
position += 1;
temporary = "";
}
}
return vector;
}
|
1daf8bb1-22c8-43fc-b2ac-aabcb2d84a2c
| 3
|
private void dispatcher(Object message) throws UnknownHostException, IOException{
if(message instanceof ReservationRequestMessage){
ReservationRequestMessage request = (ReservationRequestMessage) message;
int seat = request.getSeatReservation();
int line = seat/40;
int column = seat%40;
boolean reserved = controller.reserveSeat(request.getTheaterID(), line, column);
appClientCom.writeObject(new ReservationReplyMessage(request.getTheaterID(),
controller.getTheaterSeats(request.getTheaterID()), reserved));
}else if(message instanceof TheaterSeatsRequestMessage){
TheaterSeatsRequestMessage request = (TheaterSeatsRequestMessage) message;
TheaterSeats seats = controller.getTheaterSeats(request.getTheaterID());
appClientCom.writeObject(new TheaterSeatsReplyMessage(request.getTheaterID(), seats));
}else if(message instanceof TheatersListRequestMessage){
TheatersListRequestMessage request = (TheatersListRequestMessage) message;
LinkedList<Theater> theaters = controller.getAllTheaters(request.getZone());
appClientCom.writeObject(new TheatersListReplyMessage(request.getZone(),theaters));
}
appClientCom.closeConnection();
}
|
1d7a197d-e66f-41c7-a020-b035bcc7c877
| 4
|
public void mouseClicked(MouseEvent e) {
if(e.getX()>380&&e.getY()>100&&e.getX()<380+120&&e.getY()<100+40){
//Start.start();
target=new Target((WIDTH/2-GameBoard.BOARD_WIDTH/2)+Tile.WIDTH,(HEIGHT-GameBoard.BOARD_HEIGHT-100)-200);
board=new GameBoard((WIDTH/2-GameBoard.BOARD_WIDTH/2),HEIGHT-GameBoard.BOARD_HEIGHT-100,target);
}
}
|
c790bddc-aea2-48d9-9547-5fbf341b2175
| 5
|
public SegmentedImage[] track(String folderName, String headerName){
//perform tracking
final File folder = new File(folderName);
File[] folderFiles = folder.listFiles();
FileWrapper[] files = new FileWrapper[folderFiles.length];
SegmentedImage[] segmented = new SegmentedImage[folderFiles.length];
System.out.println("Retrieving files");
for(int i = 0; i < folderFiles.length; i++){
files[i] = new FileWrapper(folderFiles[i], getId(headerName, folderFiles[i].getName()));
}
Arrays.sort(files);
for(int i = 0; i < files.length; i++){
System.out.println("Segmenting " + files[i].getName());
segmented[i] = new SegmentedImage(folderName + "\\" + files[i].getName(), segmentator);
}
for(int i = 0; i < files.length - 1; i++){
System.out.println("Matching " + files[i].getName() + " and " + files[i+1].getName());
if(segmented[i].isValid() && segmented[i+1].isValid()){
match(segmented[i], segmented[i+1]);
}
}
return segmented;
}
|
593d6933-71ac-4d23-b26e-ea643dfda311
| 4
|
public String getLabelText(int pos) {
if (pos < 1)
pos = 1;
int labelPos = 1;
for (Widget i = wdg().child; i != null; i = i.next) {
if (i instanceof Label) {
if (labelPos == pos) {
Label l = (Label) i;
return l.text.text;
}// pos==
else {
labelPos++;
continue;
}// else
}// inst
}
return "";
}
|
14151ea0-0c06-4cc7-8eb8-24ee896d694f
| 1
|
public void addInformations(String[] code)
{
for (int i = 0; i < code.length; i++)
addInformation(code[i]);
updateSize();
notifyZElement();
}
|
6150a816-65ea-4d1f-9c73-12bee5655876
| 8
|
protected int countNeighbours(int col, int row) {
int total = 0;
total = getCell(col-1, row-1) ? total + 1 : total;
total = getCell( col , row-1) ? total + 1 : total;
total = getCell(col+1, row-1) ? total + 1 : total;
total = getCell(col-1, row ) ? total + 1 : total;
total = getCell(col+1, row ) ? total + 1 : total;
total = getCell(col-1, row+1) ? total + 1 : total;
total = getCell( col , row+1) ? total + 1 : total;
total = getCell(col+1, row+1) ? total + 1 : total;
return total;
}
|
4c2ded0f-bdaf-4baa-8609-2155ea1357dc
| 5
|
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Skills)) {
return false;
}
Skills other = (Skills) object;
if ((this.skillsid == null && other.skillsid != null) || (this.skillsid != null && !this.skillsid.equals(other.skillsid))) {
return false;
}
return true;
}
|
e391df2c-ed83-4221-b4eb-afaae60c13d3
| 0
|
public void illusion()
{
}
|
9bef7f3c-4c53-4222-8250-b9a60415921f
| 5
|
private static <L> State resolvePair(StatePair lr, Fst<L> left,
Fst<L> rigth, final Map<StatePair, State> chart, Fst<L> intersection) {
if (chart.containsKey(lr)) {
return chart.get(lr);
} else {
boolean isInit = left.isInitial(lr.fst) && rigth.isInitial(lr.snd);
boolean isAccept = left.isAccept(lr.fst) && rigth.isAccept(lr.snd);
State intersectionState = intersection.addState(
isInit ? StateFlag.INITIAL : null,
isAccept ? StateFlag.ACCEPT : null);
chart.put(lr, intersectionState);
return intersectionState;
}
}
|
1871ef0d-037b-4355-8c1f-2608956f63c4
| 8
|
MethodsStringConverter(Class<T> cls, Method toString, Method fromString, Class<?> effectiveType) {
super(cls, toString);
if (Modifier.isStatic(fromString.getModifiers()) == false) {
throw new IllegalStateException("FromString method must be static: " + fromString);
}
if (fromString.getParameterTypes().length != 1) {
throw new IllegalStateException("FromString method must have one parameter: " + fromString);
}
Class<?> param = fromString.getParameterTypes()[0];
if (param != String.class && param != CharSequence.class) {
throw new IllegalStateException("FromString method must take a String or CharSequence: " + fromString);
}
if (fromString.getReturnType().isAssignableFrom(cls) == false && cls.isAssignableFrom(fromString.getReturnType()) == false) {
throw new IllegalStateException("FromString method must return specified class or a supertype: " + fromString);
}
this.fromString = fromString;
this.effectiveType = effectiveType;
}
|
e19a29e0-cc8a-44ca-82fd-9d528b3b5bb1
| 9
|
private static boolean validateRegion(Region r, Method subCmd){
int maxHeight = -1,
maxLength = -1,
maxWidth = -1,
minHeight = 1,
minWidth = 5,
minLength = 5;
if(subCmd.isAnnotationPresent(SizeValidation.class)){
SizeValidation sizev = subCmd.getAnnotation(SizeValidation.class);
maxHeight = sizev.maxHeight();
maxLength = sizev.maxLength();
maxWidth = sizev.maxWidth();
minHeight = sizev.minHeight();
minWidth = sizev.minWidth();
minLength = sizev.minLength();
}
return !(
(r.getWidth() < minWidth) ||
(r.getHeight() < minHeight) ||
(r.getLength() < minLength) ||
(maxWidth < 0 ? false : r.getWidth() > maxWidth) ||
(maxHeight < 0 ? false : r.getHeight() > maxHeight) ||
(maxLength < 0 ? false : r.getLength() > maxLength));
}
|
a89ab84c-f25c-4374-9e80-74bef802c7c2
| 1
|
private static boolean validVariable(String s) {
return (s.charAt(0) == '<') && (s.charAt(s.length() - 1) == '>');
}
|
12df6eea-89e2-45df-ba0c-007f8c9f34e8
| 5
|
public void takeDamage(float damage) {
if (basis.destroyed()) return ;
if (damage < 0) I.complain("NEGATIVE DAMAGE!") ;
adjustRepair(0 - damage) ;
final float burnChance = damage * (1 - repairLevel()) / maxIntegrity() ;
if (flammable() && Rand.num() < burnChance) burning = true ;
if (integrity <= 0) basis.onDestruction() ;
}
|
b7454c63-c288-4a39-9f16-1afb09cbb1db
| 9
|
private void jButton_AddAccountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AddAccountActionPerformed
String nymID = "ALL";
String assetID = "ALL";
String serverID = "ALL";
if (nymMap != null && nymMap.size() > 0 && jComboBox_Nyms.getSelectedIndex() > 0) {
nymID = ((String[]) nymMap.get((Integer) jComboBox_Nyms.getSelectedIndex() - 1))[1];
}
if (assetMap != null && assetMap.size() > 0 && jComboBox_AssetContracts.getSelectedIndex() > 0) {
assetID = ((String[]) assetMap.get((Integer) jComboBox_AssetContracts.getSelectedIndex() - 1))[1];
}
if (serverMap != null && serverMap.size() > 0 && jComboBoxServerContracts.getSelectedIndex() > 0) {
serverID = ((String[]) serverMap.get((Integer) jComboBoxServerContracts.getSelectedIndex() - 1))[1];
}
new AccountAdditionDialog(this, true, nymID, assetID, serverID, "OT", (String) jTable_AccountTable.getModel().getValueAt(jTable_AccountTable.getSelectedRow(), 3)).setVisible(true);
System.out.print("assetID:" + assetID);
System.out.print("serverID:" + serverID);
System.out.print("nymiiidL:" + nymID);
}
|
0b5a5139-1fc9-41cd-8898-b6cf6ebf9186
| 2
|
public void exchange (pgrid.service.corba.CorbaRoutingTable routingTable)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("exchange", true);
pgrid.service.corba.CorbaRoutingTableHelper.write ($out, routingTable);
$in = _invoke ($out);
return;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
exchange (routingTable );
} finally {
_releaseReply ($in);
}
} // exchange
|
3adc797c-3f6d-417e-b27e-8e33f62c3ed7
| 8
|
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
Hotel hotel = new Hotel(4);
boolean einde = false;
int invoer;
do {
System.out.println("Menu: [1] Status Overzicht");
System.out.println(" [2] Check-in");
System.out.println(" [3] Check-out");
System.out.println(" [4] Einde");
System.out.print("Uw invoer: ");
if(scanner.hasNextInt()) {
invoer = scanner.nextInt();
if(invoer < 1 || invoer > 4) {
System.out.println("Ongeldige invoer!\n");
} else if(invoer == 1) {
hotel.overzicht();
} else if(invoer == 2) {
hotel.checkin();
} else if(invoer == 3) {
hotel.checkout();
} else if(invoer == 4) {
einde = true;
}
} else {
System.out.println("Ongeldige invoer!\n");
scanner.next();
}
} while(einde == false);
}
|
493568f8-bb06-40e0-b0a4-3cbc04180630
| 4
|
public static void main(String[] args) {
Map<String, ArrayList<Integer>> map = new LinkedHashMap<String, ArrayList<Integer>>();
List<String> words = new LinkedList<String>();
words.addAll(new TextFile(
"holding_your_objects/ex16/SetOperations.jav", "\\W+"));
System.out.println("Words in file: " + words);
int count = 0;
Iterator<String> itWords = words.iterator();
while(itWords.hasNext()) {
String s = itWords.next();
++count;
if(!map.keySet().contains(s)) {
ArrayList<Integer> ai = new ArrayList<Integer>();
ai.add(0, count);
map.put(s, ai);
} else {
map.get(s).add(count);
}
}
System.out.println("\nMap of word locations: " + map);
// New Map to hold sorted words, keyed by location:
Map<Integer, String> replay = new TreeMap<Integer, String>();
Iterator<Map.Entry<String, ArrayList<Integer>>> it = map.entrySet()
.iterator();
while(it.hasNext()) {
Map.Entry<String, ArrayList<Integer>> me = it.next();
for(int i = 0; i < me.getValue().size(); i++) {
replay.put(me.getValue().get(i), me.getKey());
}
}
System.out.println("\nTreeMap of ordered locations, words: " + replay);
// Display words in order as TreeMap values():
System.out.println("\nWords in original order: " + replay.values());
}
|
57502912-7ea9-49c7-96eb-597981b3bce5
| 4
|
int getB(String s1, String s2) {
int b = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (i == j) { // this situation has handled by getA.
continue;
}
if (s1.charAt(i) == s2.charAt(j)) { // if their digit matched, but their position must be different.
b++;
}
}
}
return b;
}
|
5b0b789b-60aa-401e-9ef0-2095ae8f2dce
| 2
|
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//InnerDrawPanel panel = new InnerDrawPanel();
MyDrawPanel panel = new MyDrawPanel();
frame.getContentPane().add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
for (int i = 0; i < 130; i++) {
panel.setX(panel.getX()+1);
panel.setY(panel.getY()+1);
panel.repaint();
try {
Thread.sleep(50);
} catch(Exception ex) {
System.out.println("Something's Wrong");
}
}
}
|
9168512e-ed28-47e6-bd1b-3af6dc0ff8fd
| 3
|
public void restartAt(int imPosn)
/*
* Start showing the images again, starting with image number imPosn. This
* requires a resetting of the animation time as well.
*/
{
if (numImages != 0) {
if ((imPosn < 0) || (imPosn > numImages - 1)) {
System.out.println("Out of range restart, starting at 0");
imPosn = 0;
}
imPosition = imPosn;
// calculate a suitable animation time
animTotalTime = (long) imPosition * showPeriod;
ticksIgnored = false;
}
} // end of restartAt()
|
4992c5b8-f3e9-46e3-af98-386fcc37a310
| 9
|
private void iniciar() {
fachada.criarJogo();
validadorJogarParar = fachada.gerarValidadorJogarParar();
validadorSimNao = fachada.gerarValidadorSimNao();
gerenciadorRecorde = new GerenciadorRecordeImpl();
boolean continuar = true;
while (continuar) {
imprimirPlacares();
String opcao = imprimirOpcoes();
if (opcao.equalsIgnoreCase("J")) {
fachada.jogar();
if (fachada.isPig()) {
System.out.println();
System.out.println("PIG!");
} else if (fachada.getPlacarGeral() + fachada.getPlacarRodada() >= PONTUACAO_MAXIMA) {
fachada.getJogo().setPlacarGeral(
fachada.getPlacarGeral()
+ fachada.getPlacarRodada());
System.out.println();
System.out.println("Valor Dado: "
+ fachada.getValoresJogada());
imprimirPlacares();
boolean isRecord = gerenciadorRecorde
.verificaRecorde(fachada.getNumeroJogadas());
System.out.println("Parabéns! Você chegou aos "
+ fachada.getPlacarGeral() + " pontos em "
+ fachada.getNumeroJogadas()
+ " jogadas.\nRecorde: "
+ gerenciadorRecorde.getRecorde() + " jogadas");
if (isRecord) {
System.out.println("Você bateu um novo recorde!");
}
String jogarMaisUma = jogarMaisUma();
if (jogarMaisUma.equals("S")) {
fachada.criarJogo();
} else if (jogarMaisUma.equals("N")) {
continuar = false;
}
} else {
System.out.println();
System.out.println("Valor Dado: "
+ fachada.getValoresJogada());
}
} else if (opcao.equalsIgnoreCase("P")) {
fachada.parar();
} else if (opcao.equalsIgnoreCase("S")) {
continuar = false;
}
}
}
|
9fc08ebc-d124-49fb-9930-b6ce8ee417e1
| 3
|
private void writeInterface() {
write( "public interface " + daoName + " { \n\n" );
write( TAB + "public int create( " + table.getDomName() );
write( " value ) throws DaoException;\n\n" );
write( TAB + "public int update( " + table.getDomName() );
write( " value ) throws DaoException;\n\n" );
String param = "";
for(Column col : keyColumns){
param += "@Param( \"" + col.getFldName() + "\" ) " + col.getFldType() + " " + col.getFldName() + ", ";
}
param = param.substring( 0, param.length() - 2 );
write( TAB + "public int delete( " + param + " ) throws DaoException;\n\n" );
write( TAB + "public " + table.getDomName() + " read( " + param + " ) throws DaoException;\n\n" );
for ( IndexNode node : table.getIndexList() ) {
String methodName = "readByIndex" + toTitleCase( node.getIndexName());
param = "";
for(Column col : node.getColumnList()){
param += "@Param( \"" + col.getFldName() + "\" ) " + col.getFldType() + " " + col.getFldName() + ", ";
}
param = param.substring( 0, param.length() - 2 );
write( TAB + "public " + table.getDomName() + " " + methodName + "( " + param + " ) throws DaoException;\n\n" );
}
}
|
6ac00bfd-8db7-4d1e-8403-738a947fca6b
| 4
|
private int partIt(int[] a,int left, int right, int pivot){
int leftPtr = left;
int rightPtr = right - 1;
while(true){
while(a[++leftPtr] < pivot);
while(a[--rightPtr] > pivot);
if(leftPtr >= rightPtr)
break;
else
swap(a, leftPtr, rightPtr);
}
swap(a, leftPtr, right-1);
return leftPtr;
}
|
01455a51-9c60-431c-80fc-d441cc4447da
| 7
|
public int strToInt(String s) {
boolean minus = false;
char[] chars = s.toCharArray();
if (chars[0] == '-') {
chars = ArrayUtils.subArray(chars, 1);
minus = true;
}
else if (chars[0] == '+') {
chars = ArrayUtils.subArray(chars, 1);
}
long result = 0;
for(char c : chars) {
if (c > '0' && c < '9') {
result = 10 * result + c - '0';
}
else {
throw new RuntimeException();
}
}
if (result > Integer.MAX_VALUE) {
throw new RuntimeException();
}
if (minus) {
result *= -1;
}
return (int) result;
}
|
7c11055a-a15d-49fa-af07-45f951378283
| 5
|
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof City)) {
return false;
}
City other = (City) object;
if ((this.cityID == null && other.cityID != null) || (this.cityID != null && !this.cityID.equals(other.cityID))) {
return false;
}
return true;
}
|
4662d6cf-fe44-4bb2-a8a3-2659c6731d2f
| 0
|
@Override
public void setQuestAnswer(ArrayList<String> answ) {
}
|
77e110df-5d40-40ac-aeb5-189c261e7ab3
| 6
|
void addLine(String line) {
if (curr > 0 || line != null) {
if (line == null) {
line = "";
}
if (curr >= height && height != -1) {
if (!line.isEmpty()) {
write("\f" + line);
curr = 0;
}
} else {
write(line);
curr += 1;
}
}
}
|
06754ddb-93a1-4f82-860f-79ba1b5a0a15
| 1
|
@Override
public void setX(double x){
for (KentallaOlija osa : osat){
osa.setX(x);
}
}
|
5901441d-0b29-4acd-b86a-8c968db91a02
| 2
|
public static String[] removeEmptyStrings(String[] data) {
ArrayList<String> result = new ArrayList<String>();
for (int k = 0; k < data.length; k++)
if (!data[k].equals(""))
result.add(data[k]);
String[] res = new String[result.size()];
result.toArray(res);
return res;
}
|
7437f1c5-9354-4886-b93a-c7c4996cfeb7
| 8
|
public boolean isPalindrome(String s) {
//if null, false
if (s == null) {
return false;
}
//if empty, ture
if (s.length() == 0) {
return true;
}
//make all in lower string in order to compare
s = s.toLowerCase();
int left = 0;
int right = s.length() - 1;
// Skip all invalid character
while (left < right) {
while (left < right && !isValid(s.charAt(left))) {
left++;
}
while (left < right && !isValid(s.charAt(right))) {
right--;
}
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
|
b03b743e-280c-49a6-9092-6759781c14cd
| 9
|
public static int jauStarpv(double ra, double dec,
double pmr, double pmd, double px, double rv,
double pv[][])
{
/* Smallest allowed parallax */
final double PXMIN = 1e-7;
/* Largest allowed speed (fraction of c) */
final double VMAX = 0.5;
/* Maximum number of iterations for relativistic solution */
final int IMAX = 100;
int i, iwarn;
double w, r, rd, rad, decd, v, x[] = new double[3], usr[] = new double[3], ust[] = new double[3],
vsr, vst, betst, betsr, bett, betr,
dd, ddel, ur[] = new double[3], ut[] = new double[3],
d = 0.0, del = 0.0, /* to prevent */
odd = 0.0, oddel = 0.0, /* compiler */
od = 0.0, odel = 0.0; /* warnings */
/* Distance (AU). */
if (px >= PXMIN) {
w = px;
iwarn = 0;
} else {
w = PXMIN;
iwarn = 1;
}
r = DR2AS / w;
/* Radial velocity (AU/day). */
rd = DAYSEC * rv * 1e3 / DAU;
/* Proper motion (radian/day). */
rad = pmr / DJY;
decd = pmd / DJY;
/* To pv-vector (AU,AU/day). */
double[][] pvt = jauS2pv(ra, dec, r, rad, decd, rd);
jauCpv(pvt,pv);
/* If excessive velocity, arbitrarily set it to zero. */
v = jauPm(pv[1]);
if (v / DC > VMAX) {
jauZp(pv[1]);
iwarn += 2;
}
/* Isolate the radial component of the velocity (AU/day). */
NormalizedVector nv = jauPn(pv[0]);
w = nv.r;
x = nv.u;
vsr = jauPdp(x, pv[1]);
usr = jauSxp(vsr,x);
/* Isolate the transverse component of the velocity (AU/day). */
ust = jauPmp(pv[1], usr);
vst = jauPm(ust);
/* Special-relativity dimensionless parameters. */
betsr = vsr / DC;
betst = vst / DC;
/* Determine the inertial-to-observed relativistic correction terms. */
bett = betst;
betr = betsr;
for (i = 0; i < IMAX; i++) {
d = 1.0 + betr;
del = sqrt(1.0 - betr*betr - bett*bett) - 1.0;
betr = d * betsr + del;
bett = d * betst;
if (i > 0) {
dd = abs(d - od);
ddel = abs(del - odel);
if ((i > 1) && (dd >= odd) && (ddel >= oddel)) break;
odd = dd;
oddel = ddel;
}
od = d;
odel = del;
}
if (i >= IMAX) iwarn += 4;
/* Replace observed radial velocity with inertial value. */
w = (betsr != 0.0) ? d + del / betsr : 1.0;
ur = jauSxp(w,usr);
/* Replace observed tangential velocity with inertial value. */
ut = jauSxp(d,ust);
/* Combine the two to obtain the inertial space velocity. */
pv[1] = jauPpp(ur, ut);
/* Return the status. */
return iwarn;
}
|
b8835d8e-9833-49f3-a1cd-fcb6cde121cc
| 3
|
public static int getMinimapTextureColor(int texture) {
if (Rasterizer.averageTextureColors[texture] != 0) {
return Rasterizer.averageTextureColors[texture];
}
int red = 0;
int green = 0;
int blue = 0;
int count = Rasterizer.texturePixels[texture].length;
for (int i = 0; i < count; i++) {
red += Rasterizer.texturePixels[texture][i] >> 16 & 0xff;
green += Rasterizer.texturePixels[texture][i] >> 8 & 0xff;
blue += Rasterizer.texturePixels[texture][i] & 0xff;
}
int average = (red / count << 16) + (green / count << 8) + blue / count;
average = Rasterizer.adjustBrightness(average, 1.3999999999999999D);
if (average == 0) {
average = 1;
}
Rasterizer.averageTextureColors[texture] = average;
return average;
}
|
91c47f5b-874d-4318-8239-077914ebb526
| 4
|
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
long id = Long.parseLong(request.getParameter("id"));
PublishedSwarmDetails swarmDetails = CommunityDAO.get().getSwarmDetails(id);
if( System.getProperty(EmbeddedServer.Setting.DONT_DISPLAY_PREVIEWS.getKey())
.equals(Boolean.TRUE.toString()) ) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
if( swarmDetails == null ) {
logger.warning("Swarm details are null for id: " + id);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
response.setContentType("image/png");
response.getOutputStream().write(swarmDetails.getPreviewPNG());
} catch( NumberFormatException e ) {
logger.warning("Problem during preview generation: " + e.toString());
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
} catch (IOException e) {
logger.warning("Problem during preview generation: " + e.toString());
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
|
253e3278-2cb1-4ab2-94ae-9c32d6686c58
| 1
|
public void requestUpdate(){
for(ModelChangeListener mcl : listeners){
mcl.changedStatus(serv_enabled,client_connected);
mcl.changedClientIP(client_ip);
mcl.changedServerIP(server_ip);
mcl.changedQLFiles(quick_launch_files);
mcl.changedServerName(serv_name);
mcl.changedServerPswd(psw_enable);
mcl.changedBroadcast(bcast_enabled);
}
}
|
5c8c86c9-0005-4168-ba8c-bd2b06f7ef3f
| 2
|
public int read(CharBuffer cb) {
if (count-- == 0)
return -1; // Indicates end of input
cb.append(capitals[rand.nextInt(capitals.length)]);
for (int i = 0; i < 4; i++) {
cb.append(vowels[rand.nextInt(vowels.length)]);
cb.append(lowers[rand.nextInt(lowers.length)]);
}
cb.append(" ");
return 10; // Number of characters appended
}
|
51727e5f-6752-4577-a446-408d5c754b58
| 3
|
protected void Update(double timeDelta)
{
super.Update(timeDelta);
if (IsKeyTriggered(KeyEvent.VK_F1))
ToggleDebugMode();
for (PhysicsObject obj : m_physicsOnlyObjects)
obj.Update(timeDelta);
for (GameObject obj : m_objects)
obj.Update(timeDelta);
}
|
7bd8582e-58ba-47a9-80d9-301c69f0abe8
| 4
|
public void zoneEventOccurred(String eventZone, int eventType) {
if((eventType == ZoneEvents.MOVEMENT || eventType == ZoneEvents.ENTER )
&& eventZone.equals("normalMouse")){
Gui.changeCursor(Cursor.DEFAULT_CURSOR);
}
if(Debug.gui)
System.out.println("MOUSE EVENT "+eventType);
}
|
b81df51a-3c37-493c-82f2-c180b2145195
| 4
|
private void sort_cmp_time() {
cmp_num = 0;
Iterator<String> iter = cmp_timemap.keySet().iterator();
while(iter.hasNext()) {
String ss = iter.next();
cmp_timekey[cmp_num] = ss;
cmp_num++;
}
//冒泡
for(int i=0; i<cmp_num-1; i++)
{
for(int j=0; j<cmp_num-i-1; j++)
{
int j0 = Integer.parseInt(cmp_timekey[j]);
int j1 = Integer.parseInt(cmp_timekey[j+1]);
if(j0 > j1)
{
String tmp;
tmp = cmp_timekey[j]; cmp_timekey[j] = cmp_timekey[j+1]; cmp_timekey[j+1] = tmp;
}
}
}
}
|
381ffbc9-eff3-4af0-a234-95cef37b95b3
| 3
|
public static void main (String [] args){
Logger logger = Logger.getLogger("Main");
//if args < 0, no string was introduced so program finishes.
if (args.length > 0){
logger.info("Making query request...");
JSONReader jr = new JSONReader (APIURL + args[0]);
String content = jr.read();
if(!content.equals("[]") && !content.equals("")){
logger.info("Formating data...");
JSONFormatter jf = new JSONFormatter ();
String fData = jf.format(content, fields);
logger.info("Saving data to file...");
CSVWriter tw = new CSVWriter (args[0]);
tw.save(fData);
logger.info("Program finished without errors.");
}
else{
logger.warn("No data to save.");
}
}else
logger.error("ERROR: No input string.");
}
|
45a3b143-3f73-4b3a-b15d-d228ac4c50e4
| 7
|
public DeleteList(Brain brain, int cbb) {
b = brain;
comboBoxIndex = cbb;
setBounds(100, 100, 450, 300);
//getContentPane().setLayout(new BorderLayout(0, 0));
getContentPane().setLayout(null);
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel);
contentPanel.setLayout(null);
final String today = new SimpleDateFormat("dd/MM/yyyy").format(Calendar.getInstance().getTime());
if (b == null) {
System.err.println("brain null popup");
} else
if (b.fullmap.get(comboBoxIndex) == null) {
System.err.println("no categ popup");
}
if(!b.fullmap.get(comboBoxIndex).getSecond().containsKey(today)) {
System.err.println("No products today");
}
String names[] = new String[b.fullmap.get(comboBoxIndex).getSecond().get(today).size()];
int counter = 0;
for(Product itr : b.fullmap.get(comboBoxIndex).getSecond().get(today)) {
names[counter++] = itr.getName();
};
DefaultListModel model = new DefaultListModel();
//list = new JList(names)
for(String name : names) {
model.addElement(name);
}
list = new JList(model);
list.setVisibleRowCount(3);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setLocation(0, 0);
scrollPane.setSize(229, 147);
getContentPane().add(scrollPane);
JButton btnDeleteIt = new JButton("Delete it");
btnDeleteIt.setBounds(225, 219, 117, 25);
getContentPane().add(btnDeleteIt);
btnDeleteIt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
for(Product itr : b.fullmap.get(comboBoxIndex).getSecond().get(today)) {
if(list.getSelectedValue().equals(itr.getName())) {
b.delProduct(itr);
break;
}
}
}
});
}
|
47c35a0a-080e-4eee-a30e-18a771c2ffaf
| 2
|
public void SetQuery(String Query)
{
if (ClassQuery != null)
{
try
{
Statement = this.Connection.createStatement();
}
catch(SQLException Ex)
{
Grizzly.WriteOut(Ex.getMessage());
}
}
ClassQuery = Query;
}
|
5f40764b-6891-4648-83fb-78f22a34d253
| 1
|
public static void init() {
int customerIndex = 0;
for (int bal=-1000; bal <= 1000; bal+=50) {
BankAccount newAccount =
new BankAccount(customerIds[customerIndex], BigInteger.valueOf(bal), BigInteger.valueOf(-2000));
customerIndex = (customerIndex+1)%customerIds.length;
christmasBank.addAccount(newAccount);
}
}
|
a7606f02-7852-4ef2-9b75-72d0de83f1ca
| 0
|
public Praticien() {
}
|
e9cbf773-ca91-441d-9c05-34eaefb3f062
| 4
|
@Override
public void run() {
String nMsg = "";
try {
HttpURLConnection urlConnection = (HttpURLConnection) pageURL.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
Reader r = new InputStreamReader(in);
int c;
String all = "";
while ((c = r.read()) != -1) {
String u = String.valueOf((char) c);
all += u;
}
String d = Character.toString('"');
all = "okij.in/" +all.split(d)[7];
nMsg = nMsg + all;
in.close();
r.close();
urlConnection.disconnect();
} catch (Exception e) {
return;
}
{
String msg = "";
for (String x : msga) {
if (x.equalsIgnoreCase(oldURL)) {
x = nMsg;
}
msg += x +" ";
}
player.chat(msg);
}
}
|
38c7ff62-a925-4b17-be91-efa347dfe89f
| 2
|
public void waitForNextFrame() {
long waitTime = frameTime - (System.currentTimeMillis() - lastTime);
if (waitTime > 0) {
try {
Thread.sleep(waitTime);
} catch (InterruptedException ex) {
Logger.getLogger(GameTimer.class.getName()).log(Level.SEVERE, null, ex);
}
}
lastTime = System.currentTimeMillis();
}
|
b623b4ef-7d5d-4961-8dd8-366d9f6dff4d
| 2
|
public void readFileIntoMemory(String fileName) throws IOException {
File file = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
int curVertex = 0;
int neighborVertex = 0;
int edgeToNeighbor = 1;
while (line != null) {
String[] vertexRow = line.split("\t");
HashMap<Integer, Integer> neighborCount = new HashMap<Integer, Integer>();
curVertex = Integer.parseInt(vertexRow[0]);
for (int i = 1; i < vertexRow.length; i++) {
neighborVertex = Integer.parseInt(vertexRow[i]);
neighborCount.put(neighborVertex, edgeToNeighbor);
}
graphMatrix.put(curVertex, neighborCount);
line = br.readLine();
}
br.close();
}
|
160a953c-d0e8-4b51-95d1-090503f5a82d
| 2
|
public ArrayList<ProfesorBean> getPage(int intRegsPerPag, int intPage, ArrayList<FilterBean> alFilter, HashMap<String, String> hmOrder) throws Exception {
ArrayList<Integer> arrId;
ArrayList<ProfesorBean> arrAlumno = new ArrayList<>();
try {
oMysql.conexion(enumTipoConexion);
arrId = oMysql.getPage("profesor", intRegsPerPag, intPage, alFilter, hmOrder);
Iterator<Integer> iterador = arrId.listIterator();
while (iterador.hasNext()) {
ProfesorBean oProfesorBean = new ProfesorBean(iterador.next());
arrAlumno.add(this.get(oProfesorBean));
}
oMysql.desconexion();
return arrAlumno;
} catch (Exception e) {
throw new Exception("ProfesorDao.getPage: Error: " + e.getMessage());
} finally {
oMysql.desconexion();
}
}
|
13aa21c7-13cd-4f25-9f55-7eff7665152d
| 5
|
public boolean containsAnyASection(int min, int max) {
Set<ASection> s = aDataMap.keySet();
Iterator<ASection> it = s.iterator ();
boolean found = false;
while(it.hasNext()){
ASection sect = it.next();
if ((sect.getStartOffset()> min &&
sect.getStartOffset()<= max) ||
(sect.getEndOffset()> min &&
sect.getEndOffset()<= max)
){
found = true;}
}
return found;
}
|
638fe884-518e-4bb4-aada-736e8c332201
| 3
|
public static double erf(double x) {
double erf = 0.0D;
if (x != 0.0) {
if (x == 1.0D / 0.0D) {
erf = 1.0D;
} else {
if (x >= 0) {
erf = Stat.incompleteGamma(0.5, x * x);
} else {
erf = -Stat.incompleteGamma(0.5, x * x);
}
}
}
return erf;
}
|
f286a448-a88c-480d-8bdc-42b10dc45b6e
| 7
|
private void tradeMatcher() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
long begin = System.currentTimeMillis();
//TODO: It should not be stopped.
while ((System.currentTimeMillis() - begin) < 1000){
try{
offersLock.lock();
bidsLock.lock();
//TODO: Performace would be really bad. O(N2) should turn into O(N)
for (int i=0; i<offers.size(); i++){
Offer offer = offers.get(i);
for(int j=0; j<bids.size();j++){
Bid bid = bids.get(j);
if(matches(bid, offer)){
Trade trade = createTrade(bid, offer);
deleteBidAndOffer(bid, offer);
// TODO: Should be removed and matchedTrades be used
System.out.println("Seller " + trade.getSeller().getName() + " Buyer " + trade.getBuyer().getName() + " Stock " +
trade.getStock().getCode() + " Price " + trade.getPrice() + " Buyer Price " + bid.getPrice() + " at " + trade.getTradeDate());
}
}
}
} finally {
offersLock.unlock();
bidsLock.unlock();
}
}
}
});
thread.start();
try {
thread.join();
System.out.println("Offers size " + offers.size()) ;
System.out.println("Bids size " + bids.size());
//TODO: Replace by a logic to keep data in DB
for(Offer offer: offers){
System.out.println("Offer is Seller " + offer.getSeller().getName() + " Price " + offer.getPrice() + " Stock " + offer.getStock().getCode());
}
for(Bid bid: bids){
System.out.println("Bid is Buyer " + bid.getBuyer().getName() + " Price " + bid.getPrice() + " Stock " + bid.getStock().getCode());
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
|
bb7ecd41-9cea-479a-a552-55b297b57aa2
| 7
|
public static ShortImageBuffer norm(ShortImageBuffer input)
{
ShortImageBuffer after = input.copyShape();
// calculate min and max
int min = 0xFFFF;
int max = 0;
for(int y=0;y<input.getHeight();y++)
{
for(int x=0;x<input.getWidth();x++)
{
int v = input.get(y, x) & 0xFFFF;
min = (v < min) ? v : min;
max = (v > max) ? v : max;
}
}
// apply normalisation function to scale all values
int diff = (max-min);
if (diff > 0)
{
float scale = ((float) 0xFF) / diff;
for (int y = 0; y < input.getHeight(); y++)
{
for (int x = 0; x < input.getWidth(); x++)
{
int v = input.get(y, x) & 0xFFFF;
after.set(y, x, (short)((int)((v - min) * scale) & 0xFF));
}
}
}
return after;
}
|
85d33272-31a0-4c43-a34e-d6242f5bc31a
| 1
|
public static void asm_movf(Integer befehl, Prozessor cpu) {
Integer w = cpu.getW();
Integer f = getOpcodeFromToBit(befehl, 0, 6);
Integer result = cpu.getSpeicherzellenWert(f);
if(getOpcodeFromToBit(befehl, 7, 7) == 1) {
cpu.setSpeicherzellenWert(f, result, true);
}
else {
cpu.setW(result, true);
}
cpu.incPC();
}
|
a8daeff2-bf2a-48f5-9e53-710819bc10c5
| 6
|
public void snpEffect(String vcfFile, String txtFile, String aaHgsv, String genotype) {
// Create command
String argsVcf[] = { "-classic", "-cancer", "-hgvs", "testHg3766Chr1", vcfFile };
String argsTxt[] = { "-classic", "-cancer", "-cancerSamples", txtFile, "-hgvs", "testHg3766Chr1", vcfFile };
String args[] = (txtFile == null ? argsVcf : argsTxt);
SnpEff cmd = new SnpEff(args);
SnpEffCmdEff cmdEff = (SnpEffCmdEff) cmd.snpEffCmd();
// Run command
List<VcfEntry> list = cmdEff.run(true);
// Find AA change for a genotype
boolean found = false;
for (VcfEntry vcfEntry : list) {
for (VcfEffect eff : vcfEntry.parseEffects()) {
if (genotype.equals(eff.getGenotype())) {
if (debug) Gpr.debug("AA: " + eff.getAa() + "\t" + eff.getGenotype() + "\t" + eff);
Assert.assertEquals(aaHgsv, eff.getAa());
found = true;
}
}
}
// Not found? Error
if (!found) throw new RuntimeException("Genotype '" + genotype + "' not found.");
}
|
9d6d1859-258e-482e-a65f-e9f7d724ff84
| 2
|
public static void addAction(Action newAction) {
newAction.setId(curActionId++);
boolean offerSuccessful = actionsBuffer.offer(newAction);
if(offerSuccessful && offeredListener != null) {
offeredListener.actionOffered();
}
}
|
771cf6dc-c39c-497b-a2f3-71f275ca3ce2
| 4
|
private void readFile(File diffMapperFile) {
try {
BufferedReader reader = new BufferedReader(new FileReader(diffMapperFile));
String[] title = reader.readLine().split("\t");
String line;
while((line = reader.readLine()) != null) {
String[] value = line.split("\t");
for(int i = 0; i < title.length; i++)
addValue(title[i], value[i]);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
47976d58-b671-4d72-b68b-02ea1ffa9e43
| 9
|
@Test
public static void printMarshalMethods()
throws NoSuchFieldException, IllegalAccessException {
final Field field =
Marshallers.class.getDeclaredField("MARSHAL_METHODS");
field.setAccessible(true);
@SuppressWarnings("unchecked")
final Map<?, ?> value = (Map<?, ?>) field.get(null);
for (Entry<?, ?> entry : value.entrySet()) {
final Class<?> outputType = (Class<?>) entry.getKey();
final Method method = (Method) entry.getValue();
System.out.println("output type: " + outputType);
System.out.println("method: " + method);
}
}
|
52326c05-9535-49c4-9e3e-4bf7f7d3d554
| 7
|
private boolean evaluatePlotClause(String str) {
if (!model.hasEmbeddedMovie()) {
out(ScriptEvent.FAILED, "No data is recorded or model not in recording mode.");
return false;
}
byte averageFlag = 0;
if (str.toLowerCase().startsWith("-ra")) {
str = str.substring(3).trim();
averageFlag = 1;
} else if (str.toLowerCase().startsWith("-ca")) {
str = str.substring(3).trim();
averageFlag = 2;
}
boolean xyFlag = false;
if (str.startsWith("(") && str.endsWith(")")) {
str = str.substring(1, str.length() - 1);
xyFlag = true;
}
String[] s = str.split(",");
for (int i = 0; i < s.length; i++)
s[i] = s[i].trim();
DataQueue[] q = plotMathExpression(s, averageFlag, xyFlag);
if (q != null) {
DataQueueUtilities.show(q, JOptionPane.getFrameForComponent(view));
return true;
}
out(ScriptEvent.FAILED, "Unrecognized keyword: " + str);
return false;
}
|
7128a19b-fe3f-4dfd-8bab-34978a0396d7
| 6
|
private static int convertTimeRemaining(String time){
int seconds = 0;
String[] substrings = time.split(" ");
if (substrings[1].equals("hours") || substrings[1].equals("hour")){
seconds = Integer.parseInt(substrings[0]) * 3600;
}
if (substrings[1].equals("minutes") || substrings[1].equals("minute")){
seconds = Integer.parseInt(substrings[0]) * 60;
}
if (substrings[1].equals("seconds") || substrings[1].equals("second")){
seconds = Integer.parseInt(substrings[0]);
}
int minutes = seconds/60;
return minutes;
}
|
a0847b0a-fc84-44ea-8d86-5361c6b07221
| 2
|
public boolean checkUserId(int uid) {
for(int i=1;i<=3;i++)
if( this.user_id== uid)
{
return true;
}
return false;
}
|
e9488b89-53ba-4414-91c2-c6780ecf476f
| 8
|
@SuppressWarnings("unchecked")
public ActionForward addToMyCart(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
int productseq = Integer.parseInt(request.getParameter("productseq"));
String productname = new String(request.getParameter("productname").getBytes("iso-8859-1"),"utf-8");
System.out.println(productname);//
double price = Double.parseDouble(request.getParameter("price"));
// System.out.println(price);//
//
CartBean cb = new CartBean();
cb.setProductseq(productseq);
cb.setProductname(productname);
cb.setPrice(price);
cb.setNum(1); //
//
UserBean ub = (UserBean)request.getSession().getAttribute("userbean");
//
ArrayList<CartBean> mycart = (ArrayList<CartBean>)request.getSession().getAttribute("mycart");
if (ub == null) {
//
//
if (mycart == null) {
//
mycart = new ArrayList<CartBean>();
mycart.add(cb);
//
request.getSession().setAttribute("mycart", mycart);
} else { //
boolean flag = true;//
for (int i = 0; i < mycart.size(); i++) {
if (mycart.get(i).getProductseq() == cb.getProductseq()) {
//
mycart.get(i).setNum(mycart.get(i).getNum()+1);
flag = false;
break;
}
}
if (flag) {
//
mycart.add(cb);
}
}
} else { //
//
boolean flag = true;//
for (int i = 0; i < mycart.size(); i++) {
if (mycart.get(i).getProductseq() == cb.getProductseq()) {
//
mycart.get(i).setNum(mycart.get(i).getNum()+1);
flag = false;
break;
}
}
if (flag) {
//
mycart.add(cb);
}
}
//
ActionForward forward = mapping.findForward("cart_list");
return forward;
}
|
53fa7cfd-1a19-485f-b987-dd78cd8fd044
| 6
|
public static void main(String[] args) {
List<OfficeSpace> reserved = new ArrayList<OfficeSpace>();
String token = "abcd1234";
try {
// Load initial Provider and Officespace
ProviderLoad.initialLoad("./sampleData/Provider1data.txt");
ProviderLoad.initialLoad("./sampleData/Provider2data.txt");
// Test to create, update and delete Renters
Renter r = TestDriver.testCreateRenter("./sampleData/Renterdata");
TestDriver.testCreateRenter("./sampleData/Renterdata1");
TestDriver.testUpdateRenter("./sampleData/UpdateRenterdata");
TestDriver.testDeleteRenter("Tony");
// Get list of all available renters
TestDriver.testGetRentersList(token);
// Test Search of the officeSpace based on the Criteria in the file
reserved = TestDriver.testSearchOfficeSpace("./sampleData/sampleData");
// Test Create booking on the first office space from the available list above and then check booking details by fetching it by its Conf no.
int ConfNo = TestDriver.testCreateBooking(r,reserved.get(0));
TestDriver.testGetBookingByConf(token, ConfNo);
// Search for offices again with same criteria.
TestDriver.testSearchOfficeSpace("./sampleData/sampleData"); //This time, No officeSpace will be available. Error message will be displayed
// Test Delete booking and then try to get the deleted space. Should display error message.
TestDriver.testDeleteBooking(token, ConfNo);
TestDriver.testGetBookingsOfRenter(token, r.getID());
TestDriver.testSearchOfficeSpace("./sampleData/sampleData"); //This should return deleted officeSpace as well.
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (YamlException e) {
e.printStackTrace();
} catch (AccessException e) {
e.printStackTrace();
} catch (InvalidRecordException e) {
e.printStackTrace();
} catch (InvalidRenterException e) {
e.printStackTrace();
} catch (BusinessException e) {
e.printStackTrace();
}
}
|
565409de-c0f7-4345-9664-d98e03628f85
| 5
|
private synchronized void parserNode(Node node, WebPage srb) throws Exception {
if (node instanceof TextNode) {// 判斷是否是文本結點
srb.addText(((TextNode) node).getText());
} else if (node instanceof Tag) {// 判斷是否是標籤庫結點
Tag atag = (Tag) node;
if (atag instanceof TitleTag) {// 判斷是否是標TITLE結點
srb.setTitle(atag.getText());
}
if (atag instanceof LinkTag) {// 判斷是否是標LINK結點
LinkTag linkatag = (LinkTag) atag;
this.spiderEngine.checkLink(linkatag.getLink());
}
dealTag(atag, srb);
atag = null;
} else if (node instanceof RemarkNode) {// 判斷是否是注釋
// System.out.println("this is remark");
}
}
|
7fefc29e-431a-4dd8-ab3d-621e4523efbc
| 0
|
@Override
public void mouseReleased(MouseEvent e) {
isMouseDown = false;
}
|
cf9a5ddb-7458-474a-ae26-e251d1c95e44
| 4
|
public void test(int down, int left, int right) {
if (down == fill) {
sum++;
addToResult();
return;
}
int canNot = down | left | right;
if (canNot == fill)
return;
for (int i = 0; i < n; i++) {
int put = 1 << i;
if ((canNot & put) == 0) {
insert(put);
test((down | put), (left | put) << 1, (right | put) >>> 1);
removeLast();
}
}
}
|
db77bea5-7edd-4123-bd43-7f14354039a8
| 1
|
@RequestMapping(value = "/student/{studentId}/enrolldegree", method = RequestMethod.POST)
public String enrollDegree(ModelMap model,
@PathVariable("studentId") int studentId,
@RequestParam("degreeid") int degreeId) {
logger.debug("Enrolling student " + studentId + " in degree "
+ degreeId);
if (studentSystem
.studentFulfillsDegreeRequirements(studentId, degreeId)) {
studentSystem.addDegreeToStudent(studentId, degreeId);
} else {
model.addAttribute("message",
"Student does not fulfill course requirements. ");
}
populateModel(model);
return "student";
}
|
6fbb141c-72f8-463c-880a-1cb6a4451ab3
| 7
|
public static int getAge2(
int age0,
Random aRandom) {
if (age0 < 20) {
return aRandom.nextInt(20);
}
if (age0 < 30) {
return (20 + aRandom.nextInt(10));
}
if (age0 < 40) {
return (30 + aRandom.nextInt(10));
}
if (age0 < 50) {
return (40 + aRandom.nextInt(10));
}
if (age0 < 60) {
return (50 + aRandom.nextInt(10));
}
if (age0 < 70) {
return (60 + aRandom.nextInt(10));
}
if (age0 < 80) {
return (70 + aRandom.nextInt(10));
}
return 80;
}
|
ac830ac2-c172-4838-ab17-2ad04e85c514
| 3
|
public boolean sees(Entity other) {
if (distanceSquared(other) > visualRangeSquared)
return false; // only check in circle with r=200
double p1X = this.xPos - other.xPos;
double p1Y = this.yPos - other.yPos;
double p2X = this.xPos - other.xPos + Math.cos(Math.toRadians(heading))
* 10;
double p2Y = this.yPos - other.yPos + Math.sin(Math.toRadians(heading))
* 10;
double a = p1Y - p2Y;
double b = (p2X - p1X);
double c = (p2X * p1Y - p1X * p2Y);
double discriminant = radiusSquared * (Math.pow(a, 2) + Math.pow(b, 2))
- Math.pow(c, 2);
if (discriminant < 0)
return false;
double v1X = other.xPos - this.xPos;
double v1Y = other.yPos - this.yPos;
// normalize
double v1Length = Math.sqrt(v1X * v1X + v1Y * v1Y);
v1X /= v1Length;
v1Y /= v1Length;
double v2X = Math.cos(Math.toRadians(heading));
double v2Y = Math.sin(Math.toRadians(heading));
double dotProduct = v1X * v2X + v1Y * v2Y;
if (dotProduct < 0)
return false;
return true;
}
|
d242b27e-4c15-4e0a-b41a-e0115ffbfcbf
| 2
|
public static Date stoDate(String str){
Date i = null;
if(str!=null){
try{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
i = format.parse(str);
new Date();
}catch(Exception e){
i = null;
}
}else{
i = null;
}
return i;
}
|
86c6a377-3573-49bb-bb58-ccefce5f4b9f
| 0
|
public void testPeriodic() {
// Updates sensors & actuators on the LiveWindow
LiveWindow.run();
}
|
c989a5c3-709c-4c24-93c1-bc90f00b7a56
| 4
|
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
|
9d470b93-fd78-4e97-8335-1bf94754c78f
| 6
|
private static CommandLine getCommandLine(String args[])
{
HelpFormatter formatter = new HelpFormatter();
Options options = getOptions(args);
CommandLineParser parser = new PosixParser();
CommandLine cmd = null;
try
{
cmd = parser.parse(options, args);
}
catch (ParseException e)
{
System.err.println("Error : " + e.getMessage());
formatter.printHelp("Sort", options, true);
System.exit(1);
}
if (cmd.hasOption("h"))
{
formatter.printHelp("Sort", options, true);
System.exit(0);
}
if (!(SortHelper.getAlgorithmList().contains(cmd.getOptionValue("s"))))
{
System.err.println("Algorithm specified must be one of '"
+ SortHelper.getAlgorithmList().toString() + "'");
System.exit(1);
}
if (cmd.hasOption("n"))
N = Integer.valueOf(cmd.getOptionValue("n"));
if (cmd.hasOption("i"))
{
inputType = cmd.getOptionValue("i");
if (!(SortHelper.getInputNatureList().contains(inputType)))
{
System.err
.println("The Nature of input specified must be one of '"
+ SortHelper.getInputNatureList().toString());
System.exit(1);
}
}
return cmd;
}
|
8dc498b7-ecc0-4c6f-bbce-c66d798c9e4e
| 8
|
public void addButtons() {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.insets = new Insets(2, 2, 2, 2);
int item = 0;
for (int i=0;i<5; i++) {
for (int j=0;j<5; j++) {
if (buttons[item].equals("0")) {
JButton btn;
if (Character.isDigit(buttons[item].charAt(0)) || buttons[item].equals(".")) {
btn = new Button(buttons[item]);
} else {
btn = new Button(buttons[item], true);
}
c.gridy = i;
c.gridx = j;
c.gridwidth = 2;
btn.addActionListener(this);
btn.addKeyListener(this);
buttonArray.add(btn);
pnlButtons.add(btn, c);
} else if (!buttons[item].equals("")) {
JButton btn;
if (Character.isDigit(buttons[item].charAt(0)) || buttons[item].equals(".")) {
btn = new Button(buttons[item]);
} else {
btn = new Button(buttons[item], true);
}
c.gridy = i;
c.gridx = j;
c.gridwidth = 1;
btn.addActionListener(this);
btn.addKeyListener(this);
buttonArray.add(btn);
pnlButtons.add(btn, c);
}
item++;
}
}
}
|
0b74739a-7336-4a78-91e4-14a31e471024
| 9
|
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append('[');
for (int i = 0; i < pop.fieldCount(); i++) {
if (pop.fieldCount() > 1)
sb.append(" f"+i+":");
PopField f = pop.getField(i);
if (!f.tour) {
int size = f.stringSize;
if (size > 50)
size = 8;
for (int k = 0; k < size; k++) {
sb.append(str.get(k+f.offset) ? '1' : '.');
}
} else {
int size = f.tourSites;
if (size > 20)
size = 8;
for (int k = 0; k < size; k++)
sb.append(Fmt.f(pop.getSite(this,i,k),4));
}
}
sb.append(']');
if (evalNecessary) {
sb.append("*** Eval required ***");
}
else {
sb.append(" Value:");
sb.append(Fmt.f(evaluation));
}
return sb.toString();
}
|
0ebed221-09fe-4b94-a7c2-8604856e2d06
| 7
|
public void setfocus(Widget w) {
if (focusctl) {
if (w != focused) {
Widget last = focused;
focused = w;
if (last != null)
last.hasfocus = false;
w.hasfocus = true;
if (last != null)
last.lostfocus();
w.gotfocus();
if ((ui != null) && ui.rwidgets.containsKey(w))
wdgmsg("focus", ui.rwidgets.get(w));
}
if (parent != null)
parent.setfocus(this);
} else {
parent.setfocus(w);
}
}
|
2e66992b-5246-423a-b9c1-4c7944d06ab8
| 5
|
public Object [][] getDatos(){
Object[][] data = new String[getCantidad_Cuentas ()][colum_names.length];
//realizamos la consulta sql y llenamos los datos en "Object"
try{
if (colum_names.length>=0){
r_con.Connection();
String campos = colum_names[0];
for (int i = 1; i < colum_names.length; i++) {
campos+=",";
campos+=colum_names[i];
}
String consulta = ("SELECT "+campos+" "+
"FROM "+name_tabla+" WITH (INDEX("+indices_tabla[numero_ordenamiento_elegido]+"))");
PreparedStatement pstm = r_con.getConn().prepareStatement(consulta);
ResultSet res = pstm.executeQuery();
int i = 0;
while(res.next()){
for (int j = 0; j < colum_names.length; j++) {
data[i][j] = res.getString(j+1);
}
i++;
}
res.close();
}
} catch(SQLException e){
System.out.println(e);
} finally {
r_con.cierraConexion();
}
return data;
}
|
865e1e5b-2093-4c88-afdc-5749a48c7c40
| 5
|
@SuppressWarnings("unused")
private static void AlphabeticalOrder(){
Scanner keyboard = new Scanner(System.in);
System.out.print("What is your name? ");
String input = keyboard.next();
if (input.compareTo("Carswell") <= 0)
System.out.println("you don't have to wait long");
else if (input.compareTo("Jones") <= 0)
System.out.println("that's not bad");
else if (input.compareTo("Smith") <= 0)
System.out.println("looks like a bit of a wait");
else if (input.compareTo("Young") <= 0)
System.out.println("it's gonna be a while");
else if (input.compareTo("Young") > 0)
System.out.println("not going anywhere for a while?");
keyboard.close();
}
|
9cb49c23-f881-431b-a45d-82fc5c5c4fdc
| 3
|
@Override
public void run() {
File plik = new File( path );
while( true ) {
if( plik.canRead() ) {
flaga = true;
} else flaga = false;
try {
sleep( odstep );
} catch ( InterruptedException e ) {
return;
}
}
}
|
9883434d-4104-4589-92aa-e41946541eae
| 9
|
@Override
public void atribuirJogo(String cod_jogo, String cod_equipa) {
String[] aux = cod_jogo.split("_");
int jogo = Integer.parseInt(aux[2]);
System.out.println(this.getDAOJornada().size(this.getCod_competicao()));
if ((this.getDAOJornada().size(this.getCod_competicao())-1)==(Integer.parseInt(aux[1]))) {
if (jogo % 2 == 0) {
int jornada = Integer.parseInt(aux[1]) + 1;
if (this.getJogos().containsKey(aux[0] + "_" + jornada + "_" + 1 + "_" + "0")) {
Jogo j = this.getJogos().get(aux[0] + "_" + jornada + "_" + 1 + "_" + "0");
j.setEquipa2(cod_equipa);
this.getJogos().put(j.getCod_Jogo(), j);
}
} else {
int jornada = Integer.parseInt(aux[1]) + 1;
if (this.getJogos().containsKey(aux[0] + "_" + jornada + "_" + 1 + "_" + "0")) {
Jogo j = this.getJogos().get(aux[0] + "_" + jornada + "_" + 1 + "_" + "0");
j.setEquipa1(cod_equipa);
this.getJogos().put(j.getCod_Jogo(), j);
}
}
return;
}
if (jogo / 2 == 0) {
int jornada = Integer.parseInt(aux[1]) + 1;
if (this.getJogos().containsKey(aux[0] + "_" + jornada + "_" + 1 + "_" + "1")) {
Jogo j = this.getJogos().get(aux[0] + "_" + jornada + "_" + 1 + "_" + "1");
j.setEquipa1(cod_equipa);
this.getJogos().put(j.getCod_Jogo(), j);
Jogo j2 = this.getJogos().get(aux[0] + "_" + (jornada + 1) + "_" + 1 + "_" + "2");
j2.setEquipa2(cod_equipa);
this.getJogos().put(j2.getCod_Jogo(), j2);
return;
}
}
if (jogo % 2 == 0) {
int jornada = Integer.parseInt(aux[1]) + 1;
if (this.getJogos().containsKey(aux[0] + "_" + jornada + "_" + jogo / 2 + "_" + "1")) {
Jogo j = this.getJogos().get(aux[0] + "_" + jornada + "_" + jogo / 2 + "_" + "1");
j.setEquipa2(cod_equipa);
this.getJogos().put(j.getCod_Jogo(), j);
Jogo j2 = this.getJogos().get(aux[0] + "_" + (jornada + 1) + "_" + jogo / 2 + "_" + "2");
j2.setEquipa1(cod_equipa);
this.getJogos().put(j2.getCod_Jogo(), j2);
return;
}
} else {
int jornada = Integer.parseInt(aux[1]) + 1;
if (this.getJogos().containsKey(aux[0] + "_" + jornada + "_" + ((jogo / 2) + 1) + "_" + "1")) {
Jogo j = this.getJogos().get(aux[0] + "_" + jornada + "_" + ((jogo / 2) + 1) + "_" + "1");
j.setEquipa1(cod_equipa);
this.getJogos().put(j.getCod_Jogo(), j);
Jogo j2 = this.getJogos().get(aux[0] + "_" + (jornada + 1) + "_" + ((jogo / 2) + 1) + "_" + "2");
j2.setEquipa2(cod_equipa);
this.getJogos().put(j2.getCod_Jogo(), j2);
return;
}
}
}
|
581b336d-617f-42c9-8d3a-79c35686f2eb
| 8
|
public void generate(JFormatter f) {
// generally we produce new T[x], but when T is an array type (T=T'[])
// then new T'[][x] is wrong. It has to be new T'[x][].
int arrayCount = 0;
JType t = type;
while( t.isArray() ) {
t = t.elementType();
arrayCount++;
}
f.p("new").g(t).p('[');
if (size != null)
f.g(size);
f.p(']');
for( int i=0; i<arrayCount; i++ )
f.p("[]");
if ((size == null) || (exprs != null))
f.p('{');
if (exprs != null) {
f.g(exprs);
} else {
f.p(' ');
}
if ((size == null) || (exprs != null))
f.p('}');
}
|
3d1b471e-cf4e-4ca7-8a23-74ee98c08b9c
| 7
|
public static double[] matrixMinAndMax(List<double[]> dataSet, int index, int axis){
double[] ret = new double[2];
ret[0] = Double.MAX_VALUE;
ret[1] = Double.MIN_VALUE;
int m = dataSet.size();
int n = dataSet.get(0).length;
if(axis == 0){
for(int i=0;i<m;i++){
double val = dataSet.get(i)[index];
if(val<ret[0])
ret[0] = val;
if(val>ret[1])
ret[1] = val;
}
}else{
for(int i=0;i<n;i++){
double val = dataSet.get(index)[i];
if(val<ret[0])
ret[0] = val;
if(val>ret[1])
ret[1] = val;
}
}
return ret;
}
|
17d1e231-2328-45c7-8b23-2b408970f006
| 7
|
public boolean setInputFormat(Instances instanceInfo) throws Exception {
if ((instanceInfo.classIndex() > 0) && (!getFillWithMissing())) {
throw new IllegalArgumentException("TimeSeriesDelta: Need to fill in missing values " +
"using appropriate option when class index is set.");
}
super.setInputFormat(instanceInfo);
// Create the output buffer
Instances outputFormat = new Instances(instanceInfo, 0);
for(int i = 0; i < instanceInfo.numAttributes(); i++) {
if (i != instanceInfo.classIndex()) {
if (m_SelectedCols.isInRange(i)) {
if (outputFormat.attribute(i).isNumeric()) {
outputFormat.renameAttribute(i, outputFormat.attribute(i).name()
+ " d"
+ (m_InstanceRange < 0 ? '-' : '+')
+ Math.abs(m_InstanceRange));
} else {
throw new UnsupportedAttributeTypeException("Time delta attributes must be numeric!");
}
}
}
}
outputFormat.setClassIndex(instanceInfo.classIndex());
setOutputFormat(outputFormat);
return true;
}
|
1013260c-8ce2-4550-8486-f310ae273f12
| 9
|
public Sound() {
Debug.println("Sound.Sound()");
muted = false;
fxQueue = new LinkedList<Integer>();
AudioInputStream as = null;
try {
as = AudioSystem.getAudioInputStream(ROLL_SOUND);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
roll = (Clip) AudioSystem.getClip();
roll.open(as);
} catch (Exception e) {
}
try {
as = AudioSystem.getAudioInputStream(GUTTER_SOUND);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
gutter = (Clip) AudioSystem.getClip();
gutter.open(as);
} catch (Exception e) {
}
try {
as = AudioSystem.getAudioInputStream(CLATTER_SOUND);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
clatter = (Clip) AudioSystem.getClip();
clatter.open(as);
} catch (Exception e) {
}
}
|
0cc1da2c-46c1-4b01-ab3c-547fe0840f25
| 8
|
@SuppressWarnings("unchecked")
private StackInterface<Method> instantiate(SimulationComponent mComp) {
String problem = "";
try {
Constructor<?> m = Class.forName("CallStack").getConstructor(SimulationComponent.class);
System.err.println("Call Stack instantiated... will attempt to run on VM!");
return (StackInterface<Method>) m.newInstance(mComp);
} catch (SecurityException e) {
problem = "Access to constructor denied. (SecurityException)";
} catch (NoSuchMethodException e) {
problem = "No constructor found for CallStack that takes a SimluationComponent as a parameter. (NoSuchMethodException)";
} catch (ClassNotFoundException e) {
problem = "The CallStack class doesn't exist yet (ClassNotFoundException)";
} catch (IllegalArgumentException e) {
problem = "Wrong number of arguments to the constructor (IllegalArgumentException)";
} catch (InstantiationException e) {
problem = "CallStack appears to be an abstract class --- maybe it doesn't implement all the\n" +
" methods of the interface it claims to implement. (InstantiationException)";
} catch (IllegalAccessException e) {
problem = "Constructor is inaccessible. (IllegalAccessException)";
} catch (InvocationTargetException e) {
problem = "Constructor threw an exception. (InvocationTargetException)";
}
System.err.println("Cannot instantiate CallStack, method calls won't work.");
System.err.println(problem);
return null;
}
|
4933600d-6cd9-4152-9117-e7e23e3ab2fb
| 7
|
public static void setPlatform(int plaf)
{
if (plaf < WINDOWS_XP || plaf > GNOME)
throw new IllegalArgumentException("Unknown platform: " + plaf);
CUR_PLAF = plaf;
switch (plaf) {
case WINDOWS_XP:
setRelatedGap(LPX4, LPY4);
setUnrelatedGap(LPX7, LPY9);
setParagraphGap(LPX14, LPY14);
setIndentGap(LPX9, LPY9);
setGridCellGap(LPX4, LPY4);
setMinimumButtonWidth(new UnitValue(75, UnitValue.LPX, null));
setButtonOrder("L_E+U+YNBXOCAH_R");
setDialogInsets(LPY11, LPX11, LPY11, LPX11);
setPanelInsets(LPY7, LPX7, LPY7, LPX7);
BASE_DPI = 96;
break;
case MAC_OSX:
setRelatedGap(LPX4, LPY4);
setUnrelatedGap(LPX7, LPY9);
setParagraphGap(LPX14, LPY14);
setIndentGap(LPX10, LPY10);
setGridCellGap(LPX4, LPY4);
setMinimumButtonWidth(new UnitValue(68, UnitValue.LPX, null));
setButtonOrder("L_HE+U+NYBXCOA_R");
setDialogInsets(LPY14, LPX20, LPY20, LPX20);
setPanelInsets(LPY16, LPX16, LPY16, LPX16);
// setRelatedGap(LPX8, LPY8);
// setUnrelatedGap(LPX12, LPY12);
// setParagraphGap(LPX16, LPY16);
// setIndentGap(LPX10, LPY10);
// setGridCellGap(LPX8, LPY8);
//
// setMinimumButtonWidth(new UnitValue(68, UnitValue.LPX, null));
// setButtonOrder("L_HE+U+NYBXCOA_R");
// setDialogInsets(LPY14, LPX20, LPY20, LPX20);
// setPanelInsets(LPY16, LPX16, LPY16, LPX16);
try {
BASE_DPI = System.getProperty("java.version").compareTo("1.6") < 0 ? 72 : 96; // Default DPI was 72 prior to JSE 1.6
} catch (Throwable t) {
BASE_DPI = 72;
}
break;
case GNOME:
setRelatedGap(LPX6, LPY6); // GNOME HIG 8.2.3
setUnrelatedGap(LPX12, LPY12); // GNOME HIG 8.2.3
setParagraphGap(LPX18, LPY18); // GNOME HIG 8.2.3
setIndentGap(LPX12, LPY12); // GNOME HIG 8.2.3
setGridCellGap(LPX6, LPY6); // GNOME HIG 8.2.3
// GtkButtonBox, child-min-width property default value
setMinimumButtonWidth(new UnitValue(85, UnitValue.LPX, null));
setButtonOrder("L_HE+UNYACBXIO_R"); // GNOME HIG 3.4.2, 3.7.1
setDialogInsets(LPY12, LPX12, LPY12, LPX12); // GNOME HIG 3.4.3
setPanelInsets(LPY6, LPX6, LPY6, LPX6); // ???
BASE_DPI = 96;
}
}
|
ad302754-acc5-4299-945d-21c5a39c7b19
| 5
|
public void updateAccountPassword(String user, String password) {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("update Accounts set Password=? where Username=?");
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(password.getBytes("UTF-8"));
statement.setString(1,toHexString(hash));
statement.setString(2,user);
statement.executeUpdate();
} catch(SQLException e){
e.printStackTrace();
} catch(NoSuchAlgorithmException e){
e.printStackTrace();
} catch(UnsupportedEncodingException e){
e.printStackTrace();
} finally {
try { if (statement != null) statement.close(); } catch (Exception e) {}
}
}
|
ba2376de-6daa-4200-9f1c-bc3a602728ae
| 8
|
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(negative ? "N" : "n");
sb.append(overflow ? "V" : "v");
sb.append(memory_access ? "M" : "m");
sb.append(index_register ? "X" : "x");
sb.append(decimal_mode ? "D" : "d");
sb.append(irq_disable ? "I" : "i");
sb.append(zero ? "Z" : "z");
sb.append(carry ? "C" : "c");
return sb.toString();
}
|
5e7590b2-5d35-42eb-99ea-e95274fc4528
| 2
|
protected Transition createTransition(State from, State to, Node node, Map e2t, boolean isBlock)
{
/*
* The boolean isBlock seems to be ignored in FSATransducer.java, so I'm ignoring
* it here too.
*/
String label = (String) e2t.get(TRANSITION_READ_NAME);
String output = (String) e2t.get(TRANSITION_OUTPUT_NAME);
if(label == null)
label = "";
if(output == null)
output = "";
return new MealyTransition(from, to, label, output);
}
|
f339b0a3-56c0-45a9-94ff-8698121f5b3e
| 3
|
private static HashSet<Person> getNeighbors(Person p) {
HashSet<Person> neighbors = new HashSet<Person>();
for (Person[] edge : hardConnections) {
if (edge[0].equals(p))
neighbors.add(edge[1]);
else if (edge[1].equals(p))
neighbors.add(edge[0]);
}
return neighbors;
}
|
4afd9b41-3f73-4388-a808-7586cadb820a
| 7
|
private OSMNodeData getNodeInformation(Attributes attributes) {
String idStr = attributes.getValue("id");
String latStr = attributes.getValue("lat");
String lonStr = attributes.getValue("lon");
// Avoid null pointer reference!
if (idStr != null && latStr != null && lonStr != null) {
try {
Long id = Long.parseLong(idStr);
if (mappingNodesFirst && !idMap.containsKey(id))
idMap.put(id, nodeIDCounter);
int mappedID = nodeIDCounter++;
if (!mappingNodesFirst) {
mappedID = idMap.get(id);
}
double lat = Double.parseDouble(latStr);
double lon = Double.parseDouble(lonStr);
return new OSMNodeData(mappedID, lat, lon);
} catch (NumberFormatException ex) {
Logger.getLogger(OSMParseHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.