text stringlengths 14 410k | label int32 0 9 |
|---|---|
public boolean pickAndExecuteAnAction() {
try {
//synchronized(Customers){
for(int i =0; i < Customers.size(); i++){
////print("" + Customers.get(i).s );
if(Customers.get(i).s == CustomerState.waiting){
seatCustomer(Customers.get(i));
return true;
}
}
//synchronized(Customers){
for(int i =0; i < Customers.size(); i++){
if(Customers.get(i).s == CustomerState.readyToOrder){
takeOrder(Customers.get(i));
return true;
}
}
//}
//synchronized(Customers){
for(int i =0; i < Customers.size(); i++){
if(Customers.get(i).s == CustomerState.customersFoodReady){
pickUpFood(Customers.get(i));
return true;
}
}
//}
//synchronized(Customers){
for(int i =0; i < Customers.size(); i++){
if(Customers.get(i).s == CustomerState.eating){
GetBill(Customers.get(i));
return true;
}
}
//}
waiterGui.GoToIdleSpot();
return false;
//we have tried all our rules and found
//nothing to do. So return false to main loop of abstract agent
//and wait.
}
catch (ConcurrentModificationException e) {
return false;
}
} | 9 |
public void parseFile() throws IOException{
try{
BufferedReader br = new BufferedReader(new FileReader(filePath));
LinkedList<String> messages = new LinkedList<String>();
sentences = new LinkedList<String[]>();
//Push each massage to messages
String tempString = br.readLine();
while(tempString != null){
if(tempString.length()>40){
messages.addLast(tempString.substring(20, tempString.length()-20));
}
tempString = br.readLine();
}
//Split each message into sentences
BreakIterator sentenceIterator = BreakIterator.getSentenceInstance();
for(String message: messages){
sentenceIterator.setText(message);
int start = sentenceIterator.first();
int end = sentenceIterator.next();
while(end != BreakIterator.DONE){
String[] sentence = message.substring(start,end).split(REGEX_SENTENCE_SPLIT);
//System.out.println(message.substring(start,end));
sentences.add(sentence);
start=end;
end=sentenceIterator.next();
}
}
br.close();
} catch(FileNotFoundException e){
System.out.println("Exception! " + e);
}
System.out.println("PARSED FILES");
} | 5 |
public Node getNode(Coordinate coordinate)
{
if (coordinate.getY() < 0 || coordinate.getY() >= nodeMatrix.size())
{
return null;
}
else if (coordinate.getX() < 0 ||
coordinate.getX() >= nodeMatrix.get(coordinate.getY()).size())
{
return null;
}
else
{
return this.nodeMatrix.get(coordinate.getY()).get(coordinate.getX());
}
} | 4 |
public Cookie() {
print("Cookie constructor");
} | 0 |
private void updateTileButtons(Turn turn) {
if (turn == null || turn instanceof Pass)
throw new IllegalArgumentException("Turn can't be null or a pass");
if (turn instanceof Flip) {
Flip flip = (Flip) turn;
TileButton flipped = tileButtons[flip.getX()][flip.getY()];
flipped.setIcon(flipped.getIcon());
}
else {
// A tile was moved
Move move = (Move) turn;
TileButton from = tileButtons[move.getFromX()][move.getFromY()];
TileButton to = null; // assume off-board
if (!(move instanceof Rescue)) {
to = tileButtons[move.getToX()][move.getToY()];
}
if (gameFrame.playTileNoises()) {
// Make the noise for the moving tile
from.playSound(to != null && to.getTile() != null);
}
// Update the "to" square (if any) to contain the moving tile
if (to != null) {
// Make the captured tile's sound, if any
if (gameFrame.playTileNoises() && to.getTile() != null)
to.playCapturedSound();
to.setTile(from.getTile());
}
// Empty the "from" square where the capturing tile was
from.setTile(null);
}
// Clear any currently selected tile button
selectButton(null);
validate();
paintAll(getGraphics());
} | 9 |
private void setCorrectLocationInfo(Attributes attrs) {
// loop through all attributes, setting appropriate values
for (int i = 0; i < attrs.getLength(); i++) {
if (attrs.getQName(i).equals("x"))
quizSlide.getCorrectStart().setX(
Integer.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("y"))
quizSlide.getCorrectStart().setY(
Integer.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("fontname"))
quizSlide.setCorrectFont(attrs.getValue(i));
else if (attrs.getQName(i).equals("fontsize"))
quizSlide.setCorrectSize(Float.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("fontcolor"))
quizSlide.setCorrectColour(new Color(Integer.valueOf(attrs
.getValue(i).substring(1), 16)));
else if (attrs.getQName(i).equals("alpha"))
quizSlide.setCorrectAlpha(Float.valueOf(attrs.getValue(i)));
else if (attrs.getQName(i).equals("backgroundcolor"))
quizSlide.setCorrectBkColour(new Color(Integer.valueOf(attrs
.getValue(i).substring(1), 16)));
else if (attrs.getQName(i).equals("backgroundalpha"))
quizSlide.setCorrectBkAlpha(Float.valueOf(attrs.getValue(i)));
}
} | 9 |
public int getInitialValue() {
throw_exception();
if (test_index>=test_network.test_numProposers)
throw new Error("Non-proposers should not be asking for initial value");
if(init_logic==1)
return test_index*(-1);
if(init_logic==2)
return test_index-5;
if(init_logic==3)
return test_index*5;
if(init_logic==4)
return Integer.MAX_VALUE-test_index;
if(init_logic==5)
return Integer.MIN_VALUE+test_index;
return test_index;
} | 6 |
protected final void readCRFDraftEntries () throws IOException {
String [] headersArr = null;
int cnt = 0;
String [] tempArr;
while ((tempArr = this.crfReader.readNext()) != null) {
this.OCContainer = new ModelContainer();
CRF OCCRF = new CRF ();
if (headersArr == null) {
headersArr = tempArr;
continue;
}
//set the global CRF parameters.
for (int i = 0; i < tempArr.length; i++) {
if (tempArr [i] == null || tempArr [i].trim ().length () == 0
|| tempArr [i].equals (GenUtil.NA)) {
continue;
}
switch (headersArr [i]) {
case ModelCV.RAVE_PROJECT_NAME:
OCCRF.setName(tempArr [i]);
break;
case ModelCV.RAVE_DRAFT_NAME:
OCCRF.setVersionDesc(tempArr [i]);
break;
}
}
OCCRF.setVersion(ModelCV.OC_CRF_DEF_VERSION);
OCCRF.setRevNotes(ModelCV.OC_CRF_DEF_REV_NOTES);
this.OCContainer.addCRF (OCCRF);
this.CRFMap.put (OCCRF.getName(), this.OCContainer);
cnt++;
addDefOCGroup ();
}
System.out.println ("Read : " + cnt + " CRF draft project.");
} | 8 |
@Override
public void executeTask() {
try {
String temp = "@@@" + DCServerTask.serverID + ":"
+ DCServerTask.numClients;
byte[] senddata = temp.getBytes(); // prepare valid client data for
// sending to server
System.out.println("blasting out to all servers!");
clientN = new DatagramSocket(); // create a new socket
clientN.setBroadcast(true); // enable broadcasting
try { // send to the highest order broadcast address
DatagramPacket sendPacket = new DatagramPacket(senddata,
senddata.length,
InetAddress.getByName("255.255.255.255"), 6785);
clientN.send(sendPacket);
} catch (Exception excep) // this should never fail
{
System.out.println("Failed to broadcast to : 255.255.255.255");
}
// next load all network interfaces into a list
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) // for all network interfaces
{
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback() || !networkInterface.isUp())// if
// its
// a
// 127.0.0.1
// (local
// address)
// or
// not
// connected
continue; // skip it
for (InterfaceAddress interfaceAddress : networkInterface
.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null) // if broadcast isnt allowed
continue; // skip it
try {
DatagramPacket sendPacket = new DatagramPacket(
senddata, senddata.length, broadcast, 6785);
clientN.send(sendPacket); // send the packet to the
// broadcast on all valid
// interfaces
} catch (Exception excep) {
System.out
.println("Error broadcast to : rest of broadcast pools");
}
}
}
} catch (Exception excep) {
System.out.println("failed on something major : " + excep);
}
clientN.close();
stopTask();
} | 8 |
public void checkFloating(int rowStart, int col, int maxRow) {
if (Dime[rowStart][col] != null && Dime[rowStart][col].getBubbleColor() != null) {
if (Dime[rowStart][col].isFloating) {
Bubble.FloatCount++;
Dime[rowStart][col] = new Bubble('0');//borrar
}
}
if (rowStart + 1 < maxRow) {
if (Dime[rowStart][col] == null || Dime[rowStart][col].getBubbleColor() == null) {
if (Dime[rowStart + 1][col] != null && Dime[rowStart + 1][col].getBubbleColor() != null) {
Dime[rowStart + 1][col].isFloating = true;
}
}
checkFloating(rowStart + 1, col, maxRow);//llamada recursiva
}
} | 8 |
private MidiDevice getReceivingDevice() throws MidiUnavailableException {
for (MidiDevice.Info mdi: MidiSystem.getMidiDeviceInfo()) {
MidiDevice dev = MidiSystem.getMidiDevice(mdi);
if (dev.getMaxReceivers() != 0) {
//String lcName = StringUtils.defaultString(mdi.getName()).toLowerCase(Locale.ENGLISH);
//if (lcName.contains(useExternalSynth? "usb": "java")) {
// return dev;
//}
}
}
return null;
} | 2 |
public Map<String, String> getExtra() {
return extra;
} | 0 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI().setVisible(true);
}
});
} | 6 |
@Override
public void nextIteration() {
if ( lastIterationResult == IterationResult.FINISHED_WITHOUT_RESULT) {
//minimum sigma reached, there's no point in continuation
return;
}
++iterationNo;
LOGGER.info("Iteration No. " + iterationNo);
//TODO: albo inaczej to przemyslec albo @SuppressWarnings (sic!)
T newIndividual = (T) individual.mutateIndividual( sigma) ;
if( Individual.comparator.compare(newIndividual, individual) >= 0){
//new individual is better or equal
++fi;
individual = newIndividual;
}
//update sigma if it's time...
if( (this.iterationNo % m ) == 0){
double times = fi / m;
if( times < 1/5){
sigma = c1 * sigma;
}
else if( times > 1/5){
sigma = c2 * sigma;
}
fi = 0;
}
//set status of iteration by analysing value of sigma
if( sigma < minSigma ){
//minimum sigma reached
lastIterationResult = IterationResult.FINISHED_WITHOUT_RESULT;
}
else {
//everything OK
lastIterationResult = IterationResult.OK;
}
} | 6 |
public static String filterForHTMLValue(String _sContent) {
if (_sContent == null) {
return "";
}
// _sContent = replaceStr(_sContent,"</script>","<//script>");
// _sContent = replaceStr(_sContent,"</SCRIPT>","<//SCRIPT>");
char[] srcBuff = _sContent.toCharArray();
int nLen = srcBuff.length;
if (nLen == 0) {
return "";
}
StringBuffer retBuff = new StringBuffer((int) (nLen * 1.8));
for (int i = 0; i < nLen; i++) {
char cTemp = srcBuff[i];
switch (cTemp) {
case '&': // 转化:& -->&why: 2002-3-19
// caohui@0515
// 处理unicode代码
if (i + 1 < nLen) {
cTemp = srcBuff[i + 1];
if (cTemp == '#') {
retBuff.append("&");
} else {
retBuff.append("&");
}
} else {
retBuff.append("&");
}
break;
case '<': // 转化:< --> <
retBuff.append("<");
break;
case '>': // 转化:> --> >
retBuff.append(">");
break;
case '\"': // 转化:" --> "
retBuff.append(""");
break;
default:
retBuff.append(cTemp);
}// case
}// end for
return retBuff.toString();
} | 9 |
private void findPlugins(boolean activateAll) {
File[] files = fileDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".json");
}
});
for( File f : files ) {
try{
Scanner s = new Scanner(f);
s.useDelimiter("\\Z");
Plugin p = new Gson().fromJson(s.next(), Plugin.class);
boolean add = true;
for( Plugin x : plugins ) {
if( x.getName().equalsIgnoreCase(p.getName()) ) {
add = false;
}
}
if( add ) {
plugins.add(p);
}
if(activateAll) {
activePlugins.add(p);
}
p = null;
s.close();
} catch( Exception e ) {
System.err.println("Some problem parsing json");
e.printStackTrace();
}
}
} | 6 |
protected void paint(Event event, Object element) {
if (!isOwnerDrawEnabled())
return;
ViewerCell cell= getViewerCell(event, element);
boolean applyColors= useColors(event);
GC gc = event.gc;
// remember colors to restore the GC later
Color oldForeground = gc.getForeground();
Color oldBackground = gc.getBackground();
if (applyColors) {
Color foreground= cell.getForeground();
if (foreground != null) {
gc.setForeground(foreground);
}
Color background= cell.getBackground();
if (background != null) {
gc.setBackground(background);
}
}
Image image = cell.getImage();
if (image != null) {
Rectangle imageBounds = cell.getImageBounds();
if (imageBounds != null) {
Rectangle bounds = image.getBounds();
// center the image in the given space
int x = imageBounds.x
+ Math.max(0, (imageBounds.width - bounds.width) / 2);
int y = imageBounds.y
+ Math.max(0, (imageBounds.height - bounds.height) / 2);
gc.drawImage(image, x, y);
}
}
Rectangle textBounds = cell.getTextBounds();
if (textBounds != null) {
TextLayout textLayout= getSharedTextLayout(event.display);
// text layout already configured in measure(Event, Object)
Rectangle layoutBounds = textLayout.getBounds();
int x = textBounds.x;
int y = textBounds.y
+ Math.max(0, (textBounds.height - layoutBounds.height) / 2);
textLayout.draw(gc, x, y);
}
if (drawFocus(event)) {
Rectangle focusBounds = cell.getViewerRow().getBounds();
gc.drawFocus(focusBounds.x, focusBounds.y, focusBounds.width + deltaOfLastMeasure,
focusBounds.height);
}
if (applyColors) {
gc.setForeground(oldForeground);
gc.setBackground(oldBackground);
}
} | 9 |
@Override
public final boolean setDebug(boolean d) {
return (debug = d);
} | 0 |
@Override
public void deserialize(Buffer buf) {
dungeonId = buf.readShort();
if (dungeonId < 0)
throw new RuntimeException("Forbidden value on dungeonId = " + dungeonId + ", it doesn't respect the following condition : dungeonId < 0");
inviterId = buf.readInt();
if (inviterId < 0)
throw new RuntimeException("Forbidden value on inviterId = " + inviterId + ", it doesn't respect the following condition : inviterId < 0");
int limit = buf.readUShort();
invalidBuddiesIds = new int[limit];
for (int i = 0; i < limit; i++) {
invalidBuddiesIds[i] = buf.readInt();
}
} | 3 |
public void initialize() {
lastxpos = lastypos = 0;
cellRange = cellSize; cellSize = cellRange + 2*intpad;
jPlColHeader = new JPanel() {
private static final long serialVersionUID = -9098547751937467506L;
java.awt.Rectangle r;
public void paint(Graphics g) {
r = g.getClipBounds();
g.setColor(this.getBackground());
g.fillRect(r.x, r.y, r.width, r.height);
g.setFont( f );
fm = g.getFontMetrics();
int xpos = 0, ypos = 0, attribWidth=0;
g.setColor(fontColor);
xpos = extpad;
ypos=extpad+fm.getHeight();
for(int i=0; i<m_selectedAttribs.length; i++) {
if( xpos+cellSize < r.x)
{ xpos += cellSize+extpad; continue; }
else if(xpos > r.x+r.width)
{ break; }
else {
attribWidth = fm.stringWidth(m_data.attribute(m_selectedAttribs[i]).name());
g.drawString(m_data.attribute(m_selectedAttribs[i]).name(),
(attribWidth<cellSize) ? (xpos + (cellSize/2 - attribWidth/2)):xpos,
ypos);
}
xpos += cellSize+extpad;
}
fm = null; r=null;
}
public Dimension getPreferredSize() {
fm = this.getFontMetrics(this.getFont());
return new Dimension( m_selectedAttribs.length*(cellSize+extpad),
2*extpad + fm.getHeight() );
}
};
jPlRowHeader = new JPanel() {
private static final long serialVersionUID = 8474957069309552844L;
java.awt.Rectangle r;
public void paint(Graphics g) {
r = g.getClipBounds();
g.setColor(this.getBackground());
g.fillRect(r.x, r.y, r.width, r.height);
g.setFont( f );
fm = g.getFontMetrics();
int xpos = 0, ypos = 0;
g.setColor(fontColor);
xpos = extpad;
ypos=extpad;
for(int j=m_selectedAttribs.length-1; j>=0; j--) {
if( ypos+cellSize < r.y )
{ ypos += cellSize+extpad; continue; }
else if( ypos > r.y+r.height )
break;
else {
g.drawString(m_data.attribute(m_selectedAttribs[j]).name(), xpos+extpad, ypos+cellSize/2);
}
xpos = extpad;
ypos += cellSize+extpad;
}
r=null;
}
public Dimension getPreferredSize() {
return new Dimension( 100+extpad,
m_selectedAttribs.length*(cellSize+extpad)
);
}
};
jPlColHeader.setFont(f);
jPlRowHeader.setFont(f);
this.setFont(f);
} | 7 |
private static int[][] createRandomCoordinates(int n, Random random) {
int[][] coordinates = new int[n][2];
for (int i = 0; i < coordinates.length; i++) {
//we ignore the case that two cities have the same coordinates - it should work anyway?
coordinates[i][0] = Math.abs(random.nextInt()%MAP_SIZE);
coordinates[i][1] = Math.abs(random.nextInt()%MAP_SIZE);
}
return coordinates;
} | 1 |
public void setPackgeName(String packgeName) {
this.packgeName = packgeName;
} | 0 |
private static String getImageThunb(Element work) throws Exception{
try{
Elements tmp = work.getElementsByClass("work_thumb");
if(tmp==null || tmp.size()==0) return "http://www.dlsite.com/images/web/home/no_img_sam.gif";
Element thumb = tmp.get(0).child(0);
Elements tmp1 = thumb.getElementsByTag("img");
if(tmp1==null) return "http://www.dlsite.com/images/web/home/no_img_sam.gif";
//thumbnail url
String img = tmp1.get(0).attr("src") ;
if("/images/web/home/no_img_sam.gif".equals(img)){
return "http://www.dlsite.com/images/web/home/no_img_sam.gif";
}
return "http:"+img;
}catch(Exception e){
throw new Exception(e);
}
} | 5 |
public void setFullScreen(DisplayMode dm){
JFrame f = new JFrame();
f.setUndecorated(true);
f.setIgnoreRepaint(true);
f.setResizable(false);
vc.setFullScreenWindow(f);
if(dm != null && vc.isDisplayChangeSupported()){
try{
vc.setDisplayMode(dm);
}catch(Exception ex){}
}
f.createBufferStrategy(2);
} | 3 |
private void collision(){
Rectangle r1 = pika1.getBounds();
Rectangle r2 = pikaBall.getBounds();
Rectangle r4 = pika2.getBounds();
Line2D.Double leftLine = new Line2D.Double(0, 600, 410, 600);
Line2D.Double rightLine = new Line2D.Double(410, 600, 800, 600);
Line2D.Double leftStickLine = new Line2D.Double(400, 375, 400, 600);
Line2D.Double rightStickLine = new Line2D.Double(417, 375, 417, 600);
Line2D.Double upStickLine = new Line2D.Double(400, 375, 416, 375);
if(r1.intersects(r2)){ //pika1撞球
float d = ((float)pikaBall.getX()+(float)pikaBall.getWidth()/2f)-((float)pika1.getX()+(float)pika1.getWidth()/2f);
pikaBall.hit(d, pika1.getPowHit(), 1);
}
else if(r4.intersects(r2)){ //pika2撞球
float d = ((float)pikaBall.getX()+(float)pikaBall.getWidth()/2f)-((float)pika2.getX()+(float)pika2.getWidth()/2f);
pikaBall.hit(d, pika2.getPowHit(), 2);
}
if(r2.intersectsLine(upStickLine)){ //撞到柱子上面
pikaBall.hitUpStick();
}
else if(r2.intersectsLine(rightStickLine) || r2.intersectsLine(leftStickLine)){ //撞到柱子左邊和右邊
pikaBall.hitStick();
}
if(r2.intersectsLine(leftLine) || r2.intersectsLine(rightLine)){ //球落地
if(r2.intersectsLine(leftLine)){ //球落在左邊,2P贏
record.plusCount2();
roundWin = 2;
}
else if(r2.intersectsLine(rightLine)){ //球落在右邊,1P贏
record.plusCount1();
roundWin = 1;
}
timer.cancel();
timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(), 0, 60);
timer3 = new Timer();
timer3.schedule(new HideTask(), 700, 15);
roundOver = true;
pika1.ifStart = false;
pika2.ifStart = false;
}
} | 9 |
private Tree variableListPro(){
Tree variable = null;
VariableList variables = null;
if((variable = variablePro()) != null){
if(accept(Symbol.Id.PUNCTUATORS,",")!=null){
if((variables = (VariableList) variableListPro()) != null){
return new VariableList(variable, variables);
}
return null;
}
return new VariableList(variable);
}
return null;
} | 3 |
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Grafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Grafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Grafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Grafico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Grafico().setVisible(true);
}
});
} | 6 |
@Override
protected void onSubmitAction(ActionRequest request, ActionResponse response, Object command, BindException errors) throws Exception {
final String targetParentPath = StringUtils.defaultIfEmpty(request.getParameter("folderPath"), null);
final String targetEntryPath = StringUtils.defaultIfEmpty(request.getParameter("idPath"), null);
//User edited bookmark
final CollectionFolder commandCollection = (CollectionFolder)command;
//Get the BookmarkSet from the store
final BookmarkSet bs = this.bookmarkSetRequestResolver.getBookmarkSet(request, false);
if (bs == null) {
throw new IllegalArgumentException("No BookmarkSet exists for request='" + request + "'");
}
//Get the target parent folder
final IdPathInfo targetParentPathInfo = FolderUtils.getEntryInfo(bs, targetParentPath);
if (targetParentPathInfo == null || targetParentPathInfo.getTarget() == null) {
throw new IllegalArgumentException("The specified parent Folder does not exist. BaseFolder='" + bs + "' and idPath='" + targetParentPath + "'");
}
final Folder targetParent = (Folder)targetParentPathInfo.getTarget();
final Map<Long, Entry> targetChildren = targetParent.getChildren();
//Get the original bookmark & it's parent folder
final IdPathInfo originalBookmarkPathInfo = FolderUtils.getEntryInfo(bs, targetEntryPath);
if (targetParentPathInfo == null || originalBookmarkPathInfo.getTarget() == null) {
throw new IllegalArgumentException("The specified Bookmark does not exist. BaseFolder='" + bs + "' and idPath='" + targetEntryPath + "'");
}
final Folder originalParent = originalBookmarkPathInfo.getParent();
final CollectionFolder originalCollection = (CollectionFolder)originalBookmarkPathInfo.getTarget();
//If moving the bookmark
if (targetParent.getId() != originalParent.getId()) {
final Map<Long, Entry> originalChildren = originalParent.getChildren();
originalChildren.remove(originalCollection.getId());
commandCollection.setCreated(originalCollection.getCreated());
commandCollection.setModified(new Date());
targetChildren.put(commandCollection.getId(), commandCollection);
}
//If just updaing the bookmark
//TODO should the formBackingObject be smarter on form submits for editBookmark and return the targeted bookmark?
else {
originalCollection.setModified(new Date());
originalCollection.setName(commandCollection.getName());
originalCollection.setNote(commandCollection.getNote());
originalCollection.setUrl(commandCollection.getUrl());
originalCollection.setMinimized(commandCollection.isMinimized());
}
//Persist the changes to the BookmarkSet
this.bookmarkStore.storeBookmarkSet(bs);
} | 6 |
public void transfromHeadline()
{
if(this.hlDepth > 0)
return;
int level = 0;
final Line line = this.lines;
if(line.isEmpty)
return;
int start = line.leading;
while(start < line.value.length() && line.value.charAt(start) == '#')
{
level++;
start++;
}
while(start < line.value.length() && line.value.charAt(start) == ' ')
start++;
if(start >= line.value.length())
{
line.setEmpty();
}
else
{
int end = line.value.length() - line.trailing - 1;
while(line.value.charAt(end) == '#')
end--;
while(line.value.charAt(end) == ' ')
end--;
line.value = line.value.substring(start, end + 1);
line.leading = line.trailing = 0;
}
this.hlDepth = Math.min(level, 6);
} | 9 |
public double cos(int a){
//normalizing
if(a>360){
a %= 360;
}else if(a<0){
a %= 360;
a += 360;
}
//return
if(a <= 90){
return cos[a];
}else if(a <= 180){
return -cos[180 - a];
}else if(a <= 270){
return -cos[a - 180];
}else{
return cos[360 - a];
}
} | 5 |
int exp2RK(ExpDesc e) {
this.exp2val(e);
switch (e.k) {
case LexState.VKNUM:
case LexState.VTRUE:
case LexState.VFALSE:
case LexState.VNIL: {
if (this.nk <= MAXINDEXRK) { /* constant fit in RK operand? */
e.info = (e.k == LexState.VNIL) ? this.nilK()
: (e.k == LexState.VKNUM) ? this.numberK(e.nval())
: this.boolK((e.k == LexState.VTRUE));
e.k = LexState.VK;
return RKASK(e.info);
} else
break;
}
case LexState.VK: {
if (e.info <= MAXINDEXRK) /* constant fit in argC? */
return RKASK(e.info);
else
break;
}
default:
break;
}
/* not a constant in the right range: put it in a register */
return this.exp2anyreg(e);
} | 9 |
public void writeTermsToFile(String strNumber,
Hashtable<String, Double> oTermVsTFIDF) throws IOException {
String strKey = null;
Double maxValue = Double.MIN_VALUE;
String strTerms = "";
int len = oTermVsTFIDF.size() < 5 ? oTermVsTFIDF.size() : 5;
for (int i = 0; i < len; ++i) {
for (Map.Entry<String, Double> entry : oTermVsTFIDF.entrySet()) {
if (entry.getKey().length() > 2
&& entry.getValue() > maxValue
&& !stopwordsMap.containsKey(entry.getKey()
.toLowerCase())
&& entry.getKey().matches("[a-zA-Z]+")) {
maxValue = entry.getValue();
strKey = entry.getKey();
}
}
strTerms = strTerms + " " + strKey;
oTermVsTFIDF.remove(strKey);
strKey = null;
maxValue = Double.MIN_VALUE;
}
oBufferedWriter.write(strNumber + " " + strTerms.trim() + "\n");
System.out.println(strTerms);
} | 7 |
public static void testGeneticAlgorithmDouble()
{
IMyRandomDataFunction<Double> rFunc = new IMyRandomDataFunction()
{
private final Random r = new Random();
@Override
public Double getRandom()
{
return Math.random();
}
};
IMyFitnessTestFunction<Double> tFunc = new IMyFitnessTestFunction<Double>()
{
@Override
public int testFitness(List<Double> list)
{
//System.out.println("list size:"+list.size());
return (int)list.stream().mapToInt(i->evaluate(i)).sum()/list.size();
}
private int evaluate(double given)
{
//System.out.println("g"+given);
if(given>0.333&&given<0.666)
{
return 100;
}
else
{
return 0;
}
}
};
try
{
MyDrawableGraph dg= new MyDrawableGraph(MyDrawableGraph.SortByAxis.xAxis, MyDrawableGraph.SortDirection.asc, 800, 600);
MyCanvasWindow graphWindow = new MyCanvasWindow(800, 600, dg);
graphWindow.startWindow();
MyPopulation<Double> pop = new MyPopulation(50, 10, tFunc, rFunc,false);
for(int i=0;i<1000; i++)
{
try
{
pop.nextGeneration();
int avgFitness =pop.getAverageFitness();
List<MyGraphPoint<Integer,Integer>> graphPoints=pop.getPopulation().stream().map(p->new MyGraphPoint<>(pop.getGenerationCount(),avgFitness)).collect(Collectors.toList());
graphPoints.stream().forEach(si->{try {
dg.addGraphItem(si);
} catch (Exception ex) {
Logger.getLogger(MyStartClass.class.getName()).log(Level.SEVERE, null, ex);
}
});
System.out.println("Population #"+i);
System.out.println("-average fitnes:"+avgFitness);
if(avgFitness>=99)
{
break;
}
//Thread.sleep(100);
}
catch (Exception ex)
{
Logger.getLogger(MyStartClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
pop.getMostFitIndividual().getData().forEach(i->{System.out.println(""+i);});
}
catch (Exception ex)
{
Logger.getLogger(MyStartClass.class.getName()).log(Level.SEVERE, null, ex);
}
} | 7 |
public void deal()
{
Random rand = new Random();
// array of cards that have been dealt
boolean[] dealt = new boolean[21];
int r = rand.nextInt(21);
// picks some random cards for the solution
int check = 0;
String person, weapon, room;
person = weapon = room = "";
while(check < 3)
{
Card solution = cards.get(r);
if(solution.getType() == CardType.PERSON && check ==0)
{
dealt[r] = true;
person = cards.get(r).getName();
check += 1;
}
else if(solution.getType() == CardType.WEAPON && check ==1)
{
dealt[r] = true;
weapon = cards.get(r).getName();
check += 1;
}
else if(solution.getType() == CardType.ROOM && check ==2)
{
dealt[r] = true;
room = cards.get(r).getName();
check += 1;
}
r = rand.nextInt(21);
}
answer = new Solution(person, weapon, room);
// deals the rest of the cards randomly
int playerNum;
for(int i =0; i < cards.size()-3; i++)
{
while(dealt[r])
{
r = rand.nextInt(21);
}
dealt[r] = true;
playerNum = i%6;
players.get(playerNum).getMyCards().add(cards.get(r));
}
} | 9 |
@Override
public void exceptionCaught( ChannelHandlerContext ctx, Throwable cause ) throws Exception
{
if(!(cause.getCause() instanceof IllegalStateException))
cause.printStackTrace();
ctx.close();
} | 1 |
public Boardable[] canBoard(Boardable batch[]) {
final Batch <Boardable> CB = new Batch <Boardable> () ;
if (mainEntrance() != null) CB.add(mainEntrance()) ;
if (docking != null) CB.add(docking) ;
int i = 2 ; for (Mobile m : inside()) if (m instanceof Boardable) {
CB.add((Boardable) m) ;
}
return CB.toArray(Boardable.class) ;
} | 4 |
public void onCommand(CommandSender sender, ChunkyCommand command, String label, String[] args) {
String worldName = null;
if (args.length < 1) {
if (!(sender instanceof Player)) {
Language.IN_GAME_ONLY.bad(sender);
return;
}
worldName = ((Player) sender).getWorld().getName();
} else {
worldName = Language.combineStringArray(args, " ");
}
ChunkyWorld world = ChunkyManager.getChunkyWorld(worldName);
if (world == null) {
Language.NO_SUCH_WORLD.bad(sender, worldName);
return;
}
world.setEnabled(true).save();
Language.ENABLED_WORLD.good(sender);
} | 3 |
public boolean place(int x, int y) { //if all squares are free, place ship and placed == true. if not, return false
if (randomAlignment() == true) {
x = randomWithRange(0,8);
for (int i = x; i < x + 2; i++) {
if (!Grid.isSquareEmpty(i, y)) {
Grid.addToSquare(i, y, this);
position[i][y] = 1;
} else {
return false;
}
}
} else {
x = randomWithRange(0,8);
for (int i = y; i < y + 2; i++) {
if (!Grid.isSquareEmpty(x, i)) {
Grid.addToSquare(x, i, this);
position[x][i] = 1;
} else {
return false;
}
}
}
Grid.addShipToGrid();
placed = true;
return true;
} | 5 |
@Override
public ArrayList<DetectorHit> getHits(Path3D path) { // Initialize the hit list array
ArrayList<DetectorHit> hitList = new ArrayList<>();
if (path == null) {
return hitList;
}
// Create an intersect point object that will contain the line-face
// insercetion coordinates, if there is an intersection, set by the
// intersect method
Point3D intersectPt1 = new Point3D();
Point3D intersectPt2 = new Point3D();
// Create an error point object which will remain (0,0,0) because we do
// not have error data
Point3D errorPt = new Point3D();
// Use the path's points to create lines...
// For each line:
int nPathNodes = path.nodes();
Line3D line = new Line3D();
for (int node = 1; node < nPathNodes; node++) {
line.set(path.getNode(node - 1), path.getNode(node));
if (useBoundaryFilter) {
boolean noHit = true;
for(int f=0; f<boundary.size() && noHit; f++)
if (Face3D.intersection(boundary.face(f), line, errorPt))
noHit = false;
if (noHit)
continue;
}
// For each paddle in the in the sector:
for (DetectorPaddle paddle : paddles.values()) {
// If the line intersects the front, back, or sides of the paddle
if (paddle.intersectIgnoreEnds(line, intersectPt1, intersectPt2)) {
// Create a descriptor for this paddle
DetectorDescriptor desc = new DetectorDescriptor(
detectorId, sectorId, superlayerId, layerId, paddle.getComponent());
// Add the hits to the list
hitList.add(new DetectorHit(desc, intersectPt1, errorPt));
hitList.add(new DetectorHit(desc, intersectPt2, errorPt));
}
}
}
return hitList;
} | 9 |
private static int getDist(Class<?> superClass, Class<?> klass) {
if (klass.isArray()) {
if (superClass.isArray()) {
superClass = superClass.getComponentType();
klass = klass.getComponentType();
} else {
// superClass must be Object. An array fitting into an Object
// must be more general than an array fitting into an Object[]
// array.
return 3000;
}
}
if (superClass.equals(klass)) return 0;
if (superClass.equals(Object.class)) return 2000; // specifying Object is always the most general
if (superClass.isInterface()) {
return 1000;
}
int dist = 0;
while (true) {
dist++;
klass = klass.getSuperclass();
if (superClass.equals(klass)) return dist;
}
} | 9 |
private int[] getStyle(int index) {
if (m_styleOffsets==null || m_styles==null ||
index>=m_styleOffsets.length)
{
return null;
}
int offset=m_styleOffsets[index]/4;
int style[];
{
int count=0;
for (int i=offset;i<m_styles.length;++i) {
if (m_styles[i]==-1) {
break;
}
count+=1;
}
if (count==0 || (count%3)!=0) {
return null;
}
style=new int[count];
}
for (int i=offset,j=0;i<m_styles.length;) {
if (m_styles[i]==-1) {
break;
}
style[j++]=m_styles[i++];
}
return style;
} | 9 |
public void destroy_socket(SocketBase socket_) {
slot_sync.lock ();
int tid;
// Free the associated thread slot.
try {
tid = socket_.get_tid ();
empty_slots.add (tid);
slots [tid].close();
slots [tid] = null;
// Remove the socket from the list of sockets.
sockets.remove (socket_);
// If zmq_term() was already called and there are no more socket
// we can ask reaper thread to terminate.
if (terminating && sockets.isEmpty ())
reaper.stop ();
} finally {
slot_sync.unlock ();
}
} | 2 |
public boolean matches( Class<?> clazz )
{
return this.pattern.matcher( clazz.getSimpleName() ).matches();
} | 1 |
@Override
protected void readAttributes(XMLStreamReader in)
throws XMLStreamException {
// @compat 0.9.x
if (in.getAttributeValue(null, ID_ATTRIBUTE_TAG) == null
&& "model.colony.colonyGoodsParty".equals(in.getAttributeValue(null, "source"))) {
setId("model.modifier.colonyGoodsParty");
setSource(getSpecification().getType("model.source.colonyGoodsParty"));
// end compatibility code
} else {
super.readAttributes(in);
String sourceId = in.getAttributeValue(null, "source");
if (sourceId == null) {
setSource(null);
} else if (sourceId.equals("model.monarch.colonyGoodsParty")) { // @compat 0.9.x
setSource(getSpecification().getType("model.source.colonyGoodsParty"));
// end compatibility code
} else if (getSpecification() != null) {
setSource(getSpecification().getType(sourceId));
}
}
String firstTurn = in.getAttributeValue(null, "firstTurn");
if (firstTurn != null) {
setFirstTurn(new Turn(Integer.parseInt(firstTurn)));
}
String lastTurn = in.getAttributeValue(null, "lastTurn");
if (lastTurn != null) {
setLastTurn(new Turn(Integer.parseInt(lastTurn)));
}
duration = getAttribute(in, "duration", 0);
temporary = getAttribute(in, "temporary", false);
} | 7 |
public void setStartTime(long startTime) {
if (this.startTime != 0) {
log.debug("請注意:進入點設了第二次:" + this.name);
}
this.startTime = startTime;
} | 1 |
public String toString() {
String s = "";
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
char symbol;
switch (mapxy[x][y]) {
case 0:
symbol = '.';
break;
default:
symbol = 'X';
break;
}
s += symbol;
}
s += '\n';
}
return s;
} | 3 |
public static void printXmlElementAttributes(OutputStream stream, Cons attributes) {
{ Stella_Object item = null;
Cons iter000 = attributes;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
item = iter000.value;
{ Surrogate testValue000 = Stella_Object.safePrimaryType(item);
if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_XML_ATTRIBUTE)) {
{ XmlAttribute item000 = ((XmlAttribute)(item));
stream.nativeStream.print(" " + item000.surfaceForm + "=");
}
}
else if (Surrogate.subtypeOfStringP(testValue000)) {
{ StringWrapper item000 = ((StringWrapper)(item));
stream.nativeStream.print("\"");
{ boolean foundP000 = false;
{ char ch = Stella.NULL_CHARACTER;
String vector000 = item000.wrapperValue;
int index000 = 0;
int length000 = vector000.length();
loop001 : for (;index000 < length000; index000 = index000 + 1) {
ch = vector000.charAt(index000);
if (Stella.htmlCharacterNeedsQuotingP(ch)) {
foundP000 = true;
break loop001;
}
}
}
if (foundP000) {
Stella.writeHtmlQuotingSpecialCharacters(stream.nativeStream, item000.wrapperValue);
}
else {
stream.nativeStream.print(item000.wrapperValue);
}
}
stream.nativeStream.print("\"");
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
}
}
} | 6 |
public void run() {
while (true) {
try {
_socket = _serverSocket.accept();
System.out.println("Master connected!");
_istream = _socket.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(_istream));
String receiveMessage;
String[] tokens;
while (true) {
if ((receiveMessage = receiveRead.readLine()) != null) {
System.out.println(receiveMessage);
tokens = receiveMessage.split("[ ]+");
decode(tokens);
System.out.flush();
}
if(!_socket.isConnected()) {
break;
}
}
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} | 7 |
final public void selectUnionStmt() throws ParseException {
selectStmt();
label_8:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case UNION:
case UNION_ALL:
;
break;
default:
jj_la1[20] = jj_gen;
break label_8;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case UNION:
union();
break;
case UNION_ALL:
unionAll();
break;
default:
jj_la1[21] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
selectStmt();
}
} | 7 |
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("src/utilities/kdtree.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
"src/utilities/kdtree.out")));
Scanner in = new Scanner(f);
// Scanner skp=new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt(), k = in.nextInt();
KDTree kdTree = new KDTree(k, n, out);
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
kdTree.myPoints[i].coords[j] = in.nextInt();
}
}
// initialize
kdTree.work();
// output
int cin = in.nextInt();
for (int ci = 0; ci < cin; ci++) {
for (int i = 0; i < k; i++) {
kdTree.aim.coords[i] = in.nextInt();
}
kdTree.KNN(in.nextInt());
// skp.nextLine();
}
}
out.close();
/*
* 15 2 1 3 2 7 3 5 4 2 5 3 5 7 6 6 7 3 8 7 11 7 10 4 9 2 11 3 8 1 10 1
* 1 1 3 10
*/
} | 5 |
public void ticketSubMenu(int ticketID) {
while (true) {
String[] standardOptions = {
"1 - View ticket details",
"2 - Add entry", // DavidE
"q - Go Back"
};
String[] adminOptions = {
"1 - View ticket details",
"2 - Add entry", // DavidE
"3 - Assign Technician",
"q - Go Back"
};
String prompt = "Please select one of the following options";
char choice = 'l'; //hold user's menu choice
if (currentUser.getLevel() == STANDARD) {
choice = SelectOption.variableOption(prompt, standardOptions, '1');
} else if(currentUser.getLevel() == ADMIN) {
choice = SelectOption.variableOption(prompt, adminOptions, 'l');
}
switch (choice) {
case '1':
viewTicket(ticketID);
break;
case '2':
try {
addEntry(ticketID);
viewTicket(ticketID);
} catch (Exception ex) {
System.out.println("Unable to add entry");
ex.printStackTrace();
}
break;
//case three is only accessible to admins based on the
//options sent to SelectOption.variableOption()
case '3':
assignTechnician();
break;
case 'Q':
//leave method to return to previous menu
return;
}
}
} | 8 |
public int canWalk(String side, Hexpos pos){
// 0 someone there's 1 empty but cant 2 empty and can
State state = this;
if(side != "red" && side != "blue")
return -1;
if(state.owner(pos) != null)
return 0;
MyList walkArea = pos.neighbours();
for(Object tmp : walkArea){
if(state.owner((Hexpos)tmp) == side)
return 2;
}
return 1;
} | 5 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (name != other.name)
return false;
if (visited != other.visited)
return false;
return true;
} | 5 |
public List<List<Integer>> sort(List<List<Integer>> listToSort) {
int listSize = listToSort.size();
boolean swapped;
do {
swapped = false;
for (int i = 0; i < listSize - 1; i++) {
int one = listToSort.get(i).get(1);
int two = listToSort.get(i + 1).get(1);
if (one < two) {
Collections.swap(listToSort, i, i + 1);
swapped = true;
}
}
} while (swapped == true);
return listToSort;
} | 3 |
private void printIECLines() {
System.out.print("IEC/F: ");
if ((iecLines & 0x10) == 0) {
System.out.print("A1");
} else {
System.out.print("A0");
}
// The c64 has id = 1
int sdata = ((iecLines & 0x40) == 0) ? 1 : 0;
System.out.print(" C" + sdata);
sdata = ((iecLines & 0x80) == 0) ? 1 : 0;
System.out.print(" D" + sdata);
// The 1541 has id = 2
sdata = ((c1541Chips.iecLines & 0x40) == 0) ? 1 : 0;
System.out.print(" c" + sdata);
sdata = ((c1541Chips.iecLines & 0x80) == 0) ? 1 : 0;
System.out.print(" d" + sdata);
System.out.println(" => C" +
((iecLines & c1541Chips.iecLines & 0x80) == 0 ? 1 : 0)
+ " D" +
((iecLines & c1541Chips.iecLines & 0x40) == 0 ? 1 : 0));
} | 7 |
protected static <K, V> K lookupKeyByValue(Map<K, V> map, V value) {
for (final Map.Entry<K, V> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
} | 2 |
public static boolean allEqualTo(byte[] data, byte value) {
if (data == null || data.length == 0) {
return false;
}
for (byte b : data) {
if (b != value) {
return false;
}
}
return true;
} | 4 |
public String[] getMonthTable() {
setGregorian(gregorianYear, gregorianMonth, 1);
computeChineseFields();
computeSolarTerms();
String[] table = new String[8];
String title = null;
if (gregorianMonth < 11)
title = "";
else
title = "";
title = title + monthNames[gregorianMonth - 1] + "月" + "";
String header = "日一二三四五六";
String blank = "";
table[0] = title;
table[1] = header;
int wk = 2;
String line = "";
for (int i = 1; i < dayOfWeek; i++) {
line += "" + "";
}
int days = daysInGregorianMonth(gregorianYear, gregorianMonth);
for (int i = gregorianDate; i <= days; i++) {
line += getDateString() + "";
rollUpOneDay();
if (dayOfWeek == 1) {
table[wk] = line;
line = "";
wk++;
}
}
for (int i = dayOfWeek; i <= 7; i++) {
line += "" + "";
}
table[wk] = line;
for (int i = wk + 1; i < table.length; i++) {
table[i] = blank;
}
for (int i = 0; i < table.length; i++) {
table[i] = table[i].substring(0, table[i].length() - 1);
}
return table;
} | 7 |
public Value newValue(final Type type) {
if (type == null) {
return BasicValue.UNINITIALIZED_VALUE;
}
boolean isArray = type.getSort() == Type.ARRAY;
if (isArray) {
switch (type.getElementType().getSort()) {
case Type.BOOLEAN:
case Type.CHAR:
case Type.BYTE:
case Type.SHORT:
return new BasicValue(type);
}
}
Value v = super.newValue(type);
if (BasicValue.REFERENCE_VALUE.equals(v)) {
if (isArray) {
v = newValue(type.getElementType());
String desc = ((BasicValue) v).getType().getDescriptor();
for (int i = 0; i < type.getDimensions(); ++i) {
desc = '[' + desc;
}
v = new BasicValue(Type.getType(desc));
} else {
v = new BasicValue(type);
}
}
return v;
} | 9 |
private void seeOnMap(int id){
/*
* emfanizei ton xarth me kedro thn topothesia tou oximatos
*/
JFrame mapFrame = new JFrame("Topothesia Oxhmatos");
String[] latLon=con.getLatLon(id);
String lat,lon;
if(latLon!=null){
lat=latLon[0];
lon=latLon[1];
try {
String imageUrl = "http://maps.google.com/staticmap?center="+lat+","+lon+"&zoom=16&size=630x600&maptype=roadmap&markers=color:blue%7Clabel:S%7A"+lat+","+lon+"&key=ABQIAAAAgb5KEVTm54vkPcAkU9xOvBR30EG5jFWfUzfYJTWEkWk2p04CHxTGDNV791-cU95kOnweeZ0SsURYSA&format=jpg&sensor=false";
String destinationFile = "image.jpg";
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
mapFrame.add(new JLabel(new ImageIcon((new ImageIcon("image.jpg")).getImage().getScaledInstance(630, 600,
java.awt.Image.SCALE_SMOOTH))));
mapFrame.setVisible(true);
mapFrame.pack();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
} | 4 |
public static boolean setGuildType(String[] args, CommandSender s){
//Various checks
if(Util.isBannedFromGuilds(s) == true){
//Checking if they are banned from the guilds system
s.sendMessage(ChatColor.RED + "You are currently banned from interacting with the Guilds system. Talk to your server admin if you believe this is in error.");
return false;
}
if(!s.hasPermission("zguilds.player.settype")){
//Checking if they have the permission node to proceed
s.sendMessage(ChatColor.RED + "You lack sufficient permissions to set a guilds type. Talk to your server admin if you believe this is in error.");
return false;
}
if(!Util.isInGuild(s) == true){
//Checking if they're already in a guild
s.sendMessage(ChatColor.RED + "You need to be in a guild to use this command.");
return false;
}
if(args.length > 2 || args.length == 1){
//Checking if the create command has proper args
s.sendMessage(ChatColor.RED + "Incorrectly formatted guild set type command! Proper syntax is: \"/guild settype <Type>\"");
return false;
}
if(Util.isGuildLeader(s.getName()) == false){
//Checking if the player is the guild leader or officer
s.sendMessage(ChatColor.RED + "You need to be the guild leader to use that command.");
return false;
}
if(args[1].length() > 10 || args[1].length() < 3){
//Checking if the type is valid
s.sendMessage(ChatColor.RED + "Your guild type can only be between 3 and 10 characters.");
return false;
}
sendersCurrGuild = Main.players.getString("Players." + s.getName().toLowerCase() + ".Current_Guild");
Main.guilds.set("Guilds."+sendersCurrGuild+".Type", args[1]);
s.sendMessage(ChatColor.DARK_GREEN + "You set your guilds type to \"" + args[1] + "\".");
return true;
} | 8 |
public SimpleStringProperty firstNameProperty() {
return firstName;
} | 0 |
public void addAccount() {
AddAccountDialog addaccount = new AddAccountDialog(this, "Add Account");
Point loc = getLocation();
addaccount.setLocation(loc.x + 50, loc.y + 50);
addaccount.setModal(true);
addaccount.setVisible(true);
if (!addaccount.canceled()) {
String number = null;
try {
number = bank.createAccount(addaccount.getOwnerName());
}
catch (Exception e){
error(e);
}
if(number==null){
JOptionPane.showMessageDialog(this, "Account could not be created",
"Error", JOptionPane.ERROR_MESSAGE);
}
else {
try {
Account acc = bank.getAccount(number);
accounts.put(number, acc);
String str = addaccount.getBalance().trim();
double amount;
if(str.equals("")) amount=0;
else amount = Double.parseDouble(str);
acc.deposit(amount);
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Illegal Format",
"Error", JOptionPane.ERROR_MESSAGE);
}
catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(this, "Illegal Argument",
"Error", JOptionPane.ERROR_MESSAGE);
}
catch (InactiveException e) {
JOptionPane.showMessageDialog(this, "Account is inactive",
"Error", JOptionPane.ERROR_MESSAGE);
}
catch (Exception e){
error(e);
}
ignoreItemChanges=true;
accountcombo.addItem(number);
accountcombo.setSelectedItem(number);
ignoreItemChanges=false;
refreshDialog();
}
}
} | 8 |
private static Move ForwardRightCaptureForWhite(int r, int c, Board board)
{
Move forwardRightCapture = null;
if(r<Board.rows-2 && c<Board.cols-2 &&
(
board.cell[r+1][c+1].equals(CellEntry.black)
|| board.cell[r+1][c+1].equals(CellEntry.blackKing)
)
&& board.cell[r+2][c+2].equals(CellEntry.empty)
)
{
forwardRightCapture = new Move(r,c,r+2,c+2);
//System.out.println("Forward Right Capture");
}
return forwardRightCapture;
} | 5 |
public static final Dimension getPreferredSize(Font font, String text) {
int width = 0;
int height = 0;
int length = text.length();
if (length > 0) {
TIntIntHashMap map = getWidthMap(font);
int fHeight = getFontHeight(font);
char ch = 0;
int curWidth = 0;
for (int i = 0; i < length; i++) {
ch = text.charAt(i);
if (ch == '\n') {
height += fHeight;
if (curWidth > width) {
width = curWidth;
}
curWidth = 0;
} else {
curWidth += getCharWidth(font, ch, map);
}
}
if (ch != '\n') {
height += fHeight;
}
if (curWidth > width) {
width = curWidth;
}
if (width == 0) {
width = getCharWidth(font, ' ', map);
}
}
return new Dimension(width, height);
} | 7 |
public static void main(String[] args) {
if(args.length!=1){
System.out.println("Inappropriate arguement passed, please pass only 1 arguement");
return;
}
if(!readConfig(Constants.CONFIGFILE,Integer.parseInt(args[0]))){
return ;
}
if(!ConnectionManager.createConnections(currentNode,connectionSocket, mapNodes))
return;
Thread serverThread;
Thread sendThread;
try {
serverThread = new Server(LC,sendMaxClock,sendClockReplyQueue,recvQueue,mapClockReplies);
serverThread.start();
sendThread = new MessageSender(LC,sendQueue,sendMaxClock,sendClockReplyQueue,mapClockReplies);
sendThread.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return;
}
logApplicationConfDetails();
displayMenu();
try {
if(serverThread!=null)
serverThread.join();
if(sendThread!=null)
sendThread.join();
} catch (Exception e) {
e.printStackTrace();
}
} | 7 |
public BrezenhemLine(Excel ex1, Excel ex2) {
begin = ex1;
end = ex2;
setColoredExes();
} | 0 |
public void processGroups(LevelManager lm)
{
for (Group group: lm.modelManager.units.values())
{
//System.out.println(group.position);
if (group != null)
processEntities(group.entities);
}
for (Group group: lm.modelManager.improvements.values())
if (group != null)
processEntities(group.entities);
for (Group group: lm.modelManager.resources.values())
if (group != null)
processEntities(group.entities);
for (Group group: lm.modelManager.features.values())
if (group != null)
processEntities(group.entities);
} | 8 |
protected Background(
String name, String costumeTex, String portraitTex,
int standing, int guild, Object... args
) {
this.name = name ;
if (costumeTex == null) this.costume = null ;
else this.costume = Texture.loadTexture(COSTUME_DIR+costumeTex) ;
if (portraitTex == null) this.portrait = null ;
else this.portrait = Texture.loadTexture(COSTUME_DIR+portraitTex) ;
this.standing = standing ;
this.guild = guild ;
int level = 10 ;
float chance = 0.5f ;
for (int i = 0 ; i < args.length ; i++) {
final Object o = args[i] ;
if (o instanceof Integer) { level = (Integer) o ; }
else if (o instanceof Float ) { chance = (Float) o ; }
else if (o instanceof Skill) {
baseSkills.put((Skill) o, level) ;
}
else if (o instanceof Trait) {
traitChances.put((Trait) o, chance) ;
}
else if (o instanceof Service) {
gear.add((Service) o) ;
}
}
all.add(this) ;
} | 8 |
@Override
public void init (AbstractQueue<QueueElement> queue, Properties props)
throws MalformedURLException {
this.queue = queue;
this.props = props;
String strUrl = props.getProperty("destinationURL");
if (strUrl == null) {
throw new RuntimeException("Required property destinationURL not found.");
}
url = new URL(strUrl);
String strSpecialCharMap = props.getProperty("xslt.param.specialCharMap");
if (!strSpecialCharMap.isEmpty()) {
LoadSpecialCharMap(strSpecialCharMap);
}
else {
logger.warning("Special Char Map file not specified in properties file.");
}
outputProperties.setProperty(OutputKeys.INDENT, "yes");
outputProperties.setProperty(OutputKeys.METHOD, "xml");
outputProperties.setProperty(OutputKeys.STANDALONE, "no");
outputProperties.setProperty("{http://xml.apache.org/xsl}indent-amount", "4");
//outputProperties.setProperty(OutputKeys.DOCTYPE_PUBLIC, "-//IPTC//NewsML");
//outputProperties.setProperty(OutputKeys.DOCTYPE_SYSTEM, "NewsML_1.2.dtd");
} | 2 |
public Console()
{
// create all components and add them
frame=new JFrame("Java Console");
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize=new Dimension((int)(screenSize.width/2),(int)(screenSize.height/2));
int x=(int)(frameSize.width/2);
int y=(int)(frameSize.height/2);
frame.setBounds(x,y,frameSize.width,frameSize.height);
textArea=new JTextArea();
textArea.setEditable(false);
JButton button=new JButton("clear");
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);
frame.getContentPane().add(button,BorderLayout.SOUTH);
frame.setVisible(true);
frame.setVisible(true);
frame.addWindowListener(this);
button.addActionListener(this);
try
{
PipedOutputStream pout=new PipedOutputStream(this.pin);
System.setOut(new PrintStream(pout,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDOUT to this console\n"+se.getMessage());
}
try
{
PipedOutputStream pout2=new PipedOutputStream(this.pin2);
System.setErr(new PrintStream(pout2,true));
}
catch (java.io.IOException io)
{
textArea.append("Couldn't redirect STDERR to this console\n"+io.getMessage());
}
catch (SecurityException se)
{
textArea.append("Couldn't redirect STDERR to this console\n"+se.getMessage());
}
quit=false; // signals the Threads that they should exit
// Starting two seperate threads to read from the PipedInputStreams
//
reader=new Thread(this);
reader.setDaemon(true);
reader.start();
//
reader2=new Thread(this);
reader2.setDaemon(true);
reader2.start();
} | 4 |
public void addToAll(String text) {
try {
text = "Announce: " + text;
Scanner scan = new Scanner(this);
File temp = new File("temp");
PrintWriter pw = new PrintWriter("temp");
while(scan.hasNextLine()) {
String line = scan.nextLine();
int p = 0;
for(int i = 0; i < line.length(); i++) if(String.valueOf(line.charAt(i)).equals(":")) {
p = i;
break;
}
String a = line.substring(0, p), b = p + 1 < line.length() ? text + "@" + line.substring(p + 1, line.length()) : text + "@";
pw.println(a + ":" + b);
}
pw.close();
scan = new Scanner(temp);
pw = new PrintWriter(this);
this.delete();
this.createNewFile();
while(scan.hasNextLine()) pw.println(scan.nextLine());
pw.close();
}catch(Exception ex) {
BaseUtils.warn(ex, true);
}
} | 6 |
@Basic
@Column(name = "SOL_TIPO_SOLICITUD")
public String getSolTipoSolicitud() {
return solTipoSolicitud;
} | 0 |
private void getTransitionsFromXML(Document doc, PetriNet pn) {
NodeList resourcesList = doc.getElementsByTagName("transition");
for (int i = 0; i < resourcesList.getLength(); i++) {
Node nNode = resourcesList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
Transition tr = new Transition(eElement.getAttribute("name"));
int x = Integer.parseInt(eElement.getAttribute("x"));
int y = Integer.parseInt(eElement.getAttribute("y"));
if (cobaFile) {
x = (x * 60) + 20;
y = (y * 38) + 20;
}
tr.setNote(eElement.getAttribute("note"));
tr.setX(x);
tr.setY(y);
if (eElement.getAttribute("fontSize") != "") {
tr.setFontSize(Integer.parseInt(eElement.getAttribute("fontSize")));
} else {
tr.setFontSize(16);
}
if (eElement.getAttribute("red1") != "") {
tr.setColor(new Color(Integer.parseInt(eElement.getAttribute("red1")),
Integer.parseInt(eElement.getAttribute("green1")),
Integer.parseInt(eElement.getAttribute("blue1"))));
} else {
tr.setColor(new Color(10, 10, 10));
}
if (eElement.getAttribute("red2") != "") {
tr.setColor2(new Color(Integer.parseInt(eElement.getAttribute("red2")),
Integer.parseInt(eElement.getAttribute("green2")),
Integer.parseInt(eElement.getAttribute("blue2"))));
} else {
tr.setColor2(new Color(255, 255, 255));
}
if (eElement.getAttribute("width") != "") {
tr.setWidth(Integer.parseInt(eElement.getAttribute("width")));
} else {
tr.setWidth(53);
}
if (eElement.getAttribute("height") != "") {
tr.setHeight(Integer.parseInt(eElement.getAttribute("height")));
} else {
tr.setHeight(38);
}
//tr.setDiagramElement(new DiagramElement(x, y));
pn.addTransition(tr);
}
}
} | 8 |
public void stopSleeping() {
TimerTask isNotSleeping = new TimerTask() {
public void run() {
isSleeping = false;
GUI.println("sleeping stoped");
sendGameResults();
}
};
Timer time = new Timer();
time.schedule(isNotSleeping, 20000);
} | 0 |
protected void onPrivateMessage(String sender, String login, String hostname, String message) {} | 0 |
public final int partitionByCost(int lb, int ub) { // for an outline of how this works, see the partition method for name
Person pivotElement = allPersons[lb];
int max = logicalSize;
int left = lb, right = ub;
Person temp;
while (left < right) {
while ((allPersons[left].totalCostWeek() <= pivotElement.totalCostWeek()) && left + 1 < max) {
left++;
}
while ((allPersons[right].totalCostWeek() > pivotElement.totalCostWeek()) && right - 1 >= 0) {
right--;
}
if (left < right) {
temp = allPersons[left];
allPersons[left] = allPersons[right];
allPersons[right] = temp;
}
}
for (left = lb; left <= right && left + 1 < max; left++) {
allPersons[left] = allPersons[left + 1];
}
allPersons[right] = pivotElement;
return right;
} | 8 |
@Override
public void pickUp(Player player) throws InvalidActionException {
if (isActive())
throw new InvalidActionException("You can't pick up a live grenade");
addItemToPlayersInventory(player);
} | 1 |
public DFS addByteArray(int address, int length, String label, int... format) {
if (label != null)
rom.label[address] = label;
for(int i = 0; i < length; i++) {
for (int f = 0; f < format.length; f++) {
int ca = address + format.length * i + f;
rom.type[ca] = ROM.DATA_BYTEARRAY;
rom.format[ca] = format[f];
rom.width[ca] = format.length;
if (i > 0 && i % 8 == 0 && f == 0)
rom.comment[ca] = "$" + Util.toHex(i);
}
}
return this;
} | 6 |
public Problem validate(final Object instance,
final LowerCase annotation, final Object target,
final CharSequence value)
{
if (value == null || value.length() < 1)
{
if (annotation.required())
{
return new Problem(instance, annotation, target, value);
}
return null;
}
for (int i = 0, length = value.length(); i < length; ++i)
{
char c = value.charAt(i);
if (!Character.isLowerCase(c))
{
return new Problem(instance, annotation, target, value);
}
}
return null;
} | 5 |
public ArrayList<Link> getParentsFromLink(ArrayList<Link> parents, Link link, Link parent) {
if (this == link) {
boolean found = false;
for (Link link1 : parents) {
if (parent == link1) {
found = true;
}
}
if (!found) {
parents.add(parent);
}
}
for (Link currentLink : links) {
currentLink.getParentsFromLink(parents, link, this);
}
return parents;
} | 5 |
protected void initProperties(){
properties = new HashSet();
//scan methods
for (Method method : c.getMethods()) {
String name = method.getName();
if (Modifier.isPublic(method.getModifiers()) && name.startsWith("get")) {
name = lowerFirstChar(name.substring(3));
if (!properties.contains(name) && !name.equals("class")) {
properties.add(name);
}
}
}
fieldProperties = new HashSet();
//scan fields
for (Field field : c.getFields()) {
String name = field.getName();
if (Modifier.isPublic(field.getModifiers()) && !properties.contains(name) ) {
properties.add(name);
fieldProperties.add(name);
}
}
} | 8 |
@Test
public void testFields() {
try {
postModel.getField("fake_field");
fail("Non-existent field should have thrown exception on get");
} catch (IllegalStateException e) {
}
try {
postModel.setField("fake_field", null);
fail("Non-existent field should have thrown exception on set");
} catch (IllegalStateException e) {
}
assertFalse(postModel.hasField("fake_field"));
assertTrue(postModel.hasField("title"));
try {
postModel.setField("title", "New Title");
assertEquals(postModel.getField("title"), "New Title");
} catch (IllegalStateException e) {
e.printStackTrace();
fail("Field not found when it should have been");
}
try {
postModel.setField("title", 3);
fail("Should have had class cast exception assigning int to string field");
} catch (ClassCastException e) {
}
} | 4 |
public static BufferedImage getDepthRender(Raycaster raycaster){
Screen screen = raycaster.getBuffer();
BufferedImage render = new BufferedImage(screen.getWidth(), screen.getHeight(), BufferedImage.TYPE_INT_ARGB);
int width = screen.getWidth();
int height = screen.getHeight();
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
double depth = screen.getDepth(x, y) + 1;
if(depth < 1){
continue;
}
int red = (int)(0xFF / depth);
int colour = (0xFF << 24) | (red << 16);
render.setRGB(x, y, colour);
}
}
return render;
} | 3 |
public long getSendTime() {
return sendTime;
} | 0 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AltaPerfil2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AltaPerfil2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AltaPerfil2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AltaPerfil2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AltaPerfil2().setVisible(true);
}
});
} | 6 |
* @param phase
* @param MV_returnarray
* @return int
*/
public static int computeNextMoonPhase(int n, Keyword phase, Object [] MV_returnarray) {
{ int i = 0;
double am = 0.0;
double as = 0.0;
double c = 0.0;
double x = 0.0;
double x2 = 0.0;
double extra = 0.0;
double rad = Stella.PI / 180.0;
int julianDay = 0;
if (phase == Stella.KWD_NEW_MOON) {
c = ((double)(n));
julianDay = 0;
}
else if (phase == Stella.KWD_FIRST_QUARTER) {
c = n + 0.25;
julianDay = 7;
}
else if (phase == Stella.KWD_FULL_MOON) {
c = n + 0.5;
julianDay = 14;
}
else if (phase == Stella.KWD_LAST_QUARTER) {
c = n + 0.75;
julianDay = 21;
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + phase + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
x = c / 1236.85;
x2 = x * x;
as = 359.2242 + (29.105356 * c);
am = 306.0253 + (385.816918 * c) + (0.01073 * x2);
julianDay = 2415020 + (28 * n) + julianDay;
extra = 0.75933 + (1.53058868 * c) + ((1.178e-4 - (1.55e-7 * x)) * x2);
if ((phase == Stella.KWD_NEW_MOON) ||
(phase == Stella.KWD_FULL_MOON)) {
extra = extra + (((0.1734 - (3.93e-4 * x)) * Math.sin((as * rad))) - (0.4068 * Math.sin((am * rad))));
}
else if ((phase == Stella.KWD_FIRST_QUARTER) ||
(phase == Stella.KWD_LAST_QUARTER)) {
extra = extra + (((0.1721 - (4.0e-4 * x)) * Math.sin((as * rad))) - (0.628 * Math.sin((am * rad))));
}
else {
{ OutputStringStream stream001 = OutputStringStream.newOutputStringStream();
stream001.nativeStream.print("`" + phase + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace()));
}
}
i = ((extra >= 0.0) ? Native.floor(extra) : Native.ceiling(extra - 1.0));
{ int _return_temp = julianDay + i;
MV_returnarray[0] = FloatWrapper.wrapFloat(extra - i);
return (_return_temp);
}
}
} | 9 |
@Override
protected void finalizeRecord(RecordConfig record) {
super.finalizeRecord(record);
boolean minSet = record.getMinLength() != null;
if (stream.isStrict()) {
if (record.getMinLength() == null) {
record.setMinLength(record.getMinSize());
}
if (record.getMaxLength() == null) {
record.setMaxLength(record.getMaxSize());
}
}
else {
if (record.getMinLength() == null) {
record.setMinLength(0);
}
if (record.getMaxLength() == null) {
record.setMaxLength(Integer.MAX_VALUE);
}
}
// validate maximum record length is not less than the minimum record length
if (record.getMaxLength() < record.getMinLength()) {
if (minSet) {
throw new BeanIOConfigurationException(
"Maximum record length cannot be less than minimum record length");
}
else {
throw new BeanIOConfigurationException(
"Maximum record length must be at least " + record.getMinLength());
}
}
// if there is an unbounded component in the middle of the record, we need to
// set the end position on it
if (unboundedComponent != null && unboundedComponentFollower != null) {
setEndPosition(unboundedComponent, unboundedComponentFollower.getPosition());
}
} | 9 |
public int sqrt(int x) {
if (x <= 0)
return 0;
int k = 0;
int o = x;
int base = 5;
while (x >= 1) {
++k;
x /= base;
}
int p;
if((k & 1) == 1){
p = k / 2;
}else{
p = k/2 -1;
}
int q = k - p;
for (int i = pow(p,base); i <= pow(q,base); ++i) {
if (i * i <= o && (i + 1) * (i + 1) > o) {
return i;
}
}
return p;
} | 6 |
public boolean partidoSemiCompleto() {
return (listaJugadores.size()==10) && (listaJugadores.stream().anyMatch(j -> j.getModo() instanceof Solidario)|| listaJugadores.stream().anyMatch(j -> j.getModo() instanceof Condicional));
} | 2 |
void deleteDirectory(File dirPath) {
File files[] = dirPath.listFiles();
for (File file : files) {
if (file.isFile()) {
file.delete();
} else {
String ft[] = file.list();
if (ft.length == 0) {
file.delete();
} else {
this.deleteDirectory(file);
}
}
}
dirPath.delete();
} | 3 |
public void setColumnName(String columnName) {
this.columnName = columnName;
} | 0 |
@Override
public void mouseMove(MouseEvent e) {
if(this.getMouseListener() != null)
{
this.getMouseListener().MouseMove(this, e);
}
} | 1 |
public Object GetNextReady()
{
//holds first object in the ready queue
Object tmp = null;
//pickup priority Object
tmp = readyQueue.poll();
//return the object
return tmp;
} | 0 |
@Override
public int compare(String s1, String s2)
{
if (s1.equals(s2))
return 0;
if ((s1.compareTo("NIL") == 0) || (s2.compareTo("LIN") == 0))
return 1;
if ((s2.compareTo("NIL") == 0) || (s1.compareTo("LIN") == 0))
return -1;
if (s1.compareTo(s2) < 0)
return -1;
else return 1;
}//compare(String, String) | 6 |
public int clamp(int num, int min, int max){
if(num <= min)
{
return min;
}
if(num >= max)
{
return max;
}
return num;
} | 2 |
public void eliminarUltimo(){
Nodo<T> q = this.p;
Nodo<T> t = new Nodo<T>();
if(q.getLiga() == null){
this.p = null;
}else{
while(q.getLiga() != null){
t = q;
q = q.getLiga();
}
t.setLiga(null);
}
} | 2 |
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Pair other = (Pair) obj;
if (left == null) {
if (other.left != null)
return false;
} else if (!left.equals(other.left))
return false;
if (right == null) {
if (other.right != null)
return false;
} else if (!right.equals(other.right))
return false;
return true;
} | 9 |
private boolean isSame(DListNode node, short red, short green, short blue, byte direction){
Run test = new Run(1,red,green,blue);
if (direction == CURR){
return node.run.equalsIntensities(test);
}
else if (direction == NEXT && node.next.run != null){
return node.next.run.equalsIntensities(test);
}
else if (direction == PREV && node.prev.run != null){
return node.prev.run.equalsIntensities(test);
}
return false;
} | 5 |
@Override
public void endDocument() throws SAXException {
System.out.println("end Document");
} | 0 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.