method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
5640fd46-2547-4465-8290-30bf67b2bc92 | 0 | public void setId(Integer id) {
this.id = id;
} |
5516df76-dec6-427b-b813-9a0b69e4b545 | 6 | static final void method842(boolean bool) {
anInt1501++;
Class138.aClass46Array1942 = null;
if (Class59_Sub1.aBoolean5300
&& (Class348_Sub42_Sub12.method3229() ^ 0xffffffff) != -2)
OutputStream_Sub1.method132(106,
((Class240.anInt4674 ^ 0xffffffff)
== -4) || Class240.anInt4674 == 7,
za_Sub1.method3439(107), 0,
Class348_Sub44.method3306((byte) -111),
0);
int i = 0;
if (bool != false)
method847(null, -110);
int i_1_ = 0;
if (Class59_Sub1.aBoolean5300) {
i = s_Sub3.method4008((byte) -124);
i_1_ = Class16.method260(false);
}
Class159.method1252(i_1_, r.anInt9721, i_1_, -1, i,
i + Class321.windowWidth,
i_1_ - -Class348_Sub42_Sub8_Sub2.windowHeight,
(byte) 116, i);
if (Class138.aClass46Array1942 != null) {
Class348_Sub40_Sub7.method3064
(i, EntryElementLoader.anInt4792, true, Class348_Sub1.anInt6555, i_1_,
((Widget) Class331.aClass46_4130).anInt760,
i + Class321.windowWidth, false, Class138.aClass46Array1942,
-1412584499, i_1_ - -Class348_Sub42_Sub8_Sub2.windowHeight);
Class138.aClass46Array1942 = null;
}
} |
5cc692ad-0074-4362-8e0f-f574f8ea02df | 9 | public PaymentDialog(Member member, ClassType ct,String message,int flag) {
messageTextArea.setText(message);
globalMember = member;
globalClassType = ct;
globalFlag = flag;
makePaymentButton = new JButton("Make Payment");
makePaymentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Common.makePayment(paymentTypeList.getSelectedValue(),
globalMember, (Date) utilDateModel.getValue(),
getPaymentAmount());
updatePaymentStatus(globalMember, globalClassType);
dispose();
new PaymentDialog(globalMember,globalClassType,"Payment made for "
+ globalMember.getName()
+ "\n of "
+ getPaymentAmount()
+ " for "
+ paymentTypeList.getSelectedValue()
.getPaymentTypeName() + "\n up to date: "
+ ((Date) utilDateModel.getValue()).toString(),globalFlag);
}
});
makePaymentButton.setEnabled(false);
exitButton = new JButton("Exit");
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
if(globalFlag==0) new MemberCheckInInterface(globalClassType);
}
});
BufferedImage tkdIcon = CommonUI.getTkdIcon();
BufferedImage skyIcon = CommonUI.getSkyIcon();
BufferedImage kickIcon = CommonUI.getKickIcon();
Image img = null;
switch (ct) {
case TAEKWONDO:
img = new ImageIcon(tkdIcon).getImage();
break;
case SKYBOXING:
img = new ImageIcon(skyIcon).getImage();
break;
case KICKBOXING:
img = new ImageIcon(kickIcon).getImage();
break;
case OTHER:
img = new ImageIcon(tkdIcon).getImage();
default:
img = new ImageIcon(tkdIcon).getImage();
}
setIconImage(img);
this.setTitle("Enter Payment for " + member.getName());
utilDateModel.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent arg0) {
System.out.println("DateModel changed");
setDateSelected();
if (paymentAmountSelected && dateSelected) {
makePaymentButton.setEnabled(true);
}
}
});
panel.add(paymentToPanel, BorderLayout.CENTER);
paymentTypeList.setListData(Common.getPaymentTypes(ct).toArray(
new PaymentType[1]));
paymentTypeList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
JList<PaymentType> tempList = (JList<PaymentType>) arg0
.getSource();
PaymentType pt = tempList.getSelectedValue();
paymentAmountTextField.setText(String.format("%9.2f",
pt.getPaymentAmount()));
setPaymentAmountFieldSelected();
if (paymentAmountSelected && dateSelected) {
makePaymentButton.setEnabled(true);
}
}
});
listPanel.add(paymentTypeList);
panel.add(listPanel, BorderLayout.WEST);
paymentAmountPanel.add(paymentAmountLabel);
paymentAmountPanel.add(paymentAmountTextField);
buttonPanel.add(paymentAmountPanel, BorderLayout.NORTH);
buttonPanel.add(makePaymentButton, BorderLayout.WEST);
buttonPanel.add(exitButton, BorderLayout.SOUTH);
panel.add(buttonPanel, BorderLayout.SOUTH);
paymentStatusPanel.add(paymentStatusTextArea, BorderLayout.NORTH);
paymentStatusPanel.add(messageTextArea, BorderLayout.SOUTH);
updatePaymentStatus(member, ct);
panel.add(paymentStatusPanel, BorderLayout.EAST);
this.getContentPane().add(panel);
this.setSize(CommonUI.FULLSCREEN);
this.setVisible(true);
} |
ccd8ac96-56e5-45ca-9814-da4472d212e5 | 4 | @Override
public void render(Graphics2D gd) {
_gameView.gameFieldView().render(gd);
String lifes = "LIFES:" + String.valueOf(_gameModel.player().numberOfLives());
font.drawString(gd, lifes, 10, 530);
String level = "LEVEL:" + String.valueOf(_gameModel.level());
font.drawString(gd, level, 180, 530);
String scores = "SCORE:" + String.valueOf(_gameModel.player().scores());
font.drawString(gd, scores, 350, 530);
gameState state = state();
switch (state) {
case GAME_OVER: {
_gameModel.player().reduceNumberOfLives();
if (_gameModel.player().numberOfLives() == 0) {
_gameModel.endGame();
} else {
deleteSpriteGroup();
_gameModel.newGame();
addSpriteGroup();
}
break;
}
case GAME_FINISHED: {
deleteSpriteGroup();
String finished = "YOU WIN!\nCONGRADULATIONS!!";
font.drawString(gd, finished, 350, 330);
break;
}
case END_GAME: {
deleteSpriteGroup();
String finished = "THE NUMBER OF LIVES OVER!!!";
font.drawString(gd, finished, 100, 200);
break;
}
}
} |
49e85b19-3e78-4f7c-83b3-e5188fd0dc52 | 2 | public boolean hasElement(T a)
{ if(this.a.equals(a))
{ return true;}
else if(this.next!=null)
{ return this.next.hasElement(a);
}
else
{ return false;
}
} |
f9a47881-9848-4c01-a141-0b9dac30b9f1 | 8 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {try {
//GEN-FIRST:event_jButton1ActionPerformed
list = new DrinksDao();
} catch (SAXException ex) {
Logger.getLogger(addItemToDrinkMenu.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(addItemToDrinkMenu.class.getName()).log(Level.SEVERE, null, ex);
}
Name = getItemName();
Description = getItemDescriptionName();
Price = getItemPrice();
PictureName = getPictureName();
if(Name.equals("") || Description.equals("") || Price.equals("") || PictureName.equals("")){
JOptionPane.showMessageDialog(this,
"YOU MUST ENTER ALL INFORMATION",
"CHECK VALUES AGAIN",
JOptionPane.ERROR_MESSAGE);
}
else{
list.addDrink(Name,Description, 1,Price,PictureName);
System.out.println(getItemName()+' '+getItemDescriptionName()+" " + getItemPrice()+" "+getPictureName());
JOptionPane.showMessageDialog(this,
"YOUR ITEM HAS BEEN ADDED!!!",
"CONFIRMATION DIALOG",
JOptionPane.WARNING_MESSAGE);
itemNameValue.setText("");
itemDescriptionValue.setText("");
itemPriceValue.setText("0");
itemPictureValue.setText("Click Here To Select Image");
adminLogInDialog.drinksMenu.removeAll();
try {
adminLogInDialog.drinksMenu.setUpComponents();
} catch (SAXException ex) {
Logger.getLogger(addItemToDrinkMenu.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(addItemToDrinkMenu.class.getName()).log(Level.SEVERE, null, ex);
}
adminLogInDialog.drinksEditPane.revalidate();
}
}//GEN-LAST:event_jButton1ActionPerformed |
b824f32c-6f12-402f-80ad-04072f875d8e | 7 | private int jjMoveStringLiteralDfa3_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(1, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(2, active0);
return 3;
}
switch(curChar)
{
case 70:
case 102:
if ((active0 & 0x2000000L) != 0L)
return jjStopAtPos(3, 25);
break;
case 82:
case 114:
return jjMoveStringLiteralDfa4_0(active0, 0x800000L);
default :
break;
}
return jjStartNfa_0(2, active0);
} |
e7e05f4e-a47f-40de-8be6-6a34892176f0 | 4 | public void testCompareTo() {
LocalDateTime test1 = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40);
LocalDateTime test1a = new LocalDateTime(2005, 6, 2, 10, 20, 30, 40);
assertEquals(0, test1.compareTo(test1a));
assertEquals(0, test1a.compareTo(test1));
assertEquals(0, test1.compareTo(test1));
assertEquals(0, test1a.compareTo(test1a));
LocalDateTime test2 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40);
assertEquals(-1, test1.compareTo(test2));
assertEquals(+1, test2.compareTo(test1));
LocalDateTime test3 = new LocalDateTime(2005, 7, 2, 10, 20, 30, 40, GREGORIAN_UTC);
assertEquals(-1, test1.compareTo(test3));
assertEquals(+1, test3.compareTo(test1));
assertEquals(0, test3.compareTo(test2));
DateTimeFieldType[] types = new DateTimeFieldType[] {
DateTimeFieldType.year(),
DateTimeFieldType.monthOfYear(),
DateTimeFieldType.dayOfMonth(),
DateTimeFieldType.millisOfDay(),
};
int[] values = new int[] {2005, 6, 2, MILLIS_OF_DAY_UTC};
Partial p = new Partial(types, values);
assertEquals(0, test1.compareTo(p));
try {
test1.compareTo(null);
fail();
} catch (NullPointerException ex) {}
// try {
// test1.compareTo(new Date());
// fail();
// } catch (ClassCastException ex) {}
try {
@SuppressWarnings("deprecation")
YearMonthDay ymd = new YearMonthDay();
test1.compareTo(ymd);
fail();
} catch (ClassCastException ex) {}
try {
@SuppressWarnings("deprecation")
TimeOfDay tod = new TimeOfDay();
test1.compareTo(tod);
fail();
} catch (ClassCastException ex) {}
Partial partial = new Partial()
.with(DateTimeFieldType.centuryOfEra(), 1)
.with(DateTimeFieldType.halfdayOfDay(), 0)
.with(DateTimeFieldType.dayOfMonth(), 9);
try {
new LocalDateTime(1970, 6, 9, 10, 20, 30, 40).compareTo(partial);
fail();
} catch (ClassCastException ex) {}
} |
811e1d25-d0db-4b28-99db-a45599d3f398 | 5 | private void jButtongetArrivalsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtongetArrivalsActionPerformed
if ("".equals(jXDatePickergetArrival.getEditor().getText()) || "".equals(jXDatePickergetDeparture.getEditor().getText())) {
JOptionPane.showMessageDialog(rootPane, "Make sure both arrival and departure date are entered and in the correct format");
} else {
if (jXDatePickergetArrival.getDate().before(jXDatePickergetDeparture.getDate())) {
dflBooking.removeAllElements();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
jXDatePickergetArrival.setFormats(dateFormat);
jXDatePickergetDeparture.setFormats(dateFormat);
String arrival = dateFormat.format(jXDatePickergetArrival.getDate()).toString();
String departure = dateFormat.format(jXDatePickergetDeparture.getDate()).toString();
b = con.getBookingList(arrival, departure);
if (!b.isEmpty()) {
for (int i = 0; i < b.size(); i++) {
dflBooking.addElement(b.get(i).toString());
}
} else {
jLabelStatusBooking.setText("Could not get bookings!");
}
//Reset the transaction.
con.resetBooking();
} else {
JOptionPane.showMessageDialog(rootPane, "Make sure arrival date is before departure date");
}
}
}//GEN-LAST:event_jButtongetArrivalsActionPerformed |
6413f8a6-bb02-4159-b415-76bb5493815a | 0 | public CtrlMenu getCtrlM() {
return ctrlM;
} |
6b6ebaa3-bdfe-456f-82de-84ee0e1f7305 | 6 | public static void main(String[] args) {
SavingsAccount bank[] = new SavingsAccount[2];
Scanner stdin = new Scanner(System.in);
createAccounts(bank,stdin);
System.out.println("Initial accounts:");
displayAccounts(bank);
int choice;
SavingsAccount acc;
do{
System.out.print(
"1) make a deposit\n" +
"2) make a withsrawal\n" +
"3) end the month\n" +
"0) quit \n -> ");
choice = stdin.nextInt();
switch (choice) {
case 1:
acc = selectAccount(bank,stdin);
System.out.print("Amount to deposit? ");
acc.deposit(stdin.nextDouble());
break;
case 2:
acc = selectAccount(bank,stdin);
System.out.print("Amount to withdraw? ");
if(!acc.withdraw(stdin.nextDouble()))
System.out.println("ERROR! withdrawal not allowed!");
break;
case 3:
endMonth(bank);
System.out.println("New balances: ");
displayAccounts(bank);
break;
case 0:
break;
default:
System.out.println("ERROR! not a valid selection!");
}
}while(choice != 0);
} |
b7e1aba0-4955-43ba-a5e4-df2dc2dd03bf | 1 | public ItemStack getIcon(IconType type) {
if (IconManager.getInstance().getIcon(type).getItemStack() != null) return IconManager.getInstance().getIcon(type).getItemStack();
else return null;
} |
3831f2fd-e431-4f66-a1ca-a4a6422bbfd3 | 5 | public void paint(Graphics g) {
final Shire shire = ((PopupShire)parent).getShire();
if(shire==null){return;}
final Library library = shire.getLibrary();
super.paint(g);
int r = 0;
Clan gov = shire.getGovernor();
if (gov != null) {
g.drawString("Governor: " + gov, 2, 15+15*r++);
g.drawString("of : " + gov.myOrder(), 2, 15+15*r++);
r++;
}
g.drawString("Knowledge Library", 2, 15+15*r++);
for (int i = 0; i < library.getCapacity(); i++) {
@SuppressWarnings("rawtypes")
final KnowledgeBlock kb = library.getKnowledge(i);
if (kb == null) {
if (i == 0) g.drawString("(empty)", 2, 15+15*r++);
break;
}
g.drawString(kb.toString(), 2, 15+15*r++);
}
} |
02f418ea-ce2e-4117-abab-52cf48a8fc07 | 1 | public static List<ModelFiledDesc> getModelFiledByTableColumn(TableDesc tableDesc){
List<ModelFiledDesc> result = new ArrayList<ModelFiledDesc>();
Iterator<TableColumnDesc> it = tableDesc.getTable().iterator();
while (it.hasNext()) {
ModelFiledDesc mfd = new ModelFiledDesc();
TableColumnDesc tcd = it.next();
mfd.setFiledName(getFiledName(tcd.getField()));
mfd.setTableFiledName(tcd.getField());
String type[] = tcd.getType().split("\\(");
mfd.setFiledType(map.get(type[0]));
result.add(mfd);
}
return result;
} |
947d38f4-d440-441b-970a-ab699ffcd4eb | 3 | private void showAccounts(String instanceUrl, String accessToken,
PrintWriter writer) throws ServletException, IOException {
HttpClient httpclient = new HttpClient();
GetMethod get = new GetMethod(instanceUrl
+ "/services/data/v20.0/query");
// set the token in the header
get.setRequestHeader("Authorization", "OAuth " + accessToken);
// set the SOQL as a query param
NameValuePair[] params = new NameValuePair[1];
params[0] = new NameValuePair("q",
"SELECT Name, Id from Account LIMIT 100");
get.setQueryString(params);
try {
httpclient.executeMethod(get);
if (get.getStatusCode() == HttpStatus.SC_OK) {
// Now lets use the standard java json classes to work with the
// results
try {
JSONObject response = new JSONObject(
new JSONTokener(new InputStreamReader(
get.getResponseBodyAsStream())));
System.out.println("Query response: "
+ response.toString(2));
// writer.write(response.getString("totalSize")
writer.write(response.getInt("totalSize")
+ " record(s) returned\n\n");
JSONArray results = response.getJSONArray("records");
for (int i = 0; i < results.length(); i++) {
writer.write(results.getJSONObject(i).getString("Id")
+ ", "
+ results.getJSONObject(i).getString("Name")
+ "\n");
}
writer.write("\n");
} catch (JSONException e) {
throw new ServletException(e);
}
}
} finally {
get.releaseConnection();
}
} |
28b43499-33c0-4195-9c04-d0aa33c37a0c | 5 | public void geraCruzCelulasPossiveis() {
jogandoEmCruz = true;
jogandoEmLinha = false;
podeMudarPivo = false;
int cAbaixo = celulaPivo + 10;
int cAcima = celulaPivo - 10;
int cDireita = celulaPivo + 1;
int cEsquerda = celulaPivo -1;
if(cAbaixo > 99)
cAbaixo = celulaPivo;
if(cAcima < 0)
cAcima = 0;
if( (cDireita%10) == 0)
cDireita = cDireita -1;
if(cEsquerda < 0)
cEsquerda = celulaPivo;
else if(Integer.reverse(cEsquerda)>=90)
cEsquerda += 1;
celulasPossiveis[0] = cAcima;
celulasPossiveis[1] = cAbaixo;
celulasPossiveis[2] = cDireita;
celulasPossiveis[3] = cEsquerda;
} |
765df978-6344-415d-b472-29bebdd0ca60 | 3 | public static void main(String[] args) {
try {
MainWin window = new MainWin();
for(String s : args )
{
if( s.compareTo("--hide") == 0 ) //$NON-NLS-1$
{
window.hiddenAtStart=true;
}
}
window.open();
} catch (Exception e) {
e.printStackTrace();
}
} |
5be5d48c-d16e-46fd-b2a7-d5c5261f18c8 | 7 | public void paint(Graphics g) {
if (!v.forme.equals("")) {
int p1X = (int) v.p1.getX();
int p1Y = (int) v.p1.getY();
int p2X = (int) v.p2.getX();
int p2Y = (int) v.p2.getY();
listeDessin.add(new Donnee(v.forme, v.c, p1X, p1Y, p2X, p2Y));
for (int i = 0; i < listeDessin.size(); i++) {
g.setColor(listeDessin.get(i).couleur.getCouleur());
if (listeDessin.get(i).forme.equals("Rectangle"))
g.fillRect(listeDessin.get(i).p1x, listeDessin.get(i).p1y, Math.abs(listeDessin.get(i).p1x - listeDessin.get(i).p2x),
Math.abs(listeDessin.get(i).p1y - listeDessin.get(i).p2y));
if (listeDessin.get(i).forme.equals("Carre"))
g.fillRect(listeDessin.get(i).p1x, listeDessin.get(i).p1y, Math.abs(listeDessin.get(i).p1x - listeDessin.get(i).p2x),
Math.abs(listeDessin.get(i).p1x - listeDessin.get(i).p2x));
if (listeDessin.get(i).forme.equals("Rond"))
g.fillOval(listeDessin.get(i).p1x, listeDessin.get(i).p1y, Math.abs(listeDessin.get(i).p1x - listeDessin.get(i).p2x),
Math.abs(listeDessin.get(i).p1x - listeDessin.get(i).p2x));
if (listeDessin.get(i).forme.equals("Oval"))
g.fillOval(listeDessin.get(i).p1x, listeDessin.get(i).p1y, Math.abs(listeDessin.get(i).p1x - listeDessin.get(i).p2x),
Math.abs(listeDessin.get(i).p1y - listeDessin.get(i).p2y));
if (listeDessin.get(i).forme.equals("Ligne"))
g.drawLine(listeDessin.get(i).p1x, listeDessin.get(i).p1y,listeDessin.get(i).p2x, listeDessin.get(i).p2y);
}
}
} |
246730f1-2a3a-4f33-9fb6-680703d7c84e | 4 | public int Delete(ArrayList<QueryCriteria> criteria) {
this.DBConn = new DBHelper();
String whereClause = "", QueryStr;
for (int i = 0; i < criteria.size(); i++) {
if (!whereClause.equals("")) {
whereClause += " and ";
}
whereClause += criteria.get(i).formatCriteria();
}
if (whereClause.equals("")) {
whereClause = "1";
}
QueryStr = "DELETE FROM " + this.table + " WHERE " + whereClause;
int result = this.DBConn.executeUpdate(QueryStr);
try {
this.DBConn.conn.close();
} catch (SQLException ex) {
Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
} |
91813546-3d1b-46c3-ba03-164e78133f1d | 6 | private int concurDataSizeRecv(Map<Integer, Integer> observed, Iterator<XORFragment> left) throws InsufficientFragmentsException {
if(left.hasNext()) {
// Process the next fragment
XORFragment frag = left.next();
int fragValue = frag.getClusterDataSize();
Integer count = observed.get(fragValue);
if(count == null) {
// This is the first observation of this value
observed.put(fragValue, 1);
} else {
// Increase the count of this observation
++count;
//observed.put(fragValue, count); // Not necessary since count is a reference to the Integer object already in the map
}
// Proceed with recursion
return concurDataSizeRecv(observed, left);
} else {
// There are no more fragments to inspect
// Find the most observed value
Map.Entry<Integer, Integer> winner = null;
for(Map.Entry<Integer, Integer> observation : observed.entrySet()) {
if(winner == null) {
winner = observation;
} else if(observation.getValue() > winner.getValue()) {
winner = observation;
}
// else: Do nothing and proceed to next map entry
}
// We're done here
if(winner == null) {
// There were no fragments in the cluster to begin with!
throw new InsufficientFragmentsException(0);
} else {
// This is the end of recursion
return winner.getKey();
}
}
} |
a0d4498a-8f27-4e68-bca1-f346e860de85 | 2 | public boolean hasAlpha() {
return hasAlphaChannel() ||
paletteA != null || transPixel != null;
} |
c7a8e071-ee0c-4121-a12d-3a9ad2b32dcc | 8 | public void setup() {
size(1300, 700, GLConstants.GLGRAPHICS);
smooth();
col1 = color(255, 247, 236);
col2 = color(254, 232, 200);
col3 = color(253, 212, 158);
col4 = color(253, 212, 158);
col5 = color(252, 141, 89);
col6 = color(239, 101, 72);
col7 = color(215, 48, 31);
col8 = color(179, 0, 0);
col9 = color(127, 0, 0);
tempColor0 = color(247, 252, 253);
tempColor1 = color(224, 236, 244);
tempColor2 = color(191, 211, 230);
tempColor3 = color(158, 188, 218);
tempColor4 = color(140, 150, 198);
tempColor5 = color(140, 107, 177);
tempColor6 = color(136, 65, 157);
tempColor7 = color(110, 1, 107);
font = loadFont("Nilland-48.vlw");
cp5 = new ControlP5(this);
map = new UnfoldingMap(this, 0, 0, 900, height - 25);
// Show map around the location in the given zoom level.
map.zoomAndPanTo(new Location(38.951252f, -102.26932f), 4);
map.setBackgroundColor(240);
// Add mouse and keyboard interactions
MapUtils.createDefaultEventDispatcher(this, map);
states = GeoJSONReader.loadData(this, "states-20m.json");
stateMarkers = MapUtils.createSimpleMarkers(states);
map.addMarkers(stateMarkers);
font = loadFont("Nilland-48.vlw");
climateData = loadStrings("climate_by_states.csv");
crimeData = loadStrings("CrimeStatebyState.csv");
popData = loadStrings("pop.csv");
latLonData = loadStrings("state_latlon.csv");
climateArray = new Climate[climateData.length];
crimeArray = new ArrayList<Crime>();
// crimeArray = new Crime[crimeData.length - 1];
popArray = new Population[popData.length - 1];
latLonArray = new StateLatLon[latLonData.length];
locationArray = new Location[latLonData.length];
simplePointArray = new SimplePointMarker[latLonData.length];
screenPositionArray = new ScreenPosition[latLonData.length];
for (int i = 0; i < climateData.length; i++) {
climateChunk = split(climateData[i], ",");
climateArray[i] = new Climate(this, climateChunk[0],
Float.valueOf(climateChunk[2]));
// println("State: " + climateArray[i].getState());
// println("Average temperature: " + climateArray[i].getTempC());
// println();
}
for (int i = 1; i < crimeData.length - 1; i++) {
crimeChunk = split(crimeData[i], ",");
if (Integer.parseInt(crimeChunk[3]) >= 2000)
crimeArray.add(new Crime(this, crimeChunk[0], crimeChunk[1],
crimeChunk[2], Integer.parseInt(crimeChunk[3]), Integer
.parseInt(crimeChunk[4])));
}
for (int i = 0; i < crimeArray.size(); i++) {
// Crime crime = crimeArray.get(i);
// println("State: " + crime.getState());
// println("Type of Crime: " + crime.getCrimeType());
// println("Crime: " + crime.getCrime());
// println("Year: " + crime.getYear());
// println("Count: " + crime.getCount());
// println();
}
for (int i = 1; i < popData.length; i++) {
popChunk = split(popData[i], ",");
popArray[i - 1] = new Population(this, popChunk[4],
Integer.parseInt(popChunk[6]),
Integer.parseInt(popChunk[7]),
Integer.parseInt(popChunk[8]),
Integer.parseInt(popChunk[9]),
Integer.parseInt(popChunk[10]),
Integer.parseInt(popChunk[11]));
}
for (int i = 0; i < popArray.length; i++) {
popArray[i].setAverage(popArray[i].averagePopulation());
}
for (int i = 0; i < latLonData.length; i++) {
latLonChunk = split(latLonData[i], ",");
latLonArray[i] = new StateLatLon(this, latLonChunk[0],
Double.parseDouble(latLonChunk[1]),
Double.parseDouble(latLonChunk[2]));
}
// for (int i = 0; i < latLonArray.length; i++) {
// println("State: " + latLonArray[0].getState());
// println("Latitude: " + latLonArray[1].getLat());
// println("Longitude: " + latLonArray[2].getLon());
// println();
// }
for (int i = 0; i < locationArray.length; i++) {
locationArray[i] = new Location(latLonArray[i].getLat(),
latLonArray[i].getLon());
simplePointArray[i] = new SimplePointMarker(locationArray[i]);
}
// map.addMarkers(simplePointArray);
// for (int i = 0; i < popArray.length; i++) {
// println("State: " + popArray[i].getState());
// println("00: " + popArray[i].getP0());
// println("01: " + popArray[i].getP1());
// println("02: " + popArray[i].getP2());
// println("03: " + popArray[i].getP3());
// println("04: " + popArray[i].getP4());
// println("05: " + popArray[i].getP5());
// println();
// }
crimeTypeBox = cp5.addCheckBox("Type of Crime", 1100, 120)
.setSize(15, 15).addItem("Violent Crime", 0)
.addItem("Property Crime", 1);
crimeBox = cp5.addListBox("Crime", 1050, 220, 180, 120);
crimeBox.addItem("Murder and nonnegligent Manslaughter", 0);
crimeBox.addItem("Forcible rape", 1);
crimeBox.addItem("Robbery", 2);
crimeBox.addItem("Aggravated assault", 3);
crimeBox.addItem("Burglary", 4);
crimeBox.addItem("Larceny-theft", 5);
crimeBox.addItem("Motor vehicle theft", 6);
// yearBox = cp5.addListBox("Year", 1050, 420, 180, 120);
// yearBox.addItem("2000", 0);
// yearBox.addItem("2001", 1);
// yearBox.addItem("2002", 2);
// yearBox.addItem("2003", 3);
// yearBox.addItem("2004", 4);
// yearBox.addItem("2005", 5);
//
// tempSlider = cp5.addSlider("A.A. Temperature").setPosition(950, 620)
// .setSize(150, 15).setRange(-10, 30);
} |
5305520a-8f99-43de-8f3d-24d763ddac33 | 0 | public void setOrder(String order) {
this.order = order;
} |
817e7714-bd09-47dd-8f8f-df321ab11d2c | 2 | public List<Planet> NotMyPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.Owner() != 1) {
r.add(p);
}
}
return r;
} |
3c3b1f91-467b-49dd-b049-24b6f7c27400 | 2 | private static String loadShader(String fileName)
{
StringBuilder shaderSource = new StringBuilder();
BufferedReader shaderReader = null;
try
{
shaderReader = new BufferedReader(new FileReader("./res/shaders/" + fileName));
String line;
while((line = shaderReader.readLine()) != null)
{
shaderSource.append(line).append("\n");
}
shaderReader.close();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
return shaderSource.toString();
} |
d11f0e26-2fc1-4826-a4ce-657791150929 | 9 | private void findScripture() {
boolean extracted = true;
extractChapterWord();
while (extracted == true) {
extracted = bbbcvv();
//This series of if statements check for the most complex to the
//least complex of possible scripture statements. When one is
//found, then it should break the nest, and the loop should restart
if (!extracted) {
extracted = bbbcv();
if (!extracted) {
extracted = bbbc();
if (!extracted) {
extracted = bbcvv();
if (!extracted) {
extracted = bbcv();
if (!extracted) {
extracted = bbc();
if (!extracted) {
extracted = bcvv();
if (!extracted) {
extracted = bcv();
if (!extracted) {
extracted = bc();
}
}
}
}
}
}
}
}
}
} |
7c8c509e-ffd9-4acb-adde-13ddb91304c6 | 9 | public static void DFSTest(WUGraph g, WUGraph t, DFSVertex[] vertArray) {
int[][] maxOnPath;
Neighbors neigh;
int i, j;
System.out.println("Testing the tree.");
maxOnPath = new int[VERTICES][VERTICES];
for (i = 0; i < VERTICES; i++) {
for (j = 0; j < VERTICES; j++) {
vertArray[j].visited = false;
}
DFS(t, vertArray[i], null, maxOnPath[i], -MAXINT);
for (j = 0; j < VERTICES; j++) {
if (!vertArray[j].visited) {
tree = false;
}
}
if (!tree) {
return;
}
}
// for (i = 0; i < vertArray.length; i++) {
// for (j = 0; j < vertArray.length; j++) {
// System.out.print(" " + maxOnPath[i][j]);
// }
// System.out.println();
// }
for (i = 0; i < VERTICES; i++) {
neigh = g.getNeighbors(vertArray[i]);
if (neigh != null) {
for (j = 0; j < neigh.neighborList.length; j++) {
int v = ((DFSVertex) neigh.neighborList[j]).number;
if (neigh.weightList[j] < maxOnPath[i][v]) {
minTree = false;
}
}
}
}
} |
c21f974e-ab92-4d6c-baa7-71524374c916 | 3 | public void paintComponent(Graphics g) {
super.paintComponent(g); // fill with background color.
g.setFont(bigFont);
g.setColor(Color.GREEN);
g.drawString(message, 10, getHeight() - 10);
// Draw labels for the two sets of cards.
g.drawString("Dealer's Cards:", 10, 23);
g.drawString("Your Cards:", 10, 153);
// Draw dealer's cards. Draw first card face down if
// the game is still in progress, It will be revealed
// when the game ends.
g.setFont(smallFont);
if (gameInProgress)
drawCard(g, null, 10, 30);
else
drawCard(g, dealerHand.getCard(0), 10, 30);
for (int i = 1; i < dealerHand.getCardCount(); i++)
drawCard(g, dealerHand.getCard(i), 10 + i * 90, 30);
// Draw the user's cards.
for (int i = 0; i < playerHand.getCardCount(); i++)
drawCard(g, playerHand.getCard(i), 10 + i * 90, 160);
} // end paint(); |
f896b4c5-dcbd-4bf8-afb4-e3a41cb3f3ab | 8 | public static CellFormat fromPatternString( String pattern )
{
if( (null == pattern) || "".equals( pattern ) || "General".equalsIgnoreCase( pattern ) )
{
return new GeneralCellFormat();
}
String[] pats = pattern.split( ";" );
String tester = StringTool.convertPatternExtractBracketedExpression( pats[0] );
if( tester.matches( ".*(((y{1,4}|m{1,5}|d{1,4}|h{1,2}|s{1,2}).*)+).*" ) )
{
String string;
if( pats.length > 3 )
{
string = StringTool.convertPatternFromExcelToStringFormatter( pats[3], false );
}
else
{
string = "%s";
}
return new DateCellFormat( StringTool.convertDatePatternFromExcelToStringFormatter( tester ), string );
}
String positive;
String negative;
String zero;
String string;
positive = StringTool.convertPatternFromExcelToStringFormatter( pats[0], false );
negative = StringTool.convertPatternFromExcelToStringFormatter( pats[((pats.length > 1) ? 1 : 0)], true );
if( pats.length > 2 )
{
zero = StringTool.convertPatternFromExcelToStringFormatter( pats[2], false );
}
else
{
zero = positive;
}
if( pats.length > 3 )
{
string = StringTool.convertPatternFromExcelToStringFormatter( pats[3], false );
}
else
{
string = "%s";
}
return new NumberCellFormat( positive, negative, zero, string );
} |
735690bc-a981-43fd-a754-e5c4e458cb84 | 8 | public boolean equals(PixImage image) {
int width = getWidth();
int height = getHeight();
if (image == null ||
width != image.getWidth() || height != image.getHeight()) {
return false;
}
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (! (getRed(x, y) == image.getRed(x, y) &&
getGreen(x, y) == image.getGreen(x, y) &&
getBlue(x, y) == image.getBlue(x, y))) {
return false;
}
}
}
return true;
} |
a60a58cb-f1b5-404c-b77b-b04825f1284f | 5 | public ArrayList<Integer> getRow(int rowIndex) {
//store the result
ArrayList<Integer> a = new ArrayList<>();
//store all the elements
int[] b = new int[rowIndex + 1];
if (rowIndex < 0) {
return a;
}
//the rowIndex is 3, the b.size is 4
for (int i = 0; i < rowIndex + 1; i++) {
//every time the first will be 1
b[0] = 1;
//start from the second row
if (i > 0) {
//start from the third row
//calculate from end to the begin, based on the change flow
for (int j = i - 1; j > 0; j--) {
b[j] = b[j] + b[j - 1];
}
b[i] = 1;
}
}
//set all into the list
for (int i = 0; i < b.length; i++) {
a.add(b[i]);
}
return a;
} |
b53db656-7d6c-4152-9023-d9dadba42b1c | 1 | List<Tile> getTiles(List<Component> cmps) {
List<Tile> ts = new ArrayList<Tile>();
for (Component c : cmps) ts.add(tiles.get(c));
return ts;
} |
34e06035-c295-4390-a407-f1a21c0b6e6c | 9 | private void jToggleButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton3ActionPerformed
//Agregar Clase al Plan
boolean ver = false;
if (this.getTemp().getClases().isEmpty()) {//si es diferente de 0 verificamos
for (int i = 0; i < this.getTemp().getClases().size(); i++) {//inicio for
if (this.getTemp().getClases().get(i).getNombre().equals(this.tf_nombreClase.getText())) {//fin if
ver = true;
}//fin if
}//fin for
}//fin if
if (ver == false) {//sin no agregamos la calse al plan
if (tf_nombreClase.getText().equals("")) {
JOptionPane.showMessageDialog(jd_ingresarClases, "No se ha ingresado Nombre de la Clase");
} else if (this.tf_codigoClase.getText().equals("")) {
JOptionPane.showMessageDialog(jd_ingresarClases, "No se ha ingresado Codigo de la Clase");
} else if (this.tf_unidadClase.getText().equals("")) {
JOptionPane.showMessageDialog(jd_ingresarClases, "No se ha ingresado Unidades Valorativas");
} else {
this.clase_temp.setNombre(this.tf_nombreClase.getText());
this.clase_temp.setCodigo(this.tf_codigoClase.getText());
this.clase_temp.setUnidades(Integer.parseInt(this.tf_unidadClase.getText()));
if(this.Lista_Requisitos.isEmpty()==false){
for (int i = 0; i <this.Lista_Requisitos.size(); i++) {
this.getClase_temp().setRequisitos(this.Lista_Requisitos.get(i));
}//fin for
}//si no esta vacia requisitos
this.getTemp().setClases(this.getClase_temp());
this.cb_requisitos.addItem(this.getClase_temp());
JOptionPane.showMessageDialog(jd_ingresarClases, "Se ha agregado la clase \n" + this.tf_nombreClase.getText());
/*
* Limpar Textos
*/
this.tf_codigoClase.setText("");
this.tf_nombreClase.setText("");
this.tf_unidadClase.setText("");
this.clase_temp = new Clase();//limpiamos memoria
this.Lista_Requisitos.clear();
}
} else {//si ya esta en la calse no ingresamos claae y mandamos mensaje al usuario
JOptionPane.showMessageDialog(jd_ingresarClases, "Ya has ingresado esta clase anteriormente");
}
}//GEN-LAST:event_jToggleButton3ActionPerformed |
0179fdb2-a172-4d8a-84de-7eeb3052bdb0 | 8 | public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
System.out.println(tree.isEmpty());
tree.setRoot(new Node(7, null, 'c'));
System.out.println(tree.root());
tree.setRoot(new Node(8, null, 'd'));
System.out.println(tree.root());
tree.addLeft(tree.root(), new Node(10, null, 'V'));
System.out.println(tree);
tree.addLeft(tree.root().getLeft(), new Node(11, null, 'p'));
System.out.println(tree);
tree.addRight(tree.root(), new Node(12, null, 'd'));
System.out.println(tree);
tree.addRight(tree.root().getRight(), new Node(2, null, 'a'));
System.out.println(tree);
tree.addRight(tree.root().getRight().getRight(), new Node(1, null, 'b'));
System.out.println(tree);
try {
tree.replace(new Node(1, null, 'b'), 'd');
} catch (Exception e) {
}
System.out.println(tree);
System.out.println(tree.hasRight(tree.root()));
System.out.println(tree.hasLeft(tree.root()));
System.out.println(tree.hasLeft(tree.root().getLeft().getLeft()));
System.out.println(tree.hasRight(tree.root().getLeft().getLeft()));
System.out.println(tree.hasRight(tree.root().getRight()));
System.out.println(tree.hasLeft(tree.root().getRight()));
System.out.println(tree.isRoot(tree.root()));
System.out.println(tree.isRoot(tree.get(new Node(12, null, 'd'))));
System.out.println(tree.isExternal(tree.root()));
System.out.println(tree.isExternal(tree.root().getRight().getRight()
.getRight()));
System.out.println(tree.isInternal(tree.root()));
System.out.println(tree.isInternal(tree.root().getRight().getRight()
.getRight()));
try {
System.out.println(tree.left(tree.root()));
} catch (Exception e) {
}
try {
System.out.println(tree.right(tree.root()));
} catch (Exception e) {
}
try {
System.out.println(tree.parent(tree.root().getRight()));
} catch (Exception e) {
}
tree.setRoot(new Node(1, null, 'a'));
System.out.println(tree);
Iterator<Node> it = tree.iterator();
while (it.hasNext())
System.out.println(it.next());
System.out.println();
for (Node n : tree.positions())
System.out.println(n);
System.out.println();
for (Node n : tree.children(tree.root()))
System.out.println(n);
System.out.println();
Iterable<Node> noChildren = tree.children(tree.root().getLeft().getLeft());
for (Node n : noChildren)
System.out.println(n);
} |
1ab7aa87-9b9f-4043-b00d-584f5b7e2fab | 7 | private static void assignClientToVehicle(Individual child, Individual parent1, Individual parent2, int[] assignedVehicle, int[] numberOfCustomerServed,int period)
{
for(int client=0; client<problemInstance.customerCount;client++)
{
if(child.periodAssignment[period][client]==false) continue;
int vehicle1 = RouteUtilities.assignedVehicle(parent1, client, period, problemInstance);
int vehicle2 = RouteUtilities.assignedVehicle(parent2, client, period, problemInstance);
int chosenVehicle=500000;
if(vehicle1==-1 && vehicle2==-1) System.out.println("ERROR!!!! NEVER SHOULD HAPPEN!!!!!!!!!! in varied edge recombination op....");
else if(vehicle1==-1)
chosenVehicle = vehicle2;
else if(vehicle2==-1)
chosenVehicle = vehicle1;
else
{
// if(vehicle1!=vehicle2)
// System.out.println();
int coin = Utility.randomIntInclusive(1);
if(coin==0) chosenVehicle = vehicle1;
else chosenVehicle = vehicle2;
}
assignedVehicle[client]=chosenVehicle;
numberOfCustomerServed[chosenVehicle]++;
}
} |
19aa876b-effe-4301-b009-556d8328647e | 2 | public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choise;
System.out.println("Enter 1 to run test with java.util.concurrent");
System.out.println("Enter 2 to run test without java.util.concurrent");
choise = scanner.nextInt();
switch (choise) {
case 1:
concurrentTest();
break;
case 2:
noConcurrentTest();
break;
default:
System.out.println("Wrong option!");
break;
}
} |
564c2125-ba83-46b2-a8ef-b91d224ce223 | 5 | public static void main( String [ ] args )
{
RedBlackTree<Integer> t = new RedBlackTree<>( );
final int NUMS = 400000;
final int GAP = 35461;
System.out.println( "Checking... (no more output means success)" );
for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS )
t.insert( i );
if( t.findMin( ) != 1 || t.findMax( ) != NUMS - 1 )
System.out.println( "FindMin or FindMax error!" );
for( int i = 1; i < NUMS; i++ )
if( !t.contains( i ) )
System.out.println( "Find error1!" );
} |
b9c2e960-c17f-437e-8f04-dc8ea6817bc1 | 8 | public static void main(String[] args) {
int i, rotate_x = 0, rotate_y = 60, rotate_z = 0;
for (i = 0; i < args.length; ++i) {
if (!args[i].startsWith("--rotate-x")) {
rotate_x = Integer.parseInt(args[i].substring(11));
} else if (!args[i].startsWith("--rotate-y")) {
rotate_y = Integer.parseInt(args[i].substring(11));
} else if (!args[i].startsWith("--rotate-z")) {
rotate_z = Integer.parseInt(args[i].substring(11));
} else if (!args[i].startsWith("--help")) {
System.out.println("[--rotage-x=degrees] "
+ "[--rotage-y=degrees] " + "[--rotage-z=degrees]");
return;
}
}
Clutter.init();
Stage stage = Stage.getDefault();
stage.setListener(new StageAdapter(){
public boolean onEvent(Stage s, Event event) {
switch (event.getType()) {
case Event.TYPE_BUTTON_PRESS: {
Actor actor;
float x = ((ButtonEvent)event).getX();
float y = ((ButtonEvent)event).getY();
actor = s.getActorAtPos(Stage.PICK_ALL, x, y);
Point point = actor.transformStagePoint(x, y);
if (point != null) {
String txt;
if (actor == test_rectangle) {
txt = String.format("Click on rectangle\n"
+ "Screen coords: [%d, %d]\n"
+ "Local coords : [%d, %d]", (int) x,
(int) y, (int) point.x, (int) point.y);
} else {
txt = String.format("Click on stage\n"
+ "Screen coords: [%d, %d]\n"
+ "Local coords : [%d, %d]", (int) x,
(int) y, (int) point.x, (int) point.y);
}
label.setText(txt);
} else
label.setText("Unprojection failed.");
}
break;
default:
break;
}
return false;
}
});
stage.setColor(Color.BLACK);
stage.setSize(640, 480);
Rectangle rect = new Rectangle(Color.WHITE);
rect.setSize(RECT_W, RECT_H);
rect.setPosition(RECT_L, RECT_T);
rect.setRotation(new Rotation(Rotation.X_AXIS, rotate_x, 0, 0,
0));
rect.setRotation(new Rotation(Rotation.Y_AXIS, rotate_y, 0, 0,
0));
rect.setRotation(new Rotation(Rotation.Z_AXIS, rotate_z, 0, 0,
0));
stage.add(rect);
test_rectangle = rect;
String txt = String.format("Rectangle: L %d, R %d, T %d, B %d\n"
+ "Rotation : x %d, y %d, z %d", RECT_L, RECT_L + RECT_W,
RECT_T, RECT_T + RECT_H, rotate_x, rotate_y, rotate_z);
Text label0 = new Text("Mono 8pt", txt);
label0.setColor(Color.WHITE);
label0.setPosition(10, 10);
stage.add(label0);
Text label = new Text("Mono 8pt", "Click around!");
label.setColor(Color.BLUE);
label.setPosition(10, 50);
stage.add(label);
stage.showAll();
Clutter.mainStart();
} |
59ac81df-be9b-425d-ac4d-4b40de68d2b3 | 1 | private static boolean getKeyDown(int keyCode)
{
return getKey(keyCode) && !lastKeys[keyCode];
} |
ab47eda4-ada2-48d5-9fe3-57f579564057 | 0 | public int getHeight() {
return height;
} |
11752c97-95fa-499b-be4f-333d2f69a147 | 6 | @Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == DELIVERY_PACKET_ID) {
return Integer.class;
} else if (columnIndex == MEMBER_NAME) {
return String.class;
} else if (columnIndex == EVENT) {
return String.class;
} else if (columnIndex == DELIVERY_DATE) {
return Date.class;
} else if (columnIndex == EXPECTED_RETURN_DATE) {
return Date.class;
} else {
return Object.class;
}
} |
73bb8ee4-297f-42d9-a1f1-6a9741b192ea | 7 | public final Connection getConn() throws ReportTestException, ClassNotFoundException, SQLException {
if (conn != null) {
return conn;
}
//busca as configurações do banco de dados
BancoDadosDao dao = new BancoDadosDao();
Projeto p = DataManager.getInstance().getProjeto();
BancoDados banco = dao.getBancoDados(p.getIProjeto());
if (banco == null) {
throw new ReportTestException("Não existe um banco de dados configurado para este projeto!");
}
//obtém uma conexão com o banco de dados
String driverClass = banco.getDriverClass();
String user = banco.getUser();
String pass = banco.getPass();
if (driverClass == null || user == null || driverClass.trim().length() == 0 || user.trim().length() == 0) {
throw new ReportTestException("Existem parâmetros de conexão com o banco de dados que não foram defidos! Favor analisar as configurações do sistema!");
}
String urlConnection = banco.getConnectionUrl();
Class.forName(driverClass);
Properties prop = new Properties();
prop.put("user", user);
prop.put("password", pass == null ? "" : pass.trim());
conn = DriverManager.getConnection(urlConnection, prop);
return conn;
} |
a07a3594-fff8-4202-9244-e7df8999b20b | 9 | public static void gerenciarClientes() {
int opcao;
String nome;
String cpf;
String telefone;
String endereco;
int anoCNH;
int anoValidadeCNH;
ArrayList<Cliente> clientes;
while (true) {
opcao = menu.menuClientes();
switch (opcao) {
case 1:
System.out.print("Digite o cpf :");
cpf = menu.scan.next();
System.out.print("Digite o nome :");
nome = menu.scan.next();
System.out.print("Digite o ano da CNH :");
anoCNH = menu.scan.nextInt();
System.out.print("Digite o ano da validade da CNH :");
anoValidadeCNH = menu.scan.nextInt();
Cliente cliente = new Cliente(nome, cpf, anoCNH, anoValidadeCNH);
loja.adcionarCliente(cliente);
break;
case 2:
System.out.print("Digite o cpf :");
cpf = menu.scan.next();
try {
loja.existeCliente(cpf);
loja.removerCliente(cpf);
} catch (NaoEncontradoException ex) {
System.out.println(ex + ": Cliente");
}
break;
case 3:
System.out.print("Digite o cpf :");
cpf = menu.scan.next();
try {
loja.existeCliente(cpf);
System.out.print("Digite o cpf :");
cpf = menu.scan.next();
System.out.print("Digite o nome :");
nome = menu.scan.next();
System.out.print("Digite a telefone :");
telefone = menu.scan.next();
System.out.print("Digite a endereço :");
endereco = menu.scan.next();
System.out.print("Digite o ano da CNH :");
anoCNH = menu.scan.nextInt();
System.out.print("Digite o ano de validade da CNH :");
anoValidadeCNH = menu.scan.nextInt();
loja.editarCliente(cpf, nome, telefone, endereco, anoCNH, anoValidadeCNH);
} catch (NaoEncontradoException ex) {
System.out.println(ex + ": Cliente");
}
break;
case 4:
clientes = loja.getClientes();
for (Cliente c : clientes) {
System.out.println("Cpf: " + c.getCpf());
System.out.println("Nome: " + c.getNome());
System.out.println("Telefone: " + c.getTelefone());
System.out.println("Endereço: " + c.getEndereco());
System.out.println("Ano CNH: " + c.getAnoCNH());
System.out.println("Ano validade CNH: " + c.getAnoValidadeCNH());
}
break;
case 5:
return;
}
}
} |
225918f0-ac12-4093-b0cb-360ae5900088 | 0 | public String proposeFilename(String filename, Serializable structure) {
return filename;
} |
1a4d6dbf-bfe3-4c7f-aa92-fad65bf812ed | 1 | @Override
public DateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException
{
String text = jsonParser.getText();
try
{
return dateTimeFormatter.parseDateTime(text);
}
catch (Throwable throwable)
{
throw new InvalidFormatException(throwable.getMessage(), text, String.class);
}
} |
23318591-28ed-4c3c-afd6-97ed36e7df0d | 5 | public void topList(String senderName, DB_Timers timer) {
this.plugin.util.messagePlayer(senderName, "Top " + this.plugin.top_amount + " Times:");
this.plugin.util.messagePlayer(senderName, "Timer: " + timer.getTimername());
Integer timerID = timer.getId();
HashMap<String, String> timerRanks = this.plugin.rankList.get(timerID);
if (timerRanks != null && timerRanks.size() > 0) {
int i = 0;
for (String playerName : timerRanks.keySet()) {
String[] playerInfo = timerRanks.get(playerName).split(",");
String playerTime = this.plugin.util.formatTime(Integer.valueOf(playerInfo[1]));
if (this.plugin.compact_time) {
this.plugin.util.messagePlayer(senderName, " " + String.format("%02d", Integer.valueOf(playerInfo[0])) + " | " + playerTime + " | " + playerName);
}
else {
this.plugin.util.messagePlayer(senderName, " " + String.format("%02d", Integer.valueOf(playerInfo[0])) + " | " + playerName + " | " + playerTime);
}
i++;
if (i > (this.plugin.top_amount - 1)) {
break;
}
}
}
else {
this.plugin.util.messagePlayer(senderName, "No times found for " + timer.getTimername());
}
} |
c090e302-99b2-42ed-9764-d6138b19036e | 0 | public ArrayList<CompanyApplication> getCompanyApplications() {
return CompanyApplications;
} |
d516d88e-cb1c-473a-a58d-506ef9a483c6 | 1 | public void test_getValue_long() {
assertEquals(0, MillisDurationField.INSTANCE.getValue(0L));
assertEquals(1234, MillisDurationField.INSTANCE.getValue(1234L));
assertEquals(-1234, MillisDurationField.INSTANCE.getValue(-1234L));
try {
MillisDurationField.INSTANCE.getValue(((long) (Integer.MAX_VALUE)) + 1L);
fail();
} catch (ArithmeticException ex) {}
} |
6ae4d654-3876-41a3-a1ca-da1c32f4c269 | 6 | public static void main(String args[]) {
//<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(ConfiguraBanco1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ConfiguraBanco1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ConfiguraBanco1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ConfiguraBanco1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ConfiguraBanco1().setVisible(true);
}
});
} |
ab5482bc-b1ac-4864-9b30-45e6cbc9eeac | 6 | public int getNextWalkingDirection() {
if(wQueueReadPtr == wQueueWritePtr) return -1; // walking queue empty
int dir;
do {
dir = misc.direction(currentX, currentY, walkingQueueX[wQueueReadPtr], walkingQueueY[wQueueReadPtr]);
if(dir == -1) wQueueReadPtr = (wQueueReadPtr+1) % walkingQueueSize;
else if((dir&1) != 0) {
println_debug("Invalid waypoint in walking queue!");
resetWalkingQueue();
return -1;
}
} while(dir == -1 && wQueueReadPtr != wQueueWritePtr);
if(dir == -1) return -1;
dir >>= 1;
currentX += misc.directionDeltaX[dir];
currentY += misc.directionDeltaY[dir];
absX += misc.directionDeltaX[dir];
absY += misc.directionDeltaY[dir];
return dir;
} |
b9f06dbc-fa35-4c46-a788-4c10e9fc71c5 | 4 | @Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Connection connection;
String sqlString;
String url;
//连接数据库222.205.38.252
url = "jdbc:mysql://"+jtfipField.getText()+":3306/test?user=root&password=root";
ResultSet result;
try
{
Class.forName("com.mysql.jdbc.Driver"); //数据库连接并创建Statement
System.out.println("JDBC driver starts successfully!");
connection = DriverManager.getConnection(url);
System.out.println("MySQL connects successfully!");
statement = connection.createStatement();
}
catch (Exception e1)
{
System.out.println("数据库连接错误!");
// TODO: handle exception
System.out.print("ERROR!");
}
//从数据库中查找用户,比对密码
usernameString = jtf1.getText();
passwordString = jpf1.getPassword().toString();
sqlString = "select password from administrator where id = '"+jtf1.getText()+"'";
try {
result = statement.executeQuery(sqlString);
while(result.next())
{
pw = result.getString("password");
if(pw.equals(passwordString))
{
System.out.println("Login Success!");
new ViewSecurityAccount(true);
Login.jFrame.setVisible(false);
}
}
JOptionPane.showMessageDialog(null, "Username or Password incorrect!", "ERROR", JOptionPane.ERROR_MESSAGE);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} |
f4823e13-b638-425b-bd9a-53cbcd35585b | 8 | protected void processMouseMovedEvent(MouseEvent e) {
// let the tool tip show the current coordinates
setToolTipText("(" + format.format((e.getX() - origin.x) / xScale) + ", "
+ format.format(-(e.getY() - origin.y) / yScale) + ")");
e.translatePoint(-origin.x, -origin.y);
int x = e.getX();
int y = e.getY();
if (isEnabled()) {
Ellipse2D hp;
boolean b = false;
synchronized (data) {// lock "data"
if (!data.isEmpty()) {
for (DataSource ds : data) {
if (!ds.getHideHotSpot()) {
hp = ds.getHotSpot();
if (hp != null) {
linkHotSpotToHandle(hp);
if (handle.contains(x, y)) {
b = true;
break;
}
}
}
else {
Point2D p = ds.isProximate(x / xScale, y / yScale, Math.max(5 / xScale, 5 / yScale));
if (p != null) {
b = true;
break;
}
}
}
}
}
setCursor(b ? Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) : Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
e.consume();
} |
af02d76d-4100-4144-9f99-f4f64b84dddc | 1 | private void btnFnalizarCompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFnalizarCompraActionPerformed
VendaDAO dao = new VendaDAO();
venda.setCliente((Cliente)cbxCliente.getSelectedItem());
venda.setFormaPagamento((FormasPagamento) cbxTipoPagamento.getSelectedItem());
//venda.setHorario();
if(dao.Salvar(venda)){
JOptionPane.showMessageDialog(rootPane, "Venda Salva com Sucesso!");
}
}//GEN-LAST:event_btnFnalizarCompraActionPerformed |
c23ebcb7-aa74-4bd1-9690-fb49654a9cd3 | 8 | public void onInput(String input){
if (this.abortMessage != null && this.abortMessage.equalsIgnoreCase(input)){
this.abort();
return;
}
Node<? extends Conversation<? extends CommandSender>, T> node = this.nextNode.processInput(input);
if (node != null && (!node.isRecurring() || !node.getClass().equals(this.nextNode.getClass()))){
String prompt = node.getPromptText();
if (prompt != null){
this.getWith().sendMessage(prompt);
}
}
this.nextNode = node;
} |
a7eaaf42-5286-4627-b60c-46395a0865d9 | 1 | public Ticket in(Car car) {
if(isFull()) {
throw new ParkException("停车场已满,不能停车了。");
}
Ticket ticket = new Ticket(car.getCode());
this.carList.put(ticket, car);
return ticket;
} |
37a0ef8a-e9c9-469d-99ea-a6beb8cd62bb | 2 | public static NameNode NameNodeDesserial() {
File file = new File("namenode.out");
ObjectInputStream oin;
NameNode namenode = null;
try {
oin = new ObjectInputStream(new FileInputStream(file));
namenode = (NameNode) oin.readObject();
oin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return namenode;
} |
856ee7a7-cf44-4822-b275-b9857f179821 | 2 | public void addAxon(Integer startNeuronLayer, Integer startNeuronColumn,
Integer endNeuronLayer, Integer endNeuronColumn) {
if (startNeuronLayer >= neurons.size()
|| endNeuronLayer >= neurons.size()) {
throw new IllegalArgumentException(
"Start or End Layer equals not the size of the Perceptron.");
}
// TODO: Check Columns!
Neuron startNeuron = neurons.get(startNeuronLayer).get(
startNeuronColumn);
Neuron endNeuron = neurons.get(endNeuronLayer).get(endNeuronColumn);
new Axon(startNeuron, endNeuron, this.seedmin, this.seedmax); // the
// Connection
// between
// endNeuron
// an
// Axon
// is
// handled
// in
// the
// Axon
// Constructor
} |
e4ebc057-0557-4045-aa11-0c05fbbff378 | 9 | public void setVoisins () {
// Attribut a chaque Neuron du reseau ses voisins directs
ArrayList<Neuron> voisins;
for (int col = 0 ; col < colNumber ; col ++) {
for (int row = 0 ; row < rowNumber ; row ++) {
voisins = new ArrayList<Neuron>();
if(col < colNumber -1){
voisins.add(neurons.get(row).get(col + 1));
}
if(col > 0){
voisins.add(neurons.get(row).get(col - 1));
}
if(row == 0 && neurons.size() > 1){
voisins.add(neurons.get(row + 1).get(col));
}else if(row == neurons.size() -1 && neurons.size()> 1){
voisins.add(neurons.get(row - 1).get(col));
}else if(neurons.size()> 1){
voisins.add(neurons.get(row + 1).get(col));
voisins.add(neurons.get(row - 1).get(col));
}
neurons.get(row).get(col).setNeighbors(voisins);
}
}
} |
25dc8243-4ad0-438f-91d7-63b0407e7ccc | 1 | public static String unescapeDoubleQuotes(String string) {
if (string == null) { return null; }
String result = string.replaceAll("\\\\\\\"", "\\\"");
return result.replaceAll("\\\\\\\\", "\\\\");
} |
e82bb1c4-12ae-42ac-b2d3-a3525b59c3d9 | 8 | /* */ private void checkDirection(int tx, int ty)
/* */ {
/* 153 */ if (Core.activeClass == this)
/* 154 */ if (this.y < ty) {
/* 155 */ if (this.x > tx) {
/* 156 */ if (Math.abs(this.x - tx) > Math.abs(this.y - ty))
/* 157 */ this.image = Core.unitDirections.getTileImage(3);
/* */ else {
/* 159 */ this.image = Core.unitDirections.getTileImage(2);
/* */ }
/* */ }
/* 162 */ else if (Math.abs(this.x - tx) > Math.abs(this.y - ty))
/* 163 */ this.image = Core.unitDirections.getTileImage(1);
/* */ else {
/* 165 */ this.image = Core.unitDirections.getTileImage(2);
/* */ }
/* */
/* */ }
/* 169 */ else if (this.x > tx) {
/* 170 */ if (Math.abs(this.x - tx) > Math.abs(this.y - ty))
/* 171 */ this.image = Core.unitDirections.getTileImage(3);
/* */ else {
/* 173 */ this.image = Core.unitDirections.getTileImage(0);
/* */ }
/* */ }
/* 176 */ else if (Math.abs(this.x - tx) > Math.abs(this.y - ty))
/* 177 */ this.image = Core.unitDirections.getTileImage(1);
/* */ else
/* 179 */ this.image = Core.unitDirections.getTileImage(0);
/* */ } |
bb52fa2c-543a-4f0e-99f0-e11e9d38b7a8 | 8 | public static void convertFolderToBinary(String dir, boolean recursive)
{
File file = R2DFileUtility.getResource(dir);
if(!file.exists() || !file.isDirectory())
return;
R2DFileFilter filter = new R2DFileFilter();
for(File f : file.listFiles())
{
if(f.isFile() && filter.accept(file, f.getName()))
{
try
{
String localPath = R2DFileUtility.getRelativeFile(f).getPath();
R2DFileManager read = new R2DFileManager(localPath,null);
read.read();
f.renameTo(new File(f.getAbsolutePath()+".orig"));
R2DFileManager write = new R2DFileManager(localPath.substring(0,localPath.length()-4)+".bin",null);
write.setCollection(read.getCollection());
write.write();
} catch(IOException e)
{
throw new Remote2DException(e);
}
} else if(f.isDirectory() && recursive)
convertFolderToXML(R2DFileUtility.getRelativeFile(f).getPath(),recursive);
}
} |
b0e6382f-b90b-4bce-97c1-6047c7b5b5f7 | 5 | public static int getMethod(String item) {
if ("GET".equalsIgnoreCase(item)) {
return GET;
} else if ("POST".equalsIgnoreCase(item)) {
return POST;
} else if ("PUT".equalsIgnoreCase(item)) {
return PUT;
} else if ("DELETE".equalsIgnoreCase(item)) {
return DELETE;
} else if ("HEAD".equalsIgnoreCase(item)) {
return HEAD;
} else {
return 0;
}
} |
776aa1d8-7435-494e-942d-3cd1e741eeb2 | 2 | public boolean WolfAttack(int [] inTargets){ // carries out the lead wolf's murder. returns true if allowed
int TargetRole = PlayerRoles[inTargets[this.LeadWolf() - 1] - 1];
if ((TargetRole >= 3) || (TargetRole < (0))){
return false; // Target is either a wolf, or dead. This gamestate should be removed.
} else {
PlayerRoles[inTargets[this.LeadWolf() - 1] - 1] = -TargetRole;
TimeOfDeath[inTargets[this.LeadWolf() - 1] - 1] = RoundNum;
return true;
}
} |
7de5b9be-5cdc-46ef-b369-82bc2fd83897 | 1 | int addUninitializedType(final String type, final int offset) {
key.type = TYPE_UNINIT;
key.intVal = offset;
key.strVal1 = type;
key.hashCode = 0x7FFFFFFF & (TYPE_UNINIT + type.hashCode() + offset);
Item result = get(key);
if (result == null) {
result = addType(key);
}
return result.index;
} |
2f4e8273-4782-4b58-92ca-3f3f5a55dcaf | 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 Discarded)) {
return false;
}
Discarded other = (Discarded) object;
if ((this.itemId == null && other.itemId != null) || (this.itemId != null && !this.itemId.equals(other.itemId))) {
return false;
}
return true;
} |
c9d19758-42f8-4d9c-8fc7-e89b4fe9ac8a | 9 | public static String[] toStringRaw(ItemStack is) {
ArrayList<String> msg = new ArrayList<String>();
MaterialData md = is.getData();
msg.add("Item: " + md.getItemType().name() + "; Amt: " + Integer.toString(is.getAmount()) + "; Dur: " + Short.toString(is.getDurability()));
if( is.hasItemMeta() ) {
ItemMeta im = is.getItemMeta();
if( im.hasEnchants() ) {
Map<Enchantment,Integer> enchants = im.getEnchants();
for( Entry<Enchantment, Integer> enchant : enchants.entrySet() ) {
msg.add(" - " + enchant.getKey().getName() + " @ " + Integer.toString(enchant.getValue()));
}
}
if( im.hasDisplayName()) {
msg.add("Display Name: " + im.getDisplayName());
}
if( im.hasLore() ) {
ArrayList<String> lores = (ArrayList<String>)im.getLore();
for( String lore : lores ) {
msg.add("Lore: " + lore);
}
}
if( md.getItemType() == Material.ENCHANTED_BOOK ) {
EnchantmentStorageMeta esm = (EnchantmentStorageMeta)is.getItemMeta();
if( esm.hasStoredEnchants() ) {
Map<Enchantment,Integer> enchants = esm.getStoredEnchants();
for( Entry<Enchantment, Integer> enchant : enchants.entrySet() ) {
msg.add(" - " + enchant.getKey().getName() + " @ " + Integer.toString(enchant.getValue()));
}
}
}
}
return msg.toArray(new String[msg.size()]);
} |
75ab6467-ef6f-402e-96d3-48876847bcab | 4 | public void removeVertex( Vertex<T> v ) {
int pos = getVerticesIndexFor( v );
if ( pos == -1 ) {
throw new IllegalArgumentException( "vertex not found" );
}
this.numberOfVertices--;
this.vertices[pos] = null;
// now we need to go through the adjacency matrix and
// remove all edges incident on v. We do this by walking g
// alon the row and column for v in the adjacency matrix
for ( int i = 0; i < vertices.length; i++ ) {
if ( this.adjMatrix[pos][i] == 1 ) { // row check
this.adjMatrix[pos][i] = 0;
this.numberOfEdges--;
}
if ( this.adjMatrix[i][pos] == 1 ) { // column check
this.adjMatrix[i][pos] = 0;
this.numberOfEdges--;
}
}
} |
a2d7dac0-7180-426c-9133-06fbca2b888a | 3 | public Socket acceptSocketSafe(ServerSocket x) { //Anti-nuller by Slysoft
boolean socketFound = false;
Socket s = null;
do {
try {
s = x.accept();
int i = s.getInputStream().read();
if ((i & 0xFF) == 14) {
socketFound = true;
}
} catch (Exception e) {
}
} while (!socketFound);
return s;
} |
f239efe2-17da-434c-88ce-111f2ed15ba9 | 6 | public OwnerTableCellEditor(JTable table, IManagerOwner managerOwner) {
this.table = table;
this.managerOwner = managerOwner;
panel = new JPanel();
panel.setBorder(new EmptyBorder(0, 0, 0, 0));
panel.setLayout(new GridLayout(0, 3));
buttonValid = new JButton();
buttonValid.addActionListener(this);
buttonValid.setFocusPainted(false);
buttonValid.setToolTipText("Valider la modification");
try {
URL imageURL = buttonValid.getClass().getResource("/ressource/image/valid.png");
if (imageURL != null) {
buttonValid.setIcon(new ImageIcon(ImageIO.read(imageURL)));
}
} catch (IOException e) {
}
buttonCancel = new JButton();
buttonCancel.addActionListener(this);
buttonCancel.setFocusPainted(false);
buttonCancel.setToolTipText("Annuler modification");
try {
URL imageURL = buttonCancel.getClass().getResource("/ressource/image/cancel.png");
if (imageURL != null) {
buttonCancel.setIcon(new ImageIcon(ImageIO.read(imageURL)));
}
} catch (IOException e) {
}
buttonDelete = new JButton();
buttonDelete.addActionListener(this);
buttonDelete.setFocusPainted(false);
buttonDelete.setToolTipText("Supprime le propriétaire");
try {
URL imageURL = buttonDelete.getClass().getResource("/ressource/image/delete.png");
if (imageURL != null) {
buttonDelete.setIcon(new ImageIcon(ImageIO.read(imageURL)));
}
} catch (IOException e) {
}
panel.add(buttonValid);
panel.add(buttonCancel);
panel.add(buttonDelete);
} |
8996fb78-0e78-4836-9b95-e052db4de30a | 1 | @Override
public String toString() {
return (isProvided ? "Provided" : "Required") + " interface " + getName() + " = component:" + component.getName() + " interface:" + toInterface + " EP:" + getEnergyPoints() + " size:" + size;
} |
8091de91-0a18-41d4-be47-7d7df19bc32a | 0 | public void go()
{
frame = new Frame("Frame for Flow lay out !");
b1 = new Button("B1");
b2 = new Button("B2");
b3 = new Button("B3");
b4 = new Button("B4");
frame.setLayout(new FlowLayout()); //使用FlowLayout替换默认的BorderLayout
// frame.pack();
frame.setSize(200,200);
frame.add(b1);
frame.add(b2);
frame.add(b3);
frame.add(b4);
frame.setVisible(true);
} |
ec981ae4-a506-43e6-a6c4-02a0954f01d6 | 6 | public String serialize() {
String str = "";
for (int i = 0; i < this.mapGrid.length; i++) {
for (int j = 0; j < this.mapGrid[0].length; j++) {
if (mapGrid[i][j].isPawnOn()) { // set the id if there is pawn on the cell
str = str + "-" + mapGrid[i][j].getPlayerPawnOn();
} else { // otherwise no player is on the entity and send the entity
// if the entity is an exit and it's hidden then will need to send the hiding object
if (mapGrid[i][j].getType() == Entity.EXIT && this.isExitHidden) {
if (mapGrid[i][j].getIcon() == boxIcon) {
str = str + "-" + Entity.BOX;
} else {
str = str + "-" + Entity.PATH;
}
} else { // put a normal entity with no player on and no hiddent exit
str = str + "-" + String.valueOf(mapGrid[i][j].getType());
}
}
}
}
return str;
} |
4e96f0ed-1386-410b-b712-3fd125e84af7 | 8 | private boolean isMirror(TreeNode left, TreeNode right) {
if(left== null && right == null) return true;
if(left == null && right != null) return false;
if(left != null && right == null) return false;
if(left.val != right.val) return false;
return isMirror(left.left, right.right) && isMirror(left.right, right.left);
} |
ff0f23e4-5f5e-4505-bbfb-a27b9d7bfff3 | 8 | public void redraw(Graphics g){
if (roadGraph!= null && loaded ){
roadGraph.redraw(g, origin, scale);
if (selectedNode!=null) {
g.setColor(Color.red);
selectedNode.draw(g, origin, scale);}
if(destinationNode!=null) {
g.setColor(Color.red);
destinationNode.draw(g, origin, scale);}
}
if (selectedSegments!=null){
g.setColor(Color.red);
for (Segment seg : selectedSegments){
seg.draw(g, origin, scale);
}
}
if(articulationPoints != null){
g.setColor(Color.green);
for(Node n : articulationPoints){
n.drawAP(g, origin, scale);
}
}
} |
2c69c837-5938-4686-b86f-6a8593633a1e | 3 | public Item returnItem(String search){
for (int f = 0; f < width; f++){
for (int k = 0; k < height; k++){
if (inventory[f][k].returnName().equals(search)){
return inventory[f][k];
}
}
}
return null;
} |
6864e8df-6883-4ea2-970f-fc73615d1d91 | 8 | private String [] getPDBfiles(String fName, int numFiles){
BufferedReader bufread = null;
try {
File file = new File(fName);
FileReader fr = new FileReader(file);
bufread = new BufferedReader(fr);
}
catch (FileNotFoundException e) {
System.out.println(" ... pdbs config file not found");
System.exit(1);
}
String pdbFiles[] = new String[numFiles];
boolean done = false;
String str = null;
int curFile = 0;
while (!done) {
try {
str = bufread.readLine();
}
catch ( Exception e ){
System.out.println("ERROR: An error occurred while reading input");
System.exit(0);
}
if (str == null) // stop if we've reached EOF
done = true;
else if (getToken(str,1).charAt(0)=='%') //skip comment lines
continue;
else {
if (curFile>=numFiles)
break;
else {
pdbFiles[curFile] = getToken(str,1);
curFile++;
}
}
}
if (curFile<numFiles){
String tmp[] = new String[curFile];
System.arraycopy(pdbFiles, 0, tmp, 0, tmp.length);
pdbFiles = tmp;
}
// We're done reading them in
try {
bufread.close();
}
catch(Exception e)
{}
return pdbFiles;
} |
d85e89f5-0ea3-4718-b4fb-b160b0b8169f | 2 | public void dispose() {
for (TabListItemWidget listItem : listItems) {
if(!listItem.isDisposed())
listItem.dispose();
}
super.dispose();
} |
5a3b702a-60c7-4229-bbbd-a61fb615c3ae | 6 | private boolean checkALError()
{
switch( AL10.alGetError() )
{
case AL10.AL_NO_ERROR:
return false;
case AL10.AL_INVALID_NAME:
errorMessage( "Invalid name parameter." );
return true;
case AL10.AL_INVALID_ENUM:
errorMessage( "Invalid parameter." );
return true;
case AL10.AL_INVALID_VALUE:
errorMessage( "Invalid enumerated parameter value." );
return true;
case AL10.AL_INVALID_OPERATION:
errorMessage( "Illegal call." );
return true;
case AL10.AL_OUT_OF_MEMORY:
errorMessage( "Unable to allocate memory." );
return true;
default:
errorMessage( "An unrecognized error occurred." );
return true;
}
} |
0cf4c308-9cac-467f-88da-e7bf59362b1d | 3 | private Pattern createPattern(String urlStr, String sepStr1, String sepStr2) {
if (urlStr == null || "".equals(urlStr))
return null;
String[] urlArray = urlStr.split(",");
StringBuffer buffer = new StringBuffer(urlStr.length() + urlArray.length * 2);
buffer.append(sepStr1).append(urlArray[0]);
for (int i = 1; i < urlArray.length; i++) {
buffer.append(sepStr2).append(urlArray[i]);
}
Pattern pattern = Pattern.compile(buffer.toString());
return pattern;
} |
4cf3ce7b-7488-434d-a012-a629f6fd5bf9 | 5 | private static int getPrice(Element work) throws Exception{
try{
int price = 0;
Elements tmp = work.getElementsByClass("work_price");
if(tmp==null || tmp.size()==0) return 0;
String str = tmp.get(0).text();
//数字抜き出し
StringBuilder b = new StringBuilder();
String num = str.substring(0, str.indexOf("円"));
for(int i=0; i<num.length(); i++){
if(Character.isDigit(num.charAt(i))){
b.append(num.charAt(i));
}
}
price = Integer.parseInt(b.toString());
return price;
}catch(Exception e){
throw new Exception(e);
}
} |
41be6625-f7be-4162-8476-4ba590ee8a61 | 3 | public static boolean upload(String text)
{
try
{
byte[] data = Network.getFormattedTextData(text);
HttpURLConnection con = (HttpURLConnection) new URL(Network.getServerAddress() + "internal/processor.php").openConnection();
if (!Network.processRequest(con, data))
return false;
if (!Network.processUploadResponse(con))
return false;
return true;
}
catch (IOException | URISyntaxException ex)
{
return false;
}
} |
47f85d0f-5998-4ee5-813e-d44baf4f9517 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Scene other = (Scene) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (paragraphs == null) {
if (other.paragraphs != null)
return false;
} else if (!paragraphs.equals(other.paragraphs))
return false;
return true;
} |
bee231e9-f180-41bc-b0a0-cd8c09a7a68f | 0 | public Object getColumnValue() {
return columnValue;
} |
df17a8f6-5113-4371-b9ff-7a3e387e29e6 | 8 | public void render() {
// Get the loaded materials and initialise necessary variables
Material[] materials = treeMesh.materials;
Material material;
Triangle drawTriangle;
int currentMaterial = -1;
int triangle = 0;
// For each triangle in the object
for (triangle = 0; triangle < treeMesh.triangles.length;) {
// Get the triangle that needs to be drawn
drawTriangle = treeMesh.triangles[triangle];
// Activate a new material and texture
currentMaterial = drawTriangle.materialID;
material = (materials != null && materials.length > 0 && currentMaterial >= 0) ? materials[currentMaterial]
: defaultMtl;
material.apply();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, material.getTextureHandle());
// Draw triangles until material changes
GL11.glBegin(GL11.GL_TRIANGLES);
while (triangle < treeMesh.triangles.length && drawTriangle != null
&& currentMaterial == drawTriangle.materialID) {
GL11.glTexCoord2f(drawTriangle.texture1.x,
drawTriangle.texture1.y);
GL11.glNormal3f(drawTriangle.normal1.x, drawTriangle.normal1.y,
drawTriangle.normal1.z);
GL11.glVertex3f((float) drawTriangle.point1.pos.x,
(float) drawTriangle.point1.pos.y,
(float) drawTriangle.point1.pos.z);
GL11.glTexCoord2f(drawTriangle.texture2.x,
drawTriangle.texture2.y);
GL11.glNormal3f(drawTriangle.normal2.x, drawTriangle.normal2.y,
drawTriangle.normal2.z);
GL11.glVertex3f((float) drawTriangle.point2.pos.x,
(float) drawTriangle.point2.pos.y,
(float) drawTriangle.point2.pos.z);
GL11.glTexCoord2f(drawTriangle.texture3.x,
drawTriangle.texture3.y);
GL11.glNormal3f(drawTriangle.normal3.x, drawTriangle.normal3.y,
drawTriangle.normal3.z);
GL11.glVertex3f((float) drawTriangle.point3.pos.x,
(float) drawTriangle.point3.pos.y,
(float) drawTriangle.point3.pos.z);
triangle++;
if (triangle < treeMesh.triangles.length)
drawTriangle = treeMesh.triangles[triangle];
}
GL11.glEnd();
}
} |
fc07437d-ccd5-452d-b3c3-6a213f9098bd | 1 | public PreparedStatement createStatement(String statement){
PreparedStatement con = null;
try {
con = this.connection.prepareStatement(statement);
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
} |
95524e0a-eda5-4306-bb6f-a43e4a59a95a | 4 | public static byte[] decrypt(byte[] in,byte[] key){
byte[] tmp = new byte[in.length];
byte[] bloc = new byte[16];
K = expandKey(key);
int i;
for (i = 0; i < in.length; i++) {
if (i > 0 && i % 16 == 0) {
bloc = decryptBloc(bloc);
System.arraycopy(bloc, 0, tmp, i - 16, bloc.length);
}
if (i < in.length)
bloc[i % 16] = in[i];
}
bloc = decryptBloc(bloc);
System.arraycopy(bloc, 0, tmp, i - 16, bloc.length);
tmp = deletePadding(tmp);
return tmp;
} |
6eb0563b-025c-423d-8437-6072a8055fb6 | 3 | private static void createQRImage(File qrFile, String qrCodeText, int size,
String fileType) throws WriterException, IOException {
// Create the ByteMatrix for the QR-Code that encodes the given String
Hashtable hintMap = new Hashtable();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText,
BarcodeFormat.QR_CODE, size, size, hintMap);
// Make the BufferedImage that are to hold the QRCode
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth, matrixWidth,
BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// Paint and save the image using the ByteMatrix
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
ImageIO.write(image, fileType, qrFile);
} |
d30dadb1-f175-4587-9f33-f52dae2cf016 | 9 | public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int length = to.length();
char[] circle = new char[length];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < length; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/*
* We will loop, possibly for all of the remaining characters.
*/
for (; ; ) {
j = offset;
b = true;
/*
* Compare the circle buffer with the to string.
*/
for (i = 0; i < length; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= length) {
j -= length;
}
}
/*
* If we exit the loop with b intact, then victory is ours.
*/
if (b) {
return true;
}
/*
* Get the next character. If there isn't one, then defeat is ours.
*/
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= length) {
offset -= length;
}
}
} |
4aa8fdf7-83a7-4c5c-a804-fd7e41070259 | 1 | public void runDataWindow(){
if(dataWindow == null){
dataWindow = new FrameAddArraysData();
}
} |
9b6d4f11-c248-4268-9526-fde275778d82 | 4 | @Override
public void map(LongWritable ignored, Text filepath,
OutputCollector<Text, Text> output, Reporter reporter) throws IOException {
FileSystem fs = FileSystem.get(new Configuration());
// TIFF in
LocalFile tif = new LocalFile(tempdir + "/" + filepath.toString().replaceAll(".+\\/", ""), filepath.toString(), fs);
// JP2 out
LocalFile jp2 = new LocalFile(tif.getAbsolutePath() + ".jp2");
// Used for pixel check (jp2 converted back to tif using kdu_expand)
LocalFile outtif = new LocalFile(tif.getAbsolutePath() + "out.tif");
// KB Master probaton profile for valid .jp2 files
LocalFile profile = new LocalFile(tif.getAbsolutePath() + ".profile.xml");
// log report entries
StringBuffer report = new StringBuffer(sep);
StringBuffer toolLogs = new StringBuffer(sep + sep + "TOOL LOGS FOR " + filepath + ":" + sep + "==================" + sep);
String currentStage = "aware_compress";
try {
// Compress tiff to .jp2 using aware driver (wrapped by jkn)
CliCommand aware_compress = new CliCommand(tif, jp2);
aware_compress.runCommand("jpwrappa.py", "#infile#", "#outfile#", "-p", awareOpts.getAbsolutePath());
report.append(aware_compress.getElapsedTime() + ";");
report.append("SUCCESS;");
toolLogs.append("jpwrappa.py OUT:" + sep + "---" + sep + aware_compress.getStdOut() + sep + sep);
toolLogs.append("jpwrappa.py ERR:" + sep + "---" + sep + aware_compress.getStdErr() + sep + sep);
// copy the output .jp2 to hdfs
fs.copyFromLocalFile(new Path(jp2.getAbsolutePath()), new Path(outdir + "/" + jp2.getName()));
currentStage = "jpylyzer";
// Validate the .jp2 file with jpylyzer
CliCommand jpylyzer = new CliCommand(jp2);
jpylyzer.runCommand("jpylyzer", "#infile#");
report.append(jpylyzer.getElapsedTime() + ";");
toolLogs.append("jpylyzer OUT:" + sep + "---" + sep + jpylyzer.getStdOut() + sep + sep);
toolLogs.append("jpylyzer ERR:" + sep + "---" + sep + jpylyzer.getStdErr() + sep + sep);
FileWriter w = new FileWriter(new File(profile.getAbsolutePath()));
w.write(jpylyzer.getStdOut());
w.close();
if(jpylyzer.getStdOut().contains("<isValidJP2>True</isValidJP2>")) {
report.append("SUCCESS;");
} else {
report.append("FAILURE;");
}
// Validate the jpylyzer profile against the KB master schema using probatron
currentStage = "probatron";
long probatronStart = System.nanoTime();
org.probatron.Session ses = new org.probatron.Session();
ses.setSchemaDoc("file:" + probatronSchema.getAbsolutePath());
ValidationReport probatronVR = ses.doValidation("file:" + profile.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
probatronVR.streamOut(baos);
String probatronReport = baos.toString();
long probatronElapsed = System.nanoTime() - probatronStart;
report.append((probatronElapsed / (1000 * 1000)) + ";");
if(probatronReport.contains("failed-assert")) {
report.append("FAILURE;");
} else {
report.append("SUCCESS;");
}
toolLogs.append("probatron OUT:" + sep + "---" + sep + probatronReport + sep + sep);
// Expand the .jp2 back to TIFF for pixel check using kakadu
currentStage = "kdu_expand";
CliCommand kdu_expand = new CliCommand(jp2, outtif);
kdu_expand.runCommand("kdu_expand", "-i", "#infile#", "-o", "#outfile#");
report.append(kdu_expand.getElapsedTime() + ";");
report.append("SUCCESS;");
toolLogs.append("kdu_expand OUT:" + sep + "---" + sep + kdu_expand.getStdOut() + sep + sep);
toolLogs.append("kdu_expand ERR:" + sep + "---" + sep + kdu_expand.getStdErr() + sep + sep);
// Compare the pixels of the .jp2 with the new TIFF
currentStage = "gm";
CliCommand gm = new CliCommand(outtif, tif);
gm.runCommand("gm", "compare", "-metric", "mse", "#infile#", "#outfile#");
report.append(gm.getElapsedTime() + ";");
if(gm.getStdOut().contains("Total: 0.0000000000")) {
report.append("SUCCESS;");
} else {
report.append("FAILURE;");
}
toolLogs.append("gm compare OUT:" + sep + "---" + sep + gm.getStdOut() + sep + sep);
toolLogs.append("gm compare ERR:" + sep + "---" + sep + gm.getStdErr() + sep + sep);
} catch(IOException e) {
report.append("IOEXCEPTION in stage (" + currentStage + "): " + e.getMessage());
} finally {
tif.delete();
jp2.delete();
outtif.delete();
profile.delete();
}
output.collect(new Text("TOOLLOG"), new Text(toolLogs.toString()));
output.collect(filepath, new Text(report.toString()));
} |
1d906284-1251-4aa3-9545-b3aefd3809e7 | 8 | public boolean IsAngular() {
double degree = Math.toDegrees(this.angle);
if ((degree <= 85 && degree >= 5) || (degree <= 175 && degree >= 95)
|| (degree <= 265 && degree >= 185)
|| (degree <= 355 && degree >= 275))
return true;
return false;
} |
1d07f1f5-7c5f-4d53-99b8-ea235b131cf4 | 6 | @EventHandler
public void SnowmanFireResistance(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getsnowgolemConfig().getDouble("Snowman.FireResistance.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}dodged = true;
if (plugin.getsnowgolemConfig().getBoolean("Snowman.FireResistance.Enabled", true) && damager instanceof Snowman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, plugin.getsnowgolemConfig().getInt("Snowman.FireResistance.Time"), plugin.getsnowgolemConfig().getInt("Snowman.FireResistance.Power")));
}
} |
d146c3a0-69aa-48e1-95b8-7924a0fc6b71 | 1 | public void connectMySql() throws InstantiationException,SQLException,ClassNotFoundException,IllegalAccessException{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://"+server+"/"+
dbName+"?useUnicode=true&characterEncoding=utf-8&jdbcCompliantTruncation=false",
userName,password);
if(!conn.isClosed())
System.out.println("DB connected!");
else
System.out.println("Failed to connect the database!");
useDB(dbName);
} |
1a8a3613-f270-4484-b81c-894c3eb40d4b | 0 | public void onAccount(IAccount account) throws JFException {
// アカウント情報が更新された際に呼ばれます。
// LOGGER.trace("onAccount : " + account.getAccountId());
} |
3d549c77-f324-4cca-89c3-ee44530d2391 | 8 | public void tick() {
if (items.size() > 0) {
if (player.input.up && moveTimer <= 0) {
selected--;
moveTimer = 12;
}
if (player.input.down && moveTimer <= 0) {
selected++;
moveTimer = 12;
}
if (selected < 0) selected = items.size() - 1;
if (selected >= items.size()) selected = 0;
}
if (moveTimer > 0) moveTimer--;
} |
242f6657-1d46-4528-80b6-9f3865cc8560 | 0 | public int createNewGame(String name) throws Exception {
prepareConnection();
webResource = client.resource(address + "adminPanel/newGame/" + name);
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, null);
return response.getStatus();
} |
e0e1621a-361a-4555-b4b0-df3508025f2c | 3 | public static Double[][] intializeArray(int N) {
Double[][] array = new Double[N][];
for (int i = 0; i < N; i++) {
array[i] = new Double[N];
for (int j = 0; j <= i; j++) {
if(i == j)
array[i][j] = 0.0;
else
array[i][j] = Double.POSITIVE_INFINITY;
}
}
return array;
} |
8c984303-5583-420e-a51d-4aef0a85fbb1 | 5 | public List<PastMeeting> getPastMeetingList(Contact contact)
throws IllegalArgumentException {
List<Meeting> pastMeetings = getMeetings(contact);
List<PastMeeting> pastReturn = new ArrayList<PastMeeting>();
;
if (pastMeetings != null) {
for (int i = 0; i < pastMeetings.size(); i++) {
if (pastMeetings.get(i).getDate().getTime()
.after(theCalendar.getTime())) {
pastMeetings.remove(i);
}
}
}
if (pastMeetings == null) {
System.out.println("This contact has no past meetings.");
return null;
} else {
for (int i = 0; i < pastMeetings.size(); i++) {
PastMeetingImpl holder = (PastMeetingImpl) pastMeetings.get(i);
pastReturn.add(holder);
}
}
System.out.println("");
printPastMeetings(pastReturn);
return pastReturn;
} |
29c5fa85-eeac-45ed-831e-4207607791e6 | 0 | public int getComputerScores(){
return computerScores;
} |
9c2af060-567c-4e84-9826-d126c93f56d3 | 4 | public static void main(String[] args) throws IOException {
// parse arguments
if (args.length == 0 || args.length > 2)
usage();
boolean recursive = false;
int dirArg = 0;
if (args[0].equals("-r")) {
if (args.length < 2)
usage();
recursive = true;
dirArg++;
}
//TODO Configurations to be added
//ConfigurationFactory factory = new ConfigurationFactory("config.xml");
//Configuration config = factory.getConfiguration();
// register directory and process its events
Path dir = Paths.get(args[dirArg]);
new DirectoryWatchService(dir, recursive).start();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.