method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
15fea362-97f9-4894-854c-4ab021dc3872 | 9 | @Override
public JSONObject main(Map<String, String> params, Session session)
throws Exception {
JSONObject rtn = new JSONObject();
long targetUserId = Long.parseLong(params.get("id"));
User targetUser = User.findById(targetUserId);
if(targetUser == null) {
rtn.put("rtnCode", this.getRtnCode(406));
}
long activeUserId = session.getActiveUserId();
User activeUser = User.findById(activeUserId);
if(targetUserId != activeUserId && !activeUser.isAdmin) {
rtn.put("rtnCode", this.getRtnCode(405));
return rtn;
}
if(params.containsKey("username") && !params.get("username").equals(targetUser.username)) {
if(User.findOne("username", params.get("username")) != null) {
rtn.put("rtnCode", this.getRtnCode(201));
return rtn;
}
targetUser.username = params.get("username");
}
if(params.containsKey("fullName")) {
targetUser.fullName = params.get("fullName");
}
if(params.containsKey("email")) {
targetUser.email = params.get("email");
}
if(params.containsKey("password")) {
targetUser.setPassword(params.get("password"));
}
targetUser.save();
rtn.put("rtnCode", this.getRtnCode(200));
rtn.put("user", targetUser.toJson());
return rtn;
} |
cff15972-d43e-45a1-823c-66060d1add64 | 4 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Departamento other = (Departamento) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.nombre, other.nombre)) {
return false;
}
return true;
} |
dd7ec2c6-5d65-4965-aa53-859cffb419fb | 8 | public void showFileSelectDialog() {
File f = new File("outgoing" + File.separatorChar);
JFileChooser chooser = new JFileChooser(f);
chooser.setCurrentDirectory(f);
javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter() {
@Override
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
}
String fn = pathname.getName();
int idx = fn.lastIndexOf('.');
String extension = "";
if (idx >= 0) {
extension = fn.substring(idx);
}
return extension.equalsIgnoreCase(".jar");
}
@Override
public String getDescription() {
return "JAR files";
}
};
chooser.setFileFilter(filter);
boolean done = false;
while (!done) {
done = true;
int rv = chooser.showSaveDialog(this);
String robotFileName;
if (rv == JFileChooser.APPROVE_OPTION) {
robotFileName = chooser.getSelectedFile().getPath();
if (robotFileName.toLowerCase().indexOf(".jar") < 0) {
robotFileName += ".jar";
}
File outFile = new File(robotFileName);
if (outFile.exists()) {
int ok = JOptionPane.showConfirmDialog(this,
robotFileName + " already exists. Are you sure you want to replace it?", "Warning",
JOptionPane.YES_NO_CANCEL_OPTION);
if (ok == JOptionPane.NO_OPTION) {
done = false;
continue;
}
if (ok == JOptionPane.CANCEL_OPTION) {
return;
}
}
getFilenameField().setText(robotFileName);
fireStateChanged();
}
}
} |
9d21cd63-930a-4b26-84e2-09cf571de09c | 6 | product[] readdata(String fn) {
File ifile = new File(fn);
FileInputStream f_in = null;
BufferedInputStream b_in = null;
DataInputStream d_in = null;
boolean eof = false;
product[] pr = new product[50];
try {
f_in = new FileInputStream(ifile);
b_in = new BufferedInputStream(f_in);
d_in = new DataInputStream(b_in);
rec = 0;
while (!eof) {
pr[rec] = new product();
pr[rec].id = d_in.readUTF();
pr[rec].name = d_in.readUTF();
pr[rec].price = d_in.readFloat();
rec++;
}
}
catch (EOFException e){
eof = true;
}
catch (FileNotFoundException e){
return null;
}
catch (IOException e){
return null;
}
finally {
try {
if (d_in != null)
d_in.close();
}
catch (IOException e){
System.out.println(e);
}
}
return pr;
} |
4d6a4145-e0df-4b70-9f30-eb26666d8840 | 6 | protected void installListeners() {
super.installListeners();
if (AbstractLookAndFeel.getTheme().doShowFocusFrame()) {
focusListener = new FocusListener() {
public void focusGained(FocusEvent e) {
if (getComponent() != null) {
orgBorder = getComponent().getBorder();
LookAndFeel laf = UIManager.getLookAndFeel();
if (laf instanceof AbstractLookAndFeel && orgBorder instanceof UIResource) {
Border focusBorder = ((AbstractLookAndFeel) laf).getBorderFactory().getFocusFrameBorder();
getComponent().setBorder(focusBorder);
}
getComponent().invalidate();
getComponent().repaint();
}
}
public void focusLost(FocusEvent e) {
if (getComponent() != null) {
if (orgBorder instanceof UIResource) {
getComponent().setBorder(orgBorder);
}
getComponent().invalidate();
getComponent().repaint();
}
}
};
getComponent().addFocusListener(focusListener);
}
} |
a203e3ea-943a-41dd-98f5-0ffb8e28a65d | 2 | public Server_Socket(Core core, int port)
{
this.core = core;
try {
serv_socket = new java.net.ServerSocket(port);
if (t == null) {
t = new Thread(this);
t.start();
}
//int newPort = 50000 - new java.util.Random().nextInt(5000);
// Process p = Runtime.getRuntime().exec("ssh prbls@107.170.181.249 " + port + "localhost:" + newPort);
//System.out.println(newPort);
} catch (IOException e) {
System.out.println("Error" + e.getMessage());
System.exit(-1);
}
} |
66ddaa1a-4d2a-4b2d-90f2-ce00dbe2fa22 | 9 | @Override
public void run() {
final ArrayList<Integer> keys = new ArrayList<Integer>(count.keySet());
Collections.shuffle(keys);
for (Integer key : keys) {
final Integer clicksRemaining = this.count.get(key);
if (clicksRemaining == 0) {
continue;
}
int clicksToDo = Random.nextInt(0, clicksRemaining + 1);
if (clicksToDo > 0) {
final Component component = ctx.widgets.widget(WIDGET_CHARACTER).component(key);
for (int i = 0; i < clicksToDo; i++) {
if (component.click()) {
count.put(key, clicksRemaining - 1);
Condition.sleep(300); // TODO: varp change?
}
}
}
}
for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
if (entry.getValue() > 0) {
return;
}
}
final Component accept = ctx.widgets.widget(WIDGET_CHARACTER).component(ACCEPT);
if (accept.valid()) {
if (accept.click("Accept")) {
Condition.wait(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return !accept.valid();
}
}, 200, 15);
}
}
} |
d626e581-853e-4a29-bbea-8fbf24a8b22a | 3 | public void fireChatEventToListeners(ChatEvent chatEvent) {
chatEvent = formatChatMessage(chatEvent);
for (MessageListener messageListener : messageListeners) {
if (chatEvent.getReceipient() == messageListener.getReceipient() || messageListener.getReceipient() == Receipient.GLOBAL)
messageListener.onChatEvent(chatEvent);
}
} |
9d494cec-ea38-4158-bf77-82398e6cd1a8 | 7 | @Override
public boolean tick(Tickable ticking, int tickID)
{
super.tick(ticking,tickID);
if(canAct(ticking,tickID))
{
if(ticking instanceof MOB)
assistMOB((MOB)ticking);
else
if(ticking instanceof Room)
for(int i=0;i<((Room)ticking).numInhabitants();i++)
assistMOB(((Room)ticking).fetchInhabitant(i));
else
if(ticking instanceof Area)
for(final Enumeration<Room> r=((Area)ticking).getMetroMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
for(int i=0;i<R.numInhabitants();i++)
assistMOB(R.fetchInhabitant(i));
}
}
return true;
} |
de0f20bd-c650-48bd-b755-90a074fcf5b6 | 7 | private Method findMethodWith( Class<? extends Annotation> type, boolean isOptional )
{
Method[] methods = process.getClass().getMethods();
for( Method method : methods )
{
if( method.getAnnotation( type ) == null )
continue;
int modifiers = method.getModifiers();
if( Modifier.isAbstract( modifiers ) )
throw new IllegalStateException( "given process method: " + method.getName() + " must not be abstract" );
if( Modifier.isInterface( modifiers ) )
throw new IllegalStateException( "given process method: " + method.getName() + " must be implemented" );
if( !Modifier.isPublic( modifiers ) )
throw new IllegalStateException( "given process method: " + method.getName() + " must be public" );
return method;
}
if( !isOptional )
throw new IllegalStateException( "no method found declaring annotation: " + type.getName() );
return null;
} |
2e47ec91-f004-450b-8847-c840b3a59082 | 1 | public void update(Stage stage) {
if(source != null) {
setCenterPosition(source.getX(), source.getY());
}
} |
9bdfd275-f2f7-4f41-86aa-dace95f9bed2 | 4 | public int getHandValue()
{
int total = 0;
int aces = 0;
for (Card c : cards)
{
if (c.getValue().getValue() == 11)
{
aces++;
}
else
{
total += c.getValue().getValue();
}
}
for (int i = 0; i < aces; i++)
{
if (total + 11 <= 21)
{
total += 11;
}
else
{
total +=1;
}
}
return total;
} |
9fada1a8-799b-46fc-ad14-ec5edb98e767 | 1 | public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\aawor_000\\workspace\\TCPServer\\src\\Users\\Adam.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append('\n');
line = br.readLine();
}
String everything = sb.toString();
System.out.println(everything);
} finally {
br.close();
}
} |
eb9c2ede-679f-4d76-bf9e-536ca2d3e610 | 4 | public ArrayList<Administrador> getByNombre(Administrador admin){
PreparedStatement ps;
ArrayList<Administrador> admins = new ArrayList<>();
try {
ps = mycon.prepareStatement("SELECT * FROM Administradores WHERE userName LIKE ?");
ps.setString(1, "%"+admin.getNombre()+"%");
ResultSet rs = ps.executeQuery();
if(rs!=null){
try {
while(rs.next()){
admins.add(
new Administrador(
rs.getString("userName"),
rs.getString("passwd"),
rs.getString("dni")
)
);
}
} catch (SQLException ex) {
Logger.getLogger(Administrador.class.getName()).
log(Level.SEVERE, null, ex);
}
}else{
System.out.println("Total de registros encontrados es: 0");
}
} catch (SQLException ex) {
Logger.getLogger(AdministradorCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
return admins;
} |
fda230be-862f-48ac-8308-a52ae4a0e82a | 9 | private boolean execEstimate(VectorMap queryParam, StringBuffer respBody, DBAccess dbAccess) {
try {
int clntIdx = queryParam.qpIndexOfKeyNoCase("clnt");
String clientName = (String) queryParam.getVal(clntIdx);
int ftrsIdx = queryParam.qpIndexOfKeyNoCase("ftrs");
String ftrNames = null;
if (ftrsIdx != -1) {
ftrNames = (String) queryParam.getVal(ftrsIdx);
}
int usrIdx = queryParam.qpIndexOfKeyNoCase("usr");
if (usrIdx == -1) {
WebServer.win.log.error("-Missing argument: usr");
return false;
}
String user = (String) queryParam.getVal(usrIdx);
int ftrIdx = queryParam.qpIndexOfKeyNoCase("ftr");
if (ftrIdx == -1) {
WebServer.win.log.error("-Missing argument: ftr");
return false;
}
String ftrPattern = (String) queryParam.getVal(ftrIdx);
String[] ftrs = ftrPattern.split("\\|");
respBody.append(DBAccess.xmlHeader("/resp_xsl/estimation_profile.xsl"));
respBody.append("<result>\n");
String sql = "SELECT " + DBAccess.UPROFILE_TABLE_FIELD_VALUE + " FROM " + DBAccess.UPROFILE_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' AND " + DBAccess.UPROFILE_TABLE_FIELD_USER + "='" + user + "' AND " + DBAccess.UPROFILE_TABLE_FIELD_FEATURE + "=?";
PreparedStatement selectFtr = dbAccess.getConnection().prepareStatement(sql);
String sql1 = "SELECT " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_DST + " ftr," + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_WEIGHT + " FROM " + DBAccess.UFTRASSOCIATIONS_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_USR + "='' AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_SRC + "=? AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_TYPE + "=" + DBAccess.RELATION_PHYSICAL;
String sql2 = "SELECT " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_SRC + " ftr," + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_WEIGHT + " FROM " + DBAccess.UFTRASSOCIATIONS_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_USR + "='' AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_DST + "=? AND " + DBAccess.UFTRASSOCIATIONS_TABLE_FIELD_TYPE + "=" + DBAccess.RELATION_PHYSICAL;
sql = "(" + sql1 + ") UNION (" + sql2 + ")";
PreparedStatement assocs = dbAccess.getConnection().prepareStatement(sql);
for (int i = 0; i < ftrs.length; i++) {
assocs.setString(1, ftrs[i]);
assocs.setString(2, ftrs[i]);
ResultSet rs = assocs.executeQuery();
ArrayList<String> coFeatures = new ArrayList<String>(40);
ArrayList<Float> coFeatureWeights = new ArrayList<Float>(40);
while (rs.next()) {
coFeatures.add(rs.getString(1));
coFeatureWeights.add(rs.getFloat(2));
}
rs.close();
int numOfnownCoFtrs = 0;
float weight = 0.0f;
float sum = 0.0f;
int j = 0;
for (String feature : coFeatures) {
selectFtr.setString(1, feature);
//rs = dbAccess.executeQuery(sql).getRs();
rs = selectFtr.executeQuery();
if (rs.next()) {
numOfnownCoFtrs++;
weight += rs.getFloat(1) * coFeatureWeights.get(j);
sum += coFeatureWeights.get(j);
}
rs.close();
j++;
}
if (numOfnownCoFtrs > 0) {
String record = "<row><ftr>" + ftrs[i] + "</ftr><val>" + (weight / sum) + "</val><factors>" + (numOfnownCoFtrs * 1.0 / coFeatureWeights.size()) + "</factors></row>";
respBody.append(record);
} else {
String record = "<row><ftr>" + ftrs[i] + "</ftr><val>uknown</val><factors>" + (numOfnownCoFtrs * 1.0 / coFeatureWeights.size()) + "</factors></row>";
respBody.append(record);
}
}
selectFtr.close();
assocs.close();
respBody.append("</result>");
} catch (SQLException ex) {
WebServer.win.log.error(ex.toString());
ex.printStackTrace();
return false;
}
return true;
} |
9d8de9f7-ff64-48b2-9bea-689f8e4fb601 | 7 | public void runAssert() {
// need to get the object we will run the assertions on.
final Object object;
try {
object = callable.call();
} catch (final Exception e) {
final String message = (name == null) ? "Could not retrieve object." :
"Could not retrieve object (" + name + ").";
final AssertionError a = new AssertionError(message);
a.initCause(e);
throw a;
}
// run through all the assertions.
final List<AssertionError> failures = new LinkedList<AssertionError>();
for (final Matcher entry : matchers) {
try {
MatcherAssert.assertThat(object, entry);
} catch (final AssertionError e) {
// collect all the failures
failures.add(e);
}
}
// if we have no failures we have succeeded in our assertions
if (failures.isEmpty()) {
return;
}
if (failures.size() == 1) {
final AssertionError assertionError = failures.get(0);
if (name == null) {
throw assertionError;
}
final AssertionError a = new AssertionError(name + " failed because: " + assertionError.getMessage());
a.initCause(assertionError);
throw a;
}
// throw the combined error
throw new MultipleAssertionError(name, failures);
} |
3f108e97-1358-4cc8-979c-810a2dee8878 | 0 | public void setPin(String pin) {
this.pin = pin;
} |
2d8dddd1-6495-407f-99ee-5d80a8882141 | 6 | public static boolean warpNextMap_Agent(final MapleCharacter c, final boolean fromResting) {
final int currentmap = c.getMapId();
final int thisStage = (currentmap - baseAgentMapId) / 100;
MapleMap map = c.getMap();
if (map.getSpawnedMonstersOnMap() > 0) {
return false;
}
if (!fromResting) {
clearMap(map, true);
c.modifyCSPoints(1, 40);
}
final ChannelServer ch = c.getClient().getChannelServer();
if (currentmap >= 970032700 && currentmap <= 970032800) {
map = ch.getMapFactory().getMap(baseAgentMapId);
c.changeMap(map, map.getPortal(0));
return true;
}
final int nextmapid = baseAgentMapId + ((thisStage + 1) * 100);
for (int i = nextmapid; i < nextmapid + 7; i++) {
map = ch.getMapFactory().getMap(i);
if (map.getCharactersSize() == 0) {
clearMap(map, false);
c.changeMap(map, map.getPortal(0));
map.respawn(true);
return true;
}
}
return false;
} |
da0ae4da-5eea-4200-86b3-718420876c4c | 0 | private Combination<Colors> generateAttemptCombination4() {
List<Token<Colors>> attemptTokens = new ArrayList<Token<Colors>>();
attemptTokens.add(new Token<Colors>(Colors.G));
attemptTokens.add(new Token<Colors>(Colors.Y));
attemptTokens.add(new Token<Colors>(Colors.P));
attemptTokens.add(new Token<Colors>(Colors.W));
attemptTokens.add(new Token<Colors>(Colors.R));
return new Combination<Colors>(attemptTokens);
} |
749eb771-6e50-4688-a888-8de5459fc301 | 6 | public static void addInserDzien(int ID)
{
boolean flaga=true;
for (int i=0 ; i<DniInsert[0] ; i++)
{
if(ID==DniInsert[i+2])
{
flaga=false;
break;
}
}
if(flaga)
{
// Count ArraySize
if (DniInsert[0]+2 >=DniInsert[1])
{
int[] tempArray = new int[DniInsert[1]];
for (int i = 0; i < DniInsert[1]; i++)
tempArray[i] = DniInsert[i];
tempArray[1]+= 3;
DniInsert = null;
DniInsert = new int[tempArray[1]];
for (int i = 0; i < (tempArray[1] - 3); i++) {
DniInsert[i] = tempArray[i];
}
}
DniInsert[2+DniInsert[0]] = ID;
System.out.println("dodalem :"+DniInsert[2+DniInsert[0]]);
DniInsert[0]++;
}
} |
9e82c990-963b-4825-b2a4-e806a7a8ff45 | 6 | private int jjMoveStringLiteralDfa10_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjMoveNfa_0(0, 9);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return jjMoveNfa_0(0, 9);
}
switch(curChar)
{
case 66:
return jjMoveStringLiteralDfa11_0(active0, 0x800000000000000L);
case 67:
return jjMoveStringLiteralDfa11_0(active0, 0x7ffe00000000000L);
case 98:
return jjMoveStringLiteralDfa11_0(active0, 0x800000000000000L);
case 99:
return jjMoveStringLiteralDfa11_0(active0, 0x7ffe00000000000L);
default :
break;
}
return jjMoveNfa_0(0, 10);
} |
6af7f485-99d0-4198-86bd-e33fda94c3d3 | 2 | @Override
/**
* This method will be used by the table component to get
* value of a given cell at [row, column]
*/
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
Contestant contestant = contestants.get(rowIndex);
switch (columnIndex) {
case COLUMN_USERNAME:
value = contestant.getUsername();
break;
case COLUMN_PASSWORD:
value = "******"; // password is hidden
break;
}
return value;
} |
70278e59-1706-407b-abc9-9bd876adaaac | 3 | public void resetGame(int boardSize, int handicap, Player player1, Player player2) {
if (computerMatch != null) {
computerMatch.requestStop();
}
gameOver = false;
this.player1 = player1;
this.player2 = player2;
board = new Board(boardSize, handicap);
analyzerPanel.analyze(board);
activeMove = new InitialPosition(boardSize, handicap);
boardSizer.setBoardSize(boardSize);
boardSizer.setImageSize(goPanel.getWidth(), goPanel.getHeight());
goPanel.repaint();
moveTree.reset(activeMove);
if (player1 instanceof ComputerPlayer) {
if (player2 instanceof ComputerPlayer) {
computerMatch = new ComputerMatch();
} else {
maybeMakeComputerMove();
}
}
} |
7267908b-4055-4495-af4c-5077c848213e | 2 | public AnnotationVisitor visitAnnotation(final String desc,
final boolean visible) {
if (!ClassReader.ANNOTATIONS) {
return null;
}
ByteVector bv = new ByteVector();
// write type, and reserve space for values count
bv.putShort(cw.newUTF8(desc)).putShort(0);
AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2);
if (visible) {
aw.next = anns;
anns = aw;
} else {
aw.next = ianns;
ianns = aw;
}
return aw;
} |
1c748c5d-8022-44f8-903e-a79cb4456181 | 2 | public boolean removeBook(String title)
{
boolean delete = false;
if (aBookIndex.containsKey(title)) {
Item tempBook = aBookIndex.remove(title);
authorIndex.remove(((Book)tempBook).getAuthor());
for (String s: tempBook.keywords) {
keywordIndex.get(s).remove(tempBook);
}
delete = true;
}
return delete;
} |
4e6e8b11-77c2-467f-a62f-7419058123a1 | 9 | public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Insert a bunch of numbers separated by coma bitch");
String[] array1 = input.nextLine().split(",");
int length = array1.length;
int[] array2 = new int[length];
for(int i = 0; i < length; i++)
{
array2[i] = Integer.parseInt(array1[i]);
}
for(int i = 0; i < length; i++)
{
if(array2[i] > 1000000 || array2[i] < -1000000)
{
System.out.println("Not in range");
return;
}
}
// Arrays.sort(array2);
// Bubble Sort Test
int swap;
boolean swapped = true;
while(swapped)
{
for(int i = 1; i <= length-1; i++)
{
if(array2[i-1] > array2[i])
{
swap = array2[i];
array2[i] = array2[i-1];
array2[i-1] = swap;
swapped = true;
}
else
swapped = false;
}
}
for (int i = 0; i < length; i++)
{
if(i == length -1 )
{
System.out.print(array2[i]);
}
else
{
System.out.print(array2[i] + ",");
}
}
} |
f861f976-afc5-41f0-9aa8-0669fd87b2d4 | 8 | public void setTokenizerProperties(TokenizerProperties props) throws NullPointerException {
if (props == null) {
throw new NullPointerException();
}
// set properties
if (_properties != null) {
_properties.removeTokenizerPropertyListener(this);
}
_properties = props;
_properties.addTokenizerPropertyListener(this);
// who is going to handle the various token types ?
if (_properties instanceof WhitespaceHandler) {
setWhitespaceHandler((WhitespaceHandler)_properties);
} else {
setWhitespaceHandler(new StandardWhitespaceHandler(_properties));
}
if (_properties instanceof SeparatorHandler) {
setSeparatorHandler((SeparatorHandler)_properties);
} else {
setSeparatorHandler(new StandardSeparatorHandler(_properties));
}
if (_properties instanceof SequenceHandler) {
setSequenceHandler((SequenceHandler)_properties);
} else {
setSequenceHandler(new StandardSequenceHandler(_properties));
}
if (props instanceof KeywordHandler) {
setKeywordHandler((KeywordHandler)props);
} else {
setKeywordHandler(new StandardKeywordHandler(_properties));
}
if (_properties instanceof PatternHandler) {
setPatternHandler((PatternHandler)_properties);
} else {
setPatternHandler(null);
}
// flag handling
int newFlags = _properties.getParseFlags();
if (newFlags != _flags) {
propertyChanged(new TokenizerPropertyEvent(
TokenizerPropertyEvent.PROPERTY_MODIFIED,
new TokenizerProperty(TokenizerProperty.PARSE_FLAG_MASK,
new String[] { Integer.toBinaryString(newFlags) } ),
new TokenizerProperty(TokenizerProperty.PARSE_FLAG_MASK,
new String[] { Integer.toBinaryString(_flags) } )));
}
} |
d2ddbaeb-70e9-4746-bb00-0d63a76f1c43 | 8 | @Override
public String onSkillSee(L2Npc npc, L2PcInstance caster, L2Skill skill, L2Object[] targets, boolean isPet)
{
if (npc instanceof L2ChestInstance)
{
// This behavior is only run when the target of skill is the passed npc.
if (!Util.contains(targets, npc))
return super.onSkillSee(npc, caster, skill, targets, isPet);
final L2ChestInstance chest = ((L2ChestInstance) npc);
// If this chest has already been interacted, no further AI decisions are needed.
if (!chest.isInteracted())
{
chest.setInteracted();
// If it's the first interaction, check if this is a box or mimic.
if (Rnd.get(100) < IS_BOX)
{
if (skill.getId() == SKILL_DELUXE_KEY)
{
// check the chance to open the box
int keyLevelNeeded = (chest.getLevel() / 10) - skill.getLevel();
if (keyLevelNeeded < 0)
keyLevelNeeded *= -1;
final int chance = BASE_CHANCE - keyLevelNeeded * LEVEL_DECREASE;
// Success, die with rewards.
if (Rnd.get(100) < chance)
{
chest.setSpecialDrop();
chest.doDie(caster);
}
// Used a key but failed to open: disappears with no rewards.
else
chest.deleteMe(); // TODO: replace for a better system (as chests attack once before decaying)
}
else
chest.doCast(SkillTable.getInstance().getInfo(4143, Math.min(10, Math.round(npc.getLevel() / 10))));
}
// Mimic behavior : attack the caster.
else
attack(chest, ((isPet) ? caster.getPet() : caster));
}
}
return super.onSkillSee(npc, caster, skill, targets, isPet);
} |
e2692f03-9aa6-4769-85f3-9e8697c22fd2 | 7 | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String accion = request.getParameter("accion");
if (accion != null) {
response.sendRedirect("http://www.unac.edu.co");
} else {
String correo = request.getParameter("tcorreo");
String pass = request.getParameter("tPass");
RequestDispatcher vista;
System.out.println("Intentando conectar a BD ....");
//Datos de la conexion
String driver = "com.mysql.jdbc.Driver";
String urlDB = "jdbc:mysql://localhost/test";
String userBD = "userprueba";
String passBD = "123456";
String mensaje = "";
//Objetos para manipular la conexion y los datos
Connection con = null;//Objeto para la conexion
Statement sentencia = null;//Objeto para definir y ejecutar las consultas sql
ResultSet resultado = null;//Objeto para obtener los resultados de las consultas sql
String sql = "";
try {
//CARGAR DRIVER
Class.forName(driver);
//ESTABLECER CONEXION
con = DriverManager.getConnection(urlDB, userBD, passBD);
System.out.println("Conectado ...");
//Definición de Sentencia SQL
sql = "SELECT usuarios.snombre,usuarios.nidPerfil,semail,perfiles.snombre "
+ "FROM usuarios,perfiles "
+ "WHERE usuarios.nidPerfil=perfiles.idPerfil "
+ "AND semail= '" + correo + "' AND "
+ "sclave = '" + pass + "'";
//Ejecutar sentencia
sentencia = con.createStatement();
resultado = sentencia.executeQuery(sql);
//si el resultado tiene un dato el usuario con el login y pass existe, autenticación valida.
if (resultado.next()) {
System.out.println("autenticado ...");
//creamos la sesion
HttpSession sesionOk = request.getSession();//creamos la sesion
//agregamos el usuario a la sesión
sesionOk.setAttribute("usuario", resultado.getString(1));
//agregamos el perfil a la sesión
sesionOk.setAttribute("perfil", resultado.getString(2));
//agregamos el id del usuario
sesionOk.setAttribute("email", resultado.getString("semail"));
//agregamos la descripcion del perfil
sesionOk.setAttribute("sperfil", resultado.getString(4));
vista = request.getRequestDispatcher("Home.jsp");
//request.getRequestDispatcher("/Index.jsp").include(request, response);
} else {
System.out.println("Error usuario no existe ...");
vista = request.getRequestDispatcher("index.jsp");
}
vista.forward(request, response);
} catch (ClassNotFoundException ex) {
mensaje = "No se ha podido cargar el Driver de MySQL";
System.out.println(mensaje);
//request.getRequestDispatcher("/Error.jsp").include(request, response);
//request.getRequestDispatcher("/Error.jsp").forward(request, response);
response.sendRedirect("Error.jsp");
} catch (SQLException ex) {
mensaje = "No se ha podido establecer la conexión, o el SQL esta mal formado " + sql;
mensaje = mensaje + "\n" + ex.toString();
System.out.println(mensaje);
request.setAttribute("mensaje", mensaje);
request.getRequestDispatcher("/Error.jsp").forward(request, response);
} finally {
try {
//Liberar recursos
if (sentencia != null) {
sentencia.close();
}
//cerrar conexion
if (con != null) {
con.close();
}
} catch (SQLException ex) {
request.getRequestDispatcher("/Error.jsp").include(request, response);
}
}
}
} |
9399354a-5145-4a68-8100-3da6f35aa3a8 | 5 | public void ProcessInPacketBuffer() {// process a packet for distance updates
BlastPacket bpkt, BlastPktNext;
DataPacket dpkt, DataPktNext;
while (!BlastPacketInBuf.isEmpty()) {
bpkt = BlastPacketInBuf.removeFirst(); // if (TempPkt instanceof BlastPacket) { } ?
BlastPktNext = ProcessBlastPacket(bpkt);
bpkt.DeleteMe();
if (BlastPktNext != null) {
if (BlastPktNext.LifeSpan > 0) {// snox, fiat lifespan is just for testing
BlastPacketOutBuf.add(BlastPktNext);
}
}
}
while (!DataPacketInBuf.isEmpty()) {
dpkt = DataPacketInBuf.removeFirst(); // if (TempPkt instanceof BlastPacket) { } ?
DataPktNext = ProcessDataPacket(dpkt);
dpkt.DeleteMe();
if (DataPktNext != null) {
DataPacketOutBuf.add(DataPktNext);
}
}
} |
d65acca9-4921-42e7-bc72-1e0e33c7f6ed | 9 | public boolean sendScreenCaptures(String[] cmd, String screenImgSavePath, String fileNameWithoutExtension)
{
try
{
ArrayList alToSend = CaptureScreen.captureScreens(screenImgSavePath, fileNameWithoutExtension);
if ((alToSend == null) || (alToSend.size() < 1))
{
return false;
}
IncrementObject statusIncrement = null;
try { statusIncrement = new IncrementObject(100.0D / alToSend.size()); } catch (Exception e) { statusIncrement = null; }
for (int i = 0; i < alToSend.size(); i++)
{
if ((alToSend.get(i) == null) || (!((File)alToSend.get(i)).exists()) || (!((File)alToSend.get(i)).isFile()) || (alToSend.size() < 1))
{
Driver.sop("Empty file received at index " + i + "... skipping this result");
}
else
{
FTP_Thread_Sender[] arrFTP_Sender = new FTP_Thread_Sender[alToSend.size()];
arrFTP_Sender[i] = new FTP_Thread_Sender(true, false, cmd[3], Integer.parseInt(cmd[4]), 4096, (File)alToSend.get(i), this.pwOut, true, FTP_ServerSocket.FILE_TYPE_SCREEN_CAPTURES, statusIncrement);
arrFTP_Sender[i].start();
}
}
return true;
}
catch (Exception e)
{
Driver.eop("sendScreenCaptures", strMyClassName, e, e.getLocalizedMessage(), false);
}
return false;
} |
05b3a972-c46e-4ed1-8b4a-166a5b9da391 | 7 | private void refreshCalendar(int month, int year) {
int nod, som; // Number Of Days, Start Of Month
prevMonth.setEnabled(true);// enable button
nextMonth.setEnabled(true);// enable button
if (month == 0 && year == actualYear) {
prevMonth.setEnabled(false);
} // disable button as already pass
if (month == 11 && year >= actualYear + 20) {
nextMonth.setEnabled(false);
} // disable button as out of range
displayedMonth.setText(months[month]); // Refresh the month label (at
// the top)
displayedMonth.setBounds(
160 - displayedMonth.getPreferredSize().width / 2, 5, 180, 25); // Re-align
// label
// with
// calendar
selectYear.setSelectedItem(String.valueOf(year)); // Select the correct
// year in the combo
// box
// Clear table
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++) {
calendarDTM.setValueAt(null, i, j);
}
}
GregorianCalendar cal = new GregorianCalendar(year, month, 1);
nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
som = cal.get(GregorianCalendar.DAY_OF_WEEK);
for (int i = 1; i <= nod; i++) {
int row = new Integer((i + som - 2) / 7);
int column = (i + som - 2) % 7;
calendarDTM.setValueAt(i, row, column);
}// set value for the days displayed
calendar.setDefaultRenderer(calendar.getColumnClass(0),
new CalendarRenderer());
} |
454b61a7-6b7c-4e8c-b6fe-bce1c314a7c2 | 1 | public static Entry[] mergeSortAndPopulate(int[] list) { //For testing only
Entry[] input = new Entry[list.length];
for(int i = 0; i < list.length; i++) {
input[i] = new Entry(list[i], randomName());
}
return mergeSort(input);
} |
ab9b0de9-962d-4e8d-8565-2f05fbbd6673 | 3 | public Children(Entity... childs) {
// Create a list list with the size of child's array
children = new ArrayList<Entity>(childs.length);
for (Entity child : childs) {
Spatial childSpatialComponent = child.getComponent(Spatial.class);
Equipment childEquipmentComponent = child.getComponent(Equipment.class);
if(childSpatialComponent != null && childEquipmentComponent != null){
childSpatialComponent.x = childEquipmentComponent.x;
childSpatialComponent.y = childEquipmentComponent.y;
}
children.add(child);
}
} |
b55d45cf-ffef-4bd8-85b4-90bf2a8ef325 | 0 | public void setVerboseLevel(int level) {
this.verbose_level = level;
} |
17fdae3c-a327-4ea6-b3a6-48e0b7886808 | 2 | private static double compare(String alg1, String alg2, int N, int T,
String inputType, String dataType)
{
Comparable[] a = new Comparable[N];
Comparable[] b = new Comparable[N];
try
{
SortHelper.class.getMethod("put" + inputType + "Input",
Comparable[].class).invoke(null, (Object) a);
}
catch (Exception e)
{
System.out.println(e);
System.out.println(e.getCause());
System.exit(1);
}
System.arraycopy(a, 0, b, 0, N);
double total1 = 0.0;
double total2 = 0.0;
for (int t = 0; t < T; t++)
{ // Perform one experiment (generate and sort an array).
total1 += time(alg1, a);
// System.out.println(alg1 + " : " + total1);
total2 += time(alg2, b);
// System.out.println(alg2 + " : " + total2);
}
return total2 / total1;
} |
99c82d05-9d2b-4fb6-8524-1a3b016d59b1 | 4 | public static EnumTemperature getFromValue(float rawTemp) {
if (rawTemp > 1.00f) {
return HOT;
}
else if (rawTemp > 0.85f) {
return WARM;
}
else if (rawTemp > 0.35f) {
return NORMAL;
}
else if (rawTemp > 0.0f) {
return COLD;
}
else {
return ICY;
}
} |
f80b929f-a467-4769-a4da-84e3c12bb470 | 0 | public NondeterminismPane(AutomatonPane ap) {
super(new BorderLayout());
ap.addMouseListener(new ArrowDisplayOnlyTool(ap, ap.getDrawer()));
add(ap, BorderLayout.CENTER);
add(new JLabel("Nondeterministic states are highlighted."),
BorderLayout.NORTH);
} |
22f1db6b-231f-445f-aa46-46dc26df83a7 | 5 | @RequestMapping(value = "/game/requests/response/", method = RequestMethod.POST)
public String checkResponseRequestPage(IdForm idForm, ModelMap model){
if (!idForm.getId().equals("")) {
int id = Integer.parseInt(idForm.getId());
String state = idForm.getState();
try {
if (!getRequests().isIdIncludeList(id)) {
throw new Exception();
}
Request request = requestService.getRequestById(id);
if (state.equals("agree")) {
Field field1 = new Field("", "", false);
Field field2 = new Field("", "", false);
fieldService.addField(field1);
fieldService.addField(field2);
Game game = new Game(request.getFirstLogin(), request.getSecondLogin(),
false,"", field1.getId(), field2.getId());
gameService.addGame(game);
requestService.updateRequest(id, 1, game.getId());
}
if (state.equals("refuse")) {
requestService.updateRequest(id, -1, -1);
}
return "gamePages/successfulResponse";
} catch (Exception e) {
}
}
model.put("Error", "Wrong id");
idForm.setId("");
return "gamePages/responseRequest";
} |
216001d6-8fe2-41e1-8a07-c403fb3585f9 | 1 | public void setXVal(Double[] newXVal) {
if (newXVal == null) {
this.xVal = new Double[0];
} else {
this.xVal = Arrays.copyOf(newXVal, newXVal.length);
}
} |
4edb23ea-ac12-4ae5-aa18-e2c4e4ffcaeb | 6 | @Override
public void onKeyPressed(char key, int keyCode, boolean coded)
{
// Tests the functions of the wavsound
if (!coded)
{
// On d plays the sound
if (key == 'd')
{
this.testsound.play(null);
System.out.println("Plays a sound");
}
// On e loops the sound
else if (key == 'e')
{
this.testsound.loop(null);
System.out.println("Loops a sound");
}
// On a stops the sounds
else if (key == 'a')
{
this.testsound.stop();
System.out.println("Stops the sounds");
}
// On s pauses all sounds
else if (key == 's')
{
this.testsound.pause();
System.out.println("Pauses the sounds");
}
// On w unpauses all sounds
else if (key == 'w')
{
this.testsound.unpause();
System.out.println("Unpauses the sounds");
}
}
} |
d9404266-5479-4c4a-a1f5-432fcea1980a | 1 | public MoviePathSearcher(Model m) {
this.m = m;
pathsToMovies = new Path[100];
matcher = new PathMatcher[100];
pathIndex = 0;
int i = 0;
for (String s : m.getSearchKeywords()) {
matcher[i++] = FileSystems.getDefault().getPathMatcher("glob:" + s);
}
} |
b6534407-2200-4f66-b4ef-d4385c63e2f9 | 4 | private static void mergeMaps(Map<String,Integer> map1, Map<String,Integer> map2){
Objects.requireNonNull(map2);
for (Map.Entry<String, Integer> e : Objects.requireNonNull(map1).entrySet()) {
if (e != null) {
int val = 0;
if (map2.get(e.getKey()) != null) val = map2.get(e.getKey());
if (val != 0) {
map2.put(e.getKey(), e.getValue()+val);
} else {
map2.put(e.getKey(), e.getValue());
}
}
}
} |
5286e33d-3a49-42e4-b359-729bea80972f | 4 | private void displayMiddleBorder() {
System.out.print(B_HEAD);
boolean dec = false;
for (int i=0; i < this.size; i++) {
int size = this.size;
while (size > 0) {
System.out.print("-");
size -= (dec ? 1 : 0);
dec=(!dec);
}
System.out.print((i < this.size-1 ? "-+" : ""));
}
System.out.println(B_TAIL);
} |
43192bf4-7e52-4046-a629-cb0b845d3ef8 | 0 | Physics() {
this.totalForce = new SimpleVector();
this.location = new SimpleVector();
} |
dc26ec88-15b8-481e-8d1a-5e98e4211fa3 | 2 | private static <E extends Enum<E>> E valueOf(final Class<E> type, final int ordinal) {
final E[] enums = type.getEnumConstants();
return (ordinal >= 0 && ordinal < enums.length ? enums[ordinal] : null);
} |
5fb45030-2bce-4659-a809-bdbb9494169c | 1 | @Test
public void shouldSortProvidedArray2() throws Exception {
Integer[] array = new Integer[]{4, 2, 4, 1, 3, 45, 23, 424, 3};
sort.sort(array);
for (int i : array) {
System.out.println(i);
}
} |
32074a89-1829-4ab0-a77a-e1d8d6f676d0 | 5 | public boolean removeAllEdges(Object origin, Object destination)
{
// retrieve the origin and destination vertices
Vertex o = (Vertex)theItems.get(origin);
Vertex d = (Vertex)theItems.get(destination);
if (o == null || d == null)
{
// one of the vertices does not exist
return false;
}
// remove all edges from the origin to the destination
if (!o.adjacencyList.isEmpty())
{
for (ListIterator itr = o.adjacencyList.listIterator(0); itr.hasNext(); )
{
Edge e = (Edge)itr.getCurrent();
// if Edge to destination exists remove it; otherwise advance
if (e.destination.equals(d))
itr.remove();
else
itr.next();
}
}
// edges successfully removed
return true;
} |
17b17982-d990-41b4-acf7-748cb998f8e1 | 2 | @Test
public void getWidth(){
Tile[][] tiles = new Tile[15][10];
for (int x = 0; x < tiles.length; x++){
for(int y = 0; y < tiles[0].length; y++){
tiles[x][y] = new Tile(new Position(x, y), 0);
}
}
World w = new World(tiles);
assertTrue(w.getWidth() == 15);
} |
133a1d28-4564-476b-b7b9-a9ba777004c6 | 8 | public void run(){
while(true){
String line = scan.next();
if ( line.equals("next")) next();
if ( line.equals("previous")) previous();
if ( line.equals("stop")) stopMusic();
if ( line.equals("pause")) pause();
if ( line.equals("play")) play();
if ( line.equals("random")) randomize();
if ( line.equals("tags")) currentPlayer.printTags();
}
} |
cc541abe-a75b-4597-be06-21fc70993ff8 | 6 | public int numDistinct(String S, String T) {
if (S == null || T == null) {
return 0;
}
int[][] nums = new int[S.length() + 1][T.length() + 1];
for (int i = 0; i < S.length(); i++) {
nums[i][0] = 1;
}
for (int i = 1; i <= S.length(); i++) {
for (int j = 1; j <= T.length(); j++) {
nums[i][j] = nums[i - 1][j];
if (S.charAt(i - 1) == T.charAt(j - 1)) {
nums[i][j] += nums[i - 1][j - 1];
}
}
}
return nums[S.length()][T.length()];
} |
ea3ce44c-8745-47bc-9037-655c351db780 | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(mob.fetchEffect(this.ID())!=null)
{
Ability A=mob.fetchEffect(ID());
if(A!=null)
A.unInvoke();
A=mob.fetchEffect(ID());
if(A!=null)
mob.tell(L("You are already hiding in plain site."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final MOB highestMOB=getHighestLevelMOB(mob,null);
final int levelDiff=mob.phyStats().level()-getMOBLevel(highestMOB)-(this.getXLEVELLevel(mob)*2);
final String str=L("You step to the side and become totally inconspicuous.");
boolean success=proficiencyCheck(mob,levelDiff*10,auto);
if(!success)
{
if(highestMOB!=null)
beneficialVisualFizzle(mob,highestMOB,L("<S-NAME> step(s) to the side of <T-NAMESELF>, but end(s) up looking like an idiot."));
else
beneficialVisualFizzle(mob,null,L("<S-NAME> step(s) to the side and look(s) like an idiot."));
}
else
{
final CMMsg msg=CMClass.getMsg(mob,null,this,auto?CMMsg.MSG_OK_ACTION:(CMMsg.MSG_DELICATE_HANDS_ACT|CMMsg.MASK_MOVE),str,CMMsg.NO_EFFECT,null,CMMsg.NO_EFFECT,null);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
invoker=mob;
beneficialAffect(mob,mob,asLevel,0);
mob.recoverPhyStats();
}
else
success=false;
}
return success;
} |
954b9121-d113-4a48-8ffa-9cf8c80723d4 | 4 | @Override
protected String toString(int indent) {
String str = toString(indent, "IfStatementNode\n");
if(exp1 != null)
str += exp1.toString(indent+1) + "\n";
if(stateSeq1 != null)
str += stateSeq1.toString(indent+1) + "\n";
if(elseIfs != null)
str += elseIfs.toString(indent+1) + "\n";
if(stateSeq2 != null)
str += stateSeq2.toString(indent+1) + "\n";
return str;
} |
16bb169a-4477-495b-b801-9bf302fe2ca0 | 0 | private void fireConnectEvent(ConnectEvent evt) {
fireClientConnectEvent(evt);
} |
0a8ea145-62cd-44e7-b6f4-507149d4a40b | 0 | public void stop() {
timer.cancel();
timer = null;
tick = 0;
elapseTime = 0;
state = EnumStopWatchState.STOP;
log.info("stop stopwatch, it's state:" + state + ", elapseTime:"
+ elapseTime);
} |
33613f99-e97a-4cea-9eaa-8102dd6b3be7 | 3 | public EasyDate setTimeZoneOffset(int minutes) {
StringBuilder timeZoneID = new StringBuilder().append("GMT").append((minutes > 0 ? '+' : '-')).append(minutes / 60);
int min = minutes % 60;
if (min > 0) {
timeZoneID.append(':');
if (min < 10) {
timeZoneID.append('0');
}
timeZoneID.append(min);
}
calendar.getTimeInMillis(); // 强迫更新时间,否则之前的时区设置可能不生效
calendar.setTimeZone(TimeZone.getTimeZone(timeZoneID.toString()));
return this;
} |
bd26e61e-6d94-4234-8e5d-30e56ef925a3 | 7 | private void updateFromModel()
{
if (enabledButton != null) {
enabledButton.setSelected(valueFilledIn);
enabledButton.setEnabled(enabled);
}
if ((timeClock != null) && (timeClock.isVisible())) {
timeClock.setEnabled(valueFilledIn && enabled);
}
if ((dateClock != null) && (dateClock.isVisible())) {
dateClock.setEnabled(valueFilledIn && enabled);
}
} |
294c7052-3493-4a86-97b8-52d1b3d589f9 | 4 | private void nextpoints(int alg) {
for (int i = 0; i < points; i++) {
double xf = Math.random();
double yf = Math.random();
int xi = (int) Math.floor(ximlen * xf);
int yi = (int) Math.floor(yimlen * yf);
doCalculation(xf, yf, xi, yi);
}
runtotal += points;
if (quad < 1.001) {
quad = 1;
} else {
quad = (float) (50 * Math.sqrt((float) points / runtotal));
}
if (runtotal % pixels.length == 0) {
if (runtotal == pixels.length * 2)
fixHoles = true;
long diff = (System.currentTimeMillis() - lastPassTime) / 1000;
String strStatus = "Pass: " + (runtotal / pixels.length) + " - "
+ diff + "s";
System.out.println(strStatus);
lastPassTime = System.currentTimeMillis();
}
} |
e4f6a713-5b1d-4c27-99e4-3c5b1eacf02f | 3 | public String version_string()
{
switch (h_version)
{
case MPEG1:
return "MPEG-1";
case MPEG2_LSF:
return "MPEG-2 LSF";
case MPEG25_LSF: // SZD
return "MPEG-2.5 LSF";
}
return(null);
} |
4aaf459d-36ee-473c-be0a-7d080d71f775 | 6 | public static HttpURLConnection getValidConnection(URL url) {
HttpURLConnection httpurlconnection = null;
try {
URLConnection urlconnection = url.openConnection();
urlconnection.addRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 5.0;Windows NT;DigExt)");
urlconnection.connect();
if (!(urlconnection instanceof HttpURLConnection)) {
System.out.println("Not an http connection: " + url);
// urlconnection.disconnect();
return null;
}
httpurlconnection = (HttpURLConnection) urlconnection;
// httpurlconnection.setFollowRedirects(true);
int responsecode = httpurlconnection.getResponseCode();
switch (responsecode) {
// here valid codes!
case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
// System.out.println("Code: " + responsecode);
break;
default:
System.out.println("Invalid response code: " + responsecode + " " + url);
httpurlconnection.disconnect();
return null;
}
} catch (IOException ioexception) {
System.out.println("unable to connect: " + ioexception);
if (httpurlconnection != null) {
httpurlconnection.disconnect();
}
return null;
}
return httpurlconnection;
} |
ca6d56f4-07fa-45f0-b945-c029c6290ff7 | 5 | public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Verwendung: <Akteurdatei> <Szenendatei>");
System.exit(-1);
}
File acteurs = new File(args[0]);
File scene = new File(args[1]);
if (!acteurs.exists() || acteurs.isDirectory()) {
System.err.println("Die Akteurdatei ist ungültig.");
System.exit(-1);
}
if (!scene.exists() || scene.isDirectory()) {
System.err.println("Die Szenendatei ist ungültig.");
System.exit(-1);
}
System.out.println("Lade Meer...");
Meer meer = new Meer(acteurs, scene);
System.out.println("Gehe Geschichte durch ...");
System.out.println("-------------------------");
meer.displayStory();
System.out.println("-------------------------");
System.out.println("Die Geschichte ist fertig");
} |
1f2d9740-f521-4879-8760-8672a6f2b3dc | 6 | private void selectionMouseCursor(Page currentPage, Point mouseLocation) {
if (currentPage != null &&
currentPage.isInitiated()) {
// get page text
PageText pageText = currentPage.getViewText();
if (pageText != null) {
// get page transform, same for all calculations
AffineTransform pageTransform = currentPage.getPageTransform(
Page.BOUNDARY_CROPBOX,
documentViewModel.getViewRotation(),
documentViewModel.getViewZoom());
ArrayList<LineText> pageLines = pageText.getPageLines();
boolean found = false;
Point2D.Float pageMouseLocation =
convertMouseToPageSpace(mouseLocation, pageTransform);
for (LineText pageLine : pageLines) {
// check for containment, if so break into words.
if (pageLine.getBounds().contains(pageMouseLocation)) {
found = true;
documentViewController.setViewCursor(
DocumentViewController.CURSOR_TEXT_SELECTION);
break;
}
}
if (!found) {
documentViewController.setViewCursor(
DocumentViewController.CURSOR_SELECT);
}
}
}
} |
86e1d576-efba-42de-85d0-4af5bfd49d7a | 0 | private CollectionUtils() {} |
93ce1b1e-f842-46ac-af4e-b76a0fceb565 | 2 | private void checkCollision() {
if(r.intersects(StartingClass.hb.getHeliBoy1())){
visible = false;
StartingClass.score += 1;
}
if (r.intersects(StartingClass.hb2.getHeliBoy2())){
visible = false;
StartingClass.score += 1;
}
} |
00d07b22-d918-4a91-9fc6-79b2174ab8f4 | 5 | public void clickedUnit(Unit unit) {
reset();
clickedName.setText(unit.getName());
clickedName.setOpaque(false);
gameIconPanel.add(clickedName);
if (unit.getName().equals("Tank") || unit.getName().equals("Marine")) {
String path = "/imgs/units/" + unit.getName() + ".png";
if (unit.getName() == "Marine") {
path = "/imgs/units/Marines.png";
}
this.unitIcon = new JLabel(new ImageIcon(drawImage(path)));
gameIconPanel.add(iconPanel);
iconPanel.add(unitIcon);
gameIconPanel.repaint();
textbox.setText("Health: " + unit.getCurrentHealth() + "/"
+ unit.getBaseHealth() + "\n" + "Attack Damage: "
+ unit.getCurrentAttackDamage() + "/"
+ unit.getBaseAttackDamage() + "\n" + "Units: "
+ unit.getCurrentNumberUnitsInGroup() + "/"
+ unit.getBaseNumberUnitsInGroup() + "\n" + "Moves: "
+ unit.getCurrentMoveRange() + "/"
+ unit.getBaseMoveRange() + "\n" + "Coordinates: " + "("
+ unit.getCell().getCellPosX() + ","
+ unit.getCell().getCellPosY() + ")" + "\n" + "Owner: "
+ unit.getOwner().getPlayerName());
textbox.setOpaque(false);
gameIconPanel.add(textbox);
}
if (unit.getName() == "Tank") {
rightPanel.add(setTankBar(unit));
this.add(rightPanel);
} else if (unit.getName() == "Marine") {
rightPanel.add(setMarineBar(unit));
this.add(rightPanel);
} else {
System.out.println("No switch found for unit: " + unit.getName());
}
this.revalidate();
} |
7f416aea-0f38-4d4a-99d9-247fc3b80f0c | 0 | @Test
public void testGetRoot() {
QuickUnion spy = Mockito.spy(new QuickUnion(5));
assertThat(spy.getRoot(0), is(0));
assertThat(spy.getRoot(1), is(1));
assertThat(spy.getRoot(2), is(2));
assertThat(spy.getRoot(3), is(3));
assertThat(spy.getRoot(4), is(4));
spy.union(0, 1);
assertThat(spy.getRoot(0), is(1));
assertThat(spy.getRoot(1), is(1));
spy.union(2, 3);
spy.union(4, 2);
assertThat(spy.getRoot(2), is(3));
assertThat(spy.getRoot(3), is(3));
assertThat(spy.getRoot(4), is(3));
} |
20636423-3adc-4c6e-91e3-cf1dd5ce09db | 4 | public static boolean writeCSV(RosterDB rosterDB, String absolutePath) {
// create output file
FileWriter outputStream = null;
try {
outputStream = new FileWriter(absolutePath);
outputStream.write("Name,Vorname,Handy,Aspirant\n");
for (Roster r: rosterDB.getRosters()) {
outputStream.write( r.getFamilyName() + "," + r.getGivenName() + "," +
r.getPhoneNumber() + "," + r.getIsAspirant() + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return true;
} |
3d5c91e2-8e6b-4858-8671-043791b7a646 | 0 | @Override
public String getSex() {
return super.getSex();
} |
769888ec-687a-465d-a770-3b883638658e | 2 | private void mouseHelper(int codeNeg, int codePos,
int amount)
{
GameAction gameAction;
if (amount < 0) {
gameAction = mouseActions[codeNeg];
}
else {
gameAction = mouseActions[codePos];
}
if (gameAction != null) {
gameAction.press(Math.abs(amount));
gameAction.release();
}
} |
951780ed-70d4-4db5-85b8-32ea76a28d53 | 7 | @EventHandler(priority=EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent e)
{
if(e == null)
return;
Player p = e.getPlayer();
if(e.getClickedBlock() == null)
return;
Location l = e.getClickedBlock().getLocation();
if(l == null || TreasureManager.currentTreasureLocation == null)
return;
if(TreasureManager.currentTreasureLocation.compareToLoc(l) && !TreasureManager.found && l.getBlock().getType().equals(Material.CHEST))
{
TreasureHunt.getInstance().getServer().broadcastMessage(ChatColor.GREEN + "Treasure Hunt is ending! " + p.getName() + " found the treasure chest.");
TreasureManager.found = true;
}
} |
b94a80c8-8c7b-4ccc-abf7-805af17e71d0 | 2 | public Cliente getCliente(String nome) throws ExceptionGerentePessoa{
for (Cliente c : clientes) {
if (c.getNome().equalsIgnoreCase(nome)) {
return c;
}
}
throw new ExceptionGerentePessoa("Cliente n��o cadastrado");
} |
f832f89c-9632-4175-8c94-39d971acc765 | 2 | public List<String> getArguments() {
List<String> arguments = new ArrayList<>();
for (CmdLineData one : mData) {
if (!one.isOption()) {
arguments.add(one.getArgument());
}
}
return arguments;
} |
2270c3ea-a329-4a44-9998-d21ec989ea13 | 1 | public void sizeColumnToFit(TreeColumn column) {
int width = getPreferredColumnWidth(column);
if (width != column.getWidth()) {
column.setWidth(width);
invalidateAllRowHeights();
run();
repaint();
}
} |
b4f1638f-a27f-4b90-9489-c72e0c2b1bda | 8 | private static void lagNode(Node node, String ord, int len, int index) {
while (len > index) {
char c = ord.charAt(index);
if (node != null){
HashMap<Character, Node> tempMap = node.barn;
if (!tempMap.containsKey(c) && tempMap.containsKey('?'))
tempMap.put(c, new Node());
if (len == index + 1) {
if (tempMap != null && tempMap.get(c) != null)
tempMap.get(c).posisjoner.add(pos);
pos += len + 1;
}
if (len > index + 1)
node = tempMap.get(c);
}
index++;
}
// if (len > index && node != null) {
// char c = ord.charAt(index);
// HashMap<Character, Node> tempMap = node.barn;
// if (!tempMap.isEmpty()) {
// if (!tempMap.containsKey(c) && tempMap.containsKey('?'))
// tempMap.put(c, new Node());
// if (len == index + 1)
// tempMap.get(c).posisjoner.add(pos);
// if (len > index + 1)
// lagNode(tempMap.get(c), ord, len, index + 1);
// }
// }
// pos++;
} |
aaa9df92-782a-4c91-9ecf-961f47c4f4d3 | 2 | public int getIceResistance(){
int value = 0;
for (Armor armor : armorList) {
if(armor != null) value += armor.getStats().getIceResistance();
}
return value;
} |
f9adece6-577f-4db8-a64a-d717261dd5e9 | 4 | public void createSons(){ // Tested
SimulatedPlanetWars simpw = this.getSim();
for (Planet myPlanet: simpw.MyPlanets()){
//avoid planets with only one ship
if (myPlanet.NumShips() <= 1)
continue;
// We create a son for each of the possible situations
for (Planet notMyPlanet: simpw.NotMyPlanets()){
// Create simulation environment for this son
SimulatedPlanetWars simpw2 = new SimulatedPlanetWars(simpw);
int value = Helper.Dcalculation(myPlanet, notMyPlanet);
simpw2.IssueOrder(myPlanet, notMyPlanet);
simpw2.simulateGrowth();
simpw2.simulateFirstBotAttack();
simpw2.simulateGrowth();
MyNode son;
if (this.isRoot()) {
son = new MyNode(this, simpw2, value, myPlanet, notMyPlanet);
}
else {
son = new MyNode(this, simpw2, value, this.getSource(), this.getDest()); // We only need to know from where to where we want to send our ships to get the best turn
}
this.addSon(son);
}
}
} |
d08bfdcb-01fb-461c-adc0-b9f8a3ba08c2 | 5 | @Override
public int compare(Person o1, Person o2) {
if (o1.getFirstName().equals(o2.getFirstName())
&& o1.getSecondName().equals(o2.getSecondName())
&& o1.getMail().equals(o2.getMail())
&& o1.getPhone().equals(o2.getPhone()))
return 0;
if (o1.getFirstName().length() > o2.getFirstName().length())
return 1;
else return -1;
} |
f3af2ca8-f519-43c0-9942-ae80d5e918a6 | 6 | private double medianOfMedians(ArrayList<double[]> puntos, int axis,int start,int end){
switch (end-start+1){
case 1: return puntos.get(start)[axis];
case 2: return (puntos.get(start)[axis]+puntos.get(start+1)[axis])/2;
case 3: return medianOfThree(puntos, axis,start);
case 4: return medianOfFour(puntos, axis,start);
case 5: return medianOfFive(puntos,axis,start);
default:
{
ArrayList<double[]> medians=new ArrayList<double[]>();
for(int j=start; j<=end; j+=5){
double[]pto = new double[2];
pto[axis]=medianOfMedians(puntos, axis,j,Math.min(j+4, end));
medians.add(pto);
}
return medianOfMedians(medians, axis,0,medians.size()-1);
}
}
} |
effb593d-3809-4e9b-9fb8-1c6c8be8eb14 | 9 | @Override
public void onCommand(POP3Session session, String argument1,
String argument2) throws POP3Exception {
// 检查会话状态是否合法
if (session.getState() != POP3State.TRANSACTION) {
throw new POP3Exception("-ERR auth first");
}
User user = session.getUser();
List<Email> emailList = user.getEmailList();
/*
* 不同参数有不同操作
*/
if (argument1 == null && argument2 == null) { // 没有参数,列出所有邮件的信息
// 列出总体情况
session.sendResponse("+OK " + user.getEmailNumber() + " messages("
+ user.getEmailTotalSize() + " octets)");
// 列出每一封邮件情况
listAllEmail(emailList, session);
// 结束列出
session.sendResponse(".");
} else if (argument1 != null && argument2 == null) { // 列出某一个邮件的信息
//检查参数是否数字
int emailNum = -1;
try {
emailNum = Integer.parseInt(argument1);
} catch (NumberFormatException e) {
// 参数不是数字,出错
throw new POP3Exception("-ERR syntax error");
}
//检查该标号的邮件是否存在
if (emailNum <= 0 || emailNum > user.getEmailNumber()) {
throw new POP3Exception("-ERR no such message, only "
+ user.getEmailNumber() + " messages in maildrop");
}
//获取邮件
Email email = session.getUser().getEmailList()
.get(emailNum - 1);
//检查邮件是否被删除
if (email.isDeleted() == true) {
throw new POP3Exception("-ERR message already deleted");
}
//列出邮件信息
session.sendResponse("+OK " + emailNum + " "
+ EmailUtil.getEmailSize(email));
} else {
// 错误参数
throw new POP3Exception("-ERR syntax error");
}
} |
31a20305-8210-4601-88a8-85d69443db48 | 9 | public void watch(String dirPath) {
Path dirToMonitor = Paths.get(dirPath);
try {
watcher = dirToMonitor.getFileSystem().newWatchService();
// Register create, modify and delete watchers
dirToMonitor.register(watcher,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
while (watcher != null) {
// Retrieve key
WatchKey key = watcher.take();
// Process events
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
logger.info("Created: " + event.context().toString());
changeEvent.fileCreated(dirPath
+ event.context().toString());
} else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
logger.info("Delete: " + event.context().toString());
changeEvent.fileRemoved(dirPath
+ event.context().toString());
} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
logger.info("Modify: " + event.context().toString());
changeEvent.fileModified(dirPath
+ event.context().toString());
} else if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
logger.error("WatchService overflow. Some changes might have been lost.");
// TODO: Handle this to re-initialize the service
// repository from serviceConfig
}
}
// Reset the key
boolean valid = key.reset();
if (!valid) {
logger.info("Invalid WatchKey. Exiting the loop.");
break;
}
}
} catch (Exception e) {
logger.error("An error occurred while watching directory: "
+ dirPath, e);
}
} |
4eecad4a-0cc0-4ccc-a5db-4936803ecb47 | 9 | @Override
public void run() {
boolean done = false;
int waitTime = 500;
try {
Packet pack = new Packet("PUTCHUNK", "1.0", chunk, null);
DistributedBackupSystem.cManager.sendPacket(pack, CommunicationManager.Channels.MDB);
do {
int storedCount = 0;
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {e.printStackTrace();}
for(Packet p : messages) {
if(p.getPacketType().equals("STORED") && Packet.bytesToHex(p.getFileID()).equals(Packet.bytesToHex(chunk.getFileID())) && p.getChunkNo() == chunk.getChunkNo()) {
storedCount++;
}
}
if(storedCount >= chunk.getWantedReplicationDegree()) {
System.out.println("Chunk was successfully stored with required replication degree");
done = true;
}
else if (waitTime < 8000) {
System.out.println("Timeout: did not receive enough STORED replies");
waitTime += waitTime;
}
else {
System.out.println("Chunk was not successfully stored");
DistributedBackupSystem.tManager.sendMessageToActiveTasks(new Packet("DELETE", "1.0", chunk.getFileID(), -1, 0, null, null));
done = true;
}
messages.clear();
} while (!done);
} catch (IOException e) {e.printStackTrace();}
} |
efce3826-a5e2-4872-991b-47340e335127 | 4 | private boolean validateCardType(String cardNumber, CreditCardType cardType) {
CodeValidator apacheCardValidator;
switch (cardType) {
case VISA:
apacheCardValidator = org.apache.commons.validator.routines.CreditCardValidator.VISA_VALIDATOR;
break;
case AMERICAN_EXPRESS:
apacheCardValidator = org.apache.commons.validator.routines.CreditCardValidator.AMEX_VALIDATOR;
break;
case MASTERCARD:
apacheCardValidator = org.apache.commons.validator.routines.CreditCardValidator.MASTERCARD_VALIDATOR;
break;
default:
throw new ValidatorException(new FacesMessage(
"Kartentyp wird nicht akzeptiert."));
}
org.apache.commons.validator.routines.CreditCardValidator validator = new org.apache.commons.validator.routines.CreditCardValidator(
new CodeValidator[] { apacheCardValidator });
if (validator.isValid(cardNumber)) {
return true;
} else {
addMessage(new FacesMessage(
"Der Kartentyp passt nicht zur Kartennummer"));
return false;
}
} |
5c90bd4f-0f33-42ae-a5ec-b9fe11e65afd | 2 | private void drawtracking(GOut g) {
g.chcolor(255, 0, 255, 128);
Coord oc = viewoffset(sz, mc);
for (int i = 0; i < TrackingWnd.instances.size(); i++) {
TrackingWnd wnd = TrackingWnd.instances.get(i);
if (wnd.pos == null) {
continue;
}
Coord c = m2s(wnd.pos).add(oc);
g.fellipse(c, new Coord(100, 50), wnd.a1, wnd.a2);
}
g.chcolor();
} |
f3ed15f2-5c04-47ee-968b-d42448118618 | 8 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Date now = new Date();
String username = request.getParameter("username");
String emailAddress = request.getParameter("emailAddress");
String hashedPassword = test.General.Security.getEncodedSha1Sum(request.getParameter("userPassword"));
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
//First name can only contain upper and lower case characters
if(firstName.matches("^.*[^a-zA-Z ].*$"))
{
request.setAttribute("errorMessage", "Your first name must contain only letters.");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
//Last name can only contain upper and lower case characters
if(lastName.matches("^.*[^a-zA-Z ].*$"))
{
request.setAttribute("errorMessage", "Your last name must contain only letters.");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
//Alphanumeric username regex, credit to http://stackoverflow.com/questions/8248277/how-to-determine-if-a-string-has-non-alphanumeric-characters
if(username.matches("^.*[^a-zA-Z0-9 ].*$"))
{
request.setAttribute("errorMessage", "Usernames must be alphanumeric");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
//Again, I didn't write this regular expression. Credit to: http://stackoverflow.com/questions/624581/what-is-the-best-java-email-address-validation-method
if(!emailAddress.matches(EMAIL_PATTERN))
{
request.setAttribute("errorMessage", "Invalid email address.");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
//check if the username has already been registered, if it has display an error
if(Authentication.usernameRegistered(username))
{
//This username is already in use so set the error message to 'Username is already in use.'
request.setAttribute("errorMessage", "Username is already in use.");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
//check if the email address provided has already been registered, if it has display an error
if(Authentication.emailAddressRegistered(emailAddress))
{
//This email address is already in use so set the error message to 'Email address is already in use.'
request.setAttribute("errorMessage", "Email address is already in use.");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
//attempt to register
if(Authentication.Register(emailAddress, username, hashedPassword, firstName, lastName))
{
User activeUser = Authentication.authenticateUser(emailAddress, hashedPassword);
if(activeUser != null)
{
//Registration was successful
System.out.println("Registration successful");
request.getSession().setAttribute("activeUser", activeUser);
UserMethods.follow(username, username);//follow themselves so that they can see their own messages
MessageMethods.sendMessage(username, "Hello everyone! I just registered.");//send a message telling everyone you've registered
response.sendRedirect(request.getContextPath()+"/registrationsuccessful.jsp");//go to the registration successful page
}
}
//Lots of things could cause this, so display a generic error
else
{
//Registration was unsuccessful
System.out.println("Registration unsuccessful");
request.setAttribute("errorMessage", "Something went wrong and we're not sure what. Try again later.");
request.getRequestDispatcher("register.jsp").forward(request, response);
}
} |
dea428cb-845b-48f0-8da2-a4cd2a7aa928 | 3 | public JSONObject accumulate(
String key,
Object value
) throws JSONException {
testValidity(value);
Object object = opt(key);
if (object == null) {
put(key, value instanceof JSONArray ?
new JSONArray().put(value) : value);
} else if (object instanceof JSONArray) {
((JSONArray)object).put(value);
} else {
put(key, new JSONArray().put(object).put(value));
}
return this;
} |
07e7d5be-f3bd-4357-afdd-9bf4cc7471f3 | 4 | public void verteile_neu_ohne(Spieler zuentfernenderspieler, Spieler[] andereSpieler){
/*
sag mal codest du mit dem editor??
wie gesagt , ja - und ich finde fuer Editor programmieren hab ich relativ wenig falsch gemacht.
und vlt. pfuscht du in zukunft nicht so rum, dass du die Logik zerhaust.
*/
int pos=0;
for (int i=0; i<dieLaender.length; i++){
if (dieLaender[i].gib_besitzer()==zuentfernenderspieler){
dieLaender[i].neuerBesitzer(andereSpieler[pos]);
pos++;
while(dieLaender[i].decArmeen()); // ist so richtig - versau nicht wieder den code
dieLaender[i].mehr_Armeen(1);
}
if (pos>=andereSpieler.length) pos=0;
}
} |
97068c39-d842-43e1-833a-46dd04a9ead1 | 8 | private void render(Graphics g) {
OpSolution sol = solution;
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
// render the ideal solution
int y = 0;
g.setColor(Color.cyan);
for (Double c : sol.ideal) {
int x = (int) (c * width);
g.drawLine(x, y, x, y + 8);
}
y+=9;
// render the target samples (normal and flipped)
for (int i : sol.rankedOrder) {
if (sol.isTarget[i]) {
g.setColor(sol.isFlipped[i] ? Color.yellow : Color.green);
y += 2;
OpSample s = sol.set.get(i);
s.flip(sol.isFlipped[i]);
for (Double c : s) {
int x = (int) (c * width);
g.drawLine(x, y, x, y + 1);
}
}
}
// render noise
for (int i : sol.rankedOrder) {
if (!sol.isTarget[i]) {
g.setColor(Color.red);
// figure out how to mark flipped
y += 2;
for (Double c : sol.set.get(i)) {
int x = (int) (c * width);
g.drawLine(x, y, x, y + 1);
}
}
}
// Draw a white flip line down the middle
g.setColor(Color.white);
int x = (int) (0.5 * width);
g.drawLine(x, 0, x, height);
} |
f39dfab6-3c40-4e45-b74c-5aec4f2b9365 | 7 | private void onTranslate(final String mode) {
new Thread() {
public void run() {
try {
copyMarkedText();
final String text = getClipboardData();
if(text != null) {
translator = createSelectedTranslator();
if(translator == null) return;
translator.setFrom(gui.getComboFrom().getSelectedItem());
translator.setTo(gui.getComboTo().getSelectedItem());
List<String> translations = translator.translateSingleWord(text);
if(translations != null) {
String translation = "";
for(String s : translations) {
translation += s + "\n";
}
final String t = translation;
Runnable setTranslation = new Runnable(){ public void run(){
if(mode.equals("NORMAL"))
setTranslationResultNormal(t);
else
setTranslationResultOverlay(text, t);
} };
Display.getDefault().asyncExec(setTranslation);
}
}
if(robot == null) return;
robot.keyPress(27); // escape druecken, um Markierungsbugs zu vermeiden
robot.keyRelease(27);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} |
cc74607c-c774-431e-8795-c7820beb848b | 6 | private static void editarMusica()
{
boolean salir;
String nombre, codigo;
Integer idMusica;
Musica musica;
do
{
try
{
System.out.print( "Introduce el Id del producto msica: ");
idMusica = Integer.parseInt( scanner.nextLine());
if ((musica = Musica.buscar( idMusica)) == null)
{
System.out.println( "El producto no existe");
salir = !GestionTiendas.preguntaReintentar( "Deseas intentarlo de nuevo?");
}
else
{
System.out.println( "Tipo de producto: " + musica.getNombreTipo());
System.out.println( "Nombre actual del producto: " + musica.getNombre());
System.out.print( "Introduce el nuevo nombre (vaco no modifica): ");
nombre = scanner.nextLine();
if (!nombre.isEmpty())
musica.setNombre( nombre);
System.out.println( "Cdigo actual del producto: " + musica.getCodigo());
System.out.print( "Introduce el nuevo cdigo (vaco no modifica): ");
codigo = scanner.nextLine();
if (!codigo.isEmpty())
musica.setCodigo( codigo);
System.out.println( "Precio base del producto actual " + musica.getPrecio());
System.out.print( "Nuevo precio base (vaco no modifica): ");
codigo = scanner.nextLine();
if (!codigo.isEmpty())
musica.setPrecio( (float)Double.parseDouble( codigo));
System.out.println( "- Producto editado -");
salir = true;
}
}
catch (Exception e)
{
System.out.println( e.getMessage());
salir = !GestionTiendas.preguntaReintentar( "Deseas intentarlo de nuevo?");
}
} while (!salir);
} |
4cd45782-524d-4ef5-a3fb-df226f1b40ac | 4 | private void moveListElement(int increment)
{
Object mover = jListLocations.getSelectedValue();
int oldIndex = jListLocations.getSelectedIndex();
int newIndex = oldIndex + increment;
if(oldIndex < 0 || newIndex > jListLocations.getModel().getSize() - 1)
return;
if(newIndex < 0 || newIndex > jListLocations.getModel().getSize() - 1)
return;
list.removeElementAt(oldIndex);
list.insertElementAt(mover, oldIndex + increment);
jListLocations.setSelectedIndex(newIndex);
} |
f6fc36f9-2d69-4943-a017-a2680005e7b2 | 4 | public void addBook(Book book) {
Connection con = null;
PreparedStatement pstmt = null;
try {
DBconnection dbCon = new DBconnection();
Class.forName(dbCon.getJDBC_DRIVER());
con = DriverManager.getConnection(dbCon.getDATABASE_URL(),
dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD());
pstmt = con.prepareStatement("Insert Into book "
+ "(bok_id, bok_title, bok_subtitle,bok_isbn,bok_publisher,bok_publisherdate,bok_nbpages,bookCategory_id,bookLanguage_id,BookAuthor_id,item_id,bookstatus_id) Values(?,?,?,?,?,?,?,?,?,?,?,?)");
pstmt.setString(1, book.getTitle());
pstmt.setString(2, book.getSubtitle());
pstmt.setString(3, book.getIsbn());
pstmt.setString(4, book.getPublisher());
pstmt.setDate(5, (Date) book.getPublishDate());
pstmt.setInt(6, book.getPagesNb());
pstmt.setLong(7, book.getBookCategory_id());
pstmt.setLong(8, book.getLanguage_id());
pstmt.setLong(9, book.getAuthor_id());
pstmt.setLong(10, book.getItem_id());
pstmt.setLong(11, book.getBookStatus_id());
pstmt.execute();
} catch (SQLException | ClassNotFoundException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
}
}
} |
be5413d2-ff02-477d-a41d-9566c9e418fe | 7 | public static String getDefaultNickname()
{
configLocation = System.getProperty("user.home") + File.separator + "." + title.toLowerCase() + File.separator;
try
{
FileInputStream fis = new FileInputStream(configLocation + "defaultnick");
BufferedReader br = new BufferedReader(new FileReader(new File(configLocation + "defaultnick")));
String s;
while(true)
{
s = br.readLine();
if(s == null)
{
br.close();
fis.close();
throw new FileNotFoundException();
}
if(!s.startsWith("#") && !s.isEmpty())
{
break;
}
}
br.close();
fis.close();
return s;
}
catch(UnsupportedEncodingException e)
{
debug("The UTF-8 encoding is not supported on this system. This is very odd.");
return System.getProperty("user.name");
}
catch (FileNotFoundException e)
{
saveDefaultNickname(System.getProperty("user.name"));
return System.getProperty("user.name");
}
catch (IOException e)
{
saveDefaultNickname(System.getProperty("user.name"));
return System.getProperty("user.name");
}
} |
7ee7838f-b85f-43f9-9f86-04b98cae344c | 8 | public void paintBorder(Component c, Graphics g, int x, int y, int w, int h)
{
if (c instanceof AbstractButton == false)
{
super.paintBorder(c, g, x, y, w, h);
return;
}
AbstractButton button = (AbstractButton) c;
ButtonModel model = button.getModel();
if (model.isEnabled())
{
boolean isPressed = model.isPressed() && model.isArmed();
boolean isDefault = button instanceof JButton
&& ((JButton) button).isDefaultButton();
if (isPressed && isDefault)
{
g.setColor(Color.BLACK); // outer 3D border
g.drawLine(0, 0, 0, h - 1);
g.drawLine(0, 0, w - 1, 0);
g.setColor(Color.BLACK); // inner 3D border
g.drawLine(1, 1, 1, h - 3);
g.drawLine(2, 1, w - 3, 1);
g.setColor(Color.LIGHT_GRAY); // inner 3D border
g.drawLine(1, h - 2, w - 2, h - 2);
g.drawLine(w - 2, 1, w - 2, h - 3);
g.setColor(Color.WHITE); // inner drop shadow __|
g.drawLine(0, h - 1, w - 1, h - 1);
g.drawLine(w - 1, h - 1, w - 1, 0);
}
else if (isPressed)
{
g.setColor(Color.BLACK); // outer 3D border
g.drawLine(0, 0, 0, h - 1);
g.drawLine(0, 0, w - 1, 0);
g.setColor(Color.DARK_GRAY); // inner 3D border
g.drawLine(1, 1, 1, h - 3);
g.drawLine(2, 1, w - 3, 1);
g.setColor(Color.LIGHT_GRAY); // inner 3D border
g.drawLine(1, h - 2, w - 2, h - 2);
g.drawLine(w - 2, 1, w - 2, h - 3);
g.setColor(Color.WHITE); // inner drop shadow __|
g.drawLine(0, h - 1, w - 1, h - 1);
g.drawLine(w - 1, h - 1, w - 1, 0);
}
else if (isDefault)
{
g.setColor(Color.WHITE); // outer 3D border
g.drawLine(0, 0, 0, h - 1);
g.drawLine(0, 0, w - 1, 0);
g.setColor(Color.LIGHT_GRAY); // inner 3D border
g.drawLine(1, 1, 1, h - 3);
g.drawLine(2, 1, w - 3, 1);
g.setColor(Color.DARK_GRAY); // inner 3D border
g.drawLine(1, h - 2, w - 2, h - 2);
g.drawLine(w - 2, 1, w - 2, h - 3);
g.setColor(Color.BLACK); // inner drop shadow __|
g.drawLine(0, h - 1, w - 1, h - 1);
g.drawLine(w - 1, h - 1, w - 1, 0);
}
else
{
// Default
g.setColor(Color.WHITE); // outer 3D border
g.drawLine(0, 0, 0, h - 1);
g.drawLine(0, 0, w - 1, 0);
g.setColor(Color.LIGHT_GRAY); // inner 3D border
g.drawLine(1, 1, 1, h - 3);
g.drawLine(2, 1, w - 3, 1);
g.setColor(Color.BLACK); // inner 3D border
g.drawLine(1, h - 2, w - 2, h - 2);
g.drawLine(w - 2, 1, w - 2, h - 3);
g.setColor(Color.BLACK); // inner drop shadow __|
g.drawLine(0, h - 1, w - 1, h - 1);
g.drawLine(w - 1, h - 1, w - 1, 0);
}
}
else
{
// disabled state
g.setColor(Color.WHITE); // outer 3D border
g.drawLine(0, 0, 0, h - 1);
g.drawLine(0, 0, w - 1, 0);
g.setColor(Color.LIGHT_GRAY); // inner 3D border
g.drawLine(1, 1, 1, h - 3);
g.drawLine(2, 1, w - 3, 1);
g.setColor(Color.DARK_GRAY); // inner 3D border
g.drawLine(1, h - 2, w - 2, h - 2);
g.drawLine(w - 2, 1, w - 2, h - 3);
g.setColor(Color.BLACK); // inner drop shadow __|
g.drawLine(0, h - 1, w - 1, h - 1);
g.drawLine(w - 1, h - 1, w - 1, 0);
}
} |
c20479db-80ae-4daa-9654-cfc132c97e98 | 7 | public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
} |
23a02c22-c51b-4968-ac08-e8e44d2f23cb | 3 | protected void initNewDebateComponents() {
createDebateJfme = new JFrame();
createDebateJpel = new JPanel();
createDebateJfme.add(createDebateJpel);
titleCDJlbl = new JLabel("Title:");
titleCDJlbl.setFont(new Font("Tahoma", 1, 16));
maxTurnsCDJlbl = new JLabel("Max Turns");
maxTurnsCDJlbl.setFont(new Font("Tahoma", 1, 16));
maxTimeCDJlbl = new JLabel("Max Times");
maxTimeCDJlbl.setFont(new Font("Tahoma", 1, 16));
descriptionCDJlbl = new JLabel("Description");
descriptionCDJlbl.setFont(new Font("Tahoma", 1, 16));
studentsCDJlbl = new JLabel("Students");
studentsCDJlbl.setFont(new Font("Tahoma", 1, 16));
teamACDJlbl = new JLabel("Team A");
teamACDJlbl.setFont(new Font("Tahoma", 1, 16));
teamBCDJlbl = new JLabel("Team B");
teamBCDJlbl.setFont(new Font("Tahoma", 1, 16));
litratureCDJlbl = new JLabel("Litrature");
litratureCDJlbl.setFont(new Font("Tahoma", 1, 16));
titleCDJtxt = new JTextField();
maxTurnsDCM = new DefaultComboBoxModel();
for (int i = 0; i < maxTurnsValue.length; i++) {
maxTurnsDCM.addElement(maxTurnsValue[i]);
}
maxTurnsJcbx = new JComboBox(maxTurnsDCM);
maxTimeDCM = new DefaultComboBoxModel();
for (int i = 0; i < maxTimeValue.length; i++) {
maxTimeDCM.addElement(maxTimeValue[i]);
}
maxTimeJcbx = new JComboBox(maxTimeDCM);
descriptionCDJtxa = new JTextArea();
descriptionCDJtxa.setBorder((BorderFactory.createLineBorder(Color.GRAY, 1)));
studentsCDDLM = new DefaultListModel();
studentsCDJlst = new JList(studentsCDDLM);
studentsCDJscl = new JScrollPane(studentsCDJlst);
// Get player list
getPlayerList();
teamACDDLM = new DefaultListModel();
teamACDJlst = new JList(teamACDDLM);
teamACDJscl = new JScrollPane(teamACDJlst);
teamBCDDLM = new DefaultListModel();
teamBCDJlst = new JList(teamBCDDLM);
teamBCDJscl = new JScrollPane(teamBCDJlst);
litratureCDDLM = new DefaultListModel();
litratureCDJlst = new JList(litratureCDDLM);
litratureCDJscl = new JScrollPane(litratureCDJlst);
assignToACDJbtn = new JButton("Assign to A");
assignToACDJbtn.setBackground(new Color(221, 221, 221));
assignToACDJbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Assign to team A
assignToTeamAOrB("A");
}
});
assignToBCDJbtn = new JButton("Assign to B");
assignToBCDJbtn.setBackground(new Color(221, 221, 221));
assignToBCDJbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Assign to team B
assignToTeamAOrB("B");
}
});
removeFromACDJbtn = new JButton("Remove from A");
removeFromACDJbtn.setBackground(new Color(221, 221, 221));
removeFromACDJbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Assign to team A
removeFromTeamAOrB("A");
}
});
removeFromBCDJbtn = new JButton("Remove from B");
removeFromBCDJbtn.setBackground(new Color(221, 221, 221));
removeFromBCDJbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Assign to team B
removeFromTeamAOrB("B");
}
});
setALeaderCDJbtn = new JButton("Set as Team A's Leader");
setALeaderCDJbtn.setBackground(new Color(221, 221, 221));
setALeaderCDJbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setTeamLeader("A");
}
});
setBLeaderCDJbtn = new JButton("Set as Team B's Leader");
setBLeaderCDJbtn.setBackground(new Color(221, 221, 221));
setBLeaderCDJbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setTeamLeader("B");
}
});
uploadCDJbtn = new JButton("Upload");
uploadCDJbtn.setBackground(new Color(221, 221, 221));
uploadCDJbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FileControl fileControl = new FileControl();
if (fileControl.uploadFile("src/xml/")) {
litratureCDDLM.addElement(fileControl.getUploadFileName());
}
}
});
createCDJbtn = new JButton("Create");
createCDJbtn.setBackground(new Color(221, 221, 221));
createCDJbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
createNewDebates();
}
});
GroupLayout createDebateLayout = new GroupLayout(createDebateJpel);
createDebateJpel.setLayout(createDebateLayout);
createDebateLayout.setHorizontalGroup(createDebateLayout.createSequentialGroup()
.addGap(10).addGroup(createDebateLayout.createParallelGroup()
.addGroup(createDebateLayout.createSequentialGroup()
.addComponent(titleCDJlbl)
.addGap(500).addComponent(maxTurnsCDJlbl)
.addGap(10).addComponent(maxTurnsJcbx, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE))
.addGroup(createDebateLayout.createSequentialGroup()
.addComponent(titleCDJtxt, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
.addGap(290).addComponent(maxTimeCDJlbl)
.addGap(10).addComponent(maxTimeJcbx, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE))
.addComponent(descriptionCDJlbl)
.addComponent(descriptionCDJtxa, GroupLayout.PREFERRED_SIZE, 700, GroupLayout.PREFERRED_SIZE)
.addGroup(createDebateLayout.createSequentialGroup()
.addGroup(createDebateLayout.createParallelGroup()
.addComponent(studentsCDJlbl)
.addComponent(studentsCDJscl, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE))
.addGap(10).addGroup(createDebateLayout.createParallelGroup()
.addComponent(assignToACDJbtn, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE)
.addComponent(removeFromACDJbtn, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE)
.addComponent(assignToBCDJbtn, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE)
.addComponent(removeFromBCDJbtn, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE))
.addGap(10).addGroup(createDebateLayout.createParallelGroup()
.addComponent(teamACDJlbl)
.addComponent(teamACDJscl, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE).addGap(10)
.addComponent(teamBCDJlbl)
.addComponent(teamBCDJscl, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE))
.addGap(10).addGroup(createDebateLayout.createParallelGroup()
.addComponent(setALeaderCDJbtn)
.addComponent(setBLeaderCDJbtn))
.addGap(20).addGroup(createDebateLayout.createParallelGroup()
.addComponent(litratureCDJlbl)
.addComponent(litratureCDJscl, GroupLayout.PREFERRED_SIZE, 110, GroupLayout.PREFERRED_SIZE)
.addComponent(uploadCDJbtn)
.addGap(20).addComponent(createCDJbtn)))));
createDebateLayout.setVerticalGroup(createDebateLayout.createSequentialGroup()
.addGap(10).addGroup(createDebateLayout.createParallelGroup()
.addComponent(titleCDJlbl)
.addComponent(maxTurnsCDJlbl)
.addComponent(maxTurnsJcbx, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE))
.addGap(5).addGroup(createDebateLayout.createParallelGroup()
.addComponent(titleCDJtxt, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
.addComponent(maxTimeCDJlbl)
.addComponent(maxTimeJcbx, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE))
.addGap(10).addComponent(descriptionCDJlbl)
.addGap(5).addComponent(descriptionCDJtxa, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE)
.addGap(20).addGroup(createDebateLayout.createParallelGroup()
.addGroup(createDebateLayout.createSequentialGroup()
.addComponent(studentsCDJlbl)
.addGap(5).addComponent(studentsCDJscl, GroupLayout.PREFERRED_SIZE, 220, GroupLayout.PREFERRED_SIZE))
.addGroup(createDebateLayout.createSequentialGroup()
.addGap(50).addComponent(assignToACDJbtn)
.addGap(5).addComponent(removeFromACDJbtn).addGap(55)
.addComponent(assignToBCDJbtn)
.addGap(5).addComponent(removeFromBCDJbtn))
.addGroup(createDebateLayout.createSequentialGroup()
.addComponent(teamACDJlbl)
.addGap(5).addComponent(teamACDJscl, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE).addGap(20)
.addComponent(teamBCDJlbl)
.addGap(5).addComponent(teamBCDJscl, GroupLayout.PREFERRED_SIZE, 90, GroupLayout.PREFERRED_SIZE))
.addGroup(createDebateLayout.createSequentialGroup()
.addGap(90).addComponent(setALeaderCDJbtn)
.addGap(90).addComponent(setBLeaderCDJbtn))
.addGroup(createDebateLayout.createSequentialGroup()
.addComponent(litratureCDJlbl)
.addGap(5).addComponent(litratureCDJscl, GroupLayout.PREFERRED_SIZE, 110, GroupLayout.PREFERRED_SIZE)
.addGap(10).addComponent(uploadCDJbtn)
.addGap(20).addComponent(createCDJbtn))));
createDebateJfme.setSize(750, 560);
createDebateJfme.setLocation(300, 100);
createDebateJfme.setTitle("Create Debates");
createDebateJfme.setVisible(true);
} |
4b5c54a2-5d7d-4844-a76a-6e98213187e4 | 4 | public boolean findAtNE(int piece, int x, int y){
if(x==0 || y==7 || b.get(x-1,y+1)==EMPTY_PIECE) return false;
else if(b.get(x-1,y+1)==piece) return true;
else return findAtNE(piece,x-1,y+1); // there is an opponent
} // end findAtNE |
8316c26d-7bf9-4bff-a893-73ad5b89fd1c | 6 | public List<Chromosome> select(List<Chromosome> population,
int targetPopulationSize) {
List<Chromosome> survivors = new LinkedList<Chromosome>();
List<Double> absoluteFitnesess = new LinkedList<Double>();
double totalFitness=0;
for(Chromosome c : population) {
double valor = Math.abs(f.calculate(d.decode(c)));
absoluteFitnesess.add(valor);
totalFitness+=valor;
}
List<Double> proportionalFitnesses = new LinkedList<Double>();
for(int i=0;i<absoluteFitnesess.size();i++) {
//Como eh minimizacao, pega o valor total e divide por valor,
//para obter a proporcao
double valor = absoluteFitnesess.get(i);
double calc = totalFitness / valor;
if(!proportionalFitnesses.isEmpty()) {
// se nao estiver vazia, soma com o anterior
proportionalFitnesses.add(calc+proportionalFitnesses.get(i-1));
} else {
// se estiver vazia
proportionalFitnesses.add(calc);
}
}
while(survivors.size() < targetPopulationSize) {
// PrintArray.print(proportionalFitnesses);
double max = proportionalFitnesses.get(proportionalFitnesses.size()-1);
double random = Math.random() * max;
// System.out.println();
// System.out.println(random);
// System.out.println();
for(int i=0;i<proportionalFitnesses.size();i++) {
double proporcao = proportionalFitnesses.get(i);
if(random <= proporcao) {
survivors.add(findCromosome(absoluteFitnesess.get(i), population));
break;
}
}
}
return survivors;
} |
aa3094cf-3ded-4c97-b6b5-3091ea4fb56a | 6 | private Node higherNode(T k) {
Node x = root;
while (x != NULL) {
if (k.compareTo(x.key) <0) {
if(x.left != NULL){
x = x.left;
}else{
return x;
}
} else {
if(x.right != NULL){
x = x.right;
}else{
Node current = x;
while(current.parent != NULL && current.parent.right == current) {
current = current.parent;
}
return current.parent;
}
}
}
return NULL;
} |
1b2dad86-ba34-4d99-806a-01aa704762d9 | 0 | public int getNbCoupMax(){
return Integer.parseInt(propriete.getProperty("nb_coups"));
} |
3c648818-a0ee-4642-9549-5733368e7b53 | 8 | public void actionPerformed (ActionEvent event)
{
if (event.getSource() == begin)
{
int i = 0;
double d = 0.00;
String nump = NumProducts.getText();
String dprice = DesiredPrice.getText();
String s = OptionalAdditions.getText();
output.setText(" ");
errlabel1.setForeground(Color.red);
errlabel2.setForeground(Color.red);
quantity.setText("");
cost.setText("");
additional.setText("");
//error checks number of products input
try
{
i = Integer.parseInt(nump.trim());
}
catch (NumberFormatException e)
{
errlabel1.setText ("\t\tQuantity of Products must be of format # and larger than 0. Please Try Again");
}
//error checks desired price input
try
{
d = Double.parseDouble(dprice.trim());
}
catch (NumberFormatException e)
{
errlabel2.setText ("\t\tDesired Price must be of format #.## and larger than 0. Please Try Again");
}
//error checks so that input is larger than zero.
if(i < 1)
{
errlabel1.setText ("\t\tQuantity of products must be of format # and larger than 0. Please Try Again");
}
//error checks so that input is larger than zero.
else if(d <= 0)
{
errlabel2.setText ("\t\tDesired Price must be of format #.## and larger than 0. Please Try Again");
}
//otherwise, if no errors, then have valid inputs and can stop loop
else
{
errlabel1.setText("");
errlabel2.setText("");
notificationlabel.setText("");
NumProducts.setText("");
DesiredPrice.setText("");
OptionalAdditions.setText("");
//rounds numbers to appropriate cents
d = Math.round(d*100)/100.0d;
//gets the optional search criteria
if(s == "")
{
s = "None";
}
cost.setText(" $" + d + " ");
quantity.setText(" " + i + " ");
additional.setText(" " + s);
cost.setForeground (Color.white);
quantity.setForeground (Color.white);
additional.setForeground(Color.white);
NumberCrunch crunch = new NumberCrunch(d, i, s);
try
{
output.append(crunch.getLists() + newline);
//System.out.println(crunch.getProductLists() + newline);
}
catch (org.json.simple.parser.ParseException e)
{
// TODO Auto-generated catch block
notificationlabel.setText ("An error has occurred. We apologize for the inconvenience.");
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
notificationlabel.setText ("An error has occurred. We apologize for the inconvenience.");
e.printStackTrace();
}
//notificationlabel.setText("Results:");
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.