method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
2c70fada-d434-470c-aeb6-f86ebf65ca24 | 3 | public BackGround(final JFrame frame, final String imageName ){
Container panel = frame.getContentPane();
try {
imageOrg = ImageIO.read(this.getClass().getResource("/Image/" + imageName));
image = imageOrg.getScaledInstance(panel.getWidth(), panel.getHeight(), Image.SCALE_SMOOTH);
} catch (IOException ex) {
ex.printStackTrace();
}
/**
* Using anonymous method to add a listener to the frame
* which will be used to adjust the dimensions of the image
* based on changes of the same to the frame.
*/
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
final int width = frame.getWidth();
final int height = frame.getHeight();
image = width > 0 && height > 0 ? imageOrg.getScaledInstance(width, height, Image.SCALE_SMOOTH) : imageOrg;
frame.repaint();
}
});
}//end ctor |
1222639b-d38d-40e5-aa5a-c4f219a863a6 | 9 | static void llenar(LinkedList<int[]> r, Pieza p, int vAbajo){
int v=vAbajo,x=vAbajo;
for(Pieza m=p;m!=null;m=m.piezas[(x+1)%4]){
r.add(new int[]{m.valor,v});
int i=0;
if(m.piezas[(v+1)%4]!=null)for(;i<4;i++)if(m.piezas[(v+1)%4].piezas[i]==m)break;
x=v;
v=(i+1)%4;
}
v=vAbajo;x=vAbajo;
for(Pieza m=p;m!=null;m=m.piezas[(x+3)%4]){
if(m!=p)r.addFirst(new int[]{m.valor,v});
int i=0;
if(m.piezas[(v+3)%4]!=null)for(;i<4;i++)if(m.piezas[(v+3)%4].piezas[i]==m)break;
x=v;
v=(i+3)%4;
}
} |
ec189768-89dd-4111-af97-a81044622cbe | 6 | private void runStateMachine() {
while(!tokenFoundFlag){
if(exitSMFlag)
break;
switch(nextState){
case 1: // letter
letter();
break;
case 2:
symbol();
break;
case 3:
number();
break;
case 4:
otherChar();
break;
}
}
}// end of "runStateMachine" |
dc880ece-3d13-4964-89fe-64dbf9b11063 | 4 | private static void validate(String input) throws Exception {
if (input.length() > MAX_LENGTH)
throw new Exception("word can be no longer than 30 characters");
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < input.length(); i++) {
set.add(input.charAt(i));
if (!Character.isLetter(input.charAt(i)))
throw new Exception("Word can only has letters");
}
if (set.size() > MAX_UNIQUE_CHARS)
throw new Exception(String.format("word can not have more than %d unique characters", MAX_UNIQUE_CHARS));
} |
fb24e808-b25c-4716-b6dc-7cf7ec5c49be | 0 | public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
} |
bc6b3fcf-f6a0-419b-b375-0a7b45efb726 | 3 | public static boolean isInRange(float num, float max, float min, boolean showError)
{
final boolean bool = false;
if (num > max || num < min) if (showError)
{
final IllegalArgumentException as = new IllegalArgumentException("The Number Has to be more than " + max + " and less than " + min + "!");
as.printStackTrace();
exit();
}
return bool;
} |
8de26029-ed72-446d-98c6-78801c57814d | 4 | public void shootAt(Robot paramRobot, Point paramPoint) {
Debug.println("shootAt(" + paramPoint + ")");
this.RobotsWereShootingAt.addElement(paramRobot);
paramRobot.playSound("Robot-Angry");
if (!this.active)
{
Point localPoint1 = getPosition().getMapPoint();
localPoint1.translate(1, 1);
getEnvironment().getShroud().setVisible(localPoint1, 1, true, true);
Point localPoint2 = new Point(paramPoint.x - getPosition().x + 1, paramPoint.y - getPosition().y + 1);
Debug.println(localPoint2);
int i = (int)Math.rint(Math.atan2(-localPoint2.y, localPoint2.x) * 57.295779513082323D);
if (i < 0) {
i = 360 + i;
}
Debug.println("angle: " + i + ", distance: " + this.distance);
i %= 180;
this.distance = (1 + this.distance / 3);
i = ANGLE_LOOKUP[i];
this.destOrientation = i;
Debug.println("angle: " + i + ", distance: " + this.distance);
if (this.missImages == null)
{
this.missImages = new Image[9];
for (int j = 0; j < 9; j++)
this.missImages[j] = GameApplet.thisApplet.getImage(
"com/templar/games/stormrunner/media/images/objects/cannon_miss/g_miss_0" + (j + 1) + ".gif");
}
AnimationComponent localAnimationComponent = new AnimationComponent();
AnimationComponent[] arrayOfAnimationComponent = new AnimationComponent[1];
localAnimationComponent.setCells(this.missImages);
localAnimationComponent.setSequence(missSequence, null, false);
boolean[][] arrayOfBoolean = new boolean[3][3];
Mask localMask = new Mask(getEnvironment(), new Position(paramPoint.x - 1, paramPoint.y - 1, 0, 0), null, arrayOfBoolean, true);
localMask.setLayer("miss anim");
localMask.setLayer("Robot Effects");
arrayOfAnimationComponent[0] = localAnimationComponent;
localMask.setImages(arrayOfAnimationComponent);
localMask.setVisible(false);
getEnvironment().addObject(localMask);
Debug.println("misses.put(" + paramPoint + "," + localMask + ")");
this.misses.put(paramPoint, localMask);
this.active = true;
this.shootPos = paramPoint;
}
} |
7e2585c7-c16a-40b4-88bb-95b7135005c8 | 3 | private static void launchLoginPage() {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop()
.browse(new URI(
"https://www.freesound.org/apiv2/oauth2/logout_and_authorize/?client_id=608002b12fb0074895d5&response_type=code&state=xyz"));
} catch (IOException e) {
e.printStackTrace();
flagLogIn = true;
} catch (URISyntaxException e) {
e.printStackTrace();
flagLogIn = true;
}
}
} |
0eac11e8-62c5-4270-9091-83b95d5f5e77 | 6 | public static void drawPixels(int i, int j, int k, int l, int i1)
{
if(k < topX)
{
i1 -= topX - k;
k = topX;
}
if(j < topY)
{
i -= topY - j;
j = topY;
}
if(k + i1 > bottomX)
i1 = bottomX - k;
if(j + i > bottomY)
i = bottomY - j;
int k1 = width - i1;
int l1 = k + j * width;
for(int i2 = -i; i2 < 0; i2++)
{
for(int j2 = -i1; j2 < 0; j2++)
pixels[l1++] = l;
l1 += k1;
}
} |
09c9b6d3-989d-41f3-bdf5-5981602b187e | 1 | public void setId(int id) throws ErroValidacaoException {
if(id >0) {
this.id = id;
}
else {
throw new ErroValidacaoException("O id não pode ser menor que 0 !");
}
} |
a1191ba2-3ab8-487b-a103-06572080f32f | 1 | public static void validateMove() {
if (!validMove) {
System.out.println("Invalid Move! Try Again");
System.out.println();
} else {
moves = moves + 1;
points = points + 5;
AchievementRatio = points / moves;
}
} |
808cac27-86f0-4507-9839-1f07f1722259 | 9 | public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BoundaryBoxFilter)) return false;
BoundaryBoxFilter other = (BoundaryBoxFilter) o;
if (!this.fieldName.equals(other.fieldName)
|| this.includeLower != other.includeLower
|| this.includeUpper != other.includeUpper
) { return false; }
if (this.lowerTerm != null ? !this.lowerTerm.equals(other.lowerTerm) : other.lowerTerm != null) return false;
if (this.upperTerm != null ? !this.upperTerm.equals(other.upperTerm) : other.upperTerm != null) return false;
return true;
} |
466de1a9-c2c3-40a9-a5f2-e30dc040bcae | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CompareFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CompareFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CompareFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CompareFrame.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 CompareFrame().setVisible(true);
}
});
} |
65996dfa-af2c-4ad6-b188-4b6451c8e1b2 | 4 | public int checkMouseCollision(Point clickedPoint) {
double d0 = points.get(0).getDistanceTo(clickedPoint);
if (d0 <= Constants.POINT_RADIUS) {
return 0;
}
double d1 = points.get(1).getDistanceTo(clickedPoint);
if (d1 <= Constants.POINT_RADIUS) {
return 1;
}
double d2 = points.get(2).getDistanceTo(clickedPoint);
if (d2 <= Constants.POINT_RADIUS) {
return 2;
}
double d3 = points.get(3).getDistanceTo(clickedPoint);
if (d3 <= Constants.POINT_RADIUS) {
return 3;
}
return -1;
} |
fa325955-1caf-4aae-a1f0-4595f5248033 | 8 | public void update(double elapsed) {
this.elapsed += elapsed;
while (this.elapsed > MOVE_TIME_MILLS) {
this.elapsed -= MOVE_TIME_MILLS;
for (GameElement element : gameElements) {
element.colides(schlange);
}
schlange.move();
}
//check if there are catchable diamonds
boolean catchableDias = false;
for (Diamant dia : diamanten) {
if (!dia.isCatched()) {
catchableDias = true;
}
}
if (!catchableDias) {
for (GameListener listener : listeners) {
listener.win(new GameEvent(schlange.getLength()));
}
}
//check if game is lost
if (!schlange.isAlive()) {
for (GameListener listener : listeners) {
listener.loose(new GameEvent(schlange.getLength()));
}
}
//update fps
fps = (int) (1000 / elapsed);
} |
a5c140fb-c582-44a0-bff1-1e1a1ebee0d1 | 8 | public void validateEventStructure(String eventName, List<MMTFieldValueHeader> fieldValueElements) throws MMTInitializationException {
if (this.getProtoConfig() == null) {
throw new MMTInitializationException("Initialization Exception: getProtoConfig() returns null. A valid MMTRemoteProtocolConfig must be set.");
} else {
MMTEventConfig event = this.getProtoConfig().getEventByName(eventName);
if (event == null) {
throw new MMTInitializationException("Initialization Exception: Event name \"" + eventName + "\" is not registered. Each Event MUST be registered in order to be used.");
} else {
for (MMTFieldValueHeader fvh : fieldValueElements) {
if (!event.isHeaderField(fvh.getHeaderField())) {
throw new MMTInitializationException("Initialization Exception: Unkown header field \"" + fvh.getHeaderField() + "\" in event \"" + eventName + "\". All header fields MUST be configured.");
}
}
List<String> requiredHeaderFields = event.getRequiredHeaderFields();
for (String requiredField : requiredHeaderFields) {
boolean fieldExists = false;
for (MMTFieldValueHeader fvh : fieldValueElements) {
if (requiredField.equals(fvh.getHeaderField())) {
fieldExists = true;
break;
}
}
if (!fieldExists) {
throw new MMTInitializationException("Initialization Exception: required header field \"" + requiredField + "\" is missing in event \"" + eventName + "\". All required headers MUST be present.");
}
}
}
}
} |
3586a9c3-dd49-4a4e-869e-323fae9bce72 | 6 | public int[] rangeOfBST(TreeNode root) {
int []result = {root.val,root.val};
if(root.left !=null){
int []range = rangeOfBST(root.left);
if(range[0]<=range[1]&&range[1]<root.val){
result[0]=range[0];
}
else {
result[0] = 1;result[1] = -1;
return result;
}
}
if(root.right !=null){
int []range = rangeOfBST(root.right);
if(range[0]<=range[1]&&range[0]>root.val){
result[1]=range[1];
}
else {
result[0] = 1;result[1] = -1;
return result;
}
}
return result;
} |
4412d14d-929d-490c-a6e6-cb0cc9b747d6 | 9 | @Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
if (!(value instanceof TreeItem)) {
setText(value.toString());
setBackground(isSelected ? _enabledSelectedBackground : _defaultBackground);
setForeground(isSelected ? _enabledSelectedForeground : _defaultForeground);
} else {
TreeItem item = (TreeItem) value;
sb.setLength(0);
sb.append(item._treeName);
sb.append(" (");
sb.append(item._volumeName);
sb.append(")");
setText(sb.toString());
boolean enabled = item._selected ^ _supplySide;
Color background = isSelected ? (enabled ? _enabledSelectedBackground : _disabledSelectedBackground)
: (enabled ? _defaultBackground : _disabledBackground);
Color foreground = isSelected ? (enabled ? _enabledSelectedForeground : _disabledSelectedForeground)
: (enabled ? _defaultForeground : _disabledForeground);
setBackground(background);
setForeground(foreground);
}
return this;
} |
2901d76d-66c6-461c-9268-d4f0733efffc | 7 | public void createGlobalItem(GroundItem i) {
for (Player p : Server.playerHandler.players){
if(p != null) {
Client person = (Client)p;
if(person != null){
if(person.playerId != i.getItemController()) {
if (!person.getItems().tradeable(i.getItemId()) && person.playerId != i.getItemController())
continue;
if (person.distanceToPoint(i.getItemX(), i.getItemY()) <= 60) {
person.getItems().createGroundItem(i.getItemId(), i.getItemX(), i.getItemY(), i.getItemAmount());
}
}
}
}
}
} |
b8483f6f-768f-452c-8154-861551b4cd55 | 1 | public boolean tienePrevio(){
boolean resp = false;
if(previo != null)
resp = true;
return resp;
} |
002d15d0-1e9a-4409-b422-1bcf3e399156 | 4 | @Override
public void moveCursor(int x, int y)
{
if(x < 0)
x = 0;
if(x >= size().getColumns())
x = size().getColumns() - 1;
if(y < 0)
y = 0;
if(y >= size().getRows())
y = size().getRows() - 1;
textPosition.setColumn(x);
textPosition.setRow(y);
refreshScreen();
} |
3789024e-331b-43e7-884d-55c0865d4d38 | 9 | private static int index(char c) {
switch (c) {
case '*':
return 0;
case 'S':
return 1;
case 'I':
return 2;
case 'V':
return 3;
case 'X':
return 4;
case 'L':
return 5;
case 'C':
return 6;
case 'D':
return 7;
case 'M':
return 8;
//case 'E':
// return 7;
}
return -1;
} |
f24c898e-e92f-4bf9-bbfb-ce8c5736846e | 6 | public void paintComponent(Graphics g){
super.paintComponent(g);
g.clearRect(0, 0, getWidth(), getWidth());
int height = engine.area.length;
/* if(height * cellSize >= this.getHeight()){
height = (int) Math.floor(this.getHeight()/cellSize);
}*/
int width = engine.area[0].length;
/* if(width * cellSize >= this.getWidth()){
width = (int)Math.floor( this.getWidth()/cellSize);
}*/
if (cellSize>5){
for (int i=0;i<=width-x;i++){
g.drawLine(i*cellSize, 0, i*cellSize, (height-y)*cellSize);
}
for (int i=0;i<=height-y;i++){
g.drawLine(0, i*cellSize, (width-x)*cellSize, i*cellSize);
}
}
for (int i=y;i<height;i++){
for (int j=x;j<width;j++){
if (engine.getArea()[i][j]){
painLiveCell(i-y, j-x, g);
}
}
}
} |
ade4f2b4-c918-41ff-9bb0-1529fec1c93c | 0 | public int getColumnCount() {
return 3;
} |
6e7613b9-c001-41e6-8c62-fd9713876c74 | 8 | public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
System.out.print("Veuillez entrez vos symptomes: ");
String descripMaladie = myScan.nextLine().toUpperCase();
String msgDocteur;
if (descripMaladie.contains("TOUSSE") && descripMaladie.contains("SANG")) {
msgDocteur = "Tuberculose";
} else if (descripMaladie.contains("TOUSSE") && descripMaladie.contains("GORGE")) {
msgDocteur = "Angine aigue";
} else if (descripMaladie.contains("GORGE")) {
msgDocteur = "Angine";
} else if (descripMaladie.contains("TETE")) {
msgDocteur = "Migraine";
} else if (descripMaladie.contains("FATIGUE")) {
msgDocteur = "Besoin d'exercices";
} else if (descripMaladie.contains("TOUSSE")) {
msgDocteur = "Toux sèche";
} else {
msgDocteur = "Maladie inconnue";
}
System.out.printf("Votre maladie: %s\n", msgDocteur);
} |
67998b97-e53a-4014-a1fc-1e26400a5cce | 3 | public boolean hasFlag (Integer id, Variables flag) {
if (npcData.containsKey(id + ":flag")) {
String[] flags = npcData.get(id + ":flag").split(",");
for (Integer i = 0; flags.length > i; i++) {
if (flags[i].equals(flag.toString()))
return true;
}
}
return false;
} |
27c692e5-fdd8-40e4-904d-1355b1db4370 | 1 | public String toString()
{
if (nome != null)
return nome.toString();
return id + "";
} |
559f0b3f-a5f3-4ae0-b1ed-19d3f715472e | 8 | public void tick()
{
try {
player.tick();
} catch (InterruptedException e) {
e.printStackTrace();
}
sun.tick();
wife.idle();
par.tick();
sad.tick();
/*The Bottom Bounding boxes */
//stop1 = new Rectangle(122, 725, 256, 40);
stop2 = new Rectangle(350, 440, 256, 10);
stop3 = new Rectangle(122, 718, 256, 10);
stop4 = new Rectangle(122, 718, 256, 10);
stop5 = new Rectangle(122, 718, 256, 10);
stop6 = new Rectangle(122, 718, 256, 10);
for (int i = 0; i < flyers.size(); i++) {
Flying fly = (Flying)flyers.get(i);
fly.tick();
}
for (int i = 0; i < items.size(); i++) {
Item it = (Item)items.get(i);
it.tick();
}
if(tickCount2 == DELAY){
tickCount2 = 0;
}
if(timeLeft <= 0){
timeLeft = 0;
}
if(tickCount3 >= 100 && timerStarted){
tickCount3 = 0;
timeLeft--;
}
if(tickCount == 1000){
tickCount = 0;
tickChunk += 1;
System.out.println(tickChunk);
}
tickCount3++;
tickCount2++;
tickCount++;
} |
563b3a27-45e2-48e1-83c2-01a3ac25a997 | 9 | private void animate() {
if (startGameImage.contains(currentMouseX, currentMouseY)) {
animationIsRunning = true;
if (levelSelectAnimation != null) {
remove(levelSelectAnimation);
}
if (levelEditorAnimation != null) {
remove(levelEditorAnimation);
}
startGameAnimation = new RingAnimation(startGameImage.getHeight(),
startGameImage.getHeight());
add(startGameAnimation,
startGameImage.getX() - (startGameImage.getHeight() / 2.0),
startGameImage.getY() + (startGameImage.getHeight() / 2.0));
} else if (levelSelectImage.contains(currentMouseX, currentMouseY)) {
animationIsRunning = true;
if (startGameAnimation != null) {
remove(startGameAnimation);
}
if (levelEditorAnimation != null) {
remove(levelEditorAnimation);
}
levelSelectAnimation = new RingAnimation(
levelSelectImage.getHeight(), levelSelectImage.getHeight());
add(levelSelectAnimation, levelSelectImage.getX()
- (levelSelectImage.getHeight() / 2.0),
levelSelectImage.getY()
+ (levelSelectImage.getHeight() / 2.0));
} else if (levelEditorImage.contains(currentMouseX, currentMouseY)) {
animationIsRunning = true;
if (startGameAnimation != null) {
remove(startGameAnimation);
}
if (levelSelectAnimation != null) {
remove(levelSelectAnimation);
}
levelEditorAnimation = new RingAnimation(
levelEditorImage.getHeight(), levelEditorImage.getHeight());
add(levelEditorAnimation, levelEditorImage.getX()
- (levelEditorImage.getHeight() / 2.0),
levelEditorImage.getY()
+ (levelEditorImage.getHeight() / 2.0));
}
} |
c9ed8e6a-f87d-4302-96ba-90c421ee8023 | 7 | public boolean addFrame(BufferedImage im) {
if ((im == null) || !started) {
return false;
}
boolean ok = true;
try {
if (!sizeSet) {
// use first frame's size
setSize(im.getWidth(), im.getHeight());
}
image = im;
getImagePixels(); // convert to correct format if necessary
analyzePixels(); // build color table & map pixels
if (firstFrame) {
writeLSD(); // logical screen descriptior
writePalette(); // global color table
if (repeat >= 0) {
// use NS app extension to indicate reps
writeNetscapeExt();
}
}
writeGraphicCtrlExt(); // write graphic control extension
writeImageDesc(); // image descriptor
if (!firstFrame) {
writePalette(); // local color table
}
writePixels(); // encode and write pixel data
firstFrame = false;
} catch (IOException e) {
ok = false;
}
return ok;
} |
12a8c5f9-a2e8-4fd2-8a4d-cc6ae712ce65 | 3 | public int buildAndStartNewPipelineFromGson(GsonNewPipelineRequest request) {
LatLong boundingBoxNW = new LatLong(request.NWlat, request.NWlong);
LatLong boundingBoxSE = new LatLong(request.SElat, request.SElong);
GeoParams geoParams = new GeoParams(request.resolutionX, request.resolutionY, boundingBoxNW, boundingBoxSE);
AuthFields authFields = new AuthFields(
request.oauthAccessToken,
request.oauthAccessTokenSecret,
request.oauthConsumerKey,
request.oauthConsumerKeySecret);
WrapperParams wrapperParams = new WrapperParams(request.source, request.theme);
WrapperFactory.WrapperType type = WrapperFactory.WrapperType.valueOf(request.wrapperType);
AbstractDataWrapper tw = WrapperFactory.getWrapperInstance(type, wrapperParams, authFields, geoParams);
PointStream ps = new PointStream(tw, request.pointPollingTimeMS);
EmageBuilder eb = new EmageBuilder(ps, EmageBuilder.Operator.valueOf(request.operatorType));
EmageStream es = new EmageStream(eb, request.emageCreationRateMS, request.emageWindowLength);
//Add the pipeline to our collection by it's index so we can reaccess it
final DataPipeline p = new DataPipeline(ps, es);
this.dataPipelines.put(p.pipelineID, p);
//Create the threads and Start the streams
Thread pointThread = new Thread(new Runnable(){
@Override
public void run() {
while (true) {
p.pointStream.getNextPoint();
}
}
});
Thread emageThread = new Thread(new Runnable(){
@Override
public void run() {
while (true) {
Emage emage = p.emageStream.getNextEmage();
try {
Logger.log(emage.toString());
} catch (IOException e) {
}
System.out.println(emage);
}
}
});
pointThread.start();
emageThread.start();
return p.pipelineID;
} |
14f6b0b3-5658-435e-a5f9-a451636c88e2 | 7 | public void pickupItems(int numberOfItems, float maxDistance) throws IOException {
int itemsPicked = 0;
long startDeadlockCheck = System.currentTimeMillis();
do {
float[] itemAgentIdAndDistance = this.getNearestItemToAgentEx(-2);
long currentlyElapsedTime = System.currentTimeMillis() - startDeadlockCheck;
if (itemAgentIdAndDistance[0] == 0 || itemAgentIdAndDistance[1] > maxDistance || currentlyElapsedTime > 30000) {
break;
}
boolean itemStillExists = true;
do {
//FIXME: why pickup item twice??
this.pickupItem((int) itemAgentIdAndDistance[0]);
try {
//FIXMR: why is there a sleep needed?
Thread.sleep(500);
} catch (InterruptedException ex) {
// ignore
}
itemStillExists = this.getAgentExists((int) itemAgentIdAndDistance[0]);
long startDeadlockCheck2 = System.currentTimeMillis();
long currentlyElapsedTime2 = System.currentTimeMillis() - startDeadlockCheck2;
if (currentlyElapsedTime2 > 5000) {
// try the next item
break;
}
} while (itemStillExists);
itemsPicked++;
} while (itemsPicked != numberOfItems);
} |
fbeb5eae-0325-48c6-b176-952b94e39b3d | 6 | public boolean equals(Spire s) {
if ((s.getX() == this.x) && (s.getY() == this.y) && (s.getZ() == this.z) && (s.getXs() == this.xs) && (s.getYs() == this.y) && (s.getZs() == this.zs)) {
return true;
}
return false;
} |
503b726b-7427-4e87-aaa2-a2669feef687 | 0 | public boolean isAnimating() {
return animating;
} |
778475bc-76d1-49ba-9889-2b95c2f5753c | 1 | public static List<Word> parseWords(String sentence) {
List<Word> words = new ArrayList<>();
String[] strings = sentence.split("\\s+");
for (String string : strings) {
words.add(new Word(string));
}
return words;
} |
8abf9771-477a-409e-a2dd-982d9742a339 | 3 | protected void search(String fileName){
startOutput(fileName);
while(!cobweb.getUnsearchQueue().isEmpty()){
final WebPage wp = cobweb.peekUnsearchQueue();// 查找列隊
if (!cobweb.isSearched(wp.getUrl())) {
try {
leavesContentFileWriter.write(CrawlResultFormat.webPageHead(wp));
leavesContentFileWriter.write(WebPageParser.toPureHtml(wp));
leavesContentFileWriter.write(CrawlResultFormat.webPageTail());
} catch (Exception e) {
e.printStackTrace();
}
}
}
closeOutput();
} |
63bc274c-db90-48b6-8677-ddcf82088096 | 9 | private void locateNext() {
hasNext = true;
pos += value.length();
int i = -1;
int iOr = lowered.indexOf("or", pos);
int iAnd = lowered.indexOf("and", pos);
if (iOr != -1 && iAnd != -1)
i = iOr < iAnd ? iOr : iAnd;
else if (iOr != -1)
i = iOr;
else if (iAnd != -1)
i = iAnd;
if (i == -1) {
hasNext = pos < where.length();
value = where.substring(pos);
return;
} else if (i == pos) {
value = i == iOr ? "or" : "and";
hasNext = true;
return;
}
value = where.substring(pos, i);
if (value.trim().length() == 0) {
locateNext();
}
} |
ef4b1541-b284-4e8a-8f21-bfc77a11e679 | 4 | public static TriCubicSpline[] oneDarray(int nP, int mP, int lP, int kP){
if(mP<3 || lP<3 || kP<3)throw new IllegalArgumentException("A minimum of three x three x three data points is needed");
TriCubicSpline[] a = new TriCubicSpline[nP];
for(int i=0; i<nP; i++){
a[i]=TriCubicSpline.zero(mP, lP, kP);
}
return a;
} |
e6929368-aaff-4afc-ad71-9505cfba5330 | 5 | public static double NeedlemanWunsch(String mSeqA, String mSeqB) {
final int L1 = mSeqA.length();
final int L2 = mSeqB.length();
int[][] matrix = new int[L1 + 1][L2 + 1];
for (int i = 0; i < L1 + 1; i++)
matrix[i][0] = -1 * i;
for (int j = 0; j < L2 + 1; j++)
matrix[0][j] = -1 * j;
for (int i = 1; i < L1 + 1; i++) {
for (int j = 1; j < L2 + 1; j++) {
int penalty = matrix[i - 1][j - 1] + ((mSeqA.charAt(i - 1) == mSeqB.charAt(j - 1)) ? 1 : -1);
matrix[i][j] = Math.max(Math.max(penalty, matrix[i][j - 1] - 1), matrix[i - 1][j] - 1);
}
}
return ((double) (matrix[L1][L2] / Math.max(mSeqA.length(), mSeqB.length())));
} |
4d15b809-fbca-4872-88ce-5140105bc256 | 0 | @Before
public void setUp() {
} |
a3bc6295-92b2-49eb-9dff-f436725b35ec | 1 | public static void printToConsole(String text) {
for (String line : text.split("\n")) {
log.info(line);
}
} |
b5577f01-63b5-4b6e-8e07-43c5ca047ae9 | 7 | public void followingItem(Item I)
{
if(I.container()!=null)
I.setContainer(null);
final Room R=CMLib.map().roomLocation(I);
if(R==null)
return;
if(R!=lastOwner.location())
lastOwner.location().moveItemTo(I,ItemPossessor.Expire.Never,ItemPossessor.Move.Followers);
if((inventory)&&(R.isInhabitant(lastOwner)))
{
CMLib.commands().postGet(lastOwner,null,I,true);
if(!lastOwner.isMine(I))
{
lastOwner.moveItemTo(I);
if(lastOwner.location()!=null)
lastOwner.location().recoverRoomStats();
}
}
} |
06a01293-8ef1-42ed-9cb1-754c2b780f00 | 7 | private void AddbtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddbtnActionPerformed
int Fi = Table.getSelectedRow();
if (Fi < 0) {
String Mensaje = "Elija Un Producto Antes de Continuar,"
+ "o elija menos de dos productos";
JOptionPane.showMessageDialog(null, Mensaje, "", JOptionPane.ERROR_MESSAGE);
} else {
String id = String.valueOf(Table.getValueAt(Fi, 0));
String nam = String.valueOf(Table.getValueAt(Fi, 1));
String descri = String.valueOf(Table.getValueAt(Fi, 2));
String preci = String.valueOf(Table.getValueAt(Fi, 3));
String cost = String.valueOf(Table.getValueAt(Fi, 4));
String cantidad = String.valueOf(Table.getValueAt(Fi, 5));
int n = Integer.parseInt(id);
try {
it = dao.findByID(n);
} catch (IOException ex) {
Logger.getLogger(RemoveTableFrame.class.getName()).log(Level.SEVERE, null, ex);
}
int i = it.getId();
String name = it.getName();
String desc = it.getDescripcion();
String costo = it.getCosto();
String precio = it.getPrecio();
String cant = it.getCantidad();
String Mensaje = " Producto Seleccionado\n" + "Id: " + id + "\n" + "Nombre: " + nam + "\n"
+ "Descripcion: " + descri + "\n" + "Costo: " + cost + "\n"
+ "Precio :" + preci + "\n" + "Cantidad :" + cantidad;
String valor = JOptionPane.showInputDialog(null, Mensaje, "Inventario", JOptionPane.INFORMATION_MESSAGE);
if (!(valor == null || valor == "")) {
int x = Integer.parseInt(cant);
int y = Integer.parseInt(valor);
if (y > x) {
JOptionPane.showMessageDialog(this, "El valor de unidades es menor al "
+ "disponible", "Inventario", JOptionPane.WARNING_MESSAGE);
} else {
int can = x - y;
String nc = String.valueOf(can);
it.setId(i);
it.setName(name);
it.setDescripcion(desc);
it.setCosto(costo);
it.setPrecio(precio);
it.setCantidad(nc);
try {
dao.update(it);
} catch (IOException ex) {
}
Mensaje = "Se han eliminado las unidades del Producto Seleccionado";
JOptionPane.showMessageDialog(null, Mensaje, "Invetario", JOptionPane.INFORMATION_MESSAGE);
try {
setClosed(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(RemoveTableFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {
JOptionPane.showMessageDialog(null, "Debe agregar una cantidad", "Inventario", JOptionPane.INFORMATION_MESSAGE);
}
}
}//GEN-LAST:event_AddbtnActionPerformed |
8664186c-a549-4c66-9545-558b3f4a9ab6 | 5 | private void checkShowWelcomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkShowWelcomeActionPerformed
File config = DFAMainWin.getConfigFile();
if(checkShowWelcome.isSelected()) {
if(config.exists()) {
//delete
if(!config.delete()) {
System.err.println("Could not delete config file properly.");
} else {
dFAMainWin.setShowWelcomeWindow(true);
}
}
} else {
if(!config.exists()) {
try {
config.createNewFile();
dFAMainWin.setShowWelcomeWindow(false);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}//GEN-LAST:event_checkShowWelcomeActionPerformed |
1739830e-07e2-4041-a749-d33e6247f7d7 | 1 | public String worstQuestion()
{
if(questionStats.size() > 0)
{
QuestionStatistic min = Collections.min(questionStats);
return min.questionText + ", " + min.correctAnswers + " times.";
}
return "no statistics found!";
} |
542fa658-db31-4132-851d-315d574fcd05 | 6 | public String nextCDATA() throws JSONException {
char c;
int i;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
if (c == 0) {
throw syntaxError("Unclosed CDATA");
}
sb.append(c);
i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' &&
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i);
return sb.toString();
}
}
} |
366347f2-a8e2-4f05-8f73-07cd5f8ef758 | 8 | public final void write(DataOutputStream out) throws IOException {
_debug.fine("Anmeldelistentelegramm versenden: ", this);
out.writeShort(length);
out.writeBoolean(delta);
out.writeLong(transmitterId);
if(objectsToAdd == null) {
out.writeShort(0);
}
else {
out.writeShort(objectsToAdd.length);
for(int i = 0; i < objectsToAdd.length; ++i) {
out.writeLong(objectsToAdd[i]);
}
}
if(objectsToRemove == null) {
out.writeShort(0);
}
else {
out.writeShort(objectsToRemove.length);
for(int i = 0; i < objectsToRemove.length; ++i) {
out.writeLong(objectsToRemove[i]);
}
}
if(attributeGroupAspectsToAdd == null) {
out.writeShort(0);
}
else {
out.writeShort(attributeGroupAspectsToAdd.length);
for(int i = 0; i < attributeGroupAspectsToAdd.length; ++i) {
attributeGroupAspectsToAdd[i].write(out);
}
}
if(attributeGroupAspectsToRemove == null) {
out.writeShort(0);
}
else {
out.writeShort(attributeGroupAspectsToRemove.length);
for(int i = 0; i < attributeGroupAspectsToRemove.length; ++i) {
attributeGroupAspectsToRemove[i].write(out);
}
}
} |
7bbf312c-a45e-4792-9775-03f5aa606f97 | 6 | public static void cleanDirectory(final File directory) throws IOException {
if (!directory.exists()) {
final String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
final String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
final File[] files = directory.listFiles();
if (files == null) { // null if security restricted
throw new IOException("Failed to list content of " + directory);
}
IOException exception = null;
for (final File file : files) {
try {
forceDelete(file);
} catch (final IOException ioe) {
exception = ioe;
}
}
if (null != exception) {
throw exception;
}
} |
eb03e606-c7df-48d1-87bd-c158af677cf7 | 9 | public Sequence getSubsequence(Nucleotide aStartNucleotide,
Nucleotide anEndNucleotide) throws NonConsecutiveNucleotideException {
if (!this.containsNucleotide(aStartNucleotide)
|| !this.containsNucleotide(anEndNucleotide)) {
return null;
}
if(aStartNucleotide.compareTo(anEndNucleotide) == -1 ){
return null;
}
boolean addToSubSequence = false;
Set<Nucleotide> returnMe = new LinkedHashSet<Nucleotide>();
for (Nucleotide nucleotide : this.getNucleotides()) {
if (addToSubSequence && nucleotide.equals(anEndNucleotide)) {
returnMe.add(nucleotide);
addToSubSequence = false;
break;
} else if (addToSubSequence) {
returnMe.add(nucleotide);
} else if (nucleotide.equals(aStartNucleotide)) {
returnMe.add(nucleotide);
addToSubSequence = true;
}
}
if (addToSubSequence) {
return null;
}
return new Sequence(returnMe);
} |
b8c33d97-d59a-430c-ba22-8ee6cd1a1f74 | 3 | public void init(int nplayers, int[] pref) {
this.preferences = pref.clone();
this.id = this.getIndex();
this.players = nplayers;
this.maxBowls[0] = this.players - this.id;
this.maxBowls[1] = this.id + 1;
//System.out.println("Player ID: " + this.id);
//System.out.println("Max bowls can be seen: Round 0: " + this.maxBowls[0]);
//System.out.println("Max bowls can be seen: Round 1: " + this.maxBowls[1]);
this.start[0] = 0;
this.start[1] = maxBowls[0] - 1;
this.len[0] = 0;
this.len[1] = 1;
//strategy 2: optimal stopping, 0: build distribution 1: optimal round 0
int y=10;
x=4;
if(maxBowls[0]>y)
strategy = 0;
else if((maxBowls[1]+maxBowls[0]<y) && maxBowls[0] < x)
strategy = 2;
else
strategy = 1;
} |
0aaab115-8f5e-4a86-879d-a7dafbc57bfa | 6 | public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} |
2b3527a6-0db6-48b0-9a5d-ca25a6ca9cdd | 2 | @Override
public void Insertar(Object value) {
Session session = null;
try {
Ejecutivo ejecutivo = (Ejecutivo) value;
session = NewHibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(ejecutivo);
} catch (HibernateException e) {
System.out.println(e.getMessage());
session.getTransaction().rollback();
} finally {
if (session != null) {
// session.close();
}
}
} |
d059124c-bb28-41e5-be3c-5a0027fdbf06 | 8 | public boolean addSkillXP(int amount, int skill){
if (c.expLock) {
return false;
}
if (amount+c.playerXP[skill] < 0 || c.playerXP[skill] > 200000000) {
if(c.playerXP[skill] > 200000000) {
c.playerXP[skill] = 200000000;
}
return false;
}
amount *= Config.SERVER_EXP_BONUS;
int oldLevel = getLevelForXP(c.playerXP[skill]);
c.playerXP[skill] += amount;
if (oldLevel < getLevelForXP(c.playerXP[skill])) {
if (c.playerLevel[skill] < c.getLevelForXP(c.playerXP[skill]) && skill != 3 && skill != 5)
c.playerLevel[skill] = c.getLevelForXP(c.playerXP[skill]);
levelUp(skill);
handleLevelUpGfx();
requestUpdates();
}
setSkillLevel(skill, c.playerLevel[skill], c.playerXP[skill]);
refreshSkill(skill);
return true;
} |
6988a7f2-8f37-48d3-96ed-722c91b8b03f | 5 | public static boolean pointIsWithinSectorAngleBoundries(Point2D.Double p, Point2D.Double origo,
double angle1, double angle2) {
// System.out.println("Point: "+p.getX()+"-"+p.getY());
// System.out.println("Heuristic origo: "+origo.getX()+"-"+origo.getY());
// System.out.println("Vector: "+angle1+ "===== sector: "+angle2);
Line2D.Double vectorToP = new Line2D.Double(origo, p);
double vectorToPAngle = Math.toDegrees(angle(vectorToP));
if(angle2 > 360 && vectorToPAngle >= 0.0 && vectorToPAngle <= (angle2-360)) {
vectorToPAngle += 360;
}
if(vectorToPAngle >= angle1 && vectorToPAngle <= angle2) {
return true;
}
else {
return false;
}
} |
f88cda2a-665c-46bc-bfcd-94eadf4cfdc6 | 0 | @Test
public void EnsureLeadingAndTrailingSlashIsRemoved() {
String path = "/x/y/";
String newpath = Path.trimSlashes(path);
assertEquals("x/y", newpath);
} |
c82af268-89e8-4817-9d9e-9572e1eeeaf7 | 0 | public int getCoordonneeY() {
return y;
} |
f2bbeda6-66e4-4f6e-875b-6c42ca01b3f1 | 7 | public void write(Writer out) throws IOException {
out.write(HEADER);
Object[] sumval = {result,
totalTime,
numTestTotal,
numTestPasses,
numTestFailures,
numCommandPasses,
numCommandFailures,
numCommandErrors,
seleniumVersion,
seleniumRevision,
userAgent,
suite.getUpdatedSuite()};
out.write(MessageFormat.format(SUMMARY_HTML, sumval));
// Display storedVars in a table
if (giVersion != null) {
out.write("<table id=\"gitak_vars\"><tr><td>GI Version:</td><td>" + giVersion + "</td></tr>");
} else {
out.write("<table>");
}
if (storedVars != null) {
String[] vars = storedVars.split(",");
if (vars.length > 0)
for (String var : vars) {
String[] nv = var.split("::");
if (nv.length > 1) {
String value = escapeXML(nv[1]) + " ";
out.write("<tr><td>" + nv[0] + "</td><td>" + value + "</td></tr>");
}
}
}
out.write("</table>"); // End storedvars table
for (int i = 0; i < testTables.size(); i++) {
String table = testTables.get(i).replace("\u00a0", " ");
Object[] val= {suite.getSuiteTitle()+"-"+suite.getCaseName(i), suite.getHref(i), table};
out.write(MessageFormat.format(SUITE_HTML, val));
}
out.write("</table><pre>\n");
if (log != null) {
out.write(quoteCharacters(log));
}
out.write("</pre></body></html>");
out.flush();
} |
37bda6e7-8cff-4271-b01f-2a9b69aa922b | 1 | public java.io.Serializable readAutomaton(Node parent, Document document) {
Set locatedStates = new java.util.HashSet();
Automaton root = createEmptyAutomaton(document);
if(parent == null) return root;
readBlocks(parent, root, locatedStates, document);
// Read the states and transitions.
readTransitions(parent, root, readStates(parent, root, locatedStates,
document));
//read the notes
readnotes(parent, root, document);
// Do the layout if necessary.
performLayout(root, locatedStates);
automatonMap.put(parent.getNodeName(), root);
return root;
} |
6557a257-8207-46e6-8c41-adb7fdc266fb | 5 | private static void input(String[] args) throws Exception {
// argument checking
if (args.length > 0) {
if (args[0].equals("-h")) {
System.out.println("**HELP MENU**");
System.out.println("tf2mapgen <filename>");
System.out.println("output is saved as tf2mapgenfile.vmf");
System.out.println("For use, see README");
throw new Exception("Help menu exit");
} else if (args.length > 2 && args[1].equals("-o")) {
loadPath = args[0];
generatedFilename = args[2];
} else {
loadPath = args[0];
generatedFilename = loadPath.substring(loadPath.lastIndexOf("\\") + 1, loadPath.lastIndexOf("."));
}
} else {
System.out.println("No build-file given, -h for help.");
throw new Exception("No build-file given.");
}
//Let'initKill take a look at that file then
try {
reader = new Scanner(new File(loadPath));
} catch (FileNotFoundException e) {
throw new FileNotFoundException("\nNo file found at " + loadPath + "\n" + e);
}
} |
f6a471b0-508c-4b42-9318-7a398691ebcf | 7 | public boolean hasCoupPossible() {
for (Case caseDame : tablier.getAllCase()) {
if((!tablier.isDameDansCaseBarre(joueurEnCour) && caseDame.getCouleurDame() == joueurEnCour)
|| caseDame.isCaseBarre())
for (DeSixFaces de : deSixFaces) {
if(!de.isUtilise())
if(isCoupPossible(caseDame,tablier.getCaseADistance(caseDame, de)))
return true;
}
}
return false;
} |
b2ecf61f-0c73-49fb-9ec6-3cbdc69f2d45 | 5 | @Override
public synchronized void writeCreditTransactionToFile(Transaction transaction) {
if (creditCounter % BATCH_SIZE == 0 && creditCounter > 0) {
String newCreditFileName = this.reportDao.getCurrentFileName(TransactionType.CREDIT.toString(),
creditFileName);
if (!newCreditFileName.equalsIgnoreCase(creditFileName)) {
try {
flushAndCloseFile(creditFileOut);
} catch (IOException e) {
e.printStackTrace();
}
creditFileOut = createOutFile(newCreditFileName);
}
}
try {
this.writeToFile(transaction, this.creditFileOut);
creditCounter++;
} catch (IOException e) {
logger.warn("Could not write credit transaction : " + e.getMessage());
this.writeDeadLetterTransactionToFile(transaction);
}
} |
30102c50-610d-47e2-b17c-e15192aa1902 | 4 | public static void call(final String data) throws Exception {
// delimited by a comma
// text qualified by double quotes
// ignore first record
final Parser pzparser = DefaultParserFactory.getInstance().newDelimitedParser(new File(data), ',', '\"');
final DataSet ds = pzparser.parse();
final String[] colNames = ds.getColumns();
while (ds.next()) {
for (final String colName : colNames) {
System.out.println("COLUMN NAME: " + colName + " VALUE: " + ds.getString(colName));
}
System.out.println("===========================================================================");
}
if (ds.getErrors() != null && !ds.getErrors().isEmpty()) {
System.out.println("FOUND ERRORS IN FILE");
}
} |
395bd905-a010-4d54-852e-1941bca5a977 | 9 | @Override
public void run(String arg)
{
int numImages = WindowManager.getImageCount();
if( numImages == 0 )
{
IJ.error( "Geodesic reconstruction 3D",
"At least one image needs to be open to run Geodesic reconstruction in 3D" );
return;
}
String[] names = new String[ numImages ];
for (int i = 0; i < numImages; i++)
names[ i ] = WindowManager.getImage(i + 1).getShortTitle();
GenericDialog gd = new GenericDialog("Geodesic reconstruction 3D");
if( maskIndex >= numImages)
maskIndex = 0;
if( markerIndex >= numImages)
markerIndex = 0;
gd.addChoice( "Marker", names, names[ markerIndex ] );
gd.addChoice( "Mask", names, names[ maskIndex ] );
String[] operations = new String[]{ "reconstruction by dilation" };
gd.addChoice( "Geodesic operation", operations, operations[ operationIndex ] );
gd.showDialog();
if ( gd.wasOKed() )
{
markerIndex = gd.getNextChoiceIndex();
maskIndex = gd.getNextChoiceIndex();
operationIndex = gd.getNextChoiceIndex();
final ImagePlus marker = WindowManager.getImage( markerIndex + 1 );
final ImagePlus mask = WindowManager.getImage( maskIndex + 1 );
if( null == marker || null == mask )
{
IJ.error( "Geodesic reconstruction 3D",
"Error when opening input images" );
return;
}
GeodesicReconstruction gr = new GeodesicReconstruction( marker, mask );
ImagePlus output = null;
final long start = System.currentTimeMillis();
switch( operationIndex )
{
case 0:
output = gr.reconstructionByDilationHybrid();
break;
default:
}
if ( null != output )
output.show();
final long end = System.currentTimeMillis();
IJ.log("Geodesic operation took " + (end-start) + " ms.");
}
} |
aef6b823-427a-46ad-90fc-28a0c8357f53 | 3 | public static void castVote(VoteCast vote){
if(vote == VoteCast.A) A+=1;
else if(vote == VoteCast.B) B+=1;
else if(vote == VoteCast.R) R+=1;
updatePlayerReadout();
} |
b1e67bdb-1457-4f81-9b3e-1f287732cc3f | 2 | private void btnExcelExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcelExportActionPerformed
String input = Utils.showFileChooser("Opslaan", "Rooster");
if (!input.isEmpty()) {
boolean inverted = Utils.promptQuestion("Wilt u de tabel omgedraaid of precies zoals hierboven?", false, "Zoals hierboven", "Omgedraaid");
ExcelExporter.Export(tblSchedule, new File(input.contains(".xls") ? input : input + ".xls"), inverted);
}
}//GEN-LAST:event_btnExcelExportActionPerformed |
e03628fe-e046-4e88-b8d1-50f419dd5d2f | 9 | public void personDetailsForm() {
super.personDetailsForm();
vatNumber = null;
contactName = null;
// Contact name
if (!contactNameField.getText().equals("")) {
contactName = contactNameField.getText();
contactNameLabel.setForeground(Color.black);
}
else {
errorMessage = errorMessage + "Contact name field cannot be empty!\n";
contactNameLabel.setForeground(Color.red);
}
// Vat number
if (!vatNumberField.getText().equals("")) {
vatNumber = vatNumberField.getText();
vatNumberLabel.setForeground(Color.black);
}
else {
errorMessage = errorMessage + "VAT number field cannot be empty!\n";
vatNumberLabel.setForeground(Color.red);
}
// Execute if anything has been entered into any field
if (name != null && address != null && email != null && contactNumber != null
&& vatNumber != null && contactName != null) {
// Specific handler for edit mode
if (editMode) {
driver.getPersonDB().changePersonDetails(person, name, email, contactNumber,
address, 0, null, vatNumber, contactName);
setTextField(getIndex(driver.getPersonDB().getSupplierList()), driver.getPersonDB()
.getSupplierList());
valid = true;
}
// Handler for new supplier mode
else {
valid = true;
driver.getPersonDB().createNewPerson(person, name, email, contactNumber, address,
0, null, contactName, vatNumber);
setTextField(driver.getPersonDB().getSupplierList().size() - 1, driver
.getPersonDB().getSupplierList());
}
// Enable buttons
deletePersonButton.setEnabled(true);
editPersonButton.setEnabled(true);
newPersonButton.setEnabled(true);
// Set the visibility of buttons
newPersonButton.setVisible(true);
editPersonButton.setVisible(true);
submitButton.setVisible(false);
cancelEditButton.setVisible(false);
}
// Print an error message if errors exist
else {
JOptionPane.showMessageDialog(null, "" + errorMessage);
}
revalidate();
repaint();
} |
ad824341-456a-4e16-9af1-7110caf603e8 | 3 | public void removeTask(int taskEntID) {
Task toRemove = null;
synchronized (tasks) {
for (Task t : tasks) {
if (t.getEntityID() == taskEntID) {
System.out.println("TASK TO REMOVE FOUND");
toRemove = t;
}
}
if (toRemove != null) {
tasks.remove(toRemove);
}
}
} |
2974a337-9ec5-48f7-ac43-7bd37d4ab0e5 | 2 | public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject o = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, o, null);
}
return o;
} |
30a1aac7-f98e-4d3a-8843-37d206e87eb7 | 0 | public Hashtable<String, K> getCodes() {
return codes;
} |
2d7e870d-16fe-47b6-858a-76ba97fdb4a0 | 4 | @Override
public void render()
{
double[] pos;
float[] color;
double size;
double angle;
int numVerts_ = 8;
GL11.glBegin(GL11.GL_TRIANGLES);
for(int i = 0; i < MAX_PARTICLES; i++)
{
color = getCRule(cID_[i]).getColor(r_[i], g_[i], b_[i], a_[i], age_[i], props_[i]);
size = getSRule(sID_[i]).getSize(size_[i], age_[i], props_[i]);
pos = getPRule(pID_[i]).getPos(xCoord_[i], yCoord_[i], angle_[i], age_[i], props_[i]);
if(size != 0 && color[3] > 0)
{
for(int j = 0; j < numVerts_; j++)
{
GL11.glColor4f(color[0], color[1], color[2], color[3]);
angle = j * 2 * Math.PI / numVerts_;
GL11.glVertex2d(pos[0] + (Math.cos(angle) * size), pos[1] + (Math.sin(angle) * size));
angle = (j + 1) * 2 * Math.PI / numVerts_;
GL11.glVertex2d(pos[0] + (Math.cos(angle) * size), pos[1] + (Math.sin(angle) * size));
GL11.glVertex2d(pos[0], pos[1]);
}
}
}
GL11.glEnd();
} |
42af71f8-eac2-4229-9e30-e79d8141b0b1 | 6 | private void sendPackage(String type, String... item) {
if ( (manager.getCurrentStage() != null && !manager.isStageItemsEmpty()) || type.equals(OVERLAY) ){
//printStage();
IsaacGamePackage isaacPackage = manager.createGamePackage(type, item);
try {
if (isGameActive()) {
queue.put(isaacPackage); // blocks if queue is full
} else {
notifyIsaacLogStatus(false);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
9b8667e9-8926-49cf-8e34-147332f578bc | 6 | public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
{
if (a == null || a.length == 0) return;
Manager min = a[0];
Manager max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.getBonus() > a[i].getBonus()) min = a[i];
if (max.getBonus() < a[i].getBonus()) max = a[i];
}
result.setFirst(min);
result.setSecond(max);
} |
4568cb3a-80ea-415d-a5e9-f27ab38013ca | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NucleotideInteraction other = (NucleotideInteraction) obj;
if (firstNucleotide == null) {
if (other.firstNucleotide != null)
return false;
} else if (!firstNucleotide.equals(other.firstNucleotide))
return false;
if (secondNucleotide == null) {
if (other.secondNucleotide != null)
return false;
} else if (!secondNucleotide.equals(other.secondNucleotide))
return false;
return true;
} |
0a5961f4-92c2-4ae9-9410-a677dc2f33f2 | 8 | @Override
public boolean evaluate(RuleContext ruleContext)
{
BigDecimal lhs = new BigDecimal(mValues.get(0).asString(ruleContext));
BigDecimal lower = new BigDecimal(mValues.get(1).asString(ruleContext));
BigDecimal upper = new BigDecimal(mValues.get(2).asString(ruleContext));
boolean result = false;
switch (upper.compareTo(lower))
{
case -1:
// a_upper < lower
if (ruleContext.getEvents().isDebugEnabled())
{
ruleContext.getEvents().debug(TYPE + ": upper < lhs < lower: " + upper + " < " + lhs + " < " + lower);
}
result = ((lhs.compareTo(lower) < 0) && (lhs.compareTo(upper) > 0));
break;
case 0:
// a_upper == lower
if (ruleContext.getEvents().isDebugEnabled())
{
ruleContext.getEvents().debug(TYPE + ": upper == lower, always false.");
}
result = false;
break;
case 1:
// a_upper > lower
if (ruleContext.getEvents().isDebugEnabled())
{
ruleContext.getEvents().debug(TYPE + ": lower < lhs < upper: " + lower + " < " + lhs + " < " + upper);
}
result = ((lhs.compareTo(lower) > 0) && (lhs.compareTo(upper) < 0));
break;
default:
throw new RuntimeException(TYPE + ": Unexpected comparisson result of lower='" + lower + "' and upper='" + upper + "'");
}
return result ^ mNot;
} |
eed052eb-5227-4e1d-917d-993659b889da | 5 | protected void renameProfile() {
boolean doit = true;
for(int i=profiles.size()-1; i>=0; i--) {
Profile p = profiles.get(i);
if(p.name.equals(txtProfile.getText())){
doit = false; //if we find a duplicate name, don't do it!
}
}
if(doit){
selProfile.name = txtProfile.getText();
profileListMdl.removeAllElements();
for(int i=0; i<=profiles.size()-1; i++) {
Profile p = profiles.get(i);
profileListMdl.addElement(p.name);
if(p.name.equals(txtProfile.getText())){
profileList.setSelectedValue(profileListMdl.lastElement(), true);
selectedProfile();
con.log("Log","Renamed profile");
writeData();
}
}
}
} |
e590239b-982b-4b08-8aff-4849786f1448 | 1 | @RequestMapping("/listarStock")
public ModelAndView listarStock() {
Stock stock = Stock.getInstance();
Map<String, Integer> mapStock = stock.obtenerStock();
Set<String> setStock = mapStock.keySet();
List<Producto> productList = new ArrayList<Producto>();
for (Iterator<String> iterator = setStock.iterator(); iterator.hasNext();) {
String nombre = iterator.next();
Integer cantidad = mapStock.get(nombre);
Producto otroProducto = new Producto(nombre, cantidad);
productList.add(otroProducto);
}
ModelMap model = new ModelMap();
model.put("nombre", "stockList");
model.put("productos", productList);
return new ModelAndView("listarStock", model);
} |
80c3733f-c226-41af-84c9-97ce7ed99641 | 7 | private JSONWriter append(String s) throws JSONException {
if (s == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(s);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} |
95d118e8-620b-41b0-8a1e-7eeb9e91d50d | 9 | public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (num == null)
return res;
if (num.length == 0) {
res.add(new ArrayList<Integer>());
return res;
}
Arrays.sort(num);
for (int i = 0; i < (int)Math.pow(2, num.length); i++) {
ArrayList<Integer> set = new ArrayList<Integer>();
int temp = i;
int lastUnselected = -1;
boolean add = true;
for (int j = 0; j < num.length; j++) {
if ((temp & 1) != 0) {
if (lastUnselected >= 0 && lastUnselected + 1 == j && num[lastUnselected] == num[j]) {
add = false;
break;
}
set.add(num[j]);
} else {
lastUnselected = j;
}
temp >>= 1;
}
if (add)
res.add(set);
}
return res;
} |
651fe43e-8c3b-4b25-8803-99a931666c36 | 9 | private BigInteger[] getPrimesParallel(int keyBitSize) {
GenPrimeThread[] primeThreads = new GenPrimeThread[cores];
BigInteger[] primes = new BigInteger[cores];
BigInteger[] retPrime = new BigInteger[2];
for (int i = 0; i < cores; i++) {
primeThreads[i] = new GenPrimeThread(core, keyBitSize);
}
// Start Threads
for (int i = 0; i < cores; i++) {
primeThreads[i].start();
}
for (int i = 0; i < cores; i++) {
try {
primeThreads[i].join();
} catch (InterruptedException ex) {
Logger.getLogger(KeyGenRSA.class
.getName()).log(Level.SEVERE, null, ex);
}
}
for (int i = 0; i < cores; i++) {
primes[i] = primeThreads[i].getPrime();
}
for (int i = 0; i < cores; i++) {
for (int j = cores - 1; j >= 0; j--) {
log2ofPQ = Math.abs(CryptobyHelper.logBigInteger(primes[i])
- CryptobyHelper.logBigInteger(primes[j]));
if (log2ofPQ >= 0.1 || log2ofPQ <= 30) {
retPrime[0] = primes[i];
retPrime[1] = primes[j];
return retPrime;
}
}
}
retPrime[0] = BigInteger.ZERO;
retPrime[1] = BigInteger.ZERO;
return retPrime;
} |
b87c7b38-dd1d-4062-994c-d6536fa82a98 | 5 | private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
if (!txtCaminhoBanco.getText().isEmpty() && (txtCaminhoBanco.getText().contains(":/") || txtCaminhoBanco.getText().contains(":\\"))) {
JTextField pwd = new JPasswordField(10);
JLabel label = new JLabel("Digite a senha:");
int x = JOptionPane.showConfirmDialog(null, new Object[]{label, pwd}, "Senha", JOptionPane.OK_CANCEL_OPTION);
pwd.requestFocus();
if (x == 0) {
if (pwd.getText().equals(new Validacoes().geraPassword())) {
criaXML(txtIPServidor.getText(), txtCaminhoBanco.getText());
this.dispose();
new Login().setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Senha incorreta", "Erro", JOptionPane.ERROR_MESSAGE);
}
}
}
}//GEN-LAST:event_btnOkActionPerformed |
549676d3-2277-441d-9619-44beb41603ba | 7 | private double classificationConverter(String classification)
{
double convertedClassification;
if (classification.equals("Definitive"))
convertedClassification = 1.0;
else if (classification.equals("Dependent"))
convertedClassification = 2.0/3.0;
else if (classification.equals("Dangerous"))
convertedClassification = 2.0/3.0;
else if (classification.equals("Dominant"))
convertedClassification = 2.0/3.0;
else if (classification.equals("Demanding"))
convertedClassification = 1.0/3.0;
else if (classification.equals("Dormant"))
convertedClassification = 1.0/3.0;
else if (classification.equals("Discretionary"))
convertedClassification = 1.0/3;
else
convertedClassification = 0;
return convertedClassification;
} |
5effb2a1-b39f-4993-aeae-44bd937ff936 | 7 | public static int GetCurrentSecondHighActivatedNodeAL(){
//功能:
//得到当前激活强度次高的节点的激活强度
int low=0;
int GraphSize=CognitiveGraph.size();
Vector<Integer> useforsort = new Vector<Integer>();
for(int i=0;i<GraphSize;i++){
int ListSize=CognitiveGraph.get(i).ObjOrAttri.size();
for(int ii=0;ii<ListSize;ii++){
useforsort.add(CognitiveGraph.get(i).ObjOrAttri.get(ii).ActivatedLevel);
}
}
int length=useforsort.size();
for(int i=1;i<length;i++){
for(int j=length-1;j>=i;j--){
if(useforsort.get(j-1)<useforsort.get(j)){
int temp=useforsort.get(j-1);
useforsort.set(j-1, useforsort.get(j));
useforsort.set(j, temp);
}
}
}
int max=useforsort.get(0);
for(int i=0;i<length;i++)
{
if(useforsort.get(i)<max){
low=useforsort.get(i);
break;
}
}
return low;
} |
0fa9f7d2-4d16-4bd7-873a-034024dae40a | 6 | public static ScoringStyle parseStyle(String styleString) {
if (styleString.contains("PERCENT_SCORE")) {
return PERCENT_SCORE;
} else if (styleString.contains("BULLET_DAMAGE")) {
return BULLET_DAMAGE;
} else if (styleString.contains("SURVIVAL_FIRSTS")) {
return SURVIVAL_FIRSTS;
} else if (styleString.contains("SURVIVAL_SCORE")) {
return SURVIVAL_SCORE;
} else if (styleString.contains("MOVEMENT_CHALLENGE")
|| styleString.contains("ENERGY_CONSERVED")) {
return MOVEMENT_CHALLENGE;
} else {
throw new IllegalArgumentException(
"Unrecognized scoring style: " + styleString);
}
} |
a68381cd-99e2-48b6-a46b-4835476247ed | 8 | private StringBuilder hexToString(StringBuilder hh) {
// make sure we have a valid hex value to convert to string.
// can't decrypt an empty string.
if (hh != null && hh.length() == 0){
return new StringBuilder();
}
StringBuilder sb;
// special case, test for not a 4 byte character code format
if (!((hh.charAt(0) == 'F' | hh.charAt(0) == 'f')
&& (hh.charAt(1) == 'E' | hh.charAt(1) == 'e')
&& (hh.charAt(2) == 'F' | hh.charAt(2) == 'f')
&& (hh.charAt(3) == 'F') | hh.charAt(3) == 'f')) {
int length = hh.length();
sb = new StringBuilder(length / 2);
String subStr;
for (int i = 0; i < length; i = i + 2) {
subStr = hh.substring(i, i + 2);
sb.append((char) Integer.parseInt(subStr, 16));
}
return sb;
}
// otherwise, assume 4 byte character codes
else {
int length = hh.length();
sb = new StringBuilder(length / 4);
String subStr;
for (int i = 0; i < length; i = i + 4) {
subStr = hh.substring(i, i + 4);
sb.append((char) Integer.parseInt(subStr, 16));
}
return sb;
}
} |
66a99e89-5db1-4080-b9be-8072e06dfe67 | 6 | public ReaderConfig(ResourceBundle resourceBundle) {
Enumeration<String> fileContext = resourceBundle.getKeys();
while (fileContext.hasMoreElements()) {
String element = (String) fileContext.nextElement();
if ("storiesNumber".equals(element)) {
storiesNumber = Integer.valueOf(resourceBundle
.getString(element));
} else if ("elevatorCapacity".equals(element)) {
elevatorCapacity = Integer.valueOf(resourceBundle
.getString(element));
} else if ("passengersNumber".equals(element)) {
passengersNumber = Integer.valueOf(resourceBundle
.getString(element));
} else if ("animationBoost".equals(element)) {
animationBoost = Integer.valueOf(resourceBundle
.getString(element));
} else {
System.err.println("Problem with resource file");
}
}
try{
checkRightMinNumbers( storiesNumber, elevatorCapacity,passengersNumber);
checkRightMaxNumbers(storiesNumber, elevatorCapacity, passengersNumber, animationBoost);
}catch(ExceptionInInitializerError e){
System.err.println("Error: "+e);
System.exit(1);
}
} |
c722a6dc-bf89-4c02-aa0a-7c93bc297dcc | 7 | public void moveleft(){
switch (polygonPaint) {
case 0:
line.moveLeft();
repaint();
break;
case 1:
curv.moveLeft();
repaint();
break;
case 2:
triangle.moveLeft();
repaint();
break;
case 3:
rectangle.moveLeft();
repaint();
break;
case 4:
cu.moveLeft();
repaint();
break;
case 5:
elipse.moveLeft();
repaint();
break;
case 6:
arc.moveLeft();
repaint();
break;
}
repaint();
} |
60f12eb0-6d8d-4a4e-a632-d51a152adeff | 8 | @Override
public T askChoice(boolean cancel) {
String playerName = control.getPlayer().getName();
System.out.println(playerName + ", " + promptMessage);
int choice = -1;
int cancelChoiceNb = control.getChoices().size() + 1;
int maxSize;
if (cancel) {
maxSize = cancelChoiceNb;
} else {
maxSize = control.getChoices().size();
}
while (choice < 1 || choice > maxSize) {
Iterator<T> it = control.getChoices().iterator();
int i = 1;
while (it.hasNext()) {
T t = it.next();
System.out.println(i + " : " + t);
i++;
}
if (cancel) {
System.out.println(cancel + " : Cancel");
}
choice = TextIHM.scanner.nextInt();
if (Game.IS_TEST) {
System.out.println(choice);
}
System.out.println();
}
T result;
if (cancel && choice == cancelChoiceNb) {
result = null;
} else {
result = control.getChoices().get(choice - 1);
}
return result;
} |
36d5b8ec-d0b1-490c-a964-73a574b874a2 | 8 | public void processEvent(Event event)
{
if (event.getType() == Event.COMPLETION_EVENT)
{
System.out.println(_className + ": Receive a COMPLETION_EVENT, " + event.getHandle());
return;
}
System.out.println(_className + ".processEvent: Received Login Response... ");
if (event.getType() != Event.OMM_ITEM_EVENT)
{
System.out.println("ERROR: " + _className + " Received an unsupported Event type.");
_mainApp.cleanup(-1);
return;
}
OMMItemEvent ie = (OMMItemEvent)event;
OMMMsg respMsg = ie.getMsg();
if (respMsg.getMsgModelType() != RDMMsgTypes.LOGIN)
{
System.out.println("ERROR: " + _className + " Received a non-LOGIN model type.");
_mainApp.cleanup(-1);
return;
}
if (respMsg.isFinal())
{
System.out.println(_className + ": Login Response message is final.");
GenericOMMParser.parse(respMsg);
_mainApp.processLogin(false);
return;
}
if ((respMsg.getMsgType() == OMMMsg.MsgType.STATUS_RESP) && (respMsg.has(OMMMsg.HAS_STATE))
&& (respMsg.getState().getStreamState() == OMMState.Stream.OPEN)
&& (respMsg.getState().getDataState() == OMMState.Data.OK))
{
System.out.println(_className + ": Received Login STATUS OK Response");
GenericOMMParser.parse(respMsg);
_mainApp.processLogin(true);
}
else
{
System.out.println(_className + ": Received Login Response - "
+ OMMMsg.MsgType.toString(respMsg.getMsgType()));
GenericOMMParser.parse(respMsg);
}
} |
6384837f-cf6a-4a45-94cd-14ef1dc31a82 | 1 | @Test
void testA() {
if (true)
throw new RuntimeException("This test always failed");
} |
a93ee3e2-204d-4582-8645-103847793150 | 1 | public void generateNodes(int number)
{
for(int i=0;i<number;i++)
{
Node n = new Node(i);
this.nodes.add(n);
}
} |
8f32b9e9-7bd7-434d-9124-1865859dfd99 | 7 | public int [][] loadTrainData (String fileName) {
System.out.println ("Load Train Data Start!");
wordMapping = new HashMap <String,Integer> ();
BufferedReader reader = null;
int trainData [][] = null;
try {
File file = new File (fileName);
reader = new BufferedReader (new FileReader (file));
String line = null;
String word = null;
int count = 0;
int M = 0; // Doc count
int m = 0; // a doc id
int N = 0; // Doc size
int wordId = 0;
// First line is the total count of the Doc
line = reader.readLine ();
M = Integer.valueOf (line);
System.out.println ("Doc cnt is " + M);
trainData = new int [M][];
while ((line = reader.readLine ())!= null) {
String [] words = line.split (" ");
N = words.length;
trainData [m] = new int [N];
for (int n=0;n<N;++n) {
word = words [n];
Integer wordId_ = null;
if ((wordId_ = wordMapping.get (word)) == null) {
trainData [m][n] = wordId;
wordId_ = new Integer (wordId);
wordMapping.put (word, wordId_);
++ wordId;
} else {
trainData [m][n] = wordId_.intValue ();
}
}
++ m;
}
reader.close ();
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (reader != null) {
try {
reader.close ();
} catch (IOException e) {
e.printStackTrace ();
}
}
}
if (0 != wordMapping.size ()) {
String folderPath = MyUtil.getFolderPath (fileName);
saveWordMapping (folderPath + "/wordMapping.txt", wordMapping);
}
System.out.println ("Word Dict size is " + wordMapping.size ());
System.out.println ("Doc cout " + trainData.length);
return trainData;
} |
5cb775b5-22e7-40c8-a774-aa1704580be4 | 9 | public static void main (String [] args) {
double salarioatual,salarionovo;
char salario ;
Scanner teclado = new Scanner(System.in);
System.out.print("Informe o seu salario para saber qual foi o aumento:");
salarioatual = teclado.nextInt();
if (salarioatual >0 && salarioatual <=1499){
salarionovo = ((salarioatual*15)/100)+salarioatual;
System.out.println("Voce teve um aumento salarial de 15%");
System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo);
}
if (salarioatual >1499 && salarioatual <=1750){
salarionovo = ((salarioatual*12)/100)+salarioatual;
System.out.println("Voce teve um aumento salarial de 12%");
System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo);
}
if (salarioatual >1750 && salarioatual <=2000){
salarionovo = ((salarioatual*10)/100)+salarioatual;
System.out.println("Voce teve um aumento salarial de 10%");
System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo);
}
if (salarioatual >2000 && salarioatual <=3000){
salarionovo = ((salarioatual*7)/100)+salarioatual;
System.out.println("Voce teve um aumento salarial de 7");
System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo);
}
if (salarioatual >3000){
salarionovo = ((salarioatual*5)/100)+salarioatual;
System.out.println("Voce teve um aumento salarial de 5%");
System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo);
}
} |
eef50261-6ce5-424c-a9a3-833026d6cfd1 | 5 | public MenuItem getDisplayMenu() {
if (displayMenu == null) {
displayMenu = new Menu("Display");
// Create listener for Display menu items.
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuItem item = (MenuItem) e.getSource();
if ("Error".equals(item.getLabel())) {
trayIcon.displayMessage(MESSAGE_HEADER, "This is an "
+ item.getLabel() + " message",
TrayIcon.MessageType.ERROR);
} else if ("Warning".equals(item.getLabel())) {
trayIcon.displayMessage(MESSAGE_HEADER, "This is a "
+ item.getLabel() + " message",
TrayIcon.MessageType.WARNING);
} else if ("Info".equals(item.getLabel())) {
trayIcon.displayMessage(MESSAGE_HEADER, "This is an "
+ item.getLabel() + " message",
TrayIcon.MessageType.INFO);
} else if ("None".equals(item.getLabel())) {
trayIcon.displayMessage(MESSAGE_HEADER, "This is an "
+ item.getLabel() + " message",
TrayIcon.MessageType.NONE);
}
}
};
errorItem = new MenuItem("Error");
warningItem = new MenuItem("Warning");
infoItem = new MenuItem("Info");
noneItem = new MenuItem("None");
// Add listeners to Display menu items.
errorItem.addActionListener(listener);
warningItem.addActionListener(listener);
infoItem.addActionListener(listener);
noneItem.addActionListener(listener);
displayMenu.add(errorItem);
displayMenu.add(warningItem);
displayMenu.add(infoItem);
displayMenu.add(noneItem);
}
return displayMenu;
} |
7d719ecc-6a76-4a41-87a9-dd001c9b9182 | 1 | @Override
public int hashCode() {
int hash = 0;
hash += (idPeriferico != null ? idPeriferico.hashCode() : 0);
return hash;
} |
2656c172-a4cb-4c8f-a2e0-5d376ddbf316 | 8 | private void unpackBigPacket(DemultiplexerStreaminformations stream) throws InterruptedException {
// Nutzdatenpakete (das können mehrere sein) und der Paketindex(des großen Pakets) stehen nun zur Verfügung.
// Genau an dieser Stelle greift der Thread auf eine Queue zu, die ihn schlafen legt, wenn KEIN Paket vorhanden ist.
// Um aber auf diese Schlange ein Paket zu legen, muss man sich auf die <code>DemultiplexerStreaminformations</code>
// aber synchronisieren. Hat aber der wartende Thread den Monitor noch, dann gibt es einen Deadlock.
// Aus diesem Grund wird dieser Zugriff aus jeden <code>synchronized(stream)</code> rausgehalten.
final ReferenceDataPacket referenceDataPacket = stream.getReferenceDataPacket();
// Der neue maximale Paketindex, dieser wird hier deklariert, weil er außerhalb des synch. Blocks benötigt wird.
// Er wird aber innerhalb des synch. Blocks gesetzt, dies stellt aber kein Problem dar (siehe Kommentar zum versenden des Tickets).
int newMaxStreamPacketIndex = 0;
// Wenn im synch. Block ein neuer max Index Wert berechnet wird, dann muß ein Ticket versandt werden (aber nur dann).
// Ist diese Variable auf true, dann muß ein Ticket versandt werden.
boolean sendNewTicket = false;
final int indexOfStream;
// War das null-Paket in dem großen Paket
boolean nullPacket = false;
synchronized (stream) {
// Nutzdaten und der Paketindex stehen nun zur Verfügung
// Index des Stream
indexOfStream = stream.getIndexOfStream();
// Falls der Paketindex mit dem Index an dem eine neue Sendebestätigung gesendet werden muß überein stimmt, dann wird ein Ticket verschickt
if (stream.getPacketIndexToSendNextMaxTicketIndex() == referenceDataPacket.getStreamPacketIndex()) {
// Dieses Packet muß den Sender benachrichtigen, dass er neue Pakete verschicken muß.
// Es werden _blockingFactor viele Pakete angefordert.
// Den neuen Index berechnen, bis zu dem der Sender Pakete schicken darf
newMaxStreamPacketIndex = stream.getPacketIndexToSendNextMaxTicketIndex() + _blockingFactor;
// Den neuen Index berechnen, an dem eine neue Sendeerlaubnis an den Sender verschickt werden darf. Dies entspricht
// _blockingFactor/2 oder aber der Variablen _ticketBlockingFactor. Diese wird bei einem
// _blockingFactor von 1 automatisch auf 1 gesetzt.
final int newPacketIndexToSendNextMaxTicketIndex = stream.getPacketIndexToSendNextMaxTicketIndex() + _ticketBlockingFactor;
stream.setMaxStreamPacketIndex(newMaxStreamPacketIndex);
stream.setPacketIndexToSendNextMaxTicketIndex(newPacketIndexToSendNextMaxTicketIndex);
sendNewTicket = true;
}
// Hier steht nun das große Paket zur Verfügung, alle Berechnungen ob ein Ticket verschickt werden muss
// (wenn ja, was für eins) wurden beendet. Nun können die Nutzdatenpakete (die kleinen Pakete) erzeugt werden.
// Dabei kann gleich geprüft werden, ob ein null-Paket dabei war, falls ja, muß das Ticket (wenn denn eins verschickt
// werden muss) gar nicht mehr versandt werden.
// Das ganze findet auf einem synchronisierten Stream statt, da auf die Queue für die Nutzdaten zugegriffen werden
// muss. Ist dieser nicht synchronisiert, kann die Reihenfolge der Nutzdaten durcheinander kommen.
// Wurden alle Pakete aus dem großen Paket ausgepackt
boolean unpackedAllPackets = false;
// Hier sind alle kleinen Nutzdatenpakete(die für die Empfängerapplikation bestimmt sind) verpackt
final byte[] bigDataPacket = referenceDataPacket.getData();
final InputStream in = new ByteArrayInputStream(bigDataPacket);
//deserialisieren
final Deserializer deserializer = SerializingFactory.createDeserializer(in);
while (unpackedAllPackets == false) {
try {
// Größe des Nutzdatenpakets
int sizeOfData = deserializer.readInt();
byte[] data;
if (sizeOfData >= 0) {
// Es sind Nutzdaten vorhanden, das null-Paket hat einen negativen Index
data = deserializer.readBytes(sizeOfData);
// Das gerade ausgepackte Nutzdatenpaket kann nun im Stream gespeichert werden.
// _debug.fine("Ein normales Nutzdatenpaket wird in die kleine Queue gespeichert");
stream.putDataSmallDataPacketQueue(data);
} else {
// Die Größe des Nutzdatenpakets ist negativ, somit wurde entweder ein null-Paket empfangen oder
// das große Paket hat keine kleinen Nutzdatenpakete mehr.
if (sizeOfData == -1) {
// Das bedeutet, dass die Senderapplikation keine Nutzdaten mehr für die
// Empfängerapplikation hat. Der Stream wurde auf der Senderseite bereits als
// "beendet" markiert.
// Es wird nicht weiter geguckt ob die -2 auch noch versandt wurde (was der Fall ist), weil
// die -1 bereits eindeutig ist.
data = null;
nullPacket = true;
unpackedAllPackets = true;
// Das gerade ausgepackte Nutzdatenpaket kann nun im Stream gespeichert werden.
stream.putDataSmallDataPacketQueue(data);
_debug.fine("Beim auspacken eines großen Pakets, Stream(" + indexOfStream + ") wurde ein null-Paket mit Index(Index des großen Pakets) " + referenceDataPacket.getStreamPacketIndex() + " gefunden");
} else {
// Es wurden alle bytes des byte-Arrays ausgelesen, also ist das große Paket "leer"
unpackedAllPackets = true;
_debug.finer("Ein großes Paket wurde ausgepackt, es enthielt nur Nutzdaten. Stream:" + indexOfStream + " Index des großen Pakets: " + referenceDataPacket.getStreamPacketIndex());
}
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
} // synchronized(stream)
// Das versenden darf außerhalb des synch. Blocks stehen, da auf der Gegenseite (Sender) geprüft wird, ob
// der neue maximale Index größer ist als der der gerade empfangen wird.
// Es ist also nicht schlimm, wenn der Empfänger einen "alten" Index an den Sender schickt.
if ((sendNewTicket == true) && (nullPacket == false)) {
// Ein neues Ticket muß an den Sender verschickt werden. Dies muß aber nur geschehen, wenn der Sender noch Nutzdaten
// für den Empfänger hat. Dies erkennt man daran, dass die Nutzdaten ungleich null sind. Sind sie null, dann hat
// der Sender keine Nutzdaten mehr und hat seinerseits den Stream schon beendet (falls noch Tickets für
// den Stream unterwegs sind, wird der Sender diese ignorieren)
try {
sendNewTicketIndexToSender(indexOfStream, newMaxStreamPacketIndex);
} catch (IOException e) {
e.printStackTrace();
_debug.error("Ein Fehler beim serialisieren/deserialisieren: " + e);
}
}
// Debug
_numberOfTakes[indexOfStream] = _numberOfTakes[indexOfStream] + 1;
_debug.finer("Take Stream(" + indexOfStream + ") liefert: Paket mit Index " + referenceDataPacket.getStreamPacketIndex() + " Insgesamt wurden " + _numberOfTakes[indexOfStream] + " takes auf diesem Stream ausgeführt");
} |
d32c5ccf-9af8-4d11-936f-2faf7d216694 | 3 | public static String right(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - len);
} |
04c6f26b-158f-4cf3-9008-f787c9c796cd | 4 | private static void setIsPrime() {
for(int i = 2; i < isPrime.length; i++)
isPrime[i] = true;
for(int i = 2; i < isPrime.length; i++)
if( isPrime[i] )
for(int j = 2; j*i < isPrime.length; j++)
isPrime[i*j] = false;
} |
5c9c1983-fe65-4b7c-8481-225a6e718433 | 7 | public void render(){
//BS
bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
//END BS
Graphics g = bs.getDrawGraphics();
if(gameState == GameState.MENU) g.drawImage(menuImage, 0, 0, getWidth(), getHeight(), null);
else g.drawImage(level.getDojoImage(), 0, 0, getWidth(), getHeight(), null);
if(gameState == GameState.MENU){
if(input.menuUp || input.menuDown) Sound.WUSH.play(false);
menu.render(g);
}else if(gameState == GameState.SINGLE){
level.render(g);
}else if(gameState == GameState.MULTI){
level.render(g);
}
g.dispose();
bs.show();
} |
da82ed7f-6eed-42a5-a026-0fd4a88c593d | 4 | private void process(Transferable t) {
final DataFlavor df = DataFlavor.stringFlavor;
if (t.isDataFlavorSupported(df)) {
try {
BufferedReader r = new BufferedReader(df.getReaderForText(t));
String line;
while ((line = r.readLine()) != null) {
if (Site.resolve(line) != Site.UNKNOWN) {
LOG.trace(format("Из буфера обмена прочитан URL %s", line));
loader.load(ArticleFactory.getArticle(new UrlWrapper(line)));
} else {
LOG.trace(format("Строка не является URL: %s", line));
}
}
r.close();
} catch (UnsupportedFlavorException | IOException e) {
LOG.error(e.getMessage(), e);
}
} else {
LOG.trace("Содержимое буфера обмена проигнорировано.");
}
} |
4d07f57c-07b0-46de-a6f2-41afa8076977 | 2 | public static void main(String[] args) {
TestAtom A = new TestAtom();
Movable player = new Movable();
ArrayList<VerbSignature> signatures = A.getVerbs(player).verbs;
for(VerbSignature v : signatures)
{
System.out.println("Verb: "+v.verbName);
for(VerbParameter p : v.parameters)
{
System.out.println("Param Type: "+p.type.toString());
}
}
/**
Object[] met_args = {"Head", "Beep"};
Object[] con_args = {"Hey Head!"};
if(A.callVerb("printTest", met_args)) // This should work.
System.out.println("Called PrintTest(String,String) fine");
else
System.out.println("Called PrintTest(String,String) badly");
if(A.callVerb("printTest", con_args))// This should fail because printTest(String A) does not have a @Verb
System.out.println("Called PrintTest(String) perfectly fine, wait what?");
else
System.out.println("Called PrintTest(String) failed as expected.");
HashMap<String,Object> class_variables = new HashMap<String,Object>();
class_variables.put("UID", 55);
Object B = Utils.createClass("complexion.server.Atom",con_args,class_variables);
Atom C = (Atom)B;
System.out.print(C.getUID());
**/
} |
Subsets and Splits